-
Notifications
You must be signed in to change notification settings - Fork 0
/
EOR_to_rdf.py
276 lines (190 loc) · 10.4 KB
/
EOR_to_rdf.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
from bs4 import BeautifulSoup
from rdflib import FOAF, RDFS, Graph, Literal, Namespace, RDF, URIRef
from rdflib.namespace import XSD
import json
from datetime import datetime
import urllib.parse
import requests
with open("userinfo.txt","r") as fuser:
username = fuser.readline().strip()
# Define the GeoNames API URL and username
GEONAMES_API_URL = 'http://api.geonames.org/searchJSON'
GEONAMES_USERNAME = username
# Define namespaces
my_namespace = Namespace("http://linked4resilience/data/eor/april2023/")
sem_namespace = Namespace("https://semanticweb.cs.vu.nl/2009/11/sem/")
SCHEMA = Namespace("http://schema.org/")
# Create an RDF graph
rdf_graph = Graph()
# Bind namespaces
rdf_graph.bind("res", my_namespace)
rdf_graph.bind("sem", sem_namespace)
rdf_graph.bind("xsd", XSD)
# Open the JSON file
with open("output_EOR-2023-04-30.json") as fjson:
data = json.load(fjson)
with open('ukrainian_cities.json', 'r') as ukrainian_cities:
city_uris = json.load(ukrainian_cities)
# Initialize an event ID counter
event_id = 'eor1'
i = 0
# Loop through the features in the JSON file
for feature in data['features']:
lng, lat = feature["geometry"]["coordinates"]
# Create a URI for the event using the event ID
if feature["properties"].get("country") == "Ukraine":
event_URI = my_namespace + str(event_id)
# Add triples to the graph
verified_date_str = feature['properties']['verifiedDate']
verified_date_obj = datetime.fromisoformat(verified_date_str)
verified_date_str_no_time = verified_date_obj.date().isoformat()
rdf_graph.add((URIRef(event_URI), SCHEMA.date, Literal(verified_date_str_no_time, datatype=XSD.date)))
rdf_graph.add((URIRef(event_URI), SCHEMA.lat, Literal(lat, datatype=XSD.float)))
rdf_graph.add((URIRef(event_URI), SCHEMA.lng, Literal(lng, datatype=XSD.float)))
if feature["properties"].get("violenceLevel"):
rdf_graph.add((URIRef(event_URI), SCHEMA.damageSeverity, Literal(feature['properties']['violenceLevel'], datatype=XSD.integer)))
if feature["properties"].get("description"):
rdf_graph.add((URIRef(event_URI), RDFS.label, Literal(feature["properties"]['description'])))
if feature.get("postalCode"):
rdf_graph.add((URIRef(event_URI), SCHEMA.postalCode, Literal(feature['postalCode'])))
if feature["properties"].get("country"):
city_name = feature['properties']['country']
if city_name in city_uris:
city_uri = URIRef(city_uris[city_name])
rdf_graph.add((URIRef(event_URI), SCHEMA.addressCountry, city_uri))
else:
rdf_graph.add((URIRef(event_URI), SCHEMA.addressCountry, Literal(feature["properties"]["country"])))
if feature["properties"].get("province"):
city_name = feature['properties']['province']
if city_name in city_uris:
city_uri = URIRef(city_uris[city_name])
rdf_graph.add((URIRef(event_URI), SCHEMA.region, city_uri))
else:
rdf_graph.add((URIRef(event_URI), SCHEMA.region, Literal(feature["properties"]["province"])))
if feature["properties"].get("city"):
city_name = feature['properties']['city']
if city_name in city_uris:
city_uri = URIRef(city_uris[city_name])
rdf_graph.add((URIRef(event_URI), SCHEMA.city, city_uri))
else:
geonames_url = f'http://api.geonames.org/searchJSON?q={city_name}&maxRows=1&username={username}'
response = requests.get(geonames_url).json()
if 'totalResultsCount' in response and response['totalResultsCount'] > 0:
geoname_id = response['geonames'][0]['geonameId']
city_uri = URIRef(f'http://sws.geonames.org/{geoname_id}/')
print('hi')
city_uris[city_name] = str(city_uri)
with open('ukrainian_cities.json', 'w') as uri_new:
json.dump(city_uris, uri_new, indent=4)
else:
city_uri = Literal(city_name)
rdf_graph.add((URIRef(event_URI), SCHEMA.city, city_uri))
else:
geonames_url = f'http://api.geonames.org/searchJSON?q={city_name}&maxRows=1&username={username}'
response = requests.get(geonames_url).json()
if 'totalResultsCount' in response and response['totalResultsCount'] > 0:
geoname_id = response['geonames'][0]['geonameId']
city_uri = URIRef(f'http://sws.geonames.org/{geoname_id}/')
print('hi')
for category in feature['properties']['categories']:
rdf_graph.add((URIRef(event_URI), RDFS.comment, Literal(category)))
if feature['properties'].get('url'):
rdf_graph.add((URIRef(event_URI), SCHEMA.url, Literal(feature["properties"]['url'], datatype=XSD.anyURI)))
rdf_graph.add((URIRef(event_URI), RDF.type, sem_namespace.Event))
event_num = int(event_id[3:])
event_id = f"event{event_num + 1}"
sorted_triples = sorted(rdf_graph, key=lambda triple: triple[0])
sorted_graph = Graph()
sorted_graph += sorted_triples
# serialize the sorted graph to a string in RDF/XML format
serialized = sorted_graph.serialize(format="ttl")
with open("output_EOR-2023-04-30.ttl", "wb") as f:
f.write(serialized.encode('utf-8'))
with open("output_EOR-2023-04-30.ttl", 'r', encoding="utf8") as foutput:
ttl = foutput.read()
ttl = ttl.replace('ns1:', 'schema:').replace('ns2:', 'sem:').replace('rdf-schema#', 'rdfs:')
with open("output_EOR-2023-04-30.ttl", 'w',encoding="utf8") as foutput:
foutput.write(ttl)
# from rdflib import FOAF, RDFS, Graph, Literal, Namespace, RDF, URIRef
# from rdflib.namespace import XSD
# import json
# # Define namespaces
# my_namespace = Namespace("http://resilience.vu.nl/manar/")
# sem_namespace = Namespace("http://semanticweb.cs.vu.nl/2009/11/sem/")
# SCHEMA = Namespace("http://schema.org/")
# # Create an RDF graph
# rdf_graph = Graph()
# # Bind namespaces
# rdf_graph.bind("res", my_namespace)
# rdf_graph.bind("sem", sem_namespace)
# rdf_graph.bind("xsd", XSD)
# # Open the JSON file
# with open("EOR-2023-04-30.geojson") as f:
# data = json.load(f)
# with open('ukrainian_cities.json', 'r') as ukrainian_cities:
# city_uris = json.load(ukrainian_cities)
# # Initialize an event ID counter
# event_id = 'eor1'
# # Loop through the features in the JSON file
# for feature in data['features']:
# lng, lat = feature["geometry"]["coordinates"]
# # Create a URI for the event using the event ID
# event_URI = my_namespace + str(event_id)
# # Add triples to the graph
# # rdf_graph.add((URIRef(event_URI), SCHEMA.postalCode, Literal(feature['postal_code'])))
# rdf_graph.add((URIRef(event_URI), SCHEMA.date, Literal(feature['properties']['verifiedDate'])))
# rdf_graph.add((URIRef(event_URI), sem_namespace.event, URIRef(sem_namespace + 'Event')))
# rdf_graph.add((URIRef(event_URI), SCHEMA.lat, Literal(lat)))
# rdf_graph.add((URIRef(event_URI), SCHEMA.lng, Literal(lng)))
# #rdf_graph.add((URIRef(event_URI), FOAF.page, URIRef(feature["properties"]['link'])))
# if feature["properties"].get("country"):
# city_name = feature['properties']['country']
# if city_name in city_uris:
# city_uri = URIRef(city_uris[city_name])
# rdf_graph.add((URIRef(event_URI), SCHEMA.addressCountry, city_uri))
# else:
# rdf_graph.add((URIRef(event_URI), SCHEMA.addressCountry, Literal(feature["properties"]["country"])))
# if feature["properties"].get("province"):
# city_name = feature['properties']['province']
# if city_name in city_uris:
# city_uri = URIRef(city_uris[city_name])
# rdf_graph.add((URIRef(event_URI), SCHEMA.region, city_uri))
# else:
# rdf_graph.add((URIRef(event_URI), SCHEMA.region, Literal(feature["properties"]["province"])))
# if feature["properties"].get("city"):
# city_name = feature['properties']['city']
# if city_name in city_uris:
# city_uri = URIRef(city_uris[city_name])
# rdf_graph.add((URIRef(event_URI), SCHEMA.city, city_uri))
# else:
# rdf_graph.add((URIRef(event_URI), SCHEMA.city, Literal(feature["properties"]["city"])))
# # rdf_graph.add((URIRef(event_URI), SCHEMA.district, Literal(feature["properties"]["district"])))
# if feature["properties"].get("violence_level"):
# rdf_graph.add((URIRef(event_URI), SCHEMA.damageSeverity, Literal(feature['properties']['violenceLevel'], datatype=XSD.integer)))
# # if feature["properties"].get("time"):
# # rdf_graph.add((URIRef(event_URI), SCHEMA.time, Literal(feature["properties"]["time"])))
# for category in feature['properties']['categories']:
# rdf_graph.add((URIRef(event_URI), SCHEMA.additionalType, Literal(category)))
# # Increment the event ID
# event_num = int(event_id[3:])
# event_id = f"eor{event_num + 1}"
# # Serialize the RDF graph to file
# with open("output_EOR-2023-04-30.ttl", "wb") as f:
# f.write(rdf_graph.serialize(format="nt", encoding="utf-8"))
# from collections import defaultdict
# from rdflib import Graph, URIRef
# # Read triples from a file
# g = Graph()
# g.parse('output_EOR-2023-04-30.ttl', format='turtle')
# # Initialize dictionaries to store counts
# property_counts = defaultdict(int)
# unique_entity_counts = defaultdict(set)
# # Iterate over triples and count entities
# for s, p, o in g:
# if isinstance(o, URIRef):
# unique_entity_counts[p].add(o)
# property_counts[p] += 1
# # Print results
# for p, count in property_counts.items():
# unique_count = len(unique_entity_counts[p])
# print(f"Property: {p} \tEntries: {count} \tUnique entities: {unique_count}")