This repository has been archived by the owner on Jun 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 41
/
GeoBaseMain.py
executable file
·2930 lines (2343 loc) · 94.6 KB
/
GeoBaseMain.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This module is a launcher for the GeoBases package.
"""
from sys import stdin, stderr, argv
import os
import os.path as op
from math import ceil, log
from itertools import izip_longest, chain
from textwrap import dedent
import platform
import re
# Not in standard library
from termcolor import colored
import colorama
import argparse # in standard libraray for Python >= 2.7
# Private
from GeoBases import GeoBase, DEFAULTS, SourcesManager, is_remote, is_archive
IS_WINDOWS = platform.system() in ('Windows',)
if not IS_WINDOWS:
import signal
# On windows, SIGPIPE does not exist
# Do not produce broken pipes when head and tail are used
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
try:
# readline is not available on every platform
import readline
import glob
def complete(text, state):
"""Activate autocomplete on raw_input.
"""
return (glob.glob(text + '*') + [None])[state]
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
def ask_input(prompt, prefill=''):
"""Custom default when asking for input.
"""
readline.set_startup_hook(lambda: readline.insert_text(str(prefill)))
try:
return raw_input(prompt)
finally:
readline.set_startup_hook()
except ImportError:
def ask_input(prompt, prefill=''):
"""Fallback.
"""
if prefill:
answer = raw_input('%s[%s] ' % (prompt, str(prefill)))
else:
answer = raw_input('%s' % prompt)
if answer:
return answer
else:
# No answer, returning default
return prefill
def ask_till_ok(msg, allowed=None, show=True, is_ok=None, fail_message=None, boolean=False, default=False, prefill=''):
"""Ask a question and only accept a list of possibilities as response.
"""
if boolean:
allowed = ('Y', 'y', 'N', 'n', '')
show = False
if is_ok is None:
is_ok = lambda r: True
if allowed is None:
is_allowed = lambda r: True
else:
is_allowed = lambda r: r in allowed
# Start
if show and allowed is not None:
two_col_print(allowed)
response = ask_input(msg, prefill).strip()
while not is_ok(response) or not is_allowed(response):
if fail_message is not None:
print fail_message
response = ask_input(msg, prefill).strip()
if not boolean:
return response
else:
if default is True:
return response in ('Y', 'y', '')
else:
return response in ('Y', 'y')
def is_in_path(command):
"""This checks if a command is in the PATH.
"""
path = os.popen('which %s 2> /dev/null' % command, 'r').read()
if path:
return True
else:
return False
def get_stty_size():
"""
This gives terminal size information using external
command stty.
This function is not great since where stdin is used, stty
fails and we return the default case.
"""
size = os.popen('stty size 2>/dev/null', 'r').read()
if not size:
return (80, 160)
return tuple(int(d) for d in size.split())
def get_term_size():
"""
This gives terminal size information.
"""
try:
import fcntl, termios, struct
except ImportError:
return get_stty_size()
def ioctl_GWINSZ(fd):
"""Read terminal size."""
try:
cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
except IOError:
return
return cr
env = os.environ
cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
if not cr:
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
cr = ioctl_GWINSZ(fd)
os.close(fd)
except IOError:
pass
if not cr:
cr = env.get('LINES', 25), env.get('COLUMNS', 80)
return int(cr[0]), int(cr[1])
class RotatingColors(object):
"""
This class is used for generating alternate colors
for the Linux output.
"""
def __init__(self, background):
if background == 'black':
self._availables = [
('cyan', None, []),
('white', 'on_grey', []),
]
elif background == 'white':
self._availables = [
('grey', None, []),
('blue', 'on_white', []),
]
else:
raise ValueError('Accepted background color: "black" or "white", not "%s".' % \
background)
self._background = background
self._current = 0
def next(self):
"""We increase the current color.
"""
self._current += 1
if self._current == len(self._availables):
self._current = 0
def get(self):
"""Get current color.
"""
return self._availables[self._current]
def convertRaw(self, col):
"""Get special raw color. Only change foreground color.
"""
current = list(col)
current[0] = 'yellow' if self._background == 'black' else 'cyan'
return tuple(current)
@staticmethod
def convertJoin(col):
"""Get special join color. Only change foreground color.
"""
current = list(col)
current[0] = 'green'
return tuple(current)
@staticmethod
def convertBold(col):
"""Get special field color. Only change bold type.
"""
current = list(col)
current[2] = ['bold']
return tuple(current)
@staticmethod
def getEmph():
"""Get special emphasized color.
"""
return ('white', 'on_blue', [])
@staticmethod
def getHeader():
"""Get special header color.
"""
return ('red', None, [])
@staticmethod
def getSpecial():
"""Get special field color.
"""
return ('magenta', None, [])
def flatten(value, level=0):
"""Flatten nested structures into str.
>>> flatten(())
''
>>> flatten('T0')
'T0'
>>> flatten(['T1', 'T1'])
'T1/T1'
>>> flatten([('T2', 'T2'), 'T1'])
'T2:T2/T1'
>>> flatten([('T2', ['T3', 'T3']), 'T1'])
'T2:T3,T3/T1'
None is flatten as ''.
>>> flatten([('T2', ['T3', None]), 'T1'])
'T2:T3,/T1'
"""
splitters = ['/', ':', ',']
if level >= len(splitters):
splitter = '|'
else:
splitter = splitters[level]
level += 1
if isinstance(value, (list, tuple, set)):
return splitter.join(flatten(e, level) for e in value)
else:
return str(value) if value is not None else ''
def check_ext_field(geob, field):
"""
Check if a field given by user contains
join fields and external field.
"""
l = field.split(':', 1)
if len(l) <= 1:
return field, None
f, ext_f = l
if geob.hasJoin(f):
return f, ext_f
# In case of multiple join fields
f = tuple(f.split(SPLIT))
if geob.hasJoin(f):
return f, ext_f
return field, None
def fmt_ref(ref, ref_type, no_symb=False):
"""
Display the reference depending on its type.
"""
if ref_type == 'distance':
if no_symb:
return '%.3f' % ref
return '%.2f km' % ref
if ref_type == 'percentage':
if no_symb:
return '%.3f' % ref
return '%.1f %%' % (100 * ref)
if ref_type == 'phonemes':
if isinstance(ref, (list, tuple, set)):
return SPLIT.join(str(e) for e in ref)
else:
return str(ref)
if ref_type == 'index':
return '%s' % int(ref)
raise ValueError('ref_type %s was not allowed' % ref_type)
def display_terminal(geob, list_of_things, shown_fields, ref_type, important):
"""
Main display function in Linux terminal, with
nice color and everything.
"""
if not list_of_things:
print 'No elements to display.'
return
# Different behaviour given number of results
# We adapt the width between MIN_CHAR_COL and MAX_CHAR_COL
# given number of columns and term width
n = len(list_of_things)
lim = int(get_term_size()[1] / float(n + 1))
lim = min(MAX_CHAR_COL, max(MIN_CHAR_COL, lim))
if n == 1:
# We do not truncate names if only one result
truncate = None
else:
truncate = lim
c = RotatingColors(BACKGROUND_COLOR)
for f in shown_fields:
# Computing clean fields, external fields, ...
if f == REF:
cf = REF
else:
cf, ext_f = check_ext_field(geob, f)
if ext_f is None:
get = lambda k: geob.get(k, cf)
else:
get = lambda k: geob.get(k, cf, ext_field=ext_f)
if cf in important:
col = c.getEmph()
elif cf == REF:
col = c.getHeader()
elif str(cf).startswith('__'):
col = c.getSpecial() # For special fields like __dup__
else:
col = c.get()
if str(cf).endswith('@raw'):
col = c.convertRaw(col) # For @raw fields
if geob.hasJoin(cf):
col = c.convertJoin(col) # For joined fields
# Fields on the left
l = [fixed_width(f, c.convertBold(col), lim, truncate)]
if f == REF:
for h, _ in list_of_things:
l.append(fixed_width(fmt_ref(h, ref_type), col, lim, truncate))
else:
for _, k in list_of_things:
l.append(fixed_width(get(k), col, lim, truncate))
next(c)
print ''.join(l)
def fields_to_show(defaults, omit, show, show_additional):
"""Process fields to show.
"""
if not show:
show = defaults
# Building final shown headers
shown_fields = [f for f in show if f not in omit]
# Trying to cleverly position addtional field
positions = []
for af in show_additional:
for i, f in enumerate(shown_fields):
if af.startswith(f):
positions.append(i+1)
break
else:
positions.append(-1)
already_inserted = 0
for af, p in zip(show_additional, positions):
if p == -1:
shown_fields.append(af)
else:
shown_fields.insert(p + already_inserted, af)
already_inserted += 1
return shown_fields
def display_quiet(geob, list_of_things, shown_fields, ref_type, delim, header):
"""
This function displays the results in programming
mode, with --quiet option. This is useful when you
want to use use the result in a pipe for example.
"""
# Headers joined
j_headers = delim.join(str(f) for f in shown_fields)
# Displaying headers only for RH et CH
if header == 'RH':
print j_headers
elif header == 'CH':
print '#%s' % j_headers
# Caching getters
getters = {}
for f in shown_fields:
if f == REF:
continue
cf, ext_f = check_ext_field(geob, f)
if ext_f is None:
getters[f] = cf, ext_f, lambda k, cf, ext_f: geob.get(k, cf)
else:
getters[f] = cf, ext_f, lambda k, cf, ext_f: geob.get(k, cf, ext_field=ext_f)
for h, k in list_of_things:
l = []
for f in shown_fields:
if f == REF:
l.append(fmt_ref(h, ref_type, no_symb=True))
else:
# Get from getters cache
cf, ext_f, get = getters[f]
v = get(k, cf, ext_f)
# Small workaround to display nicely lists in quiet mode
# Fields @raw are already handled with raw version, but
# __dup__ field has no raw version for dumping
if isinstance(v, (list, tuple, set)):
l.append(flatten(v))
else:
l.append(str(v) if v is not None else '')
print delim.join(l)
def display_browser(templates, output_dir, nb_res):
"""Display templates in the browser.
"""
# Save current working directory
previous_wd = os.getcwd()
if not output_dir:
output_dir = '.'
# Moving where files are
os.chdir(output_dir)
# We manually launch browser, unless we risk a crash
to_be_launched = []
for template in templates:
# Getting relative path for current working dir
template = op.relpath(template, output_dir)
if template.endswith('_table.html'):
if nb_res <= TABLE_BROWSER_LIM:
to_be_launched.append(template)
else:
print '/!\ "%s %s:%s/%s" not launched automatically. %s results, may be slow.' % \
(BROWSER, ADDRESS, PORT, template, nb_res)
elif template.endswith('_map.html'):
if nb_res <= MAP_BROWSER_LIM:
to_be_launched.append(template)
else:
print '/!\ "%s %s:%s/%s" not launched automatically. %s results, may be slow.' % \
(BROWSER, ADDRESS, PORT, template, nb_res)
else:
to_be_launched.append(template)
if to_be_launched:
urls = ['%s:%s/%s' % (ADDRESS, PORT, tpl) for tpl in to_be_launched]
os.system('%s %s 2>/dev/null &' % (BROWSER, ' '.join(urls)))
# Serving the output_dir, where we are
launch_http_server(ADDRESS, PORT)
# Moving back
os.chdir(previous_wd)
def launch_http_server(address, port):
"""Launch a SimpleHTTPServer.
"""
import SimpleHTTPServer
import SocketServer
class MyTCPServer(SocketServer.TCPServer):
"""Overrides standard library.
"""
allow_reuse_address = True
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = MyTCPServer((address, port), Handler)
try:
print '* Serving on %s:%s (hit ctrl+C to stop)' % (address, port)
httpd.serve_forever()
except KeyboardInterrupt:
print '\n* Shutting down gracefully...'
httpd.shutdown()
print '* Done'
def fixed_width(s, col, lim=25, truncate=None):
"""
This function is useful to display a string in the
terminal with a fixed width. It is especially
tricky with unicode strings containing accents.
"""
if truncate is None:
truncate = 1000
printer = '%%-%ss' % lim # is something like '%-3s'
# To truncate on the appropriate number of characters
# We decode before truncating (so non-ascii characters
# will be counted only once when using len())
# Then we encode again before display
ds = str(s).decode('utf8') # decode
es = (printer % ds[0:truncate]).encode('utf8') # encode
if len(ds) > truncate:
es = es[:-2] + '… '
return colored(es, *col)
def scan_coords(u_input, geob, verbose):
"""
This function tries to interpret the main
argument as either coordinates (lat, lng) or
a key like ORY.
"""
# First we try input a direct key
if u_input in geob:
coords = geob.getLocation(u_input)
if coords is None:
error('geocode_unknown', u_input)
return coords
# Then we try input as geocode
try:
free_geo = u_input.strip('()')
for char in '\\', '"', "'":
free_geo = free_geo.replace(char, '')
for sep in '^', ';', ',':
free_geo = free_geo.replace(sep, ' ')
coords = tuple(float(l) for l in free_geo.split())
except ValueError:
pass
else:
if len(coords) == 2 and \
-90 <= coords[0] <= 90 and \
-180 <= coords[1] <= 180:
if verbose:
print 'Geocode recognized: (%.3f, %.3f)' % coords
return coords
error('geocode_format', u_input)
# All cases failed
warn('key', u_input, geob.data, geob.loaded)
exit(1)
def guess_delimiter(row):
"""Heuristic to guess the top level delimiter.
"""
discarded = set([
'#', # this is for comments
'_', # this is for spaces
' ', # spaces are not usually delimiter, unless we find no other
'"', # this is for quoting
'.', # this is for decimal numbers
'@', # this is for duplicated keys
])
candidates = set([l for l in row.rstrip() if not l.isalnum() and l not in discarded])
counters = dict((c, row.count(c)) for c in candidates)
# Testing spaces from higher to lower, break on biggest match
for alternate in [' ' * i for i in xrange(16, 3, -1)]:
if row.count(alternate):
counters[alternate] = row.count(alternate)
break
if counters:
return max(counters.iteritems(), key=lambda x: x[1])[0]
else:
# In this case, we could not find any delimiter, we may
# as well return ' '
return ' '
def generate_headers(n):
"""Generate n headers.
"""
for i in xrange(n):
yield 'H%s' % i
ADD_INFO_REG = re.compile("([^{}]*)({?[^{}]*}?)({?[^{}]*}?)")
def clean_headers(headers):
"""
Remove additional informations from headers,
and return what was found.
"""
subdelimiters = {}
join = []
for i, h in enumerate(headers):
m = ADD_INFO_REG.match(h)
if m is None:
continue
clean_h, jn, subd = m.groups()
headers[i] = clean_h
# We consider the join only if the user did not give nothing or empty {}
jn = jn.strip('{}')
if jn:
join.append({
'fields' : clean_h,
'with' : jn.split(':', 1)
})
# For the subdelimiters we consider {} as empty string
if subd:
subd = subd.strip('{}')
if subd == '':
subdelimiters[clean_h] = ''
else:
subdelimiters[clean_h] = subd.split(':')
return join, subdelimiters
def guess_headers(row, delimiter):
"""Heuristic to guess the lat/lng fields from first row.
"""
if delimiter:
row = row.split(delimiter)
else:
row = list(row)
headers = list(generate_headers(len(row)))
# Name candidates for lat/lng
lat_candidates = set(['latitude', 'lat'])
lng_candidates = set(['longitude', 'lng', 'lon'])
lat_found, lng_found = False, False
for i, f in enumerate(row):
try:
val = float(f)
except ValueError:
# Here the line was not a number, we check the name
if f.lower() in lat_candidates and not lat_found:
headers[i] = 'lat'
lat_found = True
if f.lower() in lng_candidates and not lng_found:
headers[i] = 'lng'
lng_found = True
else:
if val == int(val):
# Round values are improbable as lat/lng
continue
if -90 <= val <= 90 and not lat_found:
# possible latitude field
headers[i] = 'lat'
lat_found = True
elif -180 <= val <= 180 and not lng_found:
# possible longitude field
headers[i] = 'lng'
lng_found = True
return headers
def score_key(v):
"""Eval likelihood of being a good field for generating keys.
The shorter the better, and int get a len() of 1.
0, 1 and floats are weird for key_fields, as well as 1-letter strings.
"""
if str(v).endswith('__key__') or str(v).lower().endswith('id'):
return 0
if isinstance(v, float):
return 1000
if isinstance(v, int):
if v <= 1: # we avoid a domain error on next case
return 10
return max(2, 25 / log(v))
return len(v) if len(v) >= 2 else 10
def guess_key_fields(row, delimiter, headers):
"""Heuristic to guess key_fields from headers and first row.
"""
if not headers:
return []
if delimiter:
row = row.split(delimiter)
else:
row = list(row)
discarded = set(['lat', 'lng'])
candidates = []
for h, v in zip(headers, row):
# Skip discarded and empty values
if h not in discarded and v:
try:
val = float(v)
except ValueError:
# is *not* a number
candidates.append((h, score_key(v)))
else:
# is a number
if val == int(val):
candidates.append((h, score_key(int(val))))
else:
candidates.append((h, score_key(val)))
if not candidates:
return [headers[0]]
return [ min(candidates, key=lambda x: x[1])[0] ]
def build_pairs(L, layout='v'):
"""
Some formatting for help.
"""
n = float(len(L))
h = int(ceil(n / 2)) # half+
if layout == 'h':
return izip_longest(L[::2], L[1::2], fillvalue='')
if layout == 'v':
return izip_longest(L[:h], L[h:], fillvalue='')
raise ValueError('Layout must be "h" or "v", but was "%s"' % layout)
def split_if_several(value):
"""Only split if several elements.
"""
value = value.split(SPLIT)
if len(value) == 1:
return value[0]
return value
def to_CLI(option, value):
"""Format stuff from the configuration file.
"""
if option == 'path':
return value['file']
if option == 'delimiter':
return str(value)
if option == 'headers':
return flatten(value)
if option == 'key_fields':
if value is None:
return ''
else:
return flatten(value)
if option == 'index':
return flatten(value)
if option == 'join':
if len(value['with']) < 2:
if not value['with'][0]:
return flatten(value['fields'])
return '%s{%s}' % (flatten(value['fields']),
value['with'][0])
else:
return '%s{%s:%s}' % (flatten(value['fields']),
value['with'][0],
flatten(value['with'][1]))
raise ValueError('Did not understand option "%s".' % option)
def best_field(candidates, possibilities, default=None):
"""Select best candidate in possibilities.
"""
for candidate in candidates:
if candidate in possibilities:
return candidate
return default
def warn(name, *args):
"""
Display a warning on stderr.
"""
if name == 'key':
print >> stderr, '/!\ Key %s was not in base, for data "%s" and source %s' % \
(args[0], args[1], args[2])
if name == 'installation':
print >> stderr, '/!\ %s is not installed, no package information available.' % \
args[0]
def error(name, *args):
"""
Display an error on stderr, then exit.
First argument is the error type.
"""
if name == 'trep_support':
print >> stderr, '\n/!\ No opentrep support. Check if OpenTrepWrapper can import libpyopentrep.'
elif name == 'geocode_support':
print >> stderr, '\n/!\ No geocoding support for data type %s.' % args[0]
elif name == 'data':
print >> stderr, '\n/!\ Wrong data type "%s". You may select:' % args[0]
for p in build_pairs(args[1]):
print >> stderr, '\t%-20s\t%-20s' % p
elif name == 'field':
print >> stderr, '\n/!\ Wrong field "%s".' % args[0]
print >> stderr, 'For data type "%s", you may select:' % args[1]
for p in build_pairs(args[2]):
print >> stderr, '\t%-20s\t%-20s' % p
elif name == 'geocode_format':
print >> stderr, '\n/!\ Bad geocode format: %s' % args[0]
elif name == 'geocode_unknown':
print >> stderr, '\n/!\ Geocode was unknown for %s' % args[0]
elif name == 'empty_stdin':
print >> stderr, '\n/!\ Stdin was empty'
elif name == 'wrong_value':
print >> stderr, '\n/!\ Wrong value "%s", should be in:' % args[0]
for p in build_pairs(args[1]):
print >> stderr, '\t%-20s\t%-20s' % p
elif name == 'type':
print >> stderr, '\n/!\ Wrong type for "%s", should be "%s".' % (args[0], args[1])
elif name == 'aborting':
print >> stderr, '\n\n/!\ %s' % args[0]
elif name == 'not_allowed':
print >> stderr, '\n/!\ Value "%s" not allowed.' % args[0]
exit(1)
def panic_mode():
"""Panic mode.
"""
# Here we have a broken source file
print '\n/!\ Source file seems broken.\n'
try:
restore = ask_till_ok('Restore file %s\nFrom origin %s [yN]? ' % \
(S_MANAGER.sources_conf_path,
S_MANAGER.sources_conf_path_origin),
boolean=True,
default=False)
except (KeyboardInterrupt, EOFError):
print '\n\nYou should have said "Yes" :).'
else:
if restore:
S_MANAGER.restore(clean_cache=False)
print '\nRestored.'
else:
print '\nDid not restore.'
#######
#
# MAIN
#
#######
# Global defaults
PACKAGE_NAME = 'GeoBases'
SCRIPT_NAME = 'GeoBase'
DESCRIPTION = 'Data services and visualization'
# Sources manager
S_MANAGER = SourcesManager()
# Contact info
CONTACT_INFO = '''
Report bugs to : geobases.dev@gmail.com
Home page : <http://opentraveldata.github.com/geobases/>
API documentation : <https://geobases.readthedocs.org/>
Wiki pages : <https://github.com/opentraveldata/geobases/wiki/_pages>
'''
try:
HELP_SOURCES = S_MANAGER.build_status()
except (KeyError, ValueError, TypeError):
# Here we have a broken source file
panic_mode()
exit(1)
CLI_EXAMPLES = '''
* Command line examples
$ %s ORY CDG # query on the keys ORY and CDG
$ %s --closest CDG # find closest from CDG
$ %s --near '48.853, 2.348' # find near some geocode
$ %s --fuzzy "san francisko" # fuzzy search, with typo ;)
$ %s --admin # administrate the data sources
$ %s --help # your best friend
$ cat data.csv | %s # with your data