forked from bkollmar/Data-Science-Project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimpl.py
2425 lines (2112 loc) · 98.2 KB
/
impl.py
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import pandas as pd
import re
import requests
import sqlite3
import json
from rdflib import Graph, URIRef, Literal
from pandas import read_csv
from rdflib.namespace import RDF
from sparql_dataframe import get
from pandas import concat
from rdflib.plugins.stores.sparqlstore import SPARQLUpdateStore
from typing import List, Union, Optional
BLAZEGRAPH_ENDPOINT = 'http://127.0.0.1:9999/blazegraph/sparql'
CSV_FILEPATH = 'data/meta.csv'
# REMEMBER: before running this code, please run the Blazegraph instance!
#
# Run command:
# `java -server -Xmx4g -jar blazegraph.jar`
class IdentifiableEntity(object): #Rubens
def __init__(self, id: str):
self.id = id
def getId(self) -> str:
return self.id
class Person(IdentifiableEntity): # Rubens
def __init__(self, id: str, name: str):
self.name = name
super().__init__(id)
def getName(self) -> str:
return self.name
class CulturalHeritageObject(IdentifiableEntity): # Ben
def __init__(
self,
id: str,
title: str,
date: Optional[str],
owner: str,
place: str,
hasAuthor: Union[Person, List[Person], None] = None,
author_id: Optional[str] = None,
author_name: Optional[str] = None,
):
super().__init__(str(id))
self.id = id
self.title = title
self.date = date
self.hasAuthor = hasAuthor or []
self.owner = str(owner)
self.place = place
self.author_id = author_id
self.author_name = author_name
if type(hasAuthor) == Person:
self.hasAuthor.append(Person)
elif type(hasAuthor) == list:
self.hasAuthor = hasAuthor
def getTitle(self) -> str:
return self.title
def getOwner(self) -> str:
return self.owner
def getPlace(self) -> str:
return self.place
def getDate(self) -> Optional[str]:
if self.date:
return self.date
return None
def getAuthors(self) -> List[Person]:
return self.hasAuthor
class NauticalChart(CulturalHeritageObject):
pass
class ManuscriptPlate(CulturalHeritageObject):
pass
class ManuscriptVolume(CulturalHeritageObject):
pass
class PrintedVolume(CulturalHeritageObject):
pass
class PrintedMaterial(CulturalHeritageObject):
pass
class Herbarium(CulturalHeritageObject):
pass
class Specimen(CulturalHeritageObject):
pass
class Painting(CulturalHeritageObject):
pass
class Model(CulturalHeritageObject):
pass
class Map(CulturalHeritageObject):
pass
class Activity(object): # Rubens
def __init__(
self,
refersTo: CulturalHeritageObject,
institute: str,
person: Optional[str],
tool: Union[str, List[str], None],
start: Optional[str],
end: Union[str, List[str], None],
):
self.refersTo = refersTo
self.institute = institute
self.person = person
self.tool = []
self.start = start
self.end = end
if type(tool) == str:
self.tool.append(tool)
elif type(tool) == list:
self.tool = tool
def getResponsibleInstitute(self) -> str:
return self.institute
def getResponsiblePerson(self) -> Optional[str]:
if self.person:
return self.person
return None
def getTools(self) -> set:
return self.tool
def getStartDate(self) -> Optional[str]:
if self.start:
return self.start
return None
def getEndDate(self) -> Optional[str]:
if self.end:
return self.end
return None
def refersTo(self) -> CulturalHeritageObject:
return self.refersTo
class Acquisition(Activity):
def __init__(
self,
refersTo: CulturalHeritageObject,
institute: str,
technique: str,
person: Optional[str],
start: Optional[str],
end: Optional[str],
tool: Union[str, List[str], None],
):
super().__init__(refersTo, institute, person, tool, start, end)
self.technique = technique
def getTechnique(self) -> str:
return self.technique
class Processing(Activity):
pass
class Modelling(Activity):
pass
class Optimising(Activity):
pass
class Exporting(Activity):
pass
class Handler(object): # Ekaterina
def __init__(self):
self.dbPathOrUrl = ""
def getDbPathOrUrl(self) -> str:
return self.dbPathOrUrl
def setDbPathOrUrl(self, pathOrUrl: str) -> bool:
self.dbPathOrUrl = pathOrUrl
return self.dbPathOrUrl == pathOrUrl
class UploadHandler(Handler): # Ekaterina
def __init__(self):
super().__init__()
def pushDataToDb(self, file_path: str) -> bool:
self.file_path = file_path
blazegraph_endpoint = "http://127.0.0.1:9999/blazegraph/sparql"
# split filepath for file extension
_, extension = os.path.splitext(file_path)
if extension == ".db":
# process json data for SQL database -> upload data to SQL Lite data base
process_qh = ProcessDataUploadHandler()
result = process_qh.setDbPathOrUrl(self.db_file)
elif extension == ".json":
# process json data for SQL database -> upload data to SQL Lite data base
process_qh = ProcessDataUploadHandler()
result = process_qh.setDbPathOrUrl(self.db_file)
elif extension == ".csv":
# process csv data & turn into RDF -> upload RDF data to blazegraph store
metadata_qh = MetadataUploadHandler()
result = metadata_qh.setDbPathOrUrl(blazegraph_endpoint)
else:
raise Exception("Only .json or .csv files can be uploaded!")
print("Finished uploading data! ✅")
return result
class ProcessDataUploadHandler(UploadHandler): # Ekaterina
def __init__(self):
super().__init__
file_path = "data/process.json"
try:
with open(file_path) as json_file:
data = json.load(json_file)
except FileNotFoundError:
print("Error: JSON file not found.")
exit()
db_file = "json.db"
try:
conn = sqlite3.connect(db_file)
c = conn.cursor()
c.execute(
"""CREATE TABLE IF NOT EXISTS Acquisition (
object_id TEXT,
responsible_institute TEXT,
responsible_person TEXT,
technique TEXT,
tool TEXT,
start_date TEXT,
end_date TEXT
)"""
)
c.execute(
"""CREATE TABLE IF NOT EXISTS Processing (
object_id TEXT,
responsible_institute TEXT,
responsible_person TEXT,
tool TEXT,
start_date TEXT,
end_date TEXT
)"""
)
c.execute(
"""CREATE TABLE IF NOT EXISTS Modelling (
object_id TEXT,
responsible_institute TEXT,
responsible_person TEXT,
tool TEXT,
start_date TEXT,
end_date TEXT
)"""
)
c.execute(
"""CREATE TABLE IF NOT EXISTS Optimising (
object_id TEXT,
responsible_institute TEXT,
responsible_person TEXT,
tool TEXT,
start_date TEXT,
end_date TEXT
)"""
)
c.execute(
"""CREATE TABLE IF NOT EXISTS Exporting (
object_id TEXT,
responsible_institute TEXT,
responsible_person TEXT,
tool TEXT,
start_date TEXT,
end_date DATE
)"""
)
for item in data:
object_id = item["object id"]
acquisition = item["acquisition"]
c.execute(
"""INSERT INTO Acquisition (object_id, responsible_institute, responsible_person, technique, tool, start_date, end_date)
VALUES (?, ?, ?, ?, ?, ?, ?)""",
(
object_id,
acquisition["responsible institute"],
acquisition["responsible person"],
acquisition["technique"],
", ".join(acquisition["tool"]) if acquisition["tool"] else None,
acquisition["start date"],
acquisition["end date"],
),
)
processing = item["processing"]
c.execute(
"""INSERT INTO Processing (object_id, responsible_institute, responsible_person, tool, start_date, end_date)
VALUES (?, ?, ?, ?, ?, ?)""",
(
object_id,
processing["responsible institute"],
processing["responsible person"],
", ".join(processing["tool"]) if processing["tool"] else None,
processing["start date"],
processing["end date"],
),
)
modelling = item["modelling"]
c.execute(
"""INSERT INTO Modelling (object_id, responsible_institute, responsible_person, tool, start_date, end_date)
VALUES (?, ?, ?, ?, ?, ?)""",
(
object_id,
modelling["responsible institute"],
modelling["responsible person"],
", ".join(modelling["tool"]) if modelling["tool"] else None,
modelling["start date"],
modelling["end date"],
),
)
optimising = item["optimising"]
c.execute(
"""INSERT INTO Optimising (object_id, responsible_institute, responsible_person, tool, start_date, end_date)
VALUES (?, ?, ?, ?, ?, ?)""",
(
object_id,
optimising["responsible institute"],
optimising["responsible person"],
", ".join(optimising["tool"]) if optimising["tool"] else None,
optimising["start date"],
optimising["end date"],
),
)
exporting = item["exporting"]
c.execute(
"""INSERT INTO Exporting (object_id, responsible_institute, responsible_person, tool, start_date, end_date)
VALUES (?, ?, ?, ?, ?, ?)""",
(
object_id,
exporting["responsible institute"],
exporting["responsible person"],
", ".join(exporting["tool"]) if exporting["tool"] else None,
exporting["start date"],
exporting["end date"],
),
)
conn.commit()
except sqlite3.Error as e:
print("\nSQLite error:", e)
finally:
conn.close()
print("\nData insertion and querying completed successfully.")
class MetadataUploadHandler(UploadHandler): # Ekaterina
def __init__(self):
super().__init__
my_graph = Graph()
# Classes of resources of CulturalHeritageObject
NauticalChart = URIRef("https://schema.org/NauticalChart")
ManuscriptPlate = URIRef("https://schema.org/ManuscriptPlate")
ManuscriptVolume = URIRef("https://schema.org/ManuscriptVolume")
PrintedVolume = URIRef("https://schema.org/PrintedVolume")
PrintedMaterial = URIRef("https://schema.org/PrintedMaterial")
Herbarium = URIRef("https://schema.org/Herbarium")
Specimen = URIRef("https://schema.org/Specimen")
Painting = URIRef("https://schema.org/Painting")
Model = URIRef("https://schema.org/Model")
Map = URIRef("https://schema.org/Map")
Author = URIRef("https://schema.org/Author")
# Attributes related to classes
title = URIRef("https://schema.org/name")
date = URIRef("https://schema.org/dateCreated")
owner = URIRef("https://schema.org/provider")
place = URIRef("https://schema.org/contentLocation")
identifier = URIRef("https://schema.org/identifier")
label = URIRef("http://www.w3.org/2000/01/rdf-schema#label")
# Relations among classes
hasAuthor = URIRef("https://schema.org/creator")
# This is the string defining the base URL used to define
# the URLs of all the resources created from the data
base_url = "https://github.com/katyakrsn/ds24project/"
file_path_csv = "data/meta.csv"
heritage = read_csv(
file_path_csv,
keep_default_na=False, # Prevent pandas from treating certain values as NaN
dtype={
"Id": "string",
"Type": "string",
"Title": "string",
"Date": "string",
"Author": "string",
"Owner": "string",
"Place": "string",
},
)
# Iterate over each row in the CSV file
for idx, row in heritage.iterrows():
# Determine the class URI based on the type of CulturalHeritageObject
class_uri = None
if row["Type"] == "Nautical chart":
class_uri = NauticalChart
elif row["Type"] == "Manuscript plate":
class_uri = ManuscriptPlate
elif row["Type"] == "Manuscript volume":
class_uri = ManuscriptVolume
elif row["Type"] == "Printed volume":
class_uri = PrintedVolume
elif row["Type"] == "Printed material":
class_uri = PrintedMaterial
elif row["Type"] == "Herbarium":
class_uri = Herbarium
elif row["Type"] == "Specimen":
class_uri = Specimen
elif row["Type"] == "Painting":
class_uri = Painting
elif row["Type"] == "Model":
class_uri = Model
elif row["Type"] == "Map":
class_uri = Map
# Create a URI for the resource using the base URL and the row ID
resource_uri = URIRef(f"{base_url}{row['Id']}")
# Handle missing date values by assigning a default value
if not row["Date"]:
row["Date"] = "Unknown"
print(f"Missing Date at index {idx}")
# Add triples to the graph
my_graph.add((resource_uri, RDF.type, class_uri))
my_graph.add((resource_uri, identifier, Literal(row["Id"])))
my_graph.add((resource_uri, title, Literal(row["Title"])))
my_graph.add((resource_uri, date, Literal(row["Date"])))
my_graph.add((resource_uri, owner, Literal(row["Owner"])))
my_graph.add((resource_uri, place, Literal(row["Place"])))
if row["Author"]:
# Split the text into two parts
text_parts = row["Author"].split(" (")
author = row["Author"]
text_before_parentheses = author.split(" (")[0]
authorID = re.findall(r"\((.*?)\)", author)
authorID = authorID[0] if authorID else "noID"
authorIRI = base_url + text_before_parentheses.replace(" ", "_").replace(
",", ""
)
my_graph.add((resource_uri, hasAuthor, URIRef(authorIRI)))
my_graph.add((URIRef(authorIRI), identifier, Literal(authorID)))
my_graph.add((URIRef(authorIRI), RDF.type, Author))
my_graph.add((URIRef(authorIRI), label, Literal(text_before_parentheses)))
else:
row["Author"] = "Unknown"
print(f"Missing Author at index {idx}")
my_graph.serialize(destination="output_triples.ttl", format="ttl")
# Initialize SPARQLUpdateStore to interact with Blazegraph
store = SPARQLUpdateStore()
endpoint = "http://127.0.0.1:9999/blazegraph/sparql"
store.open((endpoint, endpoint))
# Upload triples to the Blazegraph database
for triple in my_graph.triples((None, None, None)):
store.add(triple)
store.close()
sparql_query = f"""
SELECT ?subject ?predicate ?object
WHERE {{
?subject ?predicate ?object .
}}
ORDER BY ASC(xsd:integer(REPLACE(str(?subject), "{base_url}", "")))
"""
sparql_endpoint = "http://127.0.0.1:9999/blazegraph/sparql"
# Send the SPARQL query to the Blazegraph endpoint
response = requests.post(sparql_endpoint, data={"query": sparql_query})
if response.status_code != 200:
print(f"Error: {response.status_code} - {response.reason}")
class QueryHandler(Handler):
def __init__(self):
super().__init__()
def getById(self, input_id: str) -> pd.DataFrame: # Ekaterina/Rubens
endpoint = self.blazegraph_endpoint
id_author_query = f"""
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX schema: <https://schema.org/>
SELECT ?identifier ?name ?title
WHERE {{
?entity schema:identifier "{input_id}" .
?entity schema:creator ?Author .
?Author rdfs:label ?name .
?Author schema:identifier ?identifier .
?entity schema:name ?title
}}
"""
df_sparql = get(endpoint, id_author_query, True)
return df_sparql
class MetadataQueryHandler(QueryHandler):
def __init__(self):
self.blazegraph_endpoint = BLAZEGRAPH_ENDPOINT
self.csv_file_path = CSV_FILEPATH
def getAllPeople(self) -> pd.DataFrame: # Rubens
sparql_query = """
PREFIX schema: <https://schema.org/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?id ?name
WHERE {
?entity schema:creator ?Author .
?Author rdfs:label ?name .
?Author schema:identifier ?id .
}
"""
df_sparql = get(self.blazegraph_endpoint, sparql_query, True)
return df_sparql
def getAllCulturalHeritageObjects(self) -> pd.DataFrame: # Ekaterina
endpoint = self.blazegraph_endpoint
cultural_object_query = """
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX schema: <https://schema.org/>
SELECT (REPLACE(STR(?type), "https://schema.org/", "") AS ?type_name) ?id ?title ?date ?owner ?place ?author_id ?author_name
WHERE {
?cultural_object rdf:type ?type .
?cultural_object schema:name ?title .
OPTIONAL { ?cultural_object schema:identifier ?id }
OPTIONAL { ?cultural_object schema:dateCreated ?date }
OPTIONAL { ?cultural_object schema:provider ?owner }
OPTIONAL { ?cultural_object schema:contentLocation ?place }
OPTIONAL { ?cultural_object schema:creator ?author }
OPTIONAL { ?author schema:identifier ?author_id }
OPTIONAL { ?author rdfs:label ?author_name }
FILTER(?type IN (
<https://schema.org/NauticalChart>,
<https://schema.org/ManuscriptPlate>,
<https://schema.org/ManuscriptVolume>,
<https://schema.org/PrintedVolume>,
<https://schema.org/PrintedMaterial>,
<https://schema.org/Herbarium>,
<https://schema.org/Specimen>,
<https://schema.org/Painting>,
<https://schema.org/Model>,
<https://schema.org/Map>
))
FILTER(?author_name != "NaN")
FILTER(?author_id != "NaN")
}
"""
df_sparql = get(endpoint, cultural_object_query, True)
return df_sparql
def getAuthorsOfCulturalHeritageObject(self, input_id) -> pd.DataFrame: # Rubens
endpoint = self.blazegraph_endpoint
id_author_query = f"""
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX schema: <https://schema.org/>
SELECT ?id ?name
WHERE {{
?entity schema:identifier "{input_id}" .
?entity schema:creator ?Author .
?Author rdfs:label ?name .
?Author schema:identifier ?id .
}}
"""
df_sparql = get(endpoint, id_author_query, True)
return df_sparql
def getCulturalHeritageObjectsAuthoredBy(
self, input_id
) -> pd.DataFrame: # Ekaterina
endpoint = self.blazegraph_endpoint
id_cultural_query = f"""
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX schema: <https://schema.org/>
SELECT ?object ?type_name ?id ?title ?date ?owner ?place ?name ?author_id
WHERE {{
?entity schema:identifier "{input_id}" .
?entity schema:creator ?Author .
?object schema:creator ?Author .
?object rdf:type ?type .
?object schema:name ?title .
?object schema:identifier ?id .
?object schema:dateCreated ?date .
?object schema:provider ?owner .
?object schema:contentLocation ?place .
OPTIONAL {{
?object schema:creator ?Author .
?Author rdfs:label ?name .
?Author schema:identifier ?author_id .
}}
BIND(REPLACE(STR(?type), "https://schema.org/", "") AS ?type_name)
FILTER(?type IN (
<https://schema.org/NauticalChart>,
<https://schema.org/ManuscriptPlate>,
<https://schema.org/ManuscriptVolume>,
<https://schema.org/PrintedVolume>,
<https://schema.org/PrintedMaterial>,
<https://schema.org/Herbarium>,
<https://schema.org/Specimen>,
<https://schema.org/Painting>,
<https://schema.org/Model>,
<https://schema.org/Map>
))
}}
"""
df_sparql = get(endpoint, id_cultural_query, True)
df_sparql.drop_duplicates(inplace=True)
return df_sparql
class ProcessDataQueryHandler(QueryHandler):
def __init__(self):
super().__init__()
def getById(self, id: str): # Rubens
return pd.DataFrame()
def getAllActivities(self) -> pd.DataFrame: # Rubens
db_file = "json.db"
try:
conn = sqlite3.connect(db_file)
# Use LIKE operator to match partially with the technique string
query = """
SELECT object_id, responsible_institute, responsible_person, technique, NULL as tool, start_date, end_date, 'Acquisition' as type FROM Acquisition
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Processing' as type FROM Processing
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Modelling' as type FROM Modelling
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Optimising' as type FROM Optimising
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Exporting' as type FROM Exporting
"""
df = pd.read_sql_query(query, conn)
return df
except sqlite3.Error as e:
print("SQLite error:", e)
finally:
conn.close()
def getActivitiesByResponsibleInstitution(
self, institution_str: str
) -> pd.DataFrame: # Ekaterina
db_file = "json.db"
try:
conn = sqlite3.connect(db_file)
# Use LIKE operator to match partially with the technique string
query = """
SELECT object_id, responsible_institute, responsible_person, technique, NULL as tool, start_date, end_date, 'Acquisition' as type FROM Acquisition WHERE responsible_institute LIKE ?
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Processing' as type FROM Processing WHERE responsible_institute LIKE ?
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Modelling' as type FROM Modelling WHERE responsible_institute LIKE ?
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Optimising' as type FROM Optimising WHERE responsible_institute LIKE ?
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Exporting' as type FROM Exporting WHERE responsible_institute LIKE ?
"""
like_param = f"%{institution_str}%"
params = (like_param, like_param, like_param, like_param, like_param)
# Fetch the data using pandas
df = pd.read_sql_query(query, conn, params=params)
return df
except sqlite3.Error as e:
print("SQLite error:", e)
finally:
conn.close()
def getActivitiesByResponsiblePerson(
self, responsible_person_str: str
) -> pd.DataFrame: # Ben
db_file = "json.db"
try:
conn = sqlite3.connect(db_file)
# Use LIKE operator to match partially with the technique string
query = """
SELECT object_id, responsible_institute, responsible_person, technique, NULL as tool, start_date, end_date, 'Acquisition' as type FROM Acquisition WHERE responsible_person LIKE ?
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Processing' as type FROM Processing WHERE responsible_person LIKE ?
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Modelling' as type FROM Modelling WHERE responsible_person LIKE ?
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Optimising' as type FROM Optimising WHERE responsible_person LIKE ?
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Exporting' as type FROM Exporting WHERE responsible_person LIKE ?
"""
like_param = f"%{responsible_person_str}%"
params = (like_param, like_param, like_param, like_param, like_param)
df = pd.read_sql_query(query, conn, params=params)
return df
except sqlite3.Error as e:
print("SQLite error:", e)
finally:
conn.close()
def getActivitiesUsingTool(self, tool_str: str) -> pd.DataFrame: # Rubens
db_file = "json.db"
try:
conn = sqlite3.connect(db_file)
# Use LIKE operator to match partially with the tool string
query = """
SELECT object_id, responsible_institute, responsible_person, technique, NULL as tool, start_date, end_date, 'Acquisition' as type FROM Acquisition WHERE tool LIKE ?
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Processing' as type FROM Processing WHERE tool LIKE ?
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Modelling' as type FROM Modelling WHERE tool LIKE ?
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Optimising' as type FROM Optimising WHERE tool LIKE ?
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Exporting' as type FROM Exporting WHERE tool LIKE ?
"""
like_param = f"%{tool_str}%"
params = (like_param, like_param, like_param, like_param, like_param)
df = pd.read_sql_query(query, conn, params=params)
return df
except sqlite3.Error as e:
print("SQLite error:", e)
finally:
conn.close()
def getActivitiesStartedAfter(self, start_date: str) -> pd.DataFrame: # Amanda
db_file = "json.db"
try:
conn = sqlite3.connect(db_file)
query = """
SELECT object_id, responsible_institute, responsible_person, technique, NULL as tool, start_date, end_date, 'Acquisition' as type
FROM Acquisition WHERE start_date >= ?
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Processing' as type
FROM Processing WHERE start_date >= ?
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Modelling' as type
FROM Modelling WHERE start_date >= ?
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Optimising' as type
FROM Optimising WHERE start_date >= ?
UNION
SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Exporting' as type
FROM Exporting WHERE start_date >= ?
"""
df = pd.read_sql_query(
query,
conn,
params=(start_date, start_date, start_date, start_date, start_date),
)
return df
except sqlite3.Error as e:
print("SQLite error:", e)
finally:
conn.close()
def getActivitiesEndedBefore(self, end_date: str) -> pd.DataFrame: # Amanda
db_file = "json.db"
try:
conn = sqlite3.connect(db_file)
# Construct the SQL query with NULL columns where necessary
query = (
"SELECT object_id, responsible_institute, responsible_person, technique, NULL as tool, start_date, end_date, 'Acquisition' as type FROM Acquisition WHERE end_date <= ? UNION "
"SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Processing' as type FROM Processing WHERE end_date <= ? UNION "
"SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Modelling' as type FROM Modelling WHERE end_date <= ? UNION "
"SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Optimising' as type FROM Optimising WHERE end_date <= ? UNION "
"SELECT object_id, responsible_institute, responsible_person, NULL as technique, NULL as tool, start_date, end_date, 'Exporting' as type FROM Exporting WHERE end_date <= ?"
)
df = pd.read_sql_query(
query, conn, params=(end_date, end_date, end_date, end_date, end_date)
)
return df
except sqlite3.Error as e:
print("SQLite error:", e)
finally:
conn.close()
def getAcquisitionsByTechnique(self, technique_str: str) -> pd.DataFrame: # Rubens
db_file = "json.db"
try:
conn = sqlite3.connect(db_file)
# Use LIKE operator to match partially with the technique string
query = f"SELECT * FROM Acquisition WHERE technique LIKE ?"
# Execute the query and pass the technique_str wrapped with '%' for partial match
df = pd.read_sql_query(query, conn, params=("%" + technique_str + "%",))
# Add the type column
df["type"] = "Acquisition"
return df
except sqlite3.Error as e:
print("SQLite error:", e)
finally:
conn.close()
class BasicMashup(object):
def __init__(
self,
metadataQuery: List[MetadataQueryHandler],
processQuery: List[ProcessDataQueryHandler],
) -> None: # Rubens
self.metadataQuery = metadataQuery if metadataQuery is not None else []
self.processQuery = processQuery if processQuery is not None else []
def cleanMetadataHandlers(self) -> bool: # Rubens
self.metadataQuery.clear()
return True
def cleanProcessHandlers(self) -> bool: # Rubens
self.processQuery.clear()
return True
def addMetadataHandler(self, handler: MetadataQueryHandler) -> bool: # Rubens
self.metadataQuery.append(handler)
return True
def addProcessHandler(self, handler: ProcessDataQueryHandler) -> bool: # Rubens
self.processQuery.append(handler)
return True
def getEntityById(self, id: str) -> IdentifiableEntity | None: # Rubens
id_entity: List[Person] = []
processed_ids = set() # Set to keep track of processed IDs
for handler in self.metadataQuery:
people_df = handler.getById(id)
for _, row in people_df.iterrows():
person_id = row["identifier"]
# Check if the ID has already been processed
if person_id not in processed_ids:
person = Person(id=person_id, name=row["name"])
id_entity.append(person)
processed_ids.add(person_id) # Add the ID to the set of processed IDs
print("Entity found by Id:")
for person in id_entity:
print(
f"Name: {person.name}, Id: {person.id}, Type: {type(person).__name__}"
)
if id_entity == []:
id_entity = None
return id_entity
def getAllPeople(self) -> List[Person]: # Ben/Rubens
all_people: List[Person] = []
processed_ids = set() # Set to keep track of processed IDs
for handler in self.metadataQuery:
people_df = handler.getAllPeople()
for _, row in people_df.iterrows():
person_id = row["id"]
# Check if the ID has already been processed
if person_id not in processed_ids:
person = Person(id=person_id, name=row["name"])
all_people.append(person)
processed_ids.add(
person_id
) # Add the ID to the set of processed IDs
print("Person list created:")
for person in all_people:
print(f"Name: {person.name}, Type: {type(person).__name__}")
return all_people
def getAllCulturalHeritageObjects(
self,
) -> List[CulturalHeritageObject]: # Ekaterina
objects_list = []
df = pd.DataFrame()
if len(self.metadataQuery) > 0:
df = self.metadataQuery[0].getAllCulturalHeritageObjects()
print("DataFrame returned from SPARQL query:")
if df.empty:
print("The DataFrame is empty.")
else:
for _, row in df.iterrows():
id = str(row["id"])
title = row["title"]
date = row["date"]
owner = str(row["owner"])
place = row["place"]
author_id = str(row["author_id"])
author_name = row["author_name"]
hasAuthor = None
if author_id and author_name:
hasAuthor = [Person(author_id, author_name)]
try:
# Use if-elif-else to instantiate objects based on type name
type_name = row["type_name"]
if type_name == "NauticalChart":
obj = NauticalChart(id, title, date, owner, place, hasAuthor)
elif type_name == "ManuscriptPlate":
obj = ManuscriptPlate(id, title, date, owner, place, hasAuthor)
elif type_name == "ManuscriptVolume":
obj = ManuscriptVolume(id, title, date, owner, place, hasAuthor)
elif type_name == "PrintedVolume":
obj = PrintedVolume(id, title, date, owner, place, hasAuthor)
elif type_name == "PrintedMaterial":
obj = PrintedMaterial(id, title, date, owner, place, hasAuthor)
elif type_name == "Herbarium":
obj = Herbarium(id, title, date, owner, place, hasAuthor)