forked from maptiler/epsg.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
executable file
·1787 lines (1560 loc) · 70.9 KB
/
app.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/env python
# -*- coding: utf-8 -*-
"""
"""
VERSION = "9.8"
INDEX = "./index"
DATABASE = "./gml/gml.sqlite"
CRS_EXCEPTIONS = 'CRS_exceptions.csv'
# ['kind'(in whoosh), 'short kind', 'space for formating', 'explenation of abbr', count', 'link to new query', 'long kind']
facets_list = [
['CRS','CRS','','Coordinate reference systems',0,'http://','Coordinate reference system'],
['CRS-PROJCRS','PROJCRS',' ', 'Projected',0,'http://','Projected coordinate system'],
['CRS-GEOGCRS','GEOGCRS',' ', 'Geodetic',0,'http://', 'Geodetic coordinate system'],
['CRS-GEOG3DCRS','GEOG3DCRS', ' ', 'Geodetic 3D',0,'http://','Geodetic 3D coordinate system'],
['CRS-GCENCRS','GCENCRS',' ', 'Geocentric',0,'http://', 'Geocentric coordinate system'],
['CRS-VERTCRS','VERTCRS',' ', 'Vertical',0,'http://', 'Vertical coordinate system'],
['CRS-ENGCRS','ENGCRS',' ', 'Engineering',0,'http://', 'Engineering coordinate system'],
['CRS-COMPOUNDCRS','COMPOUNDCRS',' ', 'Compound',0,'http://', 'Compound coordinate system'],
['COORDOP','COORDOP','','Operation',0,'http://', 'Operation'],
['COORDOP-COPTRANS','COPTRANS',' ', 'Transformation',0,'http://', 'Transformation'],
['COORDOP-COPCONOP','COPCONOP',' ', 'Compound',0,'http://', 'Compound operation'],
['COORDOP-COPCON','COPCON',' ', 'Conversion',0,'http://', 'Conversion'],
['DATUM','DATUM','','Datum',0,'http://', 'Datum'],
['DATUM-VERTDAT','VERTDAT',' ', 'Vertical',0,'http://', 'Vertical datum'],
['DATUM-ENGDAT','ENGDAT',' ', 'Engineering',0,'http://', 'Engineering datum'],
['DATUM-GEODDAT','GEODDAT',' ', 'Geodetic',0,'http://', 'Geodetic datum'],
['ELLIPSOID','ELLIPSOID','', 'Ellipsoid',0,'http://', 'Ellipsoid'],
['PRIMEM','PRIMEM','', 'Prime meridian',0,'http://', 'Prime meridian'],
['METHOD','METHOD','', 'Method',0,'http://', 'Method'],
['CS','CS','', 'Coordinate systems',0,'http://', 'Coordinate system'],
['CS-VERTCS','VERTCS',' ', 'Vertical',0,'http://', 'Vertical coordinate system'],
['CS-SPHERCS','SPHERCS',' ', 'Spherical',0,'http://', 'Spherical coordinate system'],
['CS-CARTESCS','CARTESCS',' ', 'Cartesian',0,'http://', 'Cartesian coordinate system'],
['CS-ELLIPCS','ELLIPCS',' ', 'Ellipsoidal',0,'http://', 'Ellipsoidal coordinate system'],
['AXIS','AXIS','', 'Axis',0,'http://', 'Axis'],
['AREA','AREA','', 'Area',0,'http://', 'Area'],
['UNIT','UNIT','', 'Units',0,'http://', 'Unit'],
['UNIT-ANGUNIT','ANGUNIT',' ', 'Angle',0,'http://', 'Angle unit'],
['UNIT-SCALEUNIT','SCALEUNIT',' ', 'Scale',0,'http://', 'Scale unit'],
['UNIT-LENUNIT','LENUNIT',' ', 'Length',0,'http://', 'Length unit'],
['UNIT-TIMEUNIT','TIMEUNIT',' ', 'Time',0,'http://', 'Time unit']
]
# Index to the facets_list above - manual update on change!
f_crs_index = 0
f_op_index = 8
f_datum_index = 12
f_cs_index = 19
f_unit_index = 26
from flask import Flask, jsonify, redirect, render_template, url_for, request, Response, send_from_directory, make_response
# from flask_debugtoolbar import DebugToolbarExtension
import urllib2
import urllib
import urlparse
import sys
import os
from whoosh.index import open_dir
from whoosh.fields import *
from whoosh.qparser import QueryParser, MultifieldParser
from whoosh.query import *
from whoosh import sorting, qparser, scoring,index, highlight,sorting,collectors
import re
from pprint import pprint
from pygments.lexer import RegexLexer
from pygments.token import *
from pygments import highlight
from pygments.formatters import HtmlFormatter
from osgeo import gdal, osr, ogr
import time
import math
import json
import csv
import sqlite3 as sqlite
app = Flask(__name__)
# app.config['SECRET_KEY'] = '<replace with a secret key>'
# toolbar = DebugToolbarExtension(app)
if os.environ.get('SENTRY_DSN'):
import sentry_sdk
sentry_sdk.init(
dsn=os.environ['SENTRY_DSN'],
release=os.environ.get('SENTRY_RELEASE'),
environment=os.environ.get('SENTRY_ENVIRONMENT'),
server_name=os.environ.get('SENTRY_SERVER_NAME'),
send_default_pii=True,
)
re_kind = re.compile(r'kind:([\*\w-]+)')
re_deprecated = re.compile(r'deprecated:\d')
crs_ex_line = {}
try:
with open(CRS_EXCEPTIONS) as crs_ex:
text = csv.reader(crs_ex, delimiter = ',')
# skip the header
next(text, None)
for row in text:
crs_ex_line[row[0]] = row
#print crs_ex_line['4326'][2]
except:
print "!!! FAILED: NO CRS_EXCEPTIONS !!!"
#sys.exit(1)
con = sqlite.connect(DATABASE, check_same_thread=False)
if not con:
print "Connection to gml.sqlite FAILED"
#sys.exit(1)
cur = con.cursor()
def getQueryParam(q, param):
"""Return value of a param in query"""
if param == 'deprecated':
if "deprecated:1" in q:
return 1
else:
return 0 # default if not present
if param == 'kind':
m = re_kind.search(q)
if m:
return m.group(1)
else:
return "CRS" # default if not present
m = re.search(param+r':(\S+)', q)
if m:
return m.group(1)
else:
return ''
def getVerboseQuery(q):
verboseq = setQueryParam(q, 'deprecated', getQueryParam(q,'deprecated'), True)
verboseq = setQueryParam(verboseq, 'kind', getQueryParam(verboseq,'kind'), True)
return verboseq
def setQueryParam(q, param, value='', verbose=False):
"""Set in the query string the param to value"""
if param == 'deprecated':
if int(value) != 0:
if 'deprecated' in q:
q = re_deprecated.sub('deprecated:1', q)
else:
q += " deprecated:1"
else: # default deprecated:0
q = re_deprecated.sub('',q)
if verbose:
q += " deprecated:0"
elif param == 'kind':
if 'kind:' in q:
q = re_kind.sub("kind:"+value,q)
else:
q += " kind:"+value
if not verbose:
q = q.replace('kind:CRS','') # default
elif param in q:
q = re.sub(param+r':(\S+)',param+":"+str(value), q)
else:
q += " "+param+":"+str(value)
if value == '': # remove param if value is empty
q = q.replace(param+":", q)
return re.sub(r'\s+',' ', q).strip()
def jsonResponse(json_str, callback, status = 'ok', error_type = ''):
if status == 'error':
json_tmp = {}
json_tmp['message'] = json_str
json_tmp['error_type'] = error_type
json_str = json_tmp
json_str['status'] = status
if callback:
resp = '{}({})'.format(callback, json.dumps(json_str))
return Response(resp, mimetype='application/javascript')
else:
return Response(json.dumps(json_str), mimetype='application/json')
class WKTLexer(RegexLexer):
name = 'wkt'
aliases = ['wkt']
filenames = ['*.wkt']
tokens = {
'root': [
(r'\s+', Text),
(r'[{}\[\]();,-.]+', Punctuation),
(r'(PROJCS)\b', Generic.Heading),
(r'(PARAMETER|PROJECTION|SPHEROID|DATUM|GEOGCS|AXIS)\b', Keyword),
(r'(PRIMEM|UNIT|TOWGS84)\b', Keyword.Constant),
(r'(AUTHORITY)\b', Name.Builtin),
(r'[$a-zA-Z_][a-zA-Z0-9_]*', Name.Other),
(r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
(r'0x[0-9a-fA-F]+', Number.Hex),
(r'[0-9]+', Number.Integer),
(r'"(\\\\|\\"|[^"])*"', String.Double),
(r"'(\\\\|\\'|[^'])*'", String.Single),
]
}
class XmlLexer(RegexLexer):
"""
Generic lexer for XML (eXtensible Markup Language).
"""
flags = re.MULTILINE | re.DOTALL | re.UNICODE
name = 'XML'
aliases = ['xml']
filenames = ['*.xml', '*.xsl', '*.rss', '*.xslt', '*.xsd', '*.wsdl']
mimetypes = ['text/xml', 'application/xml', 'image/svg+xml',
'application/rss+xml', 'application/atom+xml']
tokens = {
'root': [
('[^<&]+', Text),
(r'&\S*?;', Name.Entity),
(r'\<\!\[CDATA\[.*?\]\]\>', Comment.Preproc),
('<!--', Comment, 'comment'),
(r'<\?.*?\?>', Comment.Preproc),
('<![^>]*>', Comment.Preproc),
(r'<\s*[\w:.-]+', Name.Tag, 'tag'),
(r'<\s*/\s*[\w:.-]+\s*>', Name.Tag),
],
'comment': [
('[^-]+', Comment),
('-->', Comment, '#pop'),
('-', Comment),
],
'tag': [
(r'\s+', Text),
(r'[\w.:-]+\s*=', Name.Attribute, 'attr'),
(r'/?\s*>', Name.Tag, '#pop'),
],
'attr': [
('\s+', Text),
('".*?"', String, '#pop'),
("'.*?'", String, '#pop'),
(r'[^\s>]+', String, '#pop'),
],
}
def area_to_url(area):
if area.rfind("-"):
qarea = area.split(" -")[:1]
elif area.rfind(";"):
qarea = area.split(";")
else:
qarea = area
if area.startswith("World"):
qarea = ["World",]
url = "/?q=" + urllib.quote_plus(qarea[0].encode('utf-8'))
return url
def get_static_map_url(center, g_coords):
if center != "" and g_coords != "":
url_static = "https://api.maptiler.com/maps/streets/static/auto/[email protected]?key=qrAJy6x3Ck8n4XFFH4PS&latlng=1&fill=rgba(255,0,0,0.15)&stroke=red&width=2&path=" + g_coords
# + "&markers=" +str(center[0])+","+str(center[1])
return urllib2.quote(url_static), url_static
else:
return ("","")
@app.route('/',methods=['GET'])
def index():
## Front page without parameters
if 'q' not in request.args:
#print len(request.GET.keys())
return render_template('index.html', version=VERSION)
## Search API
ix = open_dir(INDEX, readonly=True)
result = []
ref = osr.SpatialReference()
with ix.searcher(closereader=False) as searcher:
parser = MultifieldParser(["code","name","kind","area","area_trans","alt_title"], ix.schema)
query = request.args.get('q') # p43 - 1.9 The default query language
pagenum = int(request.args.get("page",1))
format = request.args.get('format',0)
callback = request.args.get('callback',False)
expanded_trans = request.args.get('trans',False)
if query == None:
return render_template('./templates/index',version=VERSION)
kind = getQueryParam(query, 'kind')
deprecated = getQueryParam(query, 'deprecated')
# for count inverse deprecated (if it display valid, show me a number of deprecated records)
statquery = setQueryParam(query, 'deprecated', not deprecated,True)
url_facet_statquery ="/?q=" + urllib2.quote(statquery)
# and through all kinds
#statquery = setQueryParam(statquery,'kind','*')
# show query in all kinds
#catquery = setQueryParam(query,'kind','*')
#mycatquery = parser.parse(getVerboseQuery(catquery))
#mystatquery = parser.parse(getVerboseQuery(statquery))
# delele kind and deprecated and "*" from query
query = query.replace("*","")
base_query_kind = re.sub("kind"+r':(\S+)',"", query)
base_query_kind_deprecated = re.sub("deprecated"+r':(\S+)',"", base_query_kind)
if base_query_kind_deprecated == "" or base_query_kind_deprecated == " ":
facet_query = Every()
else:
facet_query = parser.parse(base_query_kind_deprecated)
# parse and prepare for search
myquery = parser.parse(getVerboseQuery(query))
start = time.clock()
# result of query
results = searcher.search(myquery, limit = None) #(pagenum*pagelen)
# how many document include query in each kind
res_facets = searcher.search(facet_query, groupedby="kind", scored=False, sortedby=None, maptype=sorting.Count)
# "search in" number
elapsed = (time.clock() - start)
# kind and count of result from catquery
groups = res_facets.groups("kind")
# number of results on one page. If change number, edit "paging"
pagelen = 10
# last document from result on page
maxdoc = pagelen*pagenum
json_str = []
short_code = 0
codes = []
for r in results[(maxdoc-pagelen):maxdoc]:
#print r.score, r['code']
link = str(r['code'])
short_code = r['code'].split("-")
name = r['name']
type_epsg = "EPSG"
if r['information_source'] == "ESRI":
name = r['name'].replace("ESRI: ","").strip()
type_epsg = "ESRI"
if r['area'].startswith("World"):
short_area = "World"
else:
short_area = r['area']
if r['area_trans'].startswith("World"):
short_area = "World"
elif r['area_trans']:
short_area = r['area_trans']
if len(short_area) > 100:
short_area = short_area.split("-", 2)[0]
wkt = ""
if r['kind'].startswith("CRS"):
ref.ImportFromEPSG(int(short_code[0]))
wkt = ref.ExportToWkt()
result.append({'r':r, 'name':name, 'type_epsg':type_epsg, 'link':link, 'area':short_area, 'short_code':short_code})
if not expanded_trans and format == "json":
proj4 = ref.ExportToProj4().strip()
#proj4js = '%s["%s:%s"] = "%s";' % ("Proj4js.defs", type_epsg, short_code[0], proj4)
json_str.append({'code':r['code'], 'name':name, 'wkt':wkt,'proj4':proj4,'default_trans':r['code_trans'],'trans':r['trans'],'area':r['area'],'accuracy':r['accuracy'],'kind':r['kind'], 'bbox':r['bbox'], 'unit':r['uom']})
elif expanded_trans and format == "json":
for trans_codes in r['trans']:
if int(trans_codes) not in codes:
codes.append(trans_codes)
# number of results from results
num_results = len(results)
num_kind = len(res_facets)
# paging ala google
pagemax = int(math.ceil(num_results / float(pagelen) ))
paging = range(1, pagemax+1)[ max(0, pagenum-6) : (pagenum+4 if pagenum >= 10 else min(10,pagemax))]
# set all facets_list counts to zero
for i in range(0,len(facets_list)):
facets_list[i][4] = 0
#make null index of chose kind
query_kind_index = None
# title, h1
dep_found = False
q = re.sub(r'kind:\S+',"",query)
if "deprecated:1" in q: dep_found = True
q = re.sub(r'deprecated:\d',"",q)
q = q.strip()
kind_low = kind.lower()
# more then values in facets_list for condition if exist (selected_kind_index can be 0-30)
selected_kind_index = 77
if num_kind != 0:
title = "Searching for "+ '"'+ q +'"'
for i in range(0,len(facets_list)):
if kind == facets_list[i][1]:
selected_kind_index = i
if kind == "AXIS":
title = "Axes"
break
kind_low = facets_list[i][6].lower()
if q == "":
title = facets_list[i][6] +"s"
if dep_found == True: title = "Deprecated " + kind_low + "s"
else:
title = facets_list[i][6] +"s for "+'"'+q+'"'
if dep_found == True: title = "Deprecated " + kind_low +"s for "+'"'+q+'"'
else:
title = '"'+ q +'"' + " is not in EPSG.io"
kind_low = q,kind_low
# update facets counters
show_alt_search = False
for key,value in groups.iteritems():
if value>0:
show_alt_search = True
# standard kinds
for i in range(0,len(facets_list)):
if facets_list[i][0] == key:
facets_list[i][4] = int(value)
catquery = setQueryParam(base_query_kind, 'kind', facets_list[i][1])
facets_list[i][5] = "/?q=" + urllib2.quote(catquery)
# index of chose kind
if kind == facets_list[i][1]:
query_kind_index = i
# sum special kinds
if key.startswith('CRS-'):
facets_list[f_crs_index][4] += int(value)
catquery = setQueryParam(base_query_kind, 'kind', facets_list[f_crs_index][1])
facets_list[f_crs_index][5] = "/?q=" + urllib2.quote(catquery)
if key.startswith('DATUM-'):
facets_list[f_datum_index][4] += int(value)
catquery = setQueryParam(base_query_kind, 'kind', facets_list[f_datum_index][1])
facets_list[f_datum_index][5] = "/?q=" + urllib2.quote(catquery)
if key.startswith('CS-'):
facets_list[f_cs_index][4] += int(value)
catquery = setQueryParam(base_query_kind, 'kind', facets_list[f_cs_index][1])
facets_list[f_cs_index][5] = "/?q=" + urllib2.quote(catquery)
if key.startswith('UNIT-'):
facets_list[f_unit_index][4] += int(value)
catquery = setQueryParam(base_query_kind, 'kind', facets_list[f_unit_index][1])
facets_list[f_unit_index][5] = "/?q=" + urllib2.quote(catquery)
if key.startswith('COORDOP-'):
facets_list[f_op_index][4] += int(value)
catquery = setQueryParam(base_query_kind, 'kind', facets_list[f_op_index][1])
facets_list[f_op_index][5] = "/?q=" + urllib2.quote(catquery)
# show a clear query (e.g. without kind:CRS, deprecated:0)
query = setQueryParam(query,'kind',kind)
query = setQueryParam(query,'deprecated',deprecated)
num_deprecated = 0,url_facet_statquery
# condition for selected_kind_index have to be lower then initial number
if num_kind != 0 and selected_kind_index<77:
num_deprecated = abs(num_results - facets_list[selected_kind_index][4]),url_facet_statquery
export = {}
if str(format) == "json":
if expanded_trans:
wkt = ""
proj4 = ""
wkt_parent = ""
proj4_parent = ""
json_str = []
parser = MultifieldParser(["code","kind"], ix.schema)
trans_query = ""
for c in codes:
trans_query = trans_query +"code:"+str(c)+" OR "
myquery = parser.parse(trans_query + " AND kind:COORDOP")
transformation = searcher.search(myquery, limit=None)
code_with_bbox = {}
for r in results[(maxdoc-pagelen):maxdoc]:
short_code = r['code'].split("-")
ref.ImportFromEPSG(int(short_code[0]))
wkt_parent = ref.ExportToWkt()
proj4_parent = ref.ExportToProj4().strip()
for hit in transformation:
values = hit['description']
if not re.findall(r'([a-df-zA-Z_])',values):
if str(values) != str('(0,)'):
num = []
w = re.findall(r'(-?\d*\.\d*[e]?-?\d*)',values)
for n in w:
num.append(float(n))
values = tuple(num)
# do not change default TOWGS84
if int(hit['code_trans']) != int(hit['code']) :
if (values != (0.0,0.0,0.0,0.0,0.0,0.0,0.0) and type(values) == tuple and values != (0,) and values != ()):
ref.ImportFromEPSG(int(short_code[0]))
ref.SetTOWGS84(*values)
wkt = ref.ExportToWkt().decode('utf-8')
proj4 = ref.ExportToProj4().strip()
code_with_bbox[int(hit['code'])] = hit,wkt,proj4
#proj4js = '%s["%s:%s"] = "%s";' % ("Proj4js.defs", type_epsg, short_code[0], proj4)
json_bbox = []
if r['trans']:
for item in r['trans']:
json_bbox.append({'code_trans':item, 'bbox': code_with_bbox[item][0]['bbox'],'name': code_with_bbox[item][0]['name'],'accuracy': code_with_bbox[item][0]['accuracy'],'wkt':code_with_bbox[item][1], 'proj4':code_with_bbox[item][2],'area':code_with_bbox[item][0]['area'],'unit':r['uom']})
json_str.append({'code':r['code'], 'name':r['name'], 'wkt':wkt_parent,'proj4':proj4_parent,'default_trans':r['code_trans'],'accuracy':r['accuracy'],'kind':r['kind'], 'trans':json_bbox,'area':r['area'],'bbox':r['bbox'],'unit':r['uom']})
export['number_result']= num_results
export['results'] = json_str
return jsonResponse(export, callback)
return render_template('results.html', selected_kind_index=selected_kind_index, num_deprecated=num_deprecated, show_alt_search=show_alt_search, kind_low=kind_low, num_kind=num_kind, short_code=short_code, title=title, query=query, deprecated=deprecated, num_results=num_results, elapsed=elapsed, facets_list=facets_list, url_facet_statquery=url_facet_statquery, result=result, pagenum=int(pagenum),paging=paging, version=VERSION)
# links for coordinate system and for transformations, e.g. https://epsg.io/5514 and https://epsg.io/5514-1623
@app.route('/<int:id>')
@app.route('/<int:id>-<int:code>') # :re:[\d]+(-[\d]+)?
def index2(id,code=''):
# reconstruct full id with or without "code"
if code != '':
id = str(id) + '-' + str(code)
else:
id = str(id)
ref = osr.SpatialReference()
ix = open_dir(INDEX, readonly=True)
url_social = id
with ix.searcher(closereader=False) as searcher:
parser = MultifieldParser(["code","code_trans"], ix.schema)
code, code_trans = (id+'-0').split('-')[:2]
query = "code:" + code + " kind:CRS OR kind:COORDOP" #1068-datum, 1068-area,1068 (transformation)
myquery = parser.parse(query)
results = searcher.search(myquery, limit=None) #default limit is 10 , reverse = True
# For no result, better error message
if len(results) == 0:
error = 404
try_url= ""
return render_template('error.html', error=error, try_url=try_url, version=VERSION)
detail = []
trans_unsorted = []
trans = []
url_trans = []
trans_item = []
num_results = 0
# item = None
#wkt = None
default_trans = ""
url_method = ""
url_format = ""
export = ""
export_html = ""
url_area_trans = ""
# url_area = ""
g_coords = ""
center = 0,0
trans_lat = ""
trans_lon = ""
# title = ""
nadgrid = None
gcrs_code = ""
deprecated_available = 0
bbox_coords = ""
for r in results:
found = False
item = r
code_short = item['code'].split("-")
name = item['name']
type_epsg = "EPSG"
a = ref.ImportFromEPSG(int(code_short[0]))
if a == 0:
wkt = ref.ExportToWkt()
else:
wkt = ""
if item['information_source'] == "ESRI":
name = item['name'].replace("ESRI: ","").strip()
type_epsg = "ESRI"
if a != 0:
a = ref.ImportFromProj4(str(item['description']))
if a != 0:
alt_description = item['description']
else:
ref.ExportToWkt()
ref.SetProjCS(name.replace(" ", "_"))
ref.SetAuthority("PROJCS","EPSG",int(code))
ref.ExportToPrettyWkt()
alt_description = str(ref).decode('utf-8')
elif a == 0:
wkt = ref.ExportToWkt().decode('utf-8')
title = item['kind'] + ":" + item['code']
url_area = area_to_url(item['area'])
for i in range(0,len(facets_list)):
if facets_list[i][0] == item['kind']:
kind = facets_list[i][6]
url_kind = "/?q=kind:" + facets_list[i][1]
area_item = item['area']
area_trans_item = item['area_trans']
if item['area'].startswith("World:"):
area_item = "World"
if item['area_trans'].startswith("World:"):
area_trans_item = "World"
if len(area_trans_item) > 100:
if ":" in area_trans_item:
area_trans_item = area_trans_item.split(":", 1)[0]
elif "-" in area_trans_item:
area_trans_item = area_trans_item.split("-", 2)[0]
# for short link (5514, instead of 5514-15965)
if int(code_trans) == 0 and int(r['code_trans']) != 0:
code_trans = r['code_trans']
#if it default transformation code or has some other transformations
if int(code_trans) != 0 or r['trans']:
# it is at least one code of transformation (min. defalut trans. code)
for code_transformation in r['trans']:
parser = MultifieldParser(["code","kind"], ix.schema)
query = "code:"+str(code_transformation)+ " kind:COORDOP"
myquery = parser.parse(query)
transformation = searcher.search(myquery, limit=None)
for hit in transformation:
trans_item.append(hit)
# if it active do not show a link
if int(hit['code']) == int(code_trans):
link = ""
else:
link = str(r['code']) + u"-" + str(hit['code'])
# if exist default trans code
default = False
if int(r['code_trans'])== int(hit['code']):
default = True
try:
values = tuple(map(float, hit['description'][1:-1].split(',')))
except:
values = hit['description']
num_param = ""
if values[3:7] == (0,0,0,0) or values == (0,0,0,0,0,0,0):
num_param = 3
elif type(values) != tuple and str(values) != "0":
num_param = 'grid'
elif str(values) == '0':
num_param = ""
else:
num_param = 7
area_trans_trans = hit['area']
if item['area'].startswith("World:"):
area_trans_trans = "World"
if len(area_trans_trans) > 50:
if ":" in area_trans_trans:
area_trans_trans = area_trans_trans.split(":", 1)[0]
elif "-" in area_trans_trans:
area_trans_trans = area_trans_trans.split("-", 2)[0]
# if exist some deprecated transformations
if hit['deprecated'] == 1:
deprecated_available = 1
# safe the main information about each transformation
trans_unsorted.append({
'link':link,
'code':hit['code'],
'deprecated':hit['deprecated'],
'area_trans':hit['area'],
'accuracy':hit['accuracy'],
'code_trans':hit['code'],
'trans_remarks':hit['remarks'],
'default':default,
'area_trans_trans':area_trans_trans,
'num_param':num_param })
trans = sorted(trans_unsorted, key=lambda k: k['area_trans'])
# if it has NOT default transformation code
else:
ref.ImportFromEPSG(int(r['code']))
if ref.GetTOWGS84() != None:
found = True
default_trans = item
# if it has any transformation
if found == False and item['bbox']:
# default trans is active transformation
found_dt = False
for i in range(0,len(trans_item)):
if str(code_trans) == str(trans_item[i]['code']):
default_trans = trans_item[i]
found_dt = True
#elif int(code_trans) != int(trans_item[i]['code']) and not found_dt:
# default_trans = trans_item[0]
if trans_item and default_trans:
# from values of TOWGS84 edit wkt of CRS
values = default_trans['description']
if re.findall(r'([a-df-zA-Z_])',values):
nadgrid = default_trans['description']
elif str(values) != "(0,)":
#values = tuple(map(float, values[1:-1].split(',')))
num = []
w = re.findall(r'(-?\d*\.\d*[e]?-?\d*)',values)
for n in w:
num.append(float(n))
values = tuple(num)
# do not change default TOWGS84
if int(r['code_trans']) != int(default_trans['code']) :
if (values != (0.0,0.0,0.0,0.0,0.0,0.0,0.0) and type(values) == tuple and values != (0,) and values != ()):
ref.ImportFromEPSG(int(r['code']))
ref.SetTOWGS84(*values)
wkt = ref.ExportToWkt().decode('utf-8')
# if do not have trans_item or default_trans
else:
n, w, s, e = item['bbox']
if n == 90.0: n = 85.0
if w == -180.0: w = -179.9
if s == -90.0: s = -85.0
if e == 180.0: e = 179.9
#(51.05, 12.09, 47.74, 22.56)
center = (n-s)/2.0 + s, (e-w)/2.0 + w
if (e < w):
center = (n-s)/2.0+s, (w+180 + (360-(w+180)+e+180) / 2.0 ) % 360-180
if n == 85.0 and w == -179.9 and s == -85.0 and e == 179.9:
g_coords = "-85,-179.9|85,-179.9|85,0|85,179.9|-85,179.9|-85,0|-85,-179.9"
else:
g_coords = str(s) + "," + str(w) + "|" + str(n) + "," + str(w) + "|" + str(n) + "," + str(e) + "|" + str(s) + "," + str(e) + "|" + str(s) + "," + str(w)
# if it CRS (not transformation)
if str(item['kind']).startswith('CRS'):
url_format = "/"+str(item['code'])
if wkt:
if default_trans:
# if the actual transformation is different code then basic transformation and basic transformation is not 0 (geodetic systems hasnt got any transformation (4326 - not showing link 4326-4326))
if int(default_trans['code']) != int(item['code_trans']) and int(item['code_trans']) != 0:
url_format = "/"+str(item['code'])+"-"+str(default_trans['code'])
elif str(item['kind']).startswith('COORDOP'):
url_format = "/"+str(item['code'])
# for activated transformation
if default_trans:
#if default_trans['method']:
# url_method ="/?q=" + urllib.quote_plus((default_trans['method'][0]+ ' kind:METHOD').encode('utf-8'))
url_area_trans = area_to_url(default_trans['area'])
center = ""
g_coords = ""
if default_trans['bbox']:
n, w, s, e = default_trans['bbox']
if n == 90.0: n = 85.0
if w == -180.0: w = -179.9
if s == -90.0: s = -85.0
if e == 180.0: e = 179.9
#(51.05, 12.09, 47.74, 22.56)
center = (n-s)/2.0 + s, (e-w)/2.0 + w
if (e < w):
center = (n-s)/2.0+s, (w+180 + (360-(w+180)+e+180) / 2.0 ) % 360-180
if (n == 85.0 and w == -179.9 and s == -85.0 and e == 179.9) or item['code'] == "3857":
g_coords = "-85,-179.9|85,-179.9|85,0|85,179.9|-85,179.9|-85,0|-85,-179.9"
else:
g_coords = str(s) + "," + str(w) + "|" + str(n) + "," + str(w) + "|" + str(n) + "," + str(e) + "|" + str(s) + "," + str(e) + "|" + str(s) + "," + str(w)
url_static_map = get_static_map_url(center, g_coords)
ogpxml = ""
if item['kind'].startswith("CRS"):
urn = "urn:ogc:def:crs:EPSG::"+code
cur.execute('SELECT id,xml FROM gml where urn = ?', (urn,))
gml = cur.fetchall()
for id,xml in gml:
ogpxml = '<?xml version="1.0" encoding="UTF-8"?>\n %s' % (xml)
elif item['kind'].startswith("COORDOP"):
urn = "urn:ogc:def:coordinateOperation:EPSG::" + code
cur.execute('SELECT id,xml FROM gml where urn = ?', (urn,))
gml = cur.fetchall()
for id,xml in gml:
ogpxml = '<?xml version="1.0" encoding="UTF-8"?>\n %s' % (xml)
ogpxml_highlight = highlight(ogpxml, XmlLexer(), HtmlFormatter(cssclass='syntax',nobackground=True))
# explicit coding of xml(gml) - https://epsg.io/2056
ogpxml = ogpxml.decode('utf-8')
# if available wkt, default_trans and wkt has length minimum 100 characters (transformation has length maximum 100 (just a TOWGS84))
error_code = 9
xml_highlight = ""
if wkt:
trans_coords = ""
error_code = ref.ImportFromEPSG(int(item['code']))
export = {}
ref.ImportFromWkt(wkt)
export['prettywkt'] = ref.ExportToPrettyWkt()
if int(error_code) == 0:
export['usgs'] = str(ref.ExportToUSGS())
if "(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)" in export['usgs']:
export['usgs'] = ""
export['ogcwkt'] = ref.ExportToWkt()
export['proj4'] = ref.ExportToProj4()
export['html'] = highlight(ref.ExportToPrettyWkt(), WKTLexer(), HtmlFormatter(cssclass='syntax',nobackground=True))
#if correct export, then it is string, if error then return 7
if ref.ExportToXML() != 7 :
export['xml'] = '<?xml version="1.0" encoding="UTF-8"?>\n %s' % (ref.ExportToXML().replace(">",' xmlns:gml="http://www.opengis.net/gml/3.2">',1))
xml_highlight = highlight(export['xml'], XmlLexer(), HtmlFormatter(cssclass='syntax',nobackground=True))
else:
export['xml'] = ""
xml_highlight = "NOT AVAILABLE"
export['mapfile'] = 'PROJECTION\n\t'+'\n\t'.join(['"'+l.lstrip('+')+'"' for l in ref.ExportToProj4().split()])+'\nEND' ### CSS: white-space: pre-wrap
proj4 = ref.ExportToProj4().strip()
export['proj4js'] = '%s("%s:%s","%s");' % ("proj4.defs", type_epsg, code, proj4)
export['mapnik'] = '<?xml version="1.0" encoding="utf-8"?>\n<Map srs="%s">\n\t<Layer srs="%s">\n\t</Layer>\n</Map>' % (proj4,proj4)
export['mapserverpython'] = "wkt = '''%s'''\nm = mapObj('')\nm.setWKTProjection(ref.ExportToWkt())\nlyr = layerObj(m)\nlyr.setWKTProjection(ref.ExportToWkt())" % (ref.ExportToWkt()) #from mapscript import mapObj,layerObj\n
export['mapnikpython'] = "proj4 = '%s'\nm = Map(256,256,proj4)\nlyr = Layer('Name',proj4)" % (proj4) #from mapnik import Map, Layer\n
export['geoserver'] = "%s=%s" % (code,ref.ExportToWkt()) # put this custom projection in the 'user_projections' file inside the GEOSERVER_DATA_DIR '\n' # You can further work with your projections via the web admin tool.\n
export['postgis'] = 'INSERT into spatial_ref_sys (srid, auth_name, auth_srid, proj4text, srtext) values ( %s, \'%s\', %s, \'%s\', \'%s\');' % (item['code'], type_epsg, item['code'], ref.ExportToProj4(), ref.ExportToWkt())
# if ref.IsGeographic():
# code = ref.GetAuthorityCode("GEOGCS")
# else:
# code = ref.GetAuthorityCode("PROJCS")
# export_json = {}
# if code:
# export_json['type'] = 'EPSG'
# export_json['properties'] = {'code':code}
# export['json'] = export_json
if item['code'] == "3857":
wkt_3857 = 'PROJCS["WGS_1984_Web_Mercator_Auxiliary_Sphere",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Mercator_Auxiliary_Sphere"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",0.0],PARAMETER["Standard_Parallel_1",0.0],PARAMETER["Auxiliary_Sphere_Type",0.0],UNIT["Meter",1.0],AUTHORITY["EPSG",3857]]'
ref.SetFromUserInput(wkt_3857)
ref.MorphToESRI()
export['esriwkt'] = ref.ExportToWkt()
if item['bbox']:
ref.ImportFromWkt(wkt.encode('utf-8'))
wgs = osr.SpatialReference()
wgs.ImportFromEPSG(4326)
xform = osr.CoordinateTransformation(wgs,ref)
try:
trans_coords_orig = xform.TransformPoint(center[1],center[0]) #5514 - 49.3949, 17.325
#transform the bouding box coords (if have default trans, this will be a default tran else from crs)
bbox_coords_orig1 = xform.TransformPoint(e,n)
bbox_coords_orig2 = xform.TransformPoint(w,s)
if type(trans_coords_orig[0]) != float:
trans_lat = "%s" % trans_coords_orig[0]
trans_lon = "%s" % trans_coords_orig[1]
bbox_lat1 = "%s" % bbox_coords_orig1[0]
bbox_lon1 = "%s" % bbox_coords_orig1[1]
bbox_lat2 = "%s" % bbox_coords_orig2[0]
bbox_lon2 = "%s" % bbox_coords_orig2[1]
elif ref.GetAuthorityCode('UNIT') == str(9001):
trans_lat = "%.2f" % trans_coords_orig[0]
trans_lon = "%.2f" % trans_coords_orig[1]
bbox_lat1 = "%.2f" % bbox_coords_orig1[0]
bbox_lon1 = "%.2f" % bbox_coords_orig1[1]
bbox_lat2 = "%.2f" % bbox_coords_orig2[0]
bbox_lon2 = "%.2f" % bbox_coords_orig2[1]
else:
trans_lat = "%.8f" % trans_coords_orig[0]
trans_lon = "%.8f" % trans_coords_orig[1]
bbox_lat1 = "%.8f" % bbox_coords_orig1[0]
bbox_lon1 = "%.8f" % bbox_coords_orig1[1]
bbox_lat2 = "%.8f" % bbox_coords_orig2[0]
bbox_lon2 = "%.8f" % bbox_coords_orig2[1]
except:
trans_lat = ""
trans_lon = ""
bbox_lat1 = ""
bbox_lon1 = ""
bbox_lat2 = ""
bbox_lon2 = ""
bbox_coords = (bbox_lon1, bbox_lat1, bbox_lon2, bbox_lat2) #n,e,s,w
# color html of pretty wkt
ref.ImportFromWkt(wkt)
export_html = highlight(ref.ExportToPrettyWkt(), WKTLexer(), HtmlFormatter(cssclass='syntax',nobackground=True))
if 'alt_description' in item and (item['information_source'] == "ESRI" or item['information_source'] == "other") and export_html == "" and error_code != 0:
export_html = highlight(item['alt_description'], WKTLexer(), HtmlFormatter(cssclass='syntax',nobackground=True))
# if the CRS its concatenated
url_concatop=[]
found_concatop = False
if 'concatop' in item:
if item['concatop']:
for i in range(0,len(item['concatop'])):
url_concatop.append(str(item['concatop'][i]))
elif default_trans:
for i in range(0,len(default_trans['concatop'])):
url_concatop.append(str(default_trans['concatop'][i]))
alt_title = ""
if 'alt_title' in item:
if item['alt_title']:
alt_title = item['alt_title']
gcrs_code = 0
if item['geogcrs']:
gcrs_code = str(item['geogcrs'][0])
projcrs_by_gcrs = []
more_gcrs_result = ""
if gcrs_code and not item['kind'].startswith('COORDOP'):
with ix.searcher(closereader=False) as searcher:
parser = MultifieldParser(["geogcrs"], ix.schema)
gcrs_query = parser.parse(gcrs_code + " kind:PROJCRS" + " deprecated:0")
gcrs_result = searcher.search(gcrs_query, limit=5)
if len(gcrs_result) >5:
more_gcrs_result = "/?q=geogcrs:"+gcrs_code+" kind:PROJCRS deprecated:0"
for gcrs_item in gcrs_result:
# do not append if find yourself
if gcrs_item['code'] != item['code']:
projcrs_by_gcrs.append({'result': gcrs_item})
if item['kind'].startswith('COORDOP'):
with ix.searcher(closereader=False) as searcher:
parser = QueryParser("trans", ix.schema)
gcrs_query = parser.parse(code + " kind:PROJCRS" + " deprecated:0")
gcrs_result = searcher.search(gcrs_query, limit=5)
if len(gcrs_result) >5:
more_gcrs_result = "/?q=trans:"+code+" kind:PROJCRS deprecated:0"
if gcrs_result:
for gcrs_item in gcrs_result:
projcrs_by_gcrs.append({'result': gcrs_item})
else:
parser = QueryParser("geogcrs", ix.schema)
gcrs_query = parser.parse(str(gcrs_code) + " kind:PROJCRS" + " deprecated:0")
gcrs_result = searcher.search(gcrs_query, limit=5)
if len(gcrs_result) >5:
more_gcrs_result = "/?q=geogcrs:"+str(gcrs_code)+" kind:PROJCRS deprecated:0"
for gcrs_item in gcrs_result:
projcrs_by_gcrs.append({'result': gcrs_item})
# greenwich longitude is corrected by import from gml
# greenwich_longitude = 361
# 8903-primem - Paris is correct
# if str(item['greenwich_longitude']) != str(2.5969213):
# toDegree = re.compile(r'(-?)(\d+)(\.?)(\d{0,2})(\d{2})?(\d+)?')
# a = toDegree.search(str(item['greenwich_longitude']))
# if a:
# sign = a.group(1)
# if sign == None:
# sign = "+"
# degree = a.group(2)
# minutes = a.group(4)
# if minutes == None or minutes == "":
# minutes = 0
# if len(str(minutes)) == 1:
# minutes = float(minutes) * 10
# seconds = a.group(5)
# if seconds == None: seconds = 0
# frac_seconds = a.group(6)
# if frac_seconds == None: frac_seconds = 0
# result = (float(minutes)/60)+ (float(str(seconds)+"."+str(frac_seconds))/3600)
# result = float(degree)+float(result)
# greenwich_longitude = str(sign) + str(result)
# else:
greenwich_longitude = item['greenwich_longitude']
return render_template('detail.html',greenwich_longitude=greenwich_longitude, url_social=url_social, url_static_map=url_static_map, ogpxml_highlight=ogpxml_highlight, xml_highlight=xml_highlight, area_trans_item=area_trans_item, ogpxml=ogpxml, bbox_coords=bbox_coords, more_gcrs_result=more_gcrs_result, deprecated_available=deprecated_available, url_kind=url_kind, type_epsg=type_epsg, name=name, projcrs_by_gcrs=projcrs_by_gcrs, kind=kind, alt_title=alt_title, area_item=area_item, code_short=code_short, item=item, trans=trans, default_trans=default_trans, num_results=num_results, url_method=url_method, title=title, url_format=url_format, export_html=export_html, url_area_trans=url_area_trans, url_area=url_area, center=center, g_coords=g_coords, trans_lat=trans_lat, trans_lon=trans_lon, wkt=wkt, facets_list=facets_list,url_concatop=url_concatop, nadgrid=nadgrid, detail=detail,export=export, error_code=error_code, version=VERSION)
# links for NOT crs or trans. e.g. https://epsg.io/9315-datum; https://epsg.io/8901-primem
# https://github.com/maptiler/epsg.io#types-of-urls - other codes with suffix
@app.route('/<int:id>-<string:code>') # :re:[\d]+(-[a-zA-Z]+)
def index3(id, code):
# reconstruct full id
id = str(id) + '-' + code
url_social = id
ix = open_dir(INDEX, readonly=True)
with ix.searcher(closereader=False) as searcher:
parser = QueryParser("code", ix.schema)
myquery = parser.parse(id)
results = searcher.search(myquery)
url_axis = []
detail = []
url_uom = ""
url_children = ""
url_prime = ""