/
converter.py
465 lines (395 loc) · 13.3 KB
/
converter.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
# -*- coding: utf-8 -*-
import sys
from ghost_spider.settings import setup_elastic_connection as get_es_connection
def export_csv_file(name, kind, action=None):
from ghost_spider.util import LocationCsv, SalonToCsvFiles
if kind == 'hotel':
LocationCsv.dump_hotel(name, action=action)
elif kind == 'restaurant':
LocationCsv.dump_restaurant(name, action=action)
elif kind == 'salon':
file_generator = SalonToCsvFiles(name)
file_generator.dump(action=action)
else:
NotImplementedError()
def import_csv_file(filename, kind):
"""Store data from csv files.
filename: string
kind: string (hotel/restaurant)
"""
from ghost_spider.util import CsvImporter
CsvImporter.import_file(filename, kind)
def update_location_from_file(filename, kind):
import os
from ghost_spider.util import LocationCsv
f = open(filename, 'rb')
try:
LocationCsv.import_file(f, kind)
finally:
if f:
f.close()
def update_location_from_folder(foldername, kind):
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(foldername) if isfile(join(foldername, f))]
for filename in onlyfiles:
if '.csv' in filename:
print " "
print "*" * 50
print "processing % s" % filename
nf = join(foldername, filename)
update_location_from_file(nf, kind)
def index_elastic(index, action="create", config_file=None):
"""Create index or force i.e. delete if exist then create it.
action: str [create or force]
config_file: str
"""
es = get_es_connection()
if not config_file:
config_file = index
file_name = 'schema/%s/index_%s.json' % (index, config_file)
# create if not exist
if action == "create":
try:
es.request(method="get", myindex=index, mysuffix="_settings")
except:
es.request(method="post", myindex=index, jsonnize=False, mydata=_read_schema(file_name))
elif action == "force":
# force creation i.e delete and then create
try:
es.request(method="delete", myindex=index)
except:
pass
es.request(method="post", myindex=index, jsonnize=False, mydata=_read_schema(file_name))
def type_elastic(index, type, action=None):
"""Create type with mapping or merge the mapping.
type: str
index: str
action: str
"""
es = get_es_connection()
# delete the if exist
if action == "force":
try:
es.request(method="delete", myindex=index, mytype=type)
except:
pass
file_name = 'schema/%s/mapping_%s.json' % (index, type)
# create if not exist or merge
es.request(method="post", myindex=index, mytype=type, mysuffix="_mapping", jsonnize=False, mydata=_read_schema(file_name))
def type_merge(name):
"""Merge type, experimental only use if you are sure that you can get your data back (i.e reindex).
It's to avoid re-indexing when you have a merge conflict.
name: str Name of the model you want to merge
"""
# import dynamically the
mod = __import__("model", fromlist=[name])
type_es = getattr(mod, name)
es = get_es_connection()
tmp_type = "%s2" % type_es.type
# copy type in type2 force creation
file_name = 'schema/%s/mapping_%s.json' % (type_es.index, type_es.type)
es.request(method="post", myindex=type_es.index, mytype=tmp_type, mysuffix="_mapping", jsonnize=False, mydata=_read_schema(file_name))
_copy_type(type_es, type_es.type, tmp_type)
type_elastic(type_es.index, type_es.type, "force")
_copy_type(type_es, tmp_type, type_es.type)
es.request(method="delete", myindex=type_es.index, mytype=tmp_type)
def replicate_type():
"""Duplicate a type from type_from to type_to."""
# build bulk
from ghost_spider.elastic import LocationRestaurantEs
from ghost_spider import progressbar
size = 100
page = 0
progress = None
total = 0
while True:
start_from = page * size
results = LocationRestaurantEs.search({"query": {"match_all": {}}, "size": size, "from": start_from})
if not progress:
total = results["hits"]["total"]
progress = progressbar.AnimatedProgressBar(end=total, width=100)
if not results["hits"]["hits"]:
break
page += 1
bulk = ""
for result in results["hits"]["hits"]:
data = result["_source"]
bulk += LocationRestaurantEs.bulk_data(data, type_name="restaurants_back")
progress + size
progress.show_progress()
LocationRestaurantEs.send(bulk)
if progress:
progress + total
progress.show_progress()
print "total %s" % total
def update_location():
"""Duplicate a type from type_from to type_to."""
# build bulk
from ghost_spider.elastic import LocationRestaurantEs
from ghost_spider.helper import LocationHotelSelectors
from ghost_spider import progressbar
import re
size = 100
page = 0
progress = None
total = 0
query = {"query": {"match_all": {}}, "size": size, "from": 0}
query["sort"] = [{"name.untouched": "asc"}]
while True:
query["from"] = page * size
results = LocationRestaurantEs.search(query)
if not progress:
total = results["hits"]["total"]
print "total %s" % total
progress = progressbar.AnimatedProgressBar(end=total, width=100)
if not results["hits"]["hits"]:
break
page += 1
bulk = ""
for result in results["hits"]["hits"]:
location = result["_source"]
data_id = result["_id"]
genre = []
area_found = False
for a in location["page_body"]["genre"]:
result = re.findall(r'genrecd=\d+', a)
if u'genrecd=01' in result:
if not area_found:
text = re.findall(r'>(.*)</', a)
location['area'] = text[0]
if location['area']:
location['area_ascii'] = LocationRestaurantEs.analyze(location['area'], 'romaji_ascii_normal_analyzer')
area_found = True
else:
text = re.findall(r'>(.*)</', a)
if text and text[0]:
genre.append(text[0])
if not area_found and len(location["page_body"]["breadcrumbs"]) > 1:
location['area'] = location["page_body"]["breadcrumbs"][-1]
if location['area']:
location['area_ascii'] = LocationRestaurantEs.analyze(location['area'], 'romaji_ascii_normal_analyzer')
elif not area_found:
location['area'] = ''
location['area_ascii'] = ''
kind = LocationHotelSelectors.convert_latte_kind(genre)
location['genre'] = genre
location['kind'] = kind
bulk += LocationRestaurantEs.bulk_data(location, action="update", data_id=data_id)
progress + size
progress.show_progress()
LocationRestaurantEs.send(bulk)
if progress:
progress + total
progress.show_progress()
print " "
def update_airports():
"""Get the city from Latte and update airport."""
# build bulk
from ghost_spider.elastic import LocationAirportEs
from ghost_spider import progressbar
import requests
import time
size = 100
page = 0
progress = None
total = 0
query = {"query": {"match_all": {}}, "size": size, "from": 0}
query["sort"] = [{"name.untouched": "asc"}]
while True:
query["from"] = page * size
results = LocationAirportEs.search(query)
if not progress:
total = results["hits"]["total"]
print "total %s" % total
progress = progressbar.AnimatedProgressBar(end=total, width=100)
progress.show_progress()
if not results["hits"]["hits"]:
break
page += 1
bulk = ""
for result in results["hits"]["hits"]:
location = result["_source"]
data_id = result["_id"]
if not location.get('place_id'):
ret_json = []
url = u'https://latte.la/travel/json?term=%s&kind=area1-area2-area3-city1-city2-city3' % location["area"]
ret = requests.get(url, params={})
ret_json = ret.json()
found_place = None
progress + 1
progress.show_progress()
for place in ret_json:
if place.get('value') == location["area"]:
found_place = place
break
if found_place:
location["place_id"] = found_place["placeid"]
location["place_url_key"] = found_place["url_key"]
else:
location["place_url_key"] = location["url_key"]
location["place_id"] = long(location.get('place_id') or 0)
location.pop('url_key')
bulk += LocationAirportEs.bulk_data(location, action="update", data_id=data_id)
if bulk:
LocationAirportEs.send(bulk)
if progress:
progress + total
progress.show_progress()
print " "
def dump_airports(filename):
# build bulk
from ghost_spider.elastic import LocationAirportEs
from ghost_spider.util import CsvWriter
from ghost_spider import progressbar
import requests
import time
import os
size = 100
page = 0
progress = None
total = 0
query = {"query": {"match_all": {}}, "size": size, "from": 0}
query["sort"] = [{"country.untouched": "asc"}]
first_row = ["name", "name_eng", "IATA", "NTGA", "country", "city", "placeid", "place_url"]
if os.path.exists(filename):
os.remove(filename)
while True:
query["from"] = page * size
results = LocationAirportEs.search(query)
if not progress:
total = results["hits"]["total"]
print "total %s" % total
progress = progressbar.AnimatedProgressBar(end=total, width=100)
progress.show_progress()
if not results["hits"]["hits"]:
break
page += 1
bulk = ""
for result in results["hits"]["hits"]:
location = result["_source"]
data_id = result["_id"]
progress + 1
progress.show_progress()
row = []
row.append(location.get('name'))
row.append(location.get('name_eng'))
row.append(location.get('code') or '')
row.append(location.get('code2') or '')
row.append(location.get('country') or '')
row.append(location.get('area') or '')
row.append(unicode(location.get('place_id') or ''))
row.append(location.get('url_key') or '')
CsvWriter.write_to_csv(filename, row, firs_row=first_row)
if progress:
progress + total
progress.show_progress()
print " "
def delete_type(index, type):
"""delete a type from index."""
es = get_es_connection()
es.request(method="delete", myindex=index, mytype=type)
def _copy_type(type_es, type_from, type_to):
"""Duplicate a type from type_from to type_to."""
type_es.type = type_from
# build bulk
size = 100
page = 0
while True:
start_from = page * size
results = type_es.search({"query": {"match_all": {}}, "size": size, "from": start_from})
if not results["hits"]["hits"]:
break
page += 1
bulk = ""
for result in results["hits"]["hits"]:
bulk += type_es.bulk_data(result["_source"], type_name=type_to)
type_es.send(bulk)
def elastic_backup(name=None):
"""Launch a snapshot with generated name directory if not provided.
name: str
"""
es = get_es_connection()
import datetime
if not name:
name = "backup"
_check_repository(es, name)
snapshot_name = datetime.datetime.now().strftime("%Y%m%d%I%M%S")
print es.request(method="put", mysuffix="_snapshot/%s/%s?wait_for_completion=true" % (name, snapshot_name))
def _check_repository(es, name):
"""Check if the repository exist if not create it."""
try:
es.request(method="get", mysuffix="_snapshot/%s" % name)
except:
repository = {"type": "fs",
"settings": {
"location": "/tmp/%s" % name,
"compress": True
}
}
es.request(method="put", mysuffix="_snapshot/%s" % (name), mydata=repository)
def create_repository(name):
"""create repository."""
es = get_es_connection()
repository = {"type": "fs",
"settings": {
"location": "/tmp/%s" % name,
"compress": True
}
}
es.request(method="put", mysuffix="_snapshot/%s" % (name), mydata=repository)
def _read_schema(filename):
"""Read the content of a file.
filename: string
return: content of the file
"""
import os
project_root = os.path.abspath(os.path.dirname(__file__))
f = open(os.path.join(project_root, filename), 'rb')
try:
return f.read()
finally:
if f:
f.close()
def main():
from optparse import OptionParser
parser = OptionParser()
parser.add_option('--id', type='int')
parser.add_option('--name', type='str')
parser.add_option('--filename', type='str')
parser.add_option('--foldername', type='str')
parser.add_option('--kind', type='str')
parser.add_option('--file', type='str')
parser.add_option('--action', type='str')
parser.add_option('--index', type='str')
parser.add_option('--type', type='str')
parser.add_option('--delta', type='int')
parser.add_option('--ignore', type='str')
parser.add_option('--resume', type='str')
options, args = parser.parse_args()
if 1 != len(args):
parser.error('empty command.')
return
options = dict([(k, v) for k, v in options.__dict__.iteritems() if not k.startswith('_') and v is not None])
commands = {
'index_elastic': index_elastic,
'type_elastic': type_elastic,
'elastic_backup': elastic_backup,
'type_merge': type_merge,
'replicate_type': replicate_type,
'delete_type': delete_type,
'update_location': update_location,
'import_csv_file': import_csv_file,
'export_csv_file': export_csv_file,
'update_location_from_file': update_location_from_file,
'update_location_from_folder': update_location_from_folder,
'update_airports': update_airports,
'dump_airports': dump_airports
}
command = commands[args[0]]
try:
command(**options)
finally:
pass
if __name__ == '__main__':
main()