Browse Source

Inline harvesting

main
astanley 2 years ago
parent
commit
6fccf45a6e
  1. 30
      FoxmlWorker.py
  2. 9
      ImportProcessor.py
  3. 31
      ImportServerUtilities.py
  4. 72
      ImportUtilities.py

30
FoxmlWorker.py

@ -22,7 +22,8 @@ class FWorker:
'fedora': "info:fedora/fedora-system:def/relations-external#", 'fedora': "info:fedora/fedora-system:def/relations-external#",
'fedora-model': "info:fedora/fedora-system:def/model#", 'fedora-model': "info:fedora/fedora-system:def/model#",
'islandora': "http://islandora.ca/ontology/relsext#", '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() self.properties = self.get_properties()
@ -76,8 +77,9 @@ class FWorker:
dc_nodes = self.root.findall( dc_nodes = self.root.findall(
f'.//foxml:datastream[@ID="DC"]/foxml:datastreamVersion/foxml:xmlContent/oai_dc:dc', f'.//foxml:datastream[@ID="DC"]/foxml:datastreamVersion/foxml:xmlContent/oai_dc:dc',
namespaces=self.namespaces) namespaces=self.namespaces)
dc_node = dc_nodes[-1] if dc_nodes:
return ET.tostring(dc_node, encoding='unicode') dc_node = dc_nodes[-1]
return ET.tostring(dc_node, encoding='unicode')
# Returns list of Dublin Core key/value pairs. Allows for mulitples. # Returns list of Dublin Core key/value pairs. Allows for mulitples.
def get_dc_values(self): def get_dc_values(self):
@ -137,8 +139,24 @@ class FWorker:
return retval 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__': if __name__ == '__main__':
FW = FWorker('assets/sample_fox.xml') FW = FWorker('assets/foxml_inline.xml')
print(FW.get_datastream_types()) print(FW.get_inline_pbcore())

9
ImportProcessor.py

@ -102,7 +102,7 @@ class ImportProcessor:
return return
with open(output_file, 'w', newline='') as csvfile: 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() writer.writeheader()
id = 1 id = 1
@ -126,12 +126,14 @@ class ImportProcessor:
writer.writerow(row) writer.writerow(row)
id += 1 id += 1
def prepare_relationship_worksheet(self, output_file): 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: 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', 'field_member_of'])
writer.writeheader() writer.writeheader()
for relatiopship in realtionships: for relatiopship in realtionships:
row = {} row = {}
if not relatiopship['node_id']:
continue
row['node_id'] = relatiopship['node_id'] row['node_id'] = relatiopship['node_id']
row['field_member_of'] = relatiopship['member_of'] row['field_member_of'] = relatiopship['member_of']
writer.writerow(row) writer.writerow(row)
@ -139,5 +141,4 @@ class ImportProcessor:
MP = ImportProcessor('ivoices') MP = ImportProcessor('upei')
MP.prepare_relationship_worksheet('ivoices_relationships.csv')

31
ImportServerUtilities.py

@ -9,6 +9,7 @@ from typing import Optional, List
import FoxmlWorker as FW import FoxmlWorker as FW
import ImportUtilities as IU import ImportUtilities as IU
import json import json
import pickle
class ImportServerUtilities: class ImportServerUtilities:
@ -105,6 +106,12 @@ class ImportServerUtilities:
else: else:
print(f"Datastream not found for {nid}") 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 # Builds record directly from objectStore
@IU.ImportUtilities.timeit @IU.ImportUtilities.timeit
def build_record_from_pids(self, namespace, output_file): def build_record_from_pids(self, namespace, output_file):
@ -183,10 +190,32 @@ class ImportServerUtilities:
with open("dsid.json", "w") as file: with open("dsid.json", "w") as file:
json.dump(dsids, file, indent=4) 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__': if __name__ == '__main__':
MS = ImportServerUtilities('ivoices') MS = ImportServerUtilities('ivoices')
MS.stage_files(datastreams=['MEDIATRACK']) MS.get_inline_datastreams()

