-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclassifications.py
More file actions
165 lines (134 loc) · 6.36 KB
/
classifications.py
File metadata and controls
165 lines (134 loc) · 6.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
from asnake.client import ASnakeClient
import logging
import json
import pandas as pd
import re
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
filename='collection_linking.log'
)
def connect_aspace(
endpoint="https://devstaffarchivesspace.lib.rochester.edu/api/",
user="admin_api", pw="A3_h03ted997"):
client = ASnakeClient(baseurl=endpoint, username=user, password=pw)
client.authorize(user, pw)
return client
def extract_resource_id_from_url(url):
"""Extract resource ID from ArchivesSpace URL"""
match = re.search(r'/resources/(\d+)$', url)
return match.group(1) if match else None
def read_excel_assignments():
"""Read curator assignments from Excel file"""
df = pd.read_excel('updated_Curators_List_for_Classifications_2024-08.xlsx')
# Create dictionaries for Autumn and Erin's assignments
autumn_resources = []
erin_resources = []
melissa_resources = []
anna_resources = []
iel_resources = []
for i, row in df.iterrows():
if row is not None and row['Link to finding-aid'] is not None:
resource_id = extract_resource_id_from_url(str(row['Link to finding-aid']))
if resource_id:
if row["Curator Assigned"] == row["Curator Assigned"]:
if row['Curator Assigned'].strip() == 'Autumn':
autumn_resources.append(resource_id)
elif row['Curator Assigned'].strip() == 'Erin':
erin_resources.append(resource_id)
elif row['Curator Assigned'].strip() == 'Melissa':
melissa_resources.append(resource_id)
elif row['Curator Assigned'].strip() == 'Anna':
anna_resources.append(resource_id)
elif row['Curator Assigned'].strip() == 'Jessica':
iel_resources.append(resource_id)
return autumn_resources, erin_resources, melissa_resources,anna_resources,iel_resources
def get_classification_term(client, repo_id=2, term_id=1):
"""Get specific classification term"""
try:
response = client.get(f"/repositories/{repo_id}/classification_terms/{term_id}")
term_json = response.json()
logging.info(f"Retrieved classification term: {term_json.get('title')}")
return term_json
except Exception as e:
logging.error(f"Failed to retrieve classification term: {str(e)}")
logging.error("Please verify the classification term path is correct")
raise
def create_linked_record_object(collection_id, repo_id=2):
"""Create a properly formatted linked record object"""
return {
"ref": f"/repositories/{repo_id}/resources/{collection_id}",
"jsonmodel_type": "resource",
"_resolved": {
"publish": True,
"id_0": str(collection_id),
"repository": {"ref": f"/repositories/{repo_id}"}
}
}
def update_classification_term(client, term_json, resource_ids, repo_id=2):
"""Update classification term with linked collections"""
try:
# Initialize linked_records if it doesn't exist
if 'linked_records' not in term_json:
term_json['linked_records'] = []
# Convert existing string references to objects if necessary
if term_json['linked_records'] and isinstance(term_json['linked_records'][0], str):
term_json['linked_records'] = []
# Get existing refs to avoid duplicates
existing_refs = {record.get('ref') for record in term_json['linked_records']}
# Add collection references as objects
for resource_id in resource_ids:
linked_record = create_linked_record_object(resource_id, repo_id)
if linked_record['ref'] not in existing_refs:
term_json['linked_records'].append(linked_record)
existing_refs.add(linked_record['ref'])
# Log the payload for debugging
logging.debug(f"Sending payload: {json.dumps(term_json, indent=2)}")
# Update the classification term
response = client.post(
term_json['uri'],
json=term_json
)
if response.status_code == 200:
logging.info(
f"Successfully updated classification term {term_json['uri']} with {len(resource_ids)} resources")
else:
logging.error(f"Failed to update classification term. Status: {response.status_code}")
logging.error(f"Response: {response.text}")
except Exception as e:
logging.error(f"Error updating classification term: {str(e)}")
raise
def main():
try:
# Connect to ArchivesSpace
client = connect_aspace()
# Read assignments from Excel
autumn_resources, erin_resources, melissa_resources, anna_resources, iel_resources = read_excel_assignments()
# Process Autumn's assignments (classification 1, term 1)
if autumn_resources:
term_json = get_classification_term(client, term_id=1)
update_classification_term(client, term_json, autumn_resources)
logging.info(f"Processed {len(autumn_resources)} resources for Autumn")
# Process Erin's assignments (classification 1, term 2)
if erin_resources:
term_json = get_classification_term(client, term_id=2)
update_classification_term(client, term_json, erin_resources)
logging.info(f"Processed {len(erin_resources)} resources for Erin")
if melissa_resources:
term_json = get_classification_term(client, term_id=4)
update_classification_term(client, term_json, erin_resources)
logging.info(f"Processed {len(melissa_resources)} resources for Erin")
if anna_resources:
term_json = get_classification_term(client, term_id=7)
update_classification_term(client, term_json, erin_resources)
logging.info(f"Processed {len(anna_resources)} resources for Erin")
if iel_resources:
term_json = get_classification_term(client, term_id=3)
update_classification_term(client, term_json, erin_resources)
logging.info(f"Processed {len(iel_resources)} resources for Erin")
except Exception as e:
logging.error(f"Main execution failed: {str(e)}")
raise
if __name__ == "__main__":
main()