-
Notifications
You must be signed in to change notification settings - Fork 0
/
freebase_helper.py
350 lines (265 loc) · 11.6 KB
/
freebase_helper.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
#!/usr/bin/env python
"""
Script for Freebase connection.
Invocation:
$ python freebase_helper.py query
"""
import argparse
import sys
import json
import urllib
import common
import glob
import csv
import codecs
COMPOSITIONS = "compositions"
FREEBASE_COMPOSITIONS_DIR = 'data/freebase_compositions_dir'
FREEBASE_COMPOSITIONS_DATA_DIR = 'data/freebase_compositions_data_dir'
FREEBASE_ID_PREFIX = '/m/'
SUMMARY_COMPOSITIONS_FILE = 'data/summary_compositions.csv'
AUTHOR_COMPOSITIONS_FILE = 'data/author_compositions.csv'
COMPOSITIONS_DATA_FILE = 'data/compositions_data.csv'
composition_fieldnames = [
'freebase_author_id'
, 'composition_count'
]
author_composition_fieldnames = [
'author'
, 'composition'
, 'parent'
, 'main'
]
composition_data_fieldnames = [
'id'
, 'mid'
, 'name'
]
def retrieve_compositions(author_id):
if author_id:
query = [{'mid': author_id,
'name': None,
"type": "/music/composer",
COMPOSITIONS: [{}]
}]
response = find_freebase_items(query)
try:
for author in response['result']:
print author['name']
print COMPOSITIONS, author[COMPOSITIONS]
store_compositions(author_id, response)
except KeyError as ke:
print 'incorrect Freebase key:', author_id, ke
def save_mapping_authors_to_composition_count_in_csv(filename_authors, outputfile):
reader = csv.DictReader(open(filename_authors), delimiter=';', fieldnames=common.viaf_compositions_count_fieldnames, lineterminator='\n')
firstTime = True
for row in reader:
if not firstTime:
print 'row', row
author = row[common.AUTHOR_NAME]
author_id = author.split('.')[0]
name, length = count_compositions(author_id)
if name != None:
print 'author:', name, 'len compositions', length
entry = build_freebase_composition_count_entry(common.toByteStr(name), length)
write_composition_in_csv_file(outputfile, entry)
else:
firstTime = False
def build_freebase_composition_count_entry(
author_name, length):
values = [
author_name
, length
]
return dict(zip(common.viaf_compositions_count_fieldnames, values))
def write_composition_in_csv_file(outputfile, entry):
with open(outputfile, 'ab') as csvfile:
writer = csv.DictWriter(csvfile, delimiter=';', fieldnames=common.viaf_compositions_count_fieldnames, lineterminator='\n')
writer.writerow(entry)
def count_compositions(author_id):
if author_id:
query = [{'mid': common.FREEBASE_PREFIX + author_id,
common.AUTHOR_NAME_HEADER: None,
"type": "/music/composer",
COMPOSITIONS: [{"return": "count"}]
}]
response = find_freebase_items(query)
try:
if any(response[common.RESULT]) == False:
return None, None
for author in response[common.RESULT]:
print author[common.AUTHOR_NAME_HEADER]
print COMPOSITIONS, author[COMPOSITIONS]
count = 0
if author[COMPOSITIONS][0]:
count = author[COMPOSITIONS][0]
return author[common.AUTHOR_NAME_HEADER], count
except KeyError as ke:
print 'incorrect Freebase key:', author_id, ke
def retrieve_compositions_data(composition_id):
if composition_id:
query = [{'id': composition_id,
'mid': None,
'name': None,
"type": [{}],
"i18n:name": [{}],
"key": [{}]
}]
response = find_freebase_items(query)
try:
for composition in response['result']:
print composition['name']
store_compositions_data(composition['mid'], response)
except KeyError as ke:
print 'incorrect Freebase key:', composition_id, ke
response = None
return response
def store_compositions(author_id, response):
filename = str(author_id).replace(FREEBASE_ID_PREFIX,'') + common.JSON_EXT
response_json = common.is_stored_as_json_file(FREEBASE_COMPOSITIONS_DIR + common.SLASH + filename)
if(response_json == None):
#inputfile = glob.glob(FREEBASE_COMPOSITIONS_DIR + SLASH + filename)
#if not inputfile:
print 'composition not exists for author:', author_id
common.write_json_file(FREEBASE_COMPOSITIONS_DIR, filename, response)
def store_compositions_data(composition_id, response):
filename = str(composition_id).replace(FREEBASE_ID_PREFIX,'') + common.JSON_EXT
response_json = common.is_stored_as_json_file(FREEBASE_COMPOSITIONS_DATA_DIR + common.SLASH + filename)
if(response_json == None):
#inputfile = glob.glob(FREEBASE_COMPOSITIONS_DATA_DIR + SLASH + filename)
#if not inputfile:
print 'composition not exists for ID:', composition_id
common.write_json_file(FREEBASE_COMPOSITIONS_DATA_DIR, filename, response)
# Main query routine
def find_freebase_items(query):
api_key = open("freebase_api_key").read()
service_url = 'https://www.googleapis.com/freebase/v1/mqlread'
params = {
'query': json.dumps(query),
'key': api_key
}
url = service_url + '?' + urllib.urlencode(params)
response = json.loads(urllib.urlopen(url).read())
return response
def summarize_compositions():
with codecs.open(SUMMARY_COMPOSITIONS_FILE, 'w') as csvfile:
writer = csv.DictWriter(csvfile, delimiter=';', fieldnames=composition_fieldnames, lineterminator='\n')
writer.writeheader()
for inputfile in glob.glob(FREEBASE_COMPOSITIONS_DIR + common.SLASH + '*'):
print inputfile
compositions_content_json = common.read_json_file(inputfile)
#compositions_content_json = json.loads(compositions_content)
composition_list = compositions_content_json['result'][0]['compositions']
entry = build_composition_entry(inputfile.split('\\')[-1], len(composition_list))
writer.writerow(entry)
def get_composition_string_list_from_json_list(composition_json_list):
composition_list = []
for composition_json in composition_json_list:
if composition_json['name'] != None:
composition_str = common.toByteStr(composition_json['name']).lower()
if composition_str != None:
composition_list.append(composition_str)
return sorted(composition_list)
def get_composition_id_list_from_json_list(composition_json_list):
composition_list = []
for composition_json in composition_json_list:
if composition_json['id'] != None:
composition_str = common.toByteStr(composition_json['id']).lower()
if composition_str != None:
composition_list.append(composition_str)
return sorted(composition_list)
def analyze_compositions():
with codecs.open(AUTHOR_COMPOSITIONS_FILE, 'w') as csvfile:
writer = csv.DictWriter(csvfile, delimiter=';', fieldnames=author_composition_fieldnames, lineterminator='\n')
writer.writeheader()
for inputfile in glob.glob(FREEBASE_COMPOSITIONS_DIR + common.SLASH + '*'):
print inputfile
compositions_content_json = common.read_json_file(inputfile)
name = compositions_content_json['result'][0]['name']
composition_json_list = compositions_content_json['result'][0]['compositions']
composition_list = get_composition_string_list_from_json_list(composition_json_list)
if len(composition_list) > 0:
# parent = assign_parent(composition_list[0])
parent = ''
for index, composition in enumerate(composition_list):
main = composition
if index == 0:
parent = assign_parent(composition_list[0])
else:
#if parent not in composition:
if not composition.startswith(parent):
parent = assign_parent(composition)
else:
parent_new = common.find_common_substring(parent,composition_list[index-1])
#parent_new = common.find_common_parent(parent,composition_list[index-1])
# parent ending must be either ' ' or ','
if parent_new != '':
print 'parent:', parent, 'parent_new:', parent_new, 'composition:', composition
if (len(parent_new) <= len(composition)
and composition[len(parent_new)-1] != ' ' \
and composition[len(parent_new)-1] != ','):
parent_new = composition
parent = parent_new
entry = build_author_composition_entry(common.toByteStr(name), composition, parent, main)
writer.writerow(entry)
def assign_parent(value):
parent = value
if ',' in parent:
posComma = parent.index(',')
parent = parent[:posComma]
#parent = common.check_parent_at_least_a_word(parent, parent_new)
return parent
def build_composition_entry(
freebase_author_id, composition_count):
values = [
freebase_author_id
, composition_count
]
return dict(zip(composition_fieldnames, values))
def build_author_composition_entry(
author, composition, parent, main):
values = [
author
, composition
, parent
, main
]
return dict(zip(author_composition_fieldnames, values))
def build_composition_data_entry(
id, mid, name):
values = [
id
, mid
, name
]
return dict(zip(composition_data_fieldnames, values))
def aggregate_compositions_data():
with codecs.open(COMPOSITIONS_DATA_FILE, 'w') as csvfile:
writer = csv.DictWriter(csvfile, delimiter=';', fieldnames=composition_data_fieldnames, lineterminator='\n')
writer.writeheader()
for inputfile in glob.glob(FREEBASE_COMPOSITIONS_DIR + common.SLASH + '*'):
print inputfile
compositions_content_json = common.read_json_file(inputfile)
composition_json_list = compositions_content_json['result'][0]['compositions']
composition_list = get_composition_id_list_from_json_list(composition_json_list)
if len(composition_list) > 0:
for index, composition_id in enumerate(composition_list):
composition_data = retrieve_compositions_data(composition_id)
if composition_data:
try:
mid = composition_data['result'][0]['mid']
name = composition_data['result'][0]['name']
entry = build_composition_data_entry(composition_id, mid, common.toByteStr(name))
writer.writerow(entry)
except:
print 'Composition values mid and/or name is empty.'
# Command line parsing
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="Freebase query.")
parser.add_argument('query', type=str, nargs='?',
help="Input query text to be processed")
if len(sys.argv) < 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
retrieve_compositions(args.query)