goodByeHida/22_importArtifactRelation.py
2025-09-09 10:16:31 +02:00

73 lines
3.1 KiB
Python

import uuid # For UUID creation
from initDb import initDb # For database initialization
from wisski.api import Api, Pathbuilder, Entity # For WissKI API
import os # For environment variable loading
from dotenv import load_dotenv # For environment variable loading
import pandas as pd # For dataframe handling
def importArtifactRelation(api, engine):
print('Importing artifact relation...')
tableName = "c__5007_beziehung"
bundleId = 'bf4a13ee46de57819f88834caaddc301' # Artifact relation assignment
try:
processedRows = pd.read_csv(f'./logs/{tableName}.csv')
except FileNotFoundError:
processedRows = pd.DataFrame(columns=[ 'id', 'uuid', 'uri'])
# Load sources table
sqlTable = pd.read_sql_table(tableName, con=engine)
# Create entities
for index, row in sqlTable.iterrows():
# For every row in table...
if index < len(processedRows) and sqlTable.loc[index, 'id'] == processedRows.loc[index, 'id']:
# skip if already processed
print(f'Skipping already processed artifact relation {sqlTable.loc[index, "id"]}')
continue
# Create Entity property dicts
entityValues = {}
for key, value in row.items():
# For every column in row...
if (value is None) or (value == ''):
# skip if cell has no value
continue
# Properties of an entity have to be an array, so...
value = str(value).replace('&###{{new_line}}###'.format(), '&')
value = str(value).replace('###{{new_line}}###', '&')
value = str(value).replace(' & ', '&')
if '&' in str(value):
# ...Explode "&"-separated values to array items
value = [x.strip() for x in str(value).split('&')]
else:
# ...Or parse to array
value = [value]
# Map columns to fields. We use assignments for reification.
docId = ''
match key:
case 'id':
docId = value[0]
case 'f__uuid':
entityValues['ff7ebd530eb53efc489e80d9bbef293e'] = value # UUID
fUuid = value[0]
case 'f__5008_bez_obj_nr_':
entityValues['f39d0e5207a375070d84b958017a62e8'] = value # Artifact Document Identifier
case 'f__bebm_bem_beziehung':
entityValues['f9cc743b648716684ccc3a7b9710d0ed'] = value # Note
case 'f__5007_beziehung':
entityValues['f4d3047b3b54285aa5a86183aedb1680'] = value # Relation
case _:
print(f'{key} is not a valid field, skipping.')
# Create Material
entity = Entity(api=api, fields=entityValues, bundle_id=bundleId)
api.save(entity)
print(f'Created artifact relation {index}: {entity.uri} of {len(sqlTable)}')
# Write log
processedRows = processedRows._append({'id': row['id'], 'uuid': fUuid, 'uri': entity.uri}, ignore_index=True)
processedRows.to_csv(f'./logs/{tableName}.csv', index=False)
print('finished importing artifact relation')