diff --git a/FoxmlWorker.py b/FoxmlWorker.py index 62659e5..be6c418 100644 --- a/FoxmlWorker.py +++ b/FoxmlWorker.py @@ -114,10 +114,16 @@ class FWorker: cleaned = child.text.replace('info:fedora/', '').replace('\n', '') text = ' '.join(cleaned.split()) if text: - re_values[tag] = text + if tag in re_values: + re_values[tag] = re_values[tag] + '|' + text + else: + 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/', '') + if tag in re_values: + re_values[tag] = re_values[tag] + '|' + resource.replace('info:fedora/', '') + else: + 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. @@ -156,7 +162,24 @@ class FWorker: return retval + def get_inline_musicXML(self): + retval = '' + try: + mx_datastream = self.root.findall( + ".//foxml:datastream[@ID='MusicXML']/foxml:datastreamVersion/foxml:xmlContent/*", + self.namespaces + ) + if not mx_datastream: + return retval + mx_node = mx_datastream[-1] + if mx_node is not None: + retval = ET.tostring(mx_node, encoding='unicode') + except Exception as e: + print(f"An error occurred: {e}") + + return retval + if __name__ == '__main__': - FW = FWorker('assets/foxml_inline.xml') - print(FW.get_inline_pbcore()) + FW = FWorker('assets/restricted.xml') + print(FW.get_rels_ext_values()) diff --git a/ImportProcessor.py b/ImportProcessor.py index b6d6b65..46ad911 100644 --- a/ImportProcessor.py +++ b/ImportProcessor.py @@ -95,14 +95,15 @@ class ImportProcessor: writer.writerow(row) # Prepares worksheets for workbench ingest. - def prepare_intial_ingest_worksheet(self, output_file): + def prepare_initial_ingest_worksheet(self, output_file): details = self.iu.get_worksheet_details() if not details: # Check if details is None or empty print("No worksheet details found.") return with open(output_file, 'w', newline='') as csvfile: - writer = csv.DictWriter(csvfile, fieldnames=['id', 'title', 'field_pid', 'field_model', 'file']) + writer = csv.DictWriter(csvfile, + fieldnames=['id', 'title', 'field_title', 'field_pid', 'field_model', 'file']) writer.writeheader() id = 1 @@ -120,25 +121,37 @@ class ImportProcessor: row = { 'id': id, 'title': dc['title'], + 'field_title': dc['title'], 'field_pid': detail['field_pid'], 'field_model': detail.get('field_model', 'Unknown') # Use .get() with fallback for safety } - writer.writerow(row) + try: + if 'web' in detail['field_pid']: + writer.writerow(row) + except Exception as e: + print(f"Failed to write row {row}: {e}") id += 1 + def prepare_relationship_worksheet(self, output_file): - realtionships = self.iu.get_relationships(self.namespace) + relationships = 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 = csv.DictWriter(csvfile, fieldnames=['node_id', 'title', 'field_member_of']) writer.writeheader() - for relatiopship in realtionships: + for relationship in relationships: row = {} - if not relatiopship['node_id']: + if not relationship['node_id']: continue - row['node_id'] = relatiopship['node_id'] - row['field_member_of'] = relatiopship['member_of'] + row['node_id'] = relationship['node_id'] + row['field_member_of'] = relationship['member_of'] writer.writerow(row) - writer.writeheader() -MP = ImportProcessor('upei') \ No newline at end of file + + + def full_server_prep(self): + self.ms.build_record_from_pids(self.namespace) + + +MP = ImportProcessor('bdh') +MP.prepare_relationship_worksheet('worksheets/new_relations.csv') diff --git a/ImportServerUtilities.py b/ImportServerUtilities.py index 699669c..5bd1b1e 100644 --- a/ImportServerUtilities.py +++ b/ImportServerUtilities.py @@ -9,7 +9,6 @@ from typing import Optional, List import FoxmlWorker as FW import ImportUtilities as IU import json -import pickle class ImportServerUtilities: @@ -106,10 +105,25 @@ class ImportServerUtilities: else: print(f"Datastream not found for {nid}") + # Stages list of files. @IU.ImportUtilities.timeit - def stage_files_from_list(self, input_file): - with open(input_file, 'rb') as file: - pids = pickle.load(file) + def stage_files_from_list(self, datastreams, pids) -> None: + 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 @IU.ImportUtilities.timeit @@ -225,13 +239,52 @@ class ImportServerUtilities: continue pb = fw.get_inline_pbcore() if pb: - f = open(f"{row['nid']}_PBCORE.xml") + f = open(f"{self.staging_dir}/{row['nid']}_PBCORE.xml") f.write(pb) f.close() -if __name__ == '__main__': - MS = ImportServerUtilities('ivoices') - MS.get_inline_datastreams() + def stage_inline_mxml(self): + cursor = self.iu.conn.cursor() + statement = f"select pid, nid from {self.namespace}" + 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 + mx = fw.get_inline_pbcore() + if mx: + f = open(f"{self.staging_dir}/{row['nid']}_MusicXML.xml") + f.write(mx) + f.close() + @IU.ImportUtilities.timeit + def stage_bio(self): + pids = self.iu.get_pids_by_content_model(self.namespace, 'islandora:entityCModel') + headers = 'term_id', 'description' + csv_file_path = f"{self.staging_dir}/{self.namespace}_BIO.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 pid in pids: + 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 + all_files = fw.get_file_data() + if 'BIO' in all_files: + file_info = all_files['BIO'] + source = f"{self.datastreamStore}/{self.iu.dereference(file_info['filename'])}" + writer.writerow( + {'term_id': fw.get_label(), 'description': Path(source).read_text(encoding="utf-8")}) +if __name__ == '__main__': + MS = ImportServerUtilities('upei') + MS.stage_files(datastreams=['OBJ', 'TN', 'FULL_TEXT']) diff --git a/ImportUtilities.py b/ImportUtilities.py index 11b053c..11ebb29 100644 --- a/ImportUtilities.py +++ b/ImportUtilities.py @@ -5,6 +5,8 @@ import hashlib import sqlite3 import urllib import urllib.parse +from typing import Any + import lxml.etree as ET import re import time @@ -69,8 +71,8 @@ class ImportUtilities: with open(csv_file, newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: - command = f"update {table} set nid = '{row['ID']}' where pid = '{row['PID']}'" - cursor.execute(command) + command = f"UPDATE {table} SET nid = ? WHERE pid = ?" + cursor.execute(command, (row['ID'], row['PID'])) self.conn.commit() # Adds node_id to table @@ -80,8 +82,8 @@ class ImportUtilities: 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'])) + command = f"UPDATE {table} SET dublin_core = ? WHERE pid = ? and dublin_core is NULL" + cursor.execute(command, (row['dublin_core'], row['pid'])) self.conn.commit() # Identifies object and datastream location within Fedora objectStores and datastreamStore. @@ -207,6 +209,7 @@ class ImportUtilities: 'islandora:sp_large_image_cmodel': 'Image', 'islandora:sp-audioCModel': 'Audio', 'islandora:pageCModel': 'Page', + 'islandora:bd_pageCModel': 'Page', 'islandora:bookCModel': 'Paged Content', 'islandora:compoundCModel': 'Compound Object', 'islandora:sp_pdf': 'Digital Document', @@ -234,8 +237,9 @@ class ImportUtilities: value = '' if value.strip(): cleaned_line[map[key]] = value + if 'field_model' in cleaned_line: + cleaned_line['field_model'] = content_map.get(cleaned_line['field_model']) - cleaned_line['field_model'] = content_map[cleaned_line['field_model']] return cleaned_line # Get all content models from map @@ -290,9 +294,16 @@ class ImportUtilities: # 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}'" + command = f"SELECT nid from {table} where PID = '{pid}'" + result = cursor.execute(command).fetchone() + return result['nid'] if result is not None else '' + + # Get pid associated with nid. + def get_pid_from_nid(self, table: object, nid: object) -> str | Any: + cursor = self.conn.cursor() + command = f"SELECT pid from {table} where nid = '{nid}'" result = cursor.execute(command).fetchone() - return result['node_id'] if result is not None else '' + return result['pid'] if result is not None else '' # Get all pids with content model. def get_pids_by_content_model(self, table, content_model): @@ -332,42 +343,32 @@ class ImportUtilities: cursor.execute(query, values) self.conn.commit() - def get_relationships(self, table): cursor = self.conn.cursor() - 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(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(f"SELECT nid FROM {table} WHERE pid = ?", (collection_pid,)) - nid_result = cursor.fetchone() - - if nid_result: # Ensure a valid nid is found - relationships.append({ - 'node_id': nid, - 'member_of': nid_result[0] # Extract nid value - }) - + cursor.execute(f""" + SELECT child.nid, parent.nid, child.sequence, child.title + FROM {table} as child + JOIN {table} as parent + ON child.collection_pid = parent.pid + """) + rows = cursor.fetchall() + relationships = [ + {'node_id': r[0], 'member_of': r[1], 'weight': r[2] if r[2] is not None else '', 'title': r[3]} + for r in rows + ] return relationships import csv def make_media_add_worksheet(self, input_file, output_file): - with open(output_file, mode="w", newline="") as out_file: # Avoid shadowing `output_file` + with open(output_file, mode="w", newline="") as out_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 + for line in file: row = { - 'node_id': line.split('_')[0], # Get everything before the first underscore - 'file': line.strip() # Remove trailing newlines + 'node_id': line.split('_')[0], + 'file': line.strip() } if 'MODS' in line: row['media_use_tid'] = 57 @@ -375,9 +376,75 @@ class ImportUtilities: row['media_use_tid'] = 56 writer.writerow(row) + def make_archive_url_worksheet(self, output_file): + cursor = self.conn.cursor() + statement = f"select pid, nid from {self.namespace} where pid like '%batch%'" + cursor.execute(statement) + results = cursor.fetchall() + with open(output_file, mode="w", newline="") as out_file: + writer = csv.DictWriter(out_file, fieldnames=['node_id', 'field_archival_alias']) + writer.writeheader() + for result in results: + row = {} + row['node_id'] = result['nid'] + row['field_archival_alias'] = f"islandora:{result['pid'][12:]}" + writer.writerow(row) + def fix_media(self, infile, outfile): + with open(infile, mode='r', newline='', encoding='utf-8') as file: + reader = csv.DictReader(file) + pids = [] -if __name__ == '__main__': - MU = ImportUtilities('upei') - print(MU.dereference('ivoices:ivoices20100403acass001')) + for row in reader: + nid = row['Media name'][:2] + pids.append(self.get_pid_from_nid('ivoices', nid)) + print(pids) + def redwhite(self, infile, outfile): + with open(outfile, mode="w", newline="") as outfile: + writer = csv.DictWriter(outfile, fieldnames=['id','title','field_pid','field_model','field_weight','file']) + writer.writeheader() + with open(infile, mode='r', newline='', encoding='utf-8') as file: + reader = csv.DictReader(file) + for row in reader: + if row['field_pid'] == 'vre:redwhite' or 'vre:rw-batch' in row['field_pid']: + writer.writerow(row) + + + + def build_new_bdh(self, infile, outfile): + with open(outfile, mode="w", newline="") as outfile: + writer = csv.DictWriter(outfile, fieldnames=['node_id', 'field_member_of']) + writer.writeheader() + with open(infile, mode='r', newline='', encoding='utf-8') as file: + reader = csv.DictReader(file) + for row in reader: + node_id = self.get_nid_from_pid('bdh', row['pid']) + collection_pids = [] + collections = row['collections'].split('|') + for collection in collections: + collection_pids.append(self.get_nid_from_pid('bdh', collection)) + collection_string = '|'.join(collection_pids) + new_row = {'node_id': node_id, 'field_member_of': collection_string} + writer.writerow(new_row) + + def prepare_restricted_worksheet(self, input_file, output_file): + pids = [] + with open(input_file, "r") as f: + for line in f: + pids.append(line.strip()) + with open(output_file, 'w', newline='') as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=['node_id', 'published']) + writer.writeheader() + for pid in pids: + row = {} + nid = self.get_nid_from_pid('bdh', pid) + if nid is not None: + row['node_id'] = nid + row['published'] = 0 + writer.writerow(row) + + +if __name__ == '__main__': + MU = ImportUtilities('bdh') + MU.prepare_restricted_worksheet('assets/bdh_restricted_pids.csv', 'outputs/bdh_restricted_pids.csv') diff --git a/MigrationPrep.py b/MigrationPrep.py new file mode 100644 index 0000000..598a283 --- /dev/null +++ b/MigrationPrep.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 + +import ImportUtilities as IU +import ImportServerUtilities as SU +import sqlite3 +import FoxmlWorker as FW +from pathlib import Path +import csv + + +class MigrationPrepper: + def __init__(self, namespace): + self.namespace = namespace + self.objectStore = '/usr/local/fedora/data/objectStore' + self.datastreamStore = '/usr/local/fedora/data/datastreamStore' + self.conn = sqlite3.connect(f'{namespace}.db') + self.conn.row_factory = sqlite3.Row + self.su = SU.ImportServerUtilities(namespace) + self.iu = IU.ImportUtilities(self.namespace) + + + # Harvests the structure of all objects in a namespace and persists them to a database. + def get_structure(self, collections=None): + namespaces = [self.namespace] + if collections: + namespaces.extend(collections) + cursor = self.conn.cursor() + cursor.execute(f""" + CREATE TABLE if not exists {self.namespace}( + title TEXT, + pid TEXT PRIMARY KEY, + nid TEXT, + content_model TEXT, + collection_pid TEXT, + page_of TEXT, + sequence TEXT, + constituent_of TEXT, + dublin_core TEXT, + mods TEXT + )""") + self.conn.commit() + for namespace in namespaces: + pids = self.su.get_pids_from_objectstore(namespace) + for pid in pids: + foxml_file = self.iu.dereference(pid) + foxml = f"{self.objectStore}/{foxml_file}" + fw = None + if foxml: + try: + fw = FW.FWorker(foxml) + except (ValueError, RuntimeError) as e: + print(f"Skipping {foxml}: {e}") + fw = None + if (fw): + if fw.get_state() != 'Active': + continue + relations = fw.get_rels_ext_values() + 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("'", "''") + else: + mods_xml = "" + row = { + "title": fw.get_label(), + "pid": pid, + "nid": '', + "content_model": '', + "collection_pid": "", + "page_of": "", + "sequence": "", + "constituent_of": "", + "dublin_core": fw.get_dc(), + "mods": mods_xml + } + + for relation, value in relations.items(): + if relation in self.iu.rels_map: + row[self.iu.rels_map[relation]] = value + try: + command = f""" + INSERT OR REPLACE INTO {self.namespace} + (title, pid, nid, content_model, collection_pid, page_of, sequence, constituent_of, dublin_core, mods) + VALUES (:title, :pid, :nid,:content_model, :collection_pid, :page_of, :sequence, :constituent_of, :dublin_core, :mods) + """ + cursor.execute(command, row) + except sqlite3.Error as e: + print(f"SQLite Error: {e}") + print(f"SQL Command: {command}") + print(f"Parameters: {row}") + + else: + print(f"FoXML file for {pid} is missing") + self.conn.commit() + + # Prepares CSV for initial workbench ingest. + def prepare_initial_ingest_worksheet(self, output_file): + details = self.get_worksheet_details() + if not details: + print("No worksheet details found.") + return + + with open(output_file, 'w', newline='') as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=['id', 'title', 'field_pid', 'field_model', 'field_weight', 'file']) + writer.writeheader() + id = 1 + + for detail in details: + if not detail or not detail.get('field_pid'): # Add safer checks for detail and field_pid + continue + + # Prepare the row for CSV + row = { + 'id': id, + 'title': detail['title'], + 'field_pid': detail['field_pid'], + 'field_model': detail.get('field_model', 'Unknown'), + 'field_weight': detail.get('field_weight', ''), + } + try: + writer.writerow(row) + except Exception as e: + print(f"Failed to write row {row}: {e}") + id += 1 + + # Utility function to prepare database selections for workbench, + def get_worksheet_details(self): + command = f"Select * from {self.namespace}" + 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 fields. + 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', + 'title': 'title', + } + content_map = { + 'islandora:collectionCModel': 'Collection', + 'islandora:sp_large_image_cmodel': 'Image', + 'islandora:sp-audioCModel': 'Audio', + 'islandora:pageCModel': 'Page', + 'islandora:bd_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', + 'islandora:audioCModel|islandora:sp-audioCModel': 'Audio', + 'islandora:slideCModel|islandora:sp_large_image_cmodel': 'Image', + 'islandora:videoCModel|islandora:sp_videoCModel': 'Video', + 'islandora:audioCModel': 'Audio', + + } + + 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 + if 'field_model' in cleaned_line: + cleaned_line['field_model'] = content_map[cleaned_line['field_model']] + return cleaned_line + + def update_structure(self, collections=None): + namespaces = [self.namespace] + for namespace in namespaces: + pids = self.su.get_pids_from_objectstore(namespace) + for pid in pids: + foxml_file = self.iu.dereference(pid) + foxml = f"{self.objectStore}/{foxml_file}" + fw = None + if foxml: + try: + fw = FW.FWorker(foxml) + except (ValueError, RuntimeError) as e: + print(f"Skipping {foxml}: {e}") + fw = None + if (fw): + if fw.get_state() != 'Active': + continue + relations = fw.get_rels_ext_values() + pipe = '|' + has_pipe = [k for k, v in relations.items() if pipe in v] + for key, value in has_pipe: + print(f"{pid},{value}") + + + + + + + +if __name__ == '__main__': + MP = MigrationPrepper('island_newspapers') + collections = ['*'] + MP.get_structure(collections) \ No newline at end of file