72
ImportUtilities.py

@ -9,6 +9,7 @@ import lxml.etree as ET
import re import re
import time import time
import functools import functools
import pickle
import ModsTransformer as MT import ModsTransformer as MT
@ -72,6 +73,17 @@ class ImportUtilities:
cursor.execute(command) cursor.execute(command)
self.conn.commit() 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. # Identifies object and datastream location within Fedora objectStores and datastreamStore.
def dereference(self, identifier: str) -> str: def dereference(self, identifier: str) -> str:
# Replace '+' with '/' in the identifier # Replace '+' with '/' in the identifier
@ -149,13 +161,20 @@ class ImportUtilities:
self.conn.commit() self.conn.commit()
# Get all collection contents within namespace # Get all collection contents within namespace
def get_collection_content_pids(self, table, collection): def get_collection_content_pids(self, table, collection, filename):
cursor = self.conn.cursor() collection_pids = [collection]
command = f"SELECT * from {table} where collection_pid = '{collection}'" parent_types = ['islandora:bookCModel', 'islandora:collectionCModel', ]
pids = [] pids = []
for row in cursor.execute(command): cursor = self.conn.cursor()
pids.append(row['pid']) while collection_pids:
return 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 # Utility function to prepare database selections for workbench
def get_worksheet_details(self, content_model=None): def get_worksheet_details(self, content_model=None):
@ -290,16 +309,17 @@ class ImportUtilities:
cursor = self.conn.cursor() cursor = self.conn.cursor()
result = cursor.execute(f"select dublin_core from {self.namespace} where pid = '{pid}'") result = cursor.execute(f"select dublin_core from {self.namespace} where pid = '{pid}'")
dc = result.fetchone()['dublin_core'] dc = result.fetchone()['dublin_core']
root = ET.fromstring(dc) if dc:
namespaces = { root = ET.fromstring(dc)
'dc': 'http://purl.org/dc/elements/1.1/' 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 = {} tags_and_values = [(elem.tag, elem.text) for elem in root.findall('.//dc:*', namespaces)]
for tag, value in tags_and_values: dc_vals = {}
tag = re.sub(r"\{.*?\}", "", tag) for tag, value in tags_and_values:
dc_vals[tag] = value tag = re.sub(r"\{.*?\}", "", tag)
return dc_vals dc_vals[tag] = value
return dc_vals
def add_title(self): def add_title(self):
cursor = self.conn.cursor() cursor = self.conn.cursor()
@ -313,20 +333,20 @@ class ImportUtilities:
self.conn.commit() self.conn.commit()
def get_relationships(self): def get_relationships(self, table):
cursor = self.conn.cursor() 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 pairs = cursor.fetchall() # Fetch all rows
relationships = [] relationships = []
for pid, nid in pairs: for pid, nid in pairs:
if not pid: if not pid:
continue 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() collection_pid = cursor.fetchone()
if collection_pid: # Ensure there is a valid collection_pid if collection_pid: # Ensure there is a valid collection_pid
collection_pid = collection_pid[0] # Extract the value 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() nid_result = cursor.fetchone()
if nid_result: # Ensure a valid nid is found 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): 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: # 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() writer.writeheader()
with open(input_file, "r") as file: with open(input_file, "r") as file:
for line in file: # Iterate directly over lines 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 'node_id': line.split('_')[0], # Get everything before the first underscore
'file': line.strip() # Remove trailing newlines '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) writer.writerow(row)
if __name__ == '__main__': if __name__ == '__main__':
MU = ImportUtilities('ivoices') MU = ImportUtilities('upei')
MU.make_media_add_worksheet('inputs/ivoice_file.txt', 'outputs/ivoice_media.csv') print(MU.dereference('ivoices:ivoices20100403acass001'))

Loading…
Cancel
Save