From d2a373c17e06be211146f0e40d608009a2700b83 Mon Sep 17 00:00:00 2001 From: astanley Date: Thu, 20 Feb 2025 15:20:02 -0400 Subject: [PATCH] initial commit --- .idea/.gitignore | 3 + .../inspectionProfiles/profiles_settings.xml | 6 + .idea/misc.xml | 6 + .idea/modules.xml | 8 + .idea/upei_migration.iml | 10 + FoxmlWorker.py | 136 +++++ ImportProcessor.py | 118 +++++ ImportServerUtilities.py | 155 ++++++ ImportUtilities.py | 262 +++++++++ ModsTransformer.py | 499 ++++++++++++++++++ 10 files changed, 1203 insertions(+) create mode 100644 .idea/.gitignore create mode 100644 .idea/inspectionProfiles/profiles_settings.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/upei_migration.iml create mode 100644 FoxmlWorker.py create mode 100644 ImportProcessor.py create mode 100644 ImportServerUtilities.py create mode 100644 ImportUtilities.py create mode 100644 ModsTransformer.py diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..f4e2b0b --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..09b0bab --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/upei_migration.iml b/.idea/upei_migration.iml new file mode 100644 index 0000000..327f54d --- /dev/null +++ b/.idea/upei_migration.iml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/FoxmlWorker.py b/FoxmlWorker.py new file mode 100644 index 0000000..b14a2f8 --- /dev/null +++ b/FoxmlWorker.py @@ -0,0 +1,136 @@ +import lxml.etree as ET + +""" +FoxmlWorker.py encapsulates the Foxml object and provides methods to extract data from it. +""" + + +class FWorker: + def __init__(self, foxml_file): + try: + self.tree = ET.parse(foxml_file) + self.root = self.tree.getroot() + except ET.ParseError as e: + raise ValueError(f"Error: Unable to parse FOXML file '{foxml_file}'. XML may be malformed. Details: {e}") + except Exception as e: + raise RuntimeError(f"Unexpected error while parsing FOXML file '{foxml_file}': {e}") + self.namespaces = { + 'foxml': 'info:fedora/fedora-system:def/foxml#', + 'oai_dc': 'http://www.openarchives.org/OAI/2.0/oai_dc/', + 'dc': 'http://purl.org/dc/elements/1.1/', + 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', + 'fedora': "info:fedora/fedora-system:def/relations-external#", + 'fedora-model': "info:fedora/fedora-system:def/model#", + 'islandora': "http://islandora.ca/ontology/relsext#", + 'mods': 'http://www.loc.gov/mods/v3' + } + self.properties = self.get_properties() + + # Returns PID from foxml + def get_pid(self): + return self.root.attrib['PID'] + + # gets state + def get_state(self): + return self.properties['state'] + + # Gets all properties. + def get_properties(self): + values = {} + properties = self.root.findall('.//foxml:objectProperties/foxml:property', self.namespaces) + for property in properties: + name = property.attrib['NAME'].split('#')[1] + value = property.attrib['VALUE'] + values[name] = value + return values + + # Gets all datastream types from foxml. + def get_datastream_types(self): + ns = {'': 'info:fedora/fedora-system:def/foxml#'} + datastreams = self.root.findall('.//foxml:datastream', self.namespaces) + types = {} + for datastream in datastreams: + versions = datastream.findall('./foxml:datastreamVersion', self.namespaces) + mimetype = versions[-1].attrib['MIMETYPE'] + types[datastream.attrib['ID']] = mimetype + return types + + # Gets names of current managed files from foxml. + def get_file_data(self): + mapping = {} + streams = self.get_datastream_types() + for stream, mimetype in streams.items(): + location = self.root.xpath( + f'//foxml:datastream[@ID="{stream}"]/foxml:datastreamVersion/foxml:contentLocation', + namespaces=self.namespaces) + if location: + mapping[stream] = {'filename': location[-1].attrib['REF'], 'mimetype': mimetype} + return mapping + + # Returns dc stream as XML + def get_dc(self): + dc_nodes = self.root.findall( + f'.//foxml:datastream[@ID="DC"]/foxml:datastreamVersion/foxml:xmlContent/oai_dc:dc', + namespaces=self.namespaces) + dc_node = dc_nodes[-1] + return ET.tostring(dc_node, encoding='unicode') + + # Returns list of Dublin Core key/value pairs. Allows for mulitples. + def get_dc_values(self): + dc_nodes = self.root.findall(f'.//foxml:datastream[@ID="DC"]/foxml:datastreamVersion/foxml:xmlContent', + namespaces=self.namespaces) + dc_values = [] + dc_node = dc_nodes[-1] + for child in dc_node.iter(): + if child.text is not None: + cleaned = child.text.replace('\n', '') + text = ' '.join(cleaned.split()) + if text: + tag = child.xpath('local-name()') + dc_values.append({tag: text}) + return dc_values + + # Returns key/value pairs from RELS-EXT. + def get_rels_ext_values(self): + re_values = {} + re_nodes = self.root.findall( + f'.//foxml:datastream[@ID="RELS-EXT"]/foxml:datastreamVersion/foxml:xmlContent/rdf:RDF', + namespaces=self.namespaces) + if re_nodes is None: + return re_values + re_node = re_nodes[-1] + for child in re_node.iter(): + tag = child.xpath('local-name()') + if child.text is not None: + cleaned = child.text.replace('info:fedora/', '').replace('\n', '') + text = ' '.join(cleaned.split()) + if text: + re_values[tag] = text + resource = child.attrib.get('{http://www.w3.org/1999/02/22-rdf-syntax-ns#}resource') + if resource: + re_values[tag] = resource.replace('info:fedora/', '') + return re_values + + # Older Fedora objects may kep mods inline rather than ina separate file in the dataStore. + def get_inline_mods(self): + retval = '' + try: + mods_datastream = self.root.findall( + ".//foxml:datastream[@ID='MODS']/foxml:datastreamVersion/foxml:xmlContent/mods:mods", + self.namespaces + ) + if not mods_datastream: + return retval + mods_node = mods_datastream[-1] + if mods_node is not None: + retval = ET.tostring(mods_node, encoding='unicode') + + except Exception as e: + print(f"An error occurred: {e}") + + return retval + + +if __name__ == '__main__': + FW = FWorker('inputs/sample_foxml.xml') + print(FW.get_dc()) diff --git a/ImportProcessor.py b/ImportProcessor.py new file mode 100644 index 0000000..eb8a96c --- /dev/null +++ b/ImportProcessor.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 + +import csv +import time + +import FoxmlWorker as FW +import ImportServerUtilities as IS +import ImportUtilities as IU + +""" +This class is used to prepare data for ingest into the UPEI ingestion platform. +""" + + +class ImportProcessor: + + def __init__(self, namespace): + self.objectStore = '/usr/local/fedora/data/objectStore' + self.datastreamStore = '/usr/local/fedora/data/datastreamStore' + self.stream_map = { + 'islandora:sp_pdf': ['OBJ', 'PDF'], + 'islandora:sp_large_image_cmodel': ['OBJ'], + 'islandora:sp_basic_image': ['OBJ'], + 'ir:citationCModel': ['FULL_TEXT'], + 'ir:thesisCModel': ['OBJ', 'PDF', 'FULL_TEXT'], + 'islandora:sp_videoCModel': ['OBJ', 'PDF'], + 'islandora:newspaperIssueCModel': ['OBJ', 'PDF'], + 'islandora:sp-audioCModel': ['OBJ'], + } + self.iu = IU.ImportUtilities() + self.ms = IS.ImportServerUtilities(namespace) + self.namespace = namespace + self.export_dir = '/opt/islandora/upei_migration/export' + self.mimemap = {"image/jpeg": ".jpg", + "image/jp2": ".jp2", + "image/png": ".png", + "image/tiff": ".tif", + "text/xml": ".xml", + "text/plain": ".txt", + "application/pdf": ".pdf", + "application/xml": ".xml", + "audio/x-wav": ".wav", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx", + "application/octet-stream": ".bib", + "audio/mpeg": ".mp3", + "video/mp4": ".mp4", + "video/x-m4v": ".m4v", + "audio/vnd.wave": '.wav' + } + self.fieldnames = ['id', 'title', 'parent_id', 'field_member_of', 'field_edtf_date_issued', 'field_abstract', + 'field_genre', 'field_subject', 'field_geographic_subject', 'field_physical_description', + 'field_extent', 'field_resource_type', 'field_linked_agent', 'field_pid', + 'field_related_item', 'field_edtf_date_other', 'field_edtf_copyright_date', 'field_issuance', + 'field_location', 'field_publisher', 'field_edition', 'field_access_condition', + 'field_model', 'field_edtf_date_created', 'file', 'field_subtitle', 'field_identifier', + 'field_alternative_title'] + self.start = time.time() + + # Prepares workbench sheet for collection structure + def prepare_collection_worksheet(self, output_file): + collection_pids = self.iu.get_collection_pids(self.namespace) + with open(output_file, 'w', newline='') as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=self.fieldnames) + writer.writeheader() + rows = [] + for entry in collection_pids: + pid = entry.get('field_pid') + if self.namespace not in entry.get('field_member_of'): + continue + mods = self.iu.extract_from_mods(pid) + row = {'id': pid} + all_fields = entry | mods + for key, value in all_fields.items(): + if type(value) is list: + value = '|'.join(value) + row[key] = value + rows.append(row) + processed = ['islandora:root'] + while rows: + for row in rows: + if row.get('field_member_of') in processed: + writer.writerow(row) + rows.remove(row) + processed.append(row.get('id')) + + # Prepares ingest worksheets per collections + def prepare_collection_member_worksheet(self, collections, output_file): + details = self.iu.get_collection_member_details(self.namespace, collections) + with open(output_file, 'w', newline='') as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=self.fieldnames) + writer.writeheader() + for detail in details: + mods = self.iu.extract_from_mods(detail['field_pid']) + row = mods | detail + writer.writerow(row) + + # Prepares worksheets for workbench ingest. + def prepare_worksheet(self, content_model, output_file): + details = self.iu.get_worksheet_details(self.namespace, content_model) + with open(output_file, 'w', newline='') as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=self.fieldnames) + writer.writeheader() + for detail in details: + mods = self.iu.extract_from_mods(detail['field_pid']) + row = mods | detail + node_id = self.iu.get_nid_from_pid(self.namespace, row['field_member_of']) + row['id'] = row['field_pid'] + dc = self.iu.get_dc_values(detail['field_pid'], self.namespace) + if 'title' not in row: + row['title'] = dc['title'] + if node_id: + row['field_member_of'] = node_id + writer.writerow(row) + + + + +MP = ImportProcessor('ivoices') diff --git a/ImportServerUtilities.py b/ImportServerUtilities.py new file mode 100644 index 0000000..8b336c5 --- /dev/null +++ b/ImportServerUtilities.py @@ -0,0 +1,155 @@ +# Utility class for functions to be run on the server +import csv +import shutil +from pathlib import Path +from urllib.parse import unquote + +import FoxmlWorker as FW +import ImportUtilities as IU + + +class ImportServerUtilities: + def __init__(self, namespace): + self.namespace = namespace + self.objectStore = '/usr/local/fedora/data/objectStore' + self.datastreamStore = '/usr/local/fedora/data/datastreamStore' + self.staging_dir = 'staging' + self.iu = IU.ImportUtilities(namespace) + self.mimemap = {"image/jpeg": ".jpg", + "image/jp2": ".jp2", + "image/png": ".png", + "image/tiff": ".tif", + "text/xml": ".xml", + "text/plain": ".txt", + "application/pdf": ".pdf", + "application/xml": ".xml", + "audio/x-wav": ".wav", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx", + "application/octet-stream": ".bib", + "audio/mpeg": ".mp3", + "video/mp4": ".mp4", + "video/x-m4v": ".m4v", + "audio/vnd.wave": '.wav' + } + + # Retrieves FOXml object store with pid + def get_foxml_from_pid(self, pid): + foxml_file = self.iu.dereference(pid) + foxml = f"{self.objectStore}/{foxml_file}" + try: + return FW.FWorker(foxml) + except: + print(f"No results found for {pid}") + + # Gets PIDS, filtered by namespace directly from objectStore + def get_pids_from_objectstore(self, namespace=''): + wildcard = '*/*' + if namespace: + wildcard = f'*/*{namespace}*' + pids = [] + for p in Path(self.objectStore).rglob(wildcard): + pid = unquote(p.name).replace('info:fedora/', '') + pids.append(pid) + return pids + + # Gets all dc datastream from objectstore + def get_all_dc(self): + cursor = self.iu.conn.cursor() + statement = f"select pid from {self.namespace}" + headers = 'pid', 'dublin_core' + csv_file_path = f"{self.staging_dir}/{self.namespace}_dc.csv" + with open(csv_file_path, mode="w", newline="", encoding="utf-8") as file: + writer = csv.DictWriter(file, fieldnames=headers) # Pass the file object here + writer.writeheader() + for row in cursor.execute(statement): + pid = row['pid'] + foxml_file = self.iu.dereference(pid) + foxml = f"{self.objectStore}/{foxml_file}" + try: + fw = FW.FWorker(foxml) + except: + print(f"No record found for {pid}") + continue + dc = fw.get_dc() + writer.writerow({'pid': pid, 'dublin_core': dc}) + + # Copies digital assets from dataStream store to staging directory + def stage_files(self, content_model, datastreams=None): + if datastreams is None: + datastreams = ['OBJ'] + pids = self.iu.get_pids_by_content_model(self.namespace, content_model) + for pid in pids: + nid = self.iu.get_nid_from_pid(self.namespace, pid) + if nid == '': + continue + fw = self.get_foxml_from_pid(pid) + all_files = fw.get_file_data() + for datastream in datastreams: + if datastream in all_files: + file_info = all_files[datastream] + source = f"{self.datastreamStore}/{self.iu.dereference(file_info['filename'])}" + extension = self.mimemap[file_info['mimetype']] + destination = f"{self.staging_dir}/{nid}_{datastream}{extension}" + shutil.copy(source, destination) + print(f"{nid} {pid} {destination}") + else: + print(f"Datastream not found for {nid}") + + # Builds record directly from objectStore + def build_record_from_pids(self, namespace, output_file): + pids = self.get_pids_from_objectstore(namespace) + headers = [ + 'title', + 'pid', + 'content_model', + 'collection_pid', + 'page_of', + 'sequence', + 'constituent_of'] + + with open(output_file, 'w', newline='') as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=headers) + writer.writeheader() + for pid in pids: + foxml_file = self.iu.dereference(pid) + foxml = f"{self.objectStore}/{foxml_file}" + if (foxml): + fw = FW.FWorker(foxml) + if fw.get_state() != 'Active': + continue + relations = fw.get_rels_ext_values() + row = {} + row['title'] = fw.get_dc_values()[0]['title'] + row['pid'] = pid + for relation, value in relations.items(): + if relation in self.iu.rels_map: + row[self.iu.rels_map[relation]] = value + writer.writerow(row) + else: + print(f"FoXML file for {pid} is missing") + + # Adds all MODS records from datastreamStore to database. + def add_mods_to_database(self): + cursor = self.iu.conn.cursor() + pids = self.get_pids_from_objectstore(self.namespace) + for pid in pids: + foxml_file = self.iu.dereference(pid) + foxml = f"{self.objectStore}/{foxml_file}" + fw = FW.FWorker(foxml) + if fw.get_state() != 'Active': + continue + mapping = fw.get_file_data() + mods_info = mapping.get('MODS') + if mods_info: + mods_path = f"{self.datastreamStore}/{self.iu.dereference(mods_info['filename'])}" + mods_xml = Path(mods_path).read_text() + else: + mods_xml = fw.get_inline_mods() + if mods_xml: + mods_xml = mods_xml.replace("'", "''") + command = f"""UPDATE {self.namespace} set mods = '{mods_xml}' where pid = '{pid}'""" + cursor.execute(command) + self.iu.conn.commit() + + +MS = ImportServerUtilities('namespace') diff --git a/ImportUtilities.py b/ImportUtilities.py new file mode 100644 index 0000000..360d1ee --- /dev/null +++ b/ImportUtilities.py @@ -0,0 +1,262 @@ +#!/usr/bin/env python3 + +import csv +import hashlib +import sqlite3 +import urllib +import urllib.parse +import lxml.etree as ET +import re + +import ModsTransformer as MT + + +class ImportUtilities: + def __init__(self, namespace): + self.conn = sqlite3.connect(f'{namespace}.db') + self.conn.row_factory = sqlite3.Row + self.fields = ['PID', 'model', 'RELS_EXT_isMemberOfCollection_uri_ms', 'RELS_EXT_isPageOf_uri_ms'] + self.objectStore = '/usr/local/fedora/data/objectStore/' + self.datastreamStore = '/usr/local/fedora/data/datastreamStore/' + self.rels_map = {'isMemberOfCollection': 'collection_pid', + 'isMemberOf': 'collection_pid', + 'hasModel': 'content_model', + 'isPageOf': 'page_of', + 'isSequenceNumber': 'sequence', + 'isConstituentOf': 'constituent_of', + 'mods': 'mods' + } + self.mt = MT.ModsTransformer() + self.namespace = namespace + + # Adds node_id to table + def add_node_ids(self, table, csv_file): + cursor = self.conn.cursor() + with open(csv_file, newline='') as csvfile: + reader = csv.DictReader(csvfile) + for row in reader: + command = f"update {table} set node_id = '{row['ID']}' where pid = '{row['PID']}'" + cursor.execute(command) + self.conn.commit() + + # Identifies object and datastream location within Fedora objectStores and datastreamStore. + def dereference(self, identifier: str) -> str: + # Replace '+' with '/' in the identifier + slashed = identifier.replace('+', '/') + full = f"info:fedora/{slashed}" + # Generate the MD5 hash of the full string + hash_value = hashlib.md5(full.encode('utf-8')).hexdigest() + # Pattern to fill with hash (similar to the `##` placeholder) + subbed = "##" + # Replace the '#' characters in `subbed` with the corresponding characters from `hash_value` + hash_offset = 0 + pattern_offset = 0 + result = list(subbed) + + while pattern_offset < len(result) and hash_offset < len(hash_value): + if result[pattern_offset] == '#': + result[pattern_offset] = hash_value[hash_offset] + hash_offset += 1 + pattern_offset += 1 + + subbed = ''.join(result) + # URL encode the full string, replacing '_' with '%5F' + encoded = urllib.parse.quote(full, safe='').replace('_', '%5F') + return f"{subbed}/{encoded}" + + # Gets all pages from book + def get_pages(self, table, book_pid): + cursor = self.conn.cursor() + command = f"SELECT PID from {table} where page_of = '{book_pid}'" + pids = [] + for row in cursor.execute(command): + pids.append(row[0]) + return pids + + # Gets all books in the repository. + def get_books(self, table, collection): + cursor = self.conn.cursor() + command = f"SELECT PID, CONTENT_MODEL from {table} where collection_pid = '{collection}' AND CONTENT_MODEL = 'islandora:bookCModel' " + pids = [] + for row in cursor.execute(command): + pids.append(row[0]) + return pids + + # Processes CSV returned from direct objectStore harvest + def process_full_institution(self, csv_file): + cursor = self.conn.cursor() + cursor.execute(f""" + CREATE TABLE if not exists {self.namespace}( + pid TEXT PRIMARY KEY, + content_model TEXT, + collection_pid TEXT, + page_of TEXT, + sequence TEXT, + constituent_of TEXT + )""") + self.conn.commit() + with open(csv_file, newline='') as csvfile: + reader = csv.DictReader(csvfile) + for row in reader: + collection = row['collection_pid'] + page_of = row['page_of'] + if not page_of: + page_of = ' ' + constituent_of = row['constituent_of'] + if not constituent_of: + constituent_of = ' ' + try: + command = f"INSERT OR REPLACE INTO {self.namespace} VALUES('{row['pid']}', '{row['content_model']}', '{collection}','{page_of}', '{row['sequence']}','{constituent_of}')" + cursor.execute(command) + except sqlite3.Error: + print(command) + print(row['pid']) + self.conn.commit() + + # Get all collection contents within namespace + def get_collection_content_pids(self, table, collection): + cursor = self.conn.cursor() + command = f"SELECT * from {table} where collection_pid = '{collection}'" + pids = [] + for row in cursor.execute(command): + pids.append(row['pid']) + return pids + + # Utility function to prepare database selections for workbenchl + def get_worksheet_details(self, table, content_model): + command = f"Select * from {table} where content_model = 'islandora:{content_model}'" + cursor = self.conn.cursor() + details = [] + for row in cursor.execute(command): + keys = row.keys() + line = {} + for key in keys: + line[key] = (row[key]) + cleaned_line = self.map_worksheet_values(line) + details.append(cleaned_line) + return details + + # Map D7 values to D10 + def map_worksheet_values(self, line): + map = { + 'content_model': 'field_model', + 'pid': 'field_pid', + 'collection_pid': 'field_member_of', + 'page_of': 'field_member_of', + 'sequence': 'field_weight', + } + content_map = { + 'islandora:collectionCModel': 'collection', + 'islandora:sp_large_image_cmodel': 'image', + 'islandora:sp-audioCModel': 'audio', + 'islandora:pageCModel': 'page', + 'islandora:bookCModel': 'Paged Content', + 'islandora:compoundCModel': 'Compound Object', + 'islandora:sp_pdf': 'Digital Document', + 'islandora:sp_basic_image': 'image', + 'islandora:newspaperCModel': 'newspaper', + 'islandora:newspaperIssueCModel': 'Publication Issue', + 'islandora:newspaperPageCModel': 'page', + 'islandora:oralhistoriesCModel': 'Compound Object', + 'islandora:sp_videoCModel': 'Video', + 'ir:thesisCModel': 'Digital Document', + 'islandora:rootSerialCModel': 'Compound Object', + 'islandora:intermediateCModel': 'Compound Object', + 'ir:citationCModel': 'Citation' + } + + cleaned_line = {} + for key, value in line.items(): + if key in map: + if value is None: + value = '' + if value.strip(): + cleaned_line[map[key]] = value + + cleaned_line['field_model'] = content_map[cleaned_line['field_model']] + return cleaned_line + + # Get all content models from map + def get_collection_pid_model_map(self, table, collection): + cursor = self.conn.cursor() + command = f"SELECT PID, CONTENT_MODEL from {table} where collection_pid = '{collection}'" + map = {} + for row in cursor.execute(command): + map[row[0]] = row[1] + return map + + def get_subcollections(self, table, collection): + cursor = self.conn.cursor() + command = f"SELECT PID, CONTENT_MODEL from {table} where collection_pid = '{collection}' AND CONTENT_MODEL = 'islandora:collectionCModel' " + pids = [] + for row in cursor.execute(command): + pids.append(row[0]) + return pids + + def get_collection_recursive_pid_model_map(self, table, collection_pid): + descendants = {} + cursor = self.conn.cursor() + command = f"select PID, CONTENT_MODEL from {table} where COLLECTION_PID = '{collection_pid}'" + child_collections = [] + books = [] + for row in cursor.execute(command): + if row['content_model'] in ['islandora:collectionCModel', 'islandora:bookCModel']: + child_collections.append(row['PID']) + descendants[row['PID']] = row['content_model'] + else: + descendants[row['PID']] = row['content_model'] + while child_collections: + child_collection = child_collections.pop(0) + command = f"select PID, CONTENT_MODEL from {table} where COLLECTION_PID = '{child_collection}' or page_of = '{child_collection}' " + for row in cursor.execute(command): + if row['content_model'] in ['islandora:collectionCModel', 'islandora:bookCModel']: + child_collections.append(row['PID']) + descendants[row['PID']] = row['content_model'] + else: + descendants[row['PID']] = row['content_model'] + return descendants + + def extract_from_mods(self, pid): + cursor = self.conn.cursor() + command = f"SELECT MODS from MSVU where PID = '{pid}'" + result = cursor.execute(command).fetchone() + mods = result['MODS'] + if mods is not None and len(mods) < 10: + return {} + return self.mt.extract_from_mods(mods) + + # Get node_id associated with pid. + def get_nid_from_pid(self, table, pid): + cursor = self.conn.cursor() + command = f"SELECT node_id from {table} where PID = '{pid}'" + result = cursor.execute(command).fetchone() + return result['node_id'] if result is not None else '' + + # Get node_id associated with pid. + def get_pids_by_content_model(self, table, content_model): + cursor = self.conn.cursor() + command = f"SELECT PID from {table} where CONTENT_MODEL = '{content_model}'" + result = cursor.execute(command).fetchone() + return result['node_id'] if result is not None else '' + + # Get key - value pairs from stored dublin core. + def get_dc_values(self, pid, table): + cursor = self.conn.cursor() + result = cursor.execute(f"select dublin_core from {table} where pid = '{pid}'") + dc = result.fetchone()['dublin_core'] + root = ET.fromstring(dc) + namespaces = { + 'dc': 'http://purl.org/dc/elements/1.1/' + } + tags_and_values = [(elem.tag, elem.text) for elem in root.findall('.//dc:*', namespaces)] + dc_vals = {} + for tag, value in tags_and_values: + tag = re.sub(r"\{.*?\}", "", tag) + dc_vals[tag] = value + return dc_vals + + +if __name__ == '__main__': + MU = ImportUtilities() + + MU.add_node_ids('msvu', 'inputs/nid-pid.csv') diff --git a/ModsTransformer.py b/ModsTransformer.py new file mode 100644 index 0000000..dd413c7 --- /dev/null +++ b/ModsTransformer.py @@ -0,0 +1,499 @@ +import re +from datetime import datetime + +import edtf_validate.valid_edtf +import xmltodict + + +class ModsTransformer: + def __init__(self): + self.summary = {} + self.relator_map = { + '': 'relators:att', + 'Abridger': 'relators:abr', + 'Actor': 'relators:act', + 'Adapter': 'relators:adp', + 'Addressee': 'relators:rcp', + 'Analyst': 'relators:anl', + 'Animator': 'relators:anm', + 'Annotator': 'relators:ann', + 'Appellant': 'relators:apl', + 'Appellee': 'relators:ape', + 'Applicant': 'relators:app', + 'Architect': 'relators:arc', + 'Arranger': 'relators:arr', + 'Art copyist': 'relators:acp', + 'Art director': 'relators:adi', + 'Artist': 'relators:art', + 'Artistic director': 'relators:ard', + 'Assignee': 'relators:asg', + 'Associated name': 'relators:asn', + 'Auctioneer': 'relators:auc', + 'Author': 'relators:aut', + 'Author in quotations or text abstracts': 'relators:aqt', + 'Author of afterword, colophon, etc.': 'relators:aft', + 'Author of dialog': 'relators:aud', + 'Author of introduction, etc.': 'relators:aui', + 'Autographer': 'relators:ato', + 'Bibliographic antecedent': 'relators:ant', + 'Binder': 'relators:bnd', + 'Binding designer': 'relators:bdd', + 'Blurb writer': 'relators:blw', + 'Book designer': 'relators:bkd', + 'Book producer': 'relators:bkp', + 'Bookjacket designer': 'relators:bjd', + 'Bookplate designer': 'relators:bpd', + 'Bookseller': 'relators:bsl', + 'Braille embosser': 'relators:brl', + 'Broadcaster': 'relators:brd', + 'Calligrapher': 'relators:cll', + 'Cartographer': 'relators:ctg', + 'Caster': 'relators:cas', + 'Censor': 'relators:cns', + 'Choreographer': 'relators:chr', + 'Collaborator (deprecated, use Contributor)': 'relators:clb', + 'Cinematographer': 'relators:cng', + 'Client': 'relators:cli', + 'Collection registrar': 'relators:cor', + 'Collector': 'relators:col', + 'Collotyper': 'relators:clt', + 'Colorist': 'relators:clr', + 'Commentator': 'relators:cmm', + 'Commentator for written text': 'relators:cwt', + 'Compiler': 'relators:com', + 'Complainant': 'relators:cpl', + 'Complainant-appellant': 'relators:cpt', + 'Complainant-appellee': 'relators:cpe', + 'Composer': 'relators:cmp', + 'Compositor': 'relators:cmt', + 'Conceptor': 'relators:ccp', + 'Conductor': 'relators:cnd', + 'Conservator': 'relators:con', + 'Consultant': 'relators:csl', + 'Consultant to a project': 'relators:csp', + 'Contestant': 'relators:cos', + 'Contestant-appellant': 'relators:cot', + 'Contestant-appellee': 'relators:coe', + 'Contestee': 'relators:cts', + 'Contestee-appellant': 'relators:ctt', + 'Contestee-appellee': 'relators:cte', + 'Contractor': 'relators:ctr', + 'Contributor': 'relators:ctb', + 'Copyright claimant': 'relators:cpc', + 'Copyright holder': 'relators:cph', + 'Corrector': 'relators:crr', + 'Correspondent': 'relators:crp', + 'Costume designer': 'relators:cst', + 'Court governed': 'relators:cou', + 'Court reporter': 'relators:crt', + 'Cover designer': 'relators:cov', + 'Creator': 'relators:cre', + 'Curator': 'relators:cur', + 'Dancer': 'relators:dnc', + 'Data contributor': 'relators:dtc', + 'Data manager': 'relators:dtm', + 'Dedicatee': 'relators:dte', + 'Dedicator': 'relators:dto', + 'Defendant': 'relators:dfd', + 'Defendant-appellant': 'relators:dft', + 'Defendant-appellee': 'relators:dfe', + 'Degree granting institution': 'relators:dgg', + 'Degree supervisor': 'relators:dgs', + 'Delineator': 'relators:dln', + 'Depicted': 'relators:dpc', + 'Depositor': 'relators:dpt', + 'Designer': 'relators:dsr', + 'Director': 'relators:drt', + 'Dissertant': 'relators:dis', + 'Distribution place': 'relators:dbp', + 'Distributor': 'relators:dst', + 'Donor': 'relators:dnr', + 'Draftsman': 'relators:drm', + 'Dubious author': 'relators:dub', + 'Editor': 'relators:edt', + 'Editor of compilation': 'relators:edc', + 'Editor of moving image work': 'relators:edm', + 'Electrician': 'relators:elg', + 'Electrotyper': 'relators:elt', + 'Enacting jurisdiction': 'relators:enj', + 'Engineer': 'relators:eng', + 'Engraver': 'relators:egr', + 'Etcher': 'relators:etr', + 'Event place': 'relators:evp', + 'Expert': 'relators:exp', + 'Facsimilist': 'relators:fac', + 'Field director': 'relators:fld', + 'Film director': 'relators:fmd', + 'Film distributor': 'relators:fds', + 'Film editor': 'relators:flm', + 'Film producer': 'relators:fmp', + 'Filmmaker': 'relators:fmk', + 'First party': 'relators:fpy', + 'Forger': 'relators:frg', + 'Former owner': 'relators:fmo', + 'Funder': 'relators:fnd', + 'Geographic information specialist': 'relators:gis', + 'Graphic technician (deprecated, use Artist)': 'relators:grt', + 'Honoree': 'relators:hnr', + 'Host': 'relators:hst', + 'Host institution': 'relators:his', + 'Illuminator': 'relators:ilu', + 'Illustrator': 'relators:ill', + 'Inscriber': 'relators:ins', + 'Instrumentalist': 'relators:itr', + 'Interviewee': 'relators:ive', + 'Interviewer': 'relators:ivr', + 'Inventor': 'relators:inv', + 'Issuing body': 'relators:isb', + 'Issuer': 'relators:isb', + 'Judge': 'relators:jud', + 'Jurisdiction governed': 'relators:jug', + 'Laboratory': 'relators:lbr', + 'Laboratory director': 'relators:ldr', + 'Landscape architect': 'relators:lsa', + 'Lead': 'relators:led', + 'Lender': 'relators:len', + 'Libelant': 'relators:lil', + 'Libelant-appellant': 'relators:lit', + 'Libelant-appellee': 'relators:lie', + 'Libelee': 'relators:lel', + 'Libelee-appellant': 'relators:let', + 'Libelee-appellee': 'relators:lee', + 'Librettist': 'relators:lbt', + 'Licensee': 'relators:lse', + 'Licensor': 'relators:lso', + 'Lighting designer': 'relators:lgd', + 'Lithographer': 'relators:ltg', + 'Lyricist': 'relators:lyr', + 'Manufacture place': 'relators:mfp', + 'Manufacturer': 'relators:mfr', + 'Marbler': 'relators:mrb', + 'Markup editor': 'relators:mrk', + 'Medium': 'relators:med', + 'Metadata contact': 'relators:mdc', + 'Metal-engraver': 'relators:mte', + 'Minute taker': 'relators:mtk', + 'Moderator': 'relators:mod', + 'Monitor': 'relators:mon', + 'Music copyist': 'relators:mcp', + 'Musical director': 'relators:msd', + 'Musician': 'relators:mus', + 'Narrator': 'relators:nrt', + 'Onscreen presenter': 'relators:osp', + 'Opponent': 'relators:opn', + 'Organizer': 'relators:orm', + 'Originator': 'relators:org', + 'Other': 'relators:oth', + 'Owner': 'relators:own', + 'Panelist': 'relators:pan', + 'Papermaker': 'relators:ppm', + 'Patent applicant': 'relators:pta', + 'Patent holder': 'relators:pth', + 'Patron': 'relators:pat', + 'Performer': 'relators:prf', + 'Permitting agency': 'relators:pma', + 'Photographer': 'relators:pht', + 'Plaintiff': 'relators:ptf', + 'Plaintiff-appellant': 'relators:ptt', + 'Plaintiff-appellee': 'relators:pte', + 'Platemaker': 'relators:plt', + 'Praeses': 'relators:pra', + 'Presenter': 'relators:pre', + 'Printer': 'relators:prt', + 'Printer of plates': 'relators:pop', + 'Printmaker': 'relators:prm', + 'Process contact': 'relators:prc', + 'Producer': 'relators:pro', + 'Production company': 'relators:prn', + 'Production designer': 'relators:prs', + 'Production manager': 'relators:pmn', + 'Production personnel': 'relators:prd', + 'Production place': 'relators:prp', + 'Programmer': 'relators:prg', + 'Project director': 'relators:pdr', + 'Proofreader': 'relators:pfr', + 'Provider': 'relators:prv', + 'Publishing director': 'relators:pbd', + 'Puppeteer': 'relators:ppt', + 'Radio director': 'relators:rdd', + 'Radio producer': 'relators:rpc', + 'Recording engineer': 'relators:rce', + 'Recordist': 'relators:rcd', + 'Redaktor': 'relators:red', + 'Renderer': 'relators:ren', + 'Reporter': 'relators:rpt', + 'Repository': 'relators:rps', + 'Research team head': 'relators:rth', + 'Research team member': 'relators:rtm', + 'Researcher': 'relators:res', + 'Respondent': 'relators:rsp', + 'Respondent-appellant': 'relators:rst', + 'Respondent-appellee': 'relators:rse', + 'Responsible party': 'relators:rpy', + 'Restager': 'relators:rsg', + 'Restorationist': 'relators:rsr', + 'Reviewer': 'relators:rev', + 'Rubricator': 'relators:rbr', + 'Scenarist': 'relators:sce', + 'Scientific advisor': 'relators:sad', + 'Screenwriter': 'relators:aus', + 'Scribe': 'relators:scr', + 'Sculptor': 'relators:scl', + 'Second party': 'relators:spy', + 'Secretary': 'relators:sec', + 'Seller': 'relators:sll', + 'Set designer': 'relators:std', + 'Setting': 'relators:stg', + 'Signer': 'relators:sgn', + 'Singer': 'relators:sng', + 'Sound designer': 'relators:sds', + 'Speaker': 'relators:spk', + 'Sponsor': 'relators:spn', + 'Stage director': 'relators:sgd', + 'Stage manager': 'relators:stm', + 'Standards body': 'relators:stn', + 'Stereotyper': 'relators:str', + 'Storyteller': 'relators:stl', + 'Supporting host': 'relators:sht', + 'Surveyor': 'relators:srv', + 'Teacher': 'relators:tch', + 'Technical director': 'relators:tcd', + 'Television director': 'relators:tld', + 'Television producer': 'relators:tlp', + 'Thesis advisor': 'relators:ths', + 'Transcriber': 'relators:trc', + 'Translator': 'relators:trl', + 'Type designer': 'relators:tyd', + 'Typographer': 'relators:tyg', + 'University place': 'relators:uvp', + 'Videographer': 'relators:vdg', + 'Vocalist (deprecated, use Singer)': 'relators:voc', + 'Voice actor': 'relators:vac', + 'Witness': 'relators:wit', + 'Wood engraver': 'relators:wde', + 'Woodcutter': 'relators:wdc', + 'Writer of accompanying material': 'relators:wam', + 'Writer of added commentary': 'relators:wac', + 'Writer of added lyrics': 'relators:wal', + 'Writer of added text': 'relators:wat', + 'Writer of introduction': 'relators:win', + 'Writer of preface': 'relators:wpr', + 'Writer of supplementary textual content': 'relators:wst' + } + self.fields = self.get_fields() + self.to_harvest = [ + 'subject', 'titleInfo', 'originInfo', 'titleInfo', 'physicalDescription', + 'typeOfResource', 'name', 'relatedItem'] + list(self.fields.keys()) + + def get_fields(self): + return { + 'note': 'field_abstract', + 'abstract': 'field_abstract', + 'dateIssued': 'field_edtf_date_issued', + 'publisher': 'field_publisher', + 'title': 'title', + 'genre': 'field_genre', + 'typeOfResource': 'field_resource_type', + 'accessCondition': 'field_access_condition', + 'dateOther': 'field_edtf_date_other', + 'dateCreated': 'field_edtf_date_created', + 'place': 'field_location', + 'copyrightDate': 'field_edtf_copyright_date', + 'issuance': 'field_issuance', + 'edition': 'field_edition', + 'identifier': 'field_identifier', + 'sub_title': 'field_subtitle' + } + + def fix_dates(self, key): + months = { + "January": "01", "February": "02", "March": "03", "April": "04", + "May": "05", "June": "06", "July": "07", "August": "08", + "September": "09", "October": "10", "November": "11", "December": "12" + } + mistakes = { + '8 Feb 1990': '1990-02-08', + 'Sept 1993': '1993-09', + 'Winter 2005': '2005-24', + 'November. 2008': '2008-11', + 'Between 1949 and 1965': '1949-1965', + 'Between 1953 and 1966': '1953-1966', + '[before 1970]': '-1970' + + } + date = self.summary[key].strip() + if date is None: + return + if date in mistakes: + date = mistakes[date] + date = date.replace(';', '').replace(',', '') + + # Test for January 1973 + match = re.search(r'(\w+)\s+(\d{4})', date) + if match: + month_str, year = match.groups() + month_map = { + "January": "01", "February": "02", "March": "03", + "April": "04", "May": "05", "June": "06", + "July": "07", "August": "08", "September": "09", + "October": "10", "November": "11", "December": "12" + } + month = month_map.get(month_str, "??") # Handle unknown months gracefully + self.summary[key] = f"{year}-{month}" + return + + # Test for Jan 1999 + match = re.match(r"([A-Za-z]+),?\s*(\d{4})", date) + if match: + month_name, year = match.groups() + month_number = months.get(month_name) # Convert month name to number + if month_number: + return f"{year}-{month_number}" + # Test for November-December, 2010 + match = re.match(r"([A-Za-z]+)-([A-Za-z]+),?\s*(\d{4})", date) + if match: + month1, month2, year = match.groups() + month1_num = months.get(month1) + month2_num = months.get(month2) + if month1_num and month2_num: + return f"{year}-{month1_num}/{year}-{month2_num}" + + # Test for 1982-83 + pattern = r"\b(18|19|20)\d{2}-(\d{2})\b" + if re.match(pattern, date): + years = date.split('-') + century = years[0][:2] + if years[0] == '1999': + century = '20' + self.summary[key] = f"{years[0]}/{century}{years[1]}" + return + # Test for February 27, 2010 + pattern = r"^(January|February|March|April|May|June|July|August|September|October|November|December) \d{1,2},\s?\d{4}$" + if re.match(pattern, date): + try: + if date == 'February 29, 1990': + date = 'February 28, 1990' + date = re.sub(r",(\S+)", r", \1", date) + date_object = datetime.strptime(date, "%B %d, %Y") + self.summary[key] = date_object.strftime("%Y-%m-%d") + return + except ValueError as e: + print(f"Error parsing date: '{date}'. Ensure it follows 'Month day, Year' format. ({e})") + return + pattern = r"\d{4}-\d{4}" + if re.match(pattern, date): + self.summary[key] = date.replace('-', '/') + return + if 'ca.' in date: + self.summary[key] = f"{date.split()[-1]}~" + return + if edtf_validate.valid_edtf.is_valid(date): + self.summary[key] = date + return + + print(f"{date} could not be made EDTF compliant") + + def parse_name(self, input): + role = name = '' + outputs = [] + vocab = 'corporate_body' + type_map = { + 'corporate': 'corporate_body', + 'personal': 'person' + } + for key, value in input.items(): + if key == '@type': + vocab = type_map[value] + continue + if key == 'namePart': + name = value + if key == 'role' and not isinstance(value, str): + if isinstance(value, list) and isinstance(value[0], dict): + value = value[0] + else: + value = {} + + roleTerm = value.get('roleTerm', {}) + if isinstance(roleTerm, str): + role = roleTerm.capitalize() + else: + role = value.get('roleTerm', {}).get('#text', '').capitalize() + if role not in self.relator_map: + role = 'Editor' + return f"{self.relator_map[role]}:{vocab}:{name}" + + def extract_from_mods(self, mods): + self.summary = {} + result = xmltodict.parse(mods) + mods = result['mods'] + string_keys = [key for key, value in mods.items() if isinstance(value, str) and not key.startswith("@")] + all_keys = [key for key, value in mods.items() if not key.startswith("@")] + ignored = [item for item in all_keys if item not in self.to_harvest] + # print(f"ignored- {ignored}") + # Process simple string values. + for key in string_keys: + self.summary[self.fields[key]] = ' '.join(mods[key].splitlines()) + del (mods[key]) + + # Origin info + if isinstance(mods.get('originInfo'), dict): + mods['originInfo'] = [mods['originInfo']] + for originInfo in mods.get('originInfo', []): + for key, value in originInfo.items(): + self.summary[self.fields[key]] = value + + # Subject info + for key, value in mods.get('subject', {}).items(): + if key == 'geographic': + self.summary['field_geographic_subject'] = value + if key == 'topic': + self.summary['field_subject'] = value + if key == 'hierarchicalGeographic': + location = {k: v for k, v in value.items() if v is not None} + self.summary['field_geographic_subject'] = ','.join(location.values()) + + # Related item + if isinstance(mods.get('relatedItem'), dict): + mods['relatedItem'] = [mods['relatedItem']] + related_items = [] + for item in mods.get('relatedItem', {}): + related_items.append(item.get('titleInfo', {}).get('title', '')) + self.summary['field_related_item'] = '|'.join(related_items) + + # Title info + if isinstance(mods['titleInfo'], dict): + mods['titleInfo'] = [mods['titleInfo']] + for title in mods['titleInfo']: + if 'title' not in self.summary and title.get('title') is not None: + self.summary['title'] = title.get('title') + if 'field_subtitle' not in self.summary and title.get('field_subtitle'): + self.summary['field_subtitle'] = title.get('subtitle', '') + if title.get('@type', '') == 'alternative': + if title.get('title') is not None: + self.summary['field_alternative_title'] = title.get('title') + # Location. + if isinstance(mods.get('location'), dict): + mods['location'] = [mods['location']] + locations = [] + for location in mods.get('location', {}): + locations.append((location or {}).get('location', {}).get('physicalLocation', '')) + self.summary['field_location'] = '|'.join(locations) + self.summary['field_physical_description'] = ( + mods.get('physicalDescription', {}) + .get('form', {}) + .get('#text', '') + ) + self.summary['field_extent'] = mods.get('physicalDescription', {}).get('extent', '') + self.summary['field_resource_type'] = (mods.get('typeOfResource') or {}).get('#text', '') + if isinstance(mods.get('name'), dict): + mods['name'] = [mods['name']] + names = [] + for name in mods.get('name', []): + names.append(self.parse_name(name)) + self.summary['field_linked_agent'] = '|'.join(names) + + for key in self.summary: + if 'edtf' in key: + self.fix_dates(key) + + return self.summary