From 6fccf45a6e1b5199087effe0e5e1c4eab7808502 Mon Sep 17 00:00:00 2001 From: astanley Date: Wed, 2 Apr 2025 12:42:17 -0300 Subject: [PATCH] Inline harvesting --- FoxmlWorker.py | 30 +++++++++++++---- ImportProcessor.py | 9 ++--- ImportServerUtilities.py | 31 ++++++++++++++++- ImportUtilities.py | 72 +++++++++++++++++++++++++++------------- 4 files changed, 108 insertions(+), 34 deletions(-) diff --git a/FoxmlWorker.py b/FoxmlWorker.py index b990cd0..62659e5 100644 --- a/FoxmlWorker.py +++ b/FoxmlWorker.py @@ -22,7 +22,8 @@ class FWorker: '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' + 'mods': 'http://www.loc.gov/mods/v3', + 'pbcore': 'http://www.pbcore.org/PBCore/PBCoreNamespace.html' } self.properties = self.get_properties() @@ -76,8 +77,9 @@ class FWorker: 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') + if dc_nodes: + 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): @@ -137,8 +139,24 @@ class FWorker: return retval + def get_inline_pbcore(self): + retval = '' + try: + pb_datastream = self.root.findall( + ".//foxml:datastream[@ID='PBCORE']/foxml:datastreamVersion/foxml:xmlContent/*", + self.namespaces + ) + if not pb_datastream: + return retval + mods_node = pb_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('assets/sample_fox.xml') - print(FW.get_datastream_types()) - + FW = FWorker('assets/foxml_inline.xml') + print(FW.get_inline_pbcore()) diff --git a/ImportProcessor.py b/ImportProcessor.py index 03166c5..b6d6b65 100644 --- a/ImportProcessor.py +++ b/ImportProcessor.py @@ -102,7 +102,7 @@ class ImportProcessor: return with open(output_file, 'w', newline='') as csvfile: - writer = csv.DictWriter(csvfile, fieldnames=['id', 'title', 'field_pid', 'field_model']) + writer = csv.DictWriter(csvfile, fieldnames=['id', 'title', 'field_pid', 'field_model', 'file']) writer.writeheader() id = 1 @@ -126,12 +126,14 @@ class ImportProcessor: writer.writerow(row) id += 1 def prepare_relationship_worksheet(self, output_file): - realtionships = self.iu.get_relationships() + realtionships = self.iu.get_relationships(self.namespace) with open(output_file, 'w', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=['node_id', 'field_member_of']) writer.writeheader() for relatiopship in realtionships: row = {} + if not relatiopship['node_id']: + continue row['node_id'] = relatiopship['node_id'] row['field_member_of'] = relatiopship['member_of'] writer.writerow(row) @@ -139,5 +141,4 @@ class ImportProcessor: -MP = ImportProcessor('ivoices') -MP.prepare_relationship_worksheet('ivoices_relationships.csv') +MP = ImportProcessor('upei') \ No newline at end of file diff --git a/ImportServerUtilities.py b/ImportServerUtilities.py index 76716ac..d1318e8 100644 --- a/ImportServerUtilities.py +++ b/ImportServerUtilities.py @@ -9,6 +9,7 @@ from typing import Optional, List import FoxmlWorker as FW import ImportUtilities as IU import json +import pickle class ImportServerUtilities: @@ -105,6 +106,12 @@ class ImportServerUtilities: else: print(f"Datastream not found for {nid}") + @IU.ImportUtilities.timeit + def stage_files_from_list(self, input_file): + with open(input_file, 'rb') as file: + pids = pickle.load(file) + + # Builds record directly from objectStore @IU.ImportUtilities.timeit def build_record_from_pids(self, namespace, output_file): @@ -183,10 +190,32 @@ class ImportServerUtilities: with open("dsid.json", "w") as file: json.dump(dsids, file, indent=4) + def get_inline_datastreams(self): + cursor = self.iu.conn.cursor() + statement = f"select pid from {self.namespace}" + headers = ['pid', 'dublin_core', 'pb_core', 'mods'] + csv_file_path = f"{self.staging_dir}/{self.namespace}_inline.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() + pb = fw.get_inline_pbcore() + mods = fw.get_inline_mods() + writer.writerow({'pid': pid, 'dublin_core': dc, 'pb_core': pb, 'mods': mods}) + if __name__ == '__main__': MS = ImportServerUtilities('ivoices') - MS.stage_files(datastreams=['MEDIATRACK']) + MS.get_inline_datastreams() diff --git a/ImportUtilities.py b/ImportUtilities.py index 569af05..11b053c 100644 --- a/ImportUtilities.py +++ b/ImportUtilities.py @@ -9,6 +9,7 @@ import lxml.etree as ET import re import time import functools +import pickle import ModsTransformer as MT @@ -72,6 +73,17 @@ class ImportUtilities: cursor.execute(command) self.conn.commit() + # Adds node_id to table + @timeit + def add_dc_to_database(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 dublin_core = ? WHERE pid = ?" + cursor.execute(command, (row['dublin_core'], row['PID'])) + self.conn.commit() + # Identifies object and datastream location within Fedora objectStores and datastreamStore. def dereference(self, identifier: str) -> str: # Replace '+' with '/' in the identifier @@ -149,13 +161,20 @@ class ImportUtilities: 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}'" + def get_collection_content_pids(self, table, collection, filename): + collection_pids = [collection] + parent_types = ['islandora:bookCModel', 'islandora:collectionCModel', ] pids = [] - for row in cursor.execute(command): - pids.append(row['pid']) - return pids + cursor = self.conn.cursor() + while collection_pids: + collection = collection_pids.pop() + command = f"SELECT * from {table} where collection_pid = '{collection}'" + for row in cursor.execute(command): + if row['content_model'] in parent_types: + collection_pids.append(row['pid']) + pids.append(row['pid']) + with open(filename, 'wb') as file: + pickle.dump(pids, file) # Utility function to prepare database selections for workbench def get_worksheet_details(self, content_model=None): @@ -290,16 +309,17 @@ class ImportUtilities: cursor = self.conn.cursor() result = cursor.execute(f"select dublin_core from {self.namespace} 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 dc: + 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 def add_title(self): cursor = self.conn.cursor() @@ -313,20 +333,20 @@ class ImportUtilities: self.conn.commit() - def get_relationships(self): + def get_relationships(self, table): cursor = self.conn.cursor() - cursor.execute("SELECT pid, nid FROM ivoices") + cursor.execute(f"SELECT pid, nid FROM {table}") pairs = cursor.fetchall() # Fetch all rows relationships = [] for pid, nid in pairs: if not pid: continue - cursor.execute("SELECT collection_pid FROM ivoices WHERE pid = ?", (pid,)) + cursor.execute(f"SELECT collection_pid FROM {table} WHERE pid = ?", (pid,)) collection_pid = cursor.fetchone() if collection_pid: # Ensure there is a valid collection_pid collection_pid = collection_pid[0] # Extract the value - cursor.execute("SELECT nid FROM ivoices WHERE pid = ?", (collection_pid,)) + cursor.execute(f"SELECT nid FROM {table} WHERE pid = ?", (collection_pid,)) nid_result = cursor.fetchone() if nid_result: # Ensure a valid nid is found @@ -341,7 +361,7 @@ class ImportUtilities: def make_media_add_worksheet(self, input_file, output_file): with open(output_file, mode="w", newline="") as out_file: # Avoid shadowing `output_file` - writer = csv.DictWriter(out_file, fieldnames=['node_id', 'file']) + writer = csv.DictWriter(out_file, fieldnames=['node_id', 'file', 'media_use_tid']) writer.writeheader() with open(input_file, "r") as file: for line in file: # Iterate directly over lines @@ -349,9 +369,15 @@ class ImportUtilities: 'node_id': line.split('_')[0], # Get everything before the first underscore 'file': line.strip() # Remove trailing newlines } + if 'MODS' in line: + row['media_use_tid'] = 57 + if 'PBCORE' in line: + row['media_use_tid'] = 56 writer.writerow(row) if __name__ == '__main__': - MU = ImportUtilities('ivoices') - MU.make_media_add_worksheet('inputs/ivoice_file.txt', 'outputs/ivoice_media.csv') \ No newline at end of file + MU = ImportUtilities('upei') + print(MU.dereference('ivoices:ivoices20100403acass001')) + +