-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebConnector.py
1277 lines (1026 loc) · 47 KB
/
webConnector.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
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 30 15:51:54 2018
@author: s_jan001
"""
import shutil
from docutils.nodes import image
from flask import Flask, render_template, request, redirect, url_for
from matcher.matching_preprocessor import compute_similarity_matrix
from matcher.adp_map_alignment_alternating import ADPMatcher
from matcher.test_eigen2 import SpecCenScore
# from qualifier import qualify_map
from matcher.map_loader import load_map_qualify, read_map_data_from_path, read_map_data_from_string
from matcher.geojson import load_map as load_geo
from matcher.svg import load_map as load_svg
from sklearn.linear_model import LinearRegression as linear_regression
from sklearn.preprocessing import PolynomialFeatures as polynomial_features
import cv2
import numpy as np
import io
import json
import os
import sys
from settings import USER_SESSIONS_DIR,DIR_DATA, DIR_QCNS, RecordList, PnS_PROJ_ID, SMARTSKEMA_PATH, QUALITATIVE_REPRESENTATION
#SketchMapName, BaseMapName
# STATIC_DIR,UPLOADED_DIR_PATH,PROJ_DIR_PATH,MODIF_DIR_PATH,OUTPUT_DIR_PATH,SVG_DIR_PATH,UUID
import logging
from logging.handlers import RotatingFileHandler
from matplotlib import pyplot as plt
import base64
from lib import svg2paths
from pathlib import Path
from sketchProcessor.helperLibraries.utils import draw
from sketchProcessor.helperLibraries.utils import contour_classification as cc
import svgutils
from owlready2 import *
import owlready2
from domainModel.owlProcessor import *
import datetime
from domainModel.spatialQueries import *
import matplotlib as plot
import mimetypes
from time import sleep
import uuid
import base64
import io
import shapely
import urllib.request
from shapely.geometry import Polygon,LinearRing
from geometryVisualizer import config
from geometryVisualizer.left_right_tiles import GLeftRightTiles as g_left_right_tiles
from geometryVisualizer.rcc_tiles import GRccTiles as g_rcc_tiles
from geometryVisualizer.reldist_tiles import GRelDistTiles as g_reldist_tiles
from geometryVisualizer.tessellations import Tessellations as tessellation
from geometryVisualizer.tiles_to_geoJson import *
import requests
from platform_PnS.platform_PnS import*
#sys.setrecursionlimit(22000)
"""
create flask web app instance
"""
mimetypes.add_type('image/svg+xml', '.svg')
DEBUG_SESSID = "39bb2657-d663-4a78-99c5-a66c152693b2"
#STATIC_DIR = os.path.join("./static", "usessions")
UPLOADED_DIR_PATH = "uploaded"
MODIF_DIR_PATH = "modified"
OUTPUT_DIR_PATH = "output"
# probably delete this
#SVG_DIR_PATH = "svg"
INPUT_RASTER_SKETCH = "input_sketch_image.png"
REDUCED_RASTER_SKETCH = "reduced_sketch_image.png"
VECTORIZED_SKETCH = "vectorized_sketch_svg.svg"
VECTOR_BASEMAP = "vector_base_map.geojson"
GEOREFERENCED_SKETCH_FEATURES = "georeferenced_sketch_features.json"
MATCHED_FEATURES = "matches.json"
SKETCH_MAP_QCN = "sketchmap_qcn.json"
BASEMAP_QCN = "basemap_qcn.json"
PARTIES_FILE = "parties.json"
LADM_FILE = "ladm.owl"
TENURE_RECORD_FILE = "tenureRecord.json"
APROX_TILE = "approx_tile_file.geojson"
INPUT_RASTER_COMPLEX_SKETCH = "input_complex_sketch_image.png"
REDUCED_RASTER_COMPLEX_SKETCH = "reduced_complex_sketch_image.png"
ALIGNED_RESULT = "alignedResult.json"
app = Flask(__name__)
"""
This belongs to the utils modules but is here for quickly constructing directory/file paths from path lists
"""
def build_path(path_list):
return os.path.join(*path_list)
def path_to_project(d):
global USER_SESSIONS_DIR
global PnS_PROJ_ID
PnS_PROJ_ID = d.get("sessID")
#print("pathto project p an s id",PnS_PROJ_ID)
#print(os.path.join(USER_SESSIONS_DIR, PnS_PROJ_ID, d.get("projectType")))
return os.path.join(USER_SESSIONS_DIR, PnS_PROJ_ID, d.get("projectType"))
#return os.path.join(USER_SESSIONS_DIR, d.get("sessID"), d.get("projectType"))
"""/getSessionID
try:
sess_id = request.args.get("sessID")
except KeyError:
sess_id = str(uuid.uuid4())
"""
@app.route("/")
def main_page():
return render_template("smartSkeMa.html")
@app.route("/getSessionID", methods=["GET"])
def get_session_id():
global USER_SESSIONS_DIR
global PnS_PROJ_ID
""" comment out if using full alignment in debug mode """
#if app.debug:
#print("using predefined session ID!")
#print("here session id",debug_get_session_id())
# return debug_get_session_id()
#sess_id = str(uuid.uuid4())
"""getting session id from PnS platform to create folder"""
sess_id = str(get_PnS_Project_ID())
if sess_id != None:
PnS_PROJ_ID = str(sess_id)
proj_dir_path = os.path.join(USER_SESSIONS_DIR, PnS_PROJ_ID)
try:
if not (os.path.exists(proj_dir_path)):
os.mkdir(proj_dir_path)
except IOError:
print("problem in createing session..")
# print(url_for('.smartSkeMa'))
#print("generated session ID - now returning!")
return PnS_PROJ_ID # redirect("dashboard.html", sessId=sess_id)
def debug_get_session_id():
return DEBUG_SESSID
@app.route("/setProjectType", methods=["POST"])
def setProjectType():
global UPLOADED_DIR_PATH
global MODIF_DIR_PATH
global OUTPUT_DIR_PATH
#global SVG_DIR_PATH
global PROJ_DIR_PATH
try:
#print("request.form",request.form)
proj_type_dir_path = path_to_project(request.form)
print("here you go:proj_type_dir_path",proj_type_dir_path)
PROJ_DIR_PATH = proj_type_dir_path
if not (os.path.exists(proj_type_dir_path)):
os.mkdir(proj_type_dir_path)
os.mkdir(os.path.join(proj_type_dir_path, UPLOADED_DIR_PATH))
os.mkdir(os.path.join(proj_type_dir_path, MODIF_DIR_PATH))
os.mkdir(os.path.join(proj_type_dir_path, OUTPUT_DIR_PATH))
#os.mkdir(os.path.join(proj_type_dir_path, SVG_DIR_PATH))
except IOError:
print("problem in creating PROJ_DIR and Sub_DIRs for P and S..")
return ""
@app.route("/smartSkeMa_new", methods=["POST", "GET"])
def domainModel():
return render_template("smartSkeMa.html")
@app.route("/metricFileName", methods=["POST", "GET"])
def getMetricMapID():
metricMapID = request.args.get("metricFileName")
BaseMapName=metricMapID
return "msg"
@app.route("/sketchFileName", methods=["POST", "GET"])
def getSketchMapID():
sketchMapID = request.args.get("sketchFileName")
SketchMapName= sketchMapID
return "msg"
# the function calls the reasoner to execuite the submitted query
@app.route("/reasoner_process_spatial_queries",methods = ["POST","GET"])
def reasoner_process_spatial_queries():
owlready2.JAVA_EXE = "C:\\Program Files (x86)\\Common Files\\Oracle\\Java\\javapath"
feat_type = request.args.get('main_feat_id')
feat_type = request.args.get('main_feat_type')
loaded_ladm_path = request.args.get('loaded_ladm_path')
print(loaded_ladm_path)
ontology = get_ontology(loaded_ladm_path).load()
sync_reasoner(ontology)
result = ontology.Jan.__class__
print(sync_reasoner(ontology))
return result
@app.route("/getParty", methods =["POST"])
def getParty():
global UPLOADED_DIR_PATH
global PARTIES_FILE
global PROJ_DIR_PATH
proj_type_dir_path = path_to_project(request.form)
fileName_full = request.form.get('loadedPartyFile')
partyJson = json.loads(request.form.get('partyJson'))
#print("project to path",proj_type_dir_path)
#fileName_full = request.args.get('loadedPartyFile')
#partyJson = json.loads(request.args.get('partyJson'))
party = partyJson.get("parties")
try:
uploaded_filepath = os.path.join(proj_type_dir_path, UPLOADED_DIR_PATH, PARTIES_FILE)
if os.path.exists(uploaded_filepath):
os.remove(uploaded_filepath)
f = open(uploaded_filepath, "w")
f.write(json.dumps(partyJson, indent=4))
f.close()
except IOError:
print("problem in Writing JSON file to the location...")
return json.dumps(party)
@app.route("/qualitative_spatial_queries", methods=["POST"])
def qualitative_spatial_queries():
global OUTPUT_DIR_PATH
global SKETCH_MAP_QCN
global QUALITATIVE_REPRESENTATION
selected_feat_lr_rel = []
selected_feat_rcc8_rel = []
selected_feat_relDist_rel = []
try:
main_feat_id = request.form.get('main_feat_id')
main_feat_type = request.form.get('main_feat_type')
proj_type_dir_path = path_to_project(request.form)
#print(main_feat_id, main_feat_type)
smQCNFilePath = os.path.join(proj_type_dir_path,OUTPUT_DIR_PATH, SKETCH_MAP_QCN)
except IOError:
print("sketchmap_qcn.json path has problem ")
with open(smQCNFilePath) as smJson:
smQCNs = json.loads(smJson.read())
with open(QUALITATIVE_REPRESENTATION) as qr_file:
qualReps = json.loads(qr_file.read())
qualiReps_list = get_qualitativeRepresentaitons(qualReps)
#print("listofRepresentations",qualiReps_list)
for i in range(len(qualiReps_list)):
if (qualiReps_list[i] == "LEFT_RIGHT"):
lr_relations = getTotalLeftRightRelations_sm(smQCNs)
river_id = get_river_sm(smQCNs)
for j in lr_relations:
obj2 = j["obj_2"]
if (main_feat_id == obj2):
selected_feat_lr_rel.append(j)
if(qualiReps_list[i]=="RCC8"):
rcc8_relations = getTotalRCC8Relations_sm(smQCNs)
selected_feat_rcc8_rel = get_main_feature_rcc8rel_(main_feat_id,rcc8_relations)
if (qualiReps_list[i] == "REL_DIST"):
relDist_relations = getTotalRelDistRelations_sm(smQCNs)
selected_feat_relDist_rel = get_main_feature_relDist_(main_feat_id, relDist_relations)
#print(selected_feat_lr_rel,selected_feat_rcc8_rel,selected_feat_relDist_rel)
return json.dumps({"selected_feat_lr_rel":selected_feat_lr_rel,"selected_feat_rcc8_rel":selected_feat_rcc8_rel,"selected_feat_relDist_rel":selected_feat_relDist_rel})
@app.route("/get_approx_location_from_relations", methods=["POST"])
def get_approx_location_from_relations():
#global main_feat_type
global OUTPUT_DIR_PATH
global UPLOADED_DIR_PATH
global VECTOR_BASEMAP
global APROX_TILE
#global UPLOADED_DIR_PATH, MM_fileName_full
try:
proj_type_dir_path = path_to_project(request.form)
lr_relations = json.loads(request.form.get('clicked_relations'))
mm_json_FilePath = os.path.join(proj_type_dir_path, UPLOADED_DIR_PATH, VECTOR_BASEMAP)
#print("here basemap json",mm_json_FilePath)
relatum = lr_relations['relatum']
representation = lr_relations['representation']
main_feat_id = lr_relations['main_feat_id']
main_feat_type = lr_relations['main_feat_type']
lr_relations = lr_relations['relation']
except IOError:
print("sketchmap_qcn.json path has problem ")
# mm_json_FilePath = os.path.join(UPLOADED_DIR_PATH,MM_fileName_full)
#mm_json_FilePath = "./static/metric_map_v6.geojson"
print("relatum..:", relatum)
print("rellations ..:", lr_relations)
print(" representaiton..:", representation)
print(" main_feat_id..:", main_feat_id)
print(" main_feat_type..:", main_feat_type)
geo_data_properties, data_geom = load_geo(read_map_data_from_path(mm_json_FilePath, "geojson"), "geojson")
#print(geo_data_properties,data_geom)
relatum_feat_type = get_relatum_feat_type(relatum, data_geom)
print("relatum_feat_type", relatum_feat_type)
try:
geoJson_tiles_type = ""
if representation == "left_right":
geoJson_tiles_type = "left_right"
filter_params = {'filter_geoms': 6, 'filter_types': False, 'type_list': [], 'filter_ids': False,
'id_list': [], 'filter_names': False, 'name_list': []}
filter_params['filter_ids'] = True
filter_params['id_list'].append(relatum)
tessellation_sets = {}
tessellation_sets = tessellation('left_right', g_left_right_tiles, 1, data_geom, False,
**filter_params).get_tessellations()
# print(tessellation_sets)
filter_params['filter_geoms'] = config.FILTER_ALL
if lr_relations['relation'] == "left":
shapelyObject = tessellation_sets[(relatum,)].get_tile('left')
elif lr_relations['relation'] == "right":
shapelyObject = tessellation_sets[(relatum,)].get_tile('right')
else:
shapelyObject = tessellation_sets.values()
coords = shapelyObject.exterior.coords[::-1]
shapelyObject = Polygon(coords)
computed_tiles = shapely.geometry.mapping(shapelyObject) #
geoJson_tiles = convert_tiles_into_geojson(computed_tiles, geo_data_properties)
elif representation == "RCC8":
geoJson_tiles_type = "RCC8"
filter_params = {'filter_geoms': 6, 'filter_types': False, 'type_list': [], 'filter_ids': False,
'id_list': [], 'filter_names': False, 'name_list': []}
filter_params['filter_ids'] = True
filter_params['id_list'].append(relatum)
tessellation_sets = {}
tessellation_sets = tessellation('rcc', g_rcc_tiles, 1, data_geom, False,
**filter_params).get_tessellations()
filter_params['filter_geoms'] = config.FILTER_ALL
if lr_relations['relation'].upper() == 'PO' or 'EQ' or 'TPP' or 'TPPI' or 'NTPP' or 'NTPPI':
shapelyObject = tessellation_sets[(relatum,)].get_tile('interior')
elif lr_relations['relation'].upper() == 'EC' or 'PO' or 'EQ' or 'TPP' or 'TPPI' or 'NTPPI':
shapelyObject = tessellation_sets[(relatum,)].get_tile('boundary')
elif lr_relations['relation'].upper() == 'DC' or 'EC' or 'PO' or 'TPPI' or 'NTPPI':
shapelyObject = tessellation_sets[(relatum,)].get_tile('exterior')
else:
shapelyObject = tessellation_sets.values()
coords = shapelyObject.exterior.coords[::-1]
shapelyObject = Polygon(coords)
computed_tiles = shapely.geometry.mapping(shapelyObject) #
geoJson_tiles = convert_tiles_into_geojson(computed_tiles, geo_data_properties)
elif representation == "REL_DIST":
geoJson_tiles_type = "REL_DIST"
tessellation_sets = {}
filter_params = {'filter_geoms': 6, 'filter_types': True, 'type_list': [relatum_feat_type, main_feat_type],
'filter_ids': False,
'id_list': [], 'filter_names': False, 'name_list': []}
filter_params['filter_ids'] = False
filter_params['id_list'].append(relatum)
filter_params['filter_geoms'] = config.FILTER_ALL
tessellation_sets = tessellation('REL_DIST', g_reldist_tiles, 1, data_geom, False, [main_feat_type],
**filter_params)
# print("here is tessellation_sets",tessellation_sets)
tessellation_sets = tessellation_sets.get_tessellations()
if lr_relations['relation'] == "near":
shapelyObject = tessellation_sets[(relatum,)].get_tile('near')
elif lr_relations['relation'] == "far":
shapelyObject = tessellation_sets[(relatum,)].get_tile('far')
elif lr_relations['relation'] == "vfar":
shapelyObject = tessellation_sets[(relatum,)].get_tile('vfar')
else:
shapelyObject = tessellation_sets.values()
computed_tiles = shapely.geometry.mapping(shapelyObject) #
geoJson_tiles = convert_tiles_into_geojson(computed_tiles, geo_data_properties)
geoJson_tiles = json.dumps(geoJson_tiles)
geoJson_tiles = json.loads(geoJson_tiles)
except IOError:
print("Problem in Computing Approxmate tiles ")
try:
outputFilePath = os.path.join(proj_type_dir_path, OUTPUT_DIR_PATH, APROX_TILE)
#outputFilePath = os.path.join("./output", "geoJson_tiles.geojson")
if os.path.exists(outputFilePath):
os.remove(outputFilePath)
f = open(outputFilePath, "w")
f.write(json.dumps(geoJson_tiles, indent=4))
f.close()
except IOError:
print("Problem in Writing tiles ")
return json.dumps({"geoJson_tiles": geoJson_tiles, "geoJson_tiles_type": geoJson_tiles_type})
@app.route("/get_approx_location_lr",methods = ["POST", "GET"])
def get_approx_location_lr():
lr_relations = json.loads(request.args.get('clicked_relations'))
print("that is i am here ", lr_relations)
return ""
@app.route("/get_tenure_record",methods =["POST"])
def get_tenure_record():
global OUTPUT_DIR_PATH
global MATCHED_FEATURES
global TENURE_RECORD_FILE
matchedRecord=""
try:
feat_id = request.form.get('feat_id')
feat_type = request.form.get('feat_type')
proj_type_dir_path = path_to_project(request.form)
matchesDictFile = os.path.join(proj_type_dir_path,OUTPUT_DIR_PATH,MATCHED_FEATURES)
tenureRecoredFilePath = os.path.join(proj_type_dir_path,OUTPUT_DIR_PATH, TENURE_RECORD_FILE)
except IOError:
print("problem in reading matches file and tenure recored in the /get_tenure_record()..")
matched_feat = ""
#print(matchesDictFile)
with open(matchesDictFile) as matches:
matches = json.loads(matches.read())
#print(matches)
for key, value in matches.items():
if key==feat_id:
matched_obj = value
if matched_obj !=None:
matched_feat= matched_obj
else:
matched_feat="NONE"
#print(matched_feat)
#print(matched_feat)
#tenureRecoredFilePath = os.path.join(OUTPUT_DIR_PATH,"tenureRecord.json")
with open(tenureRecoredFilePath) as record_json:
records = json.loads(record_json.read())
for record in records:
for feature in record["features"]:
feature_ID = feature["feature_id"]
if feature_ID == feat_id:
matchedRecord = record
#print("empity recored",matchedRecord)
if (matchedRecord !=""):
record_no = matchedRecord["record_no"]
spatial_source = matchedRecord["spatial_source"]
for feature in matchedRecord["features"]:
for relation in feature["relations"]:
ownership = relation["ownership"]
party = relation["party"]
rrrs = relation["rrrs"]
return json.dumps([{"Record no.": record_no, "Spatial Source": spatial_source,
"Feature ID": feat_id, "Feature Type": feat_type,"Aligned Object":matched_feat,
"Party": party,"Right": ownership, "Condition": rrrs}])
else:
return "None"
@app.route("/getMapMatches", methods=["POST"])
def getMapMatches():
global OUTPUT_DIR_PATH
global MATCHED_FEATURES
global PROJ_DIR_PATH
#matchedRecord = ""
#print("request.form", request.form)
proj_type_dir_path = path_to_project(request.form)
#print("project path in the getMapMatches",proj_type_dir_path)
#feat_id = request.args.get('feat_id')
#feat_type = request.args.get('feat_type')
#print("feat_id in tenurerecord:", feat_id)
mm_feature_id = ""
#print("output file path",OUTPUT_DIR_PATH)
matchesFilePath = os.path.join(proj_type_dir_path, OUTPUT_DIR_PATH, MATCHED_FEATURES)
#print("here matches file path",matchesFilePath)
#matchesFilePath = os.path.join(OUTPUT_DIR_PATH,"matches.json")
with open(matchesFilePath) as matches:
matches = json.loads(matches.read())
return json.dumps(matches)
@app.route("/add_tenure_record", methods =["POST","GET"])
def add_tenure_record():
newlist = []
data_and_time = str(datetime.datetime.now())
#print(data_and_time)
spatialSource = request.args.get('spatialSource')
feat_id = request.args.get('feat_id')
feat_type = request.args.get('feat_type')
ownership = request.args.get('ownership_type')
party = request.args.get('party')
rrrs = json.loads(request.args.get('rrrs_list'))
#print("feat_id:",feat_id)
#print("feat_type:",feat_type)
#print("ownership:",ownership)
#print("party",party)
#print("rrrs:",rrrs)
record_json= generate_tuenure_record_json(spatialSource,data_and_time,feat_id,feat_type,ownership,party,rrrs)
RecordList.append(record_json)
return "Rights are recorded! "
@app.route("/save_tenure_record", methods =["POST"])
def save_tenure_record():
global OUTPUT_DIR_PATH
global TENURE_RECORD_FILE
proj_type_dir_path = path_to_project(request.form)
tenurefilepath = os.path.join(proj_type_dir_path,OUTPUT_DIR_PATH, TENURE_RECORD_FILE)
#print("final tenure record path...", tenurefilepath)
try:
f = open(tenurefilepath, "w")
f.write(json.dumps(RecordList, indent=4))
#f.write(record_json)
f.close()
except IOError:
print("tenureRecord.json path has problem ")
#print(record_json)
return "Records are saved as a JSON file"
@app.route("/postLADM",methods =["POST"])
def postLADM():
global UPLOADED_DIR_PATH
global LADM_FILE
global PROJ_DIR_PATH
proj_type_dir_path = path_to_project(request.form)
#print("proj to path",proj_type_dir_path)
fileName_full = str(request.form.get('LDMFileName'))
owlContent = request.form.get('LDMContent')
uploaded_filepath = os.path.join(proj_type_dir_path, UPLOADED_DIR_PATH, LADM_FILE)
#uploaded_filepath = os.path.join(UPLOADED_DIR_PATH, fileName_full)
try:
if os.path.exists(uploaded_filepath):
os.remove(uploaded_filepath)
f = open(uploaded_filepath, "w")
f.write(owlContent)
f.close()
except IOError:
print("problem in Writing JSON file to the location...")
return owlContent
@app.route("/get_domain_model_ownerships",methods =["POST"])
def get_domain_model():
global UPLOADED_DIR_PATH
global LADM_FILE
try:
fileName_full = request.form.get('LDMFileName')
feat_type = request.form.get('feat_type')
proj_type_dir_path = path_to_project(request.form)
uploaded_filepath = os.path.join(proj_type_dir_path,UPLOADED_DIR_PATH, LADM_FILE)
ontology = get_ontology(uploaded_filepath).load()
except IOError:
print("problem in Reading Owl file in the Function: /get_domain_model_ownerships...")
if feat_type == "boma1":
boma_ownerships = get_ownerships(ontology)
#print(boma_ownerships)
return json.dumps(boma_ownerships)
elif feat_type== "olopololi1":
olopololi_ownerships = get_olopololi_ownerships(ontology)
#print(olopololi_ownerships)
return json.dumps(olopololi_ownerships)
else:
ownerships = get_ownerships(ontology)
# print(boma_ownerships)
return json.dumps(ownerships)
return "Please select the drawn object!"
@app.route("/get_domain_model_rrrs",methods =["POST"])
def get_domain_model_rrrs():
global UPLOADED_DIR_PATH
global LADM_FILE
try:
fileName_full = request.form.get('LDMFileName')
proj_type_dir_path = path_to_project(request.form)
#print("project path:",proj_type_dir_path)
uploaded_filepath = os.path.join(proj_type_dir_path,UPLOADED_DIR_PATH, LADM_FILE)
#uploaded_filepath = os.path.join(UPLOADED_DIR_PATH, fileName_full)
ontology = get_ontology(uploaded_filepath).load()
rrrs = get_has_rrr(ontology)
#print(rrrs)
except IOError:
print("problem in Reading Owl file in the Function: /get_domain_model_rrrs...")
return json.dumps(rrrs)
"""
initialize database
- it will delete all the previous records and
- create new main structure for neo4j
"""
"""
@app.route("/initializeDatabase", methods =["POST","GET"])
def initializeDatabase():
deleted = dbInitilizer.deleteAllRecords()
msg = dbInitilizer.createGraphStructure()
return msg
"""
"""
- resize image to load in the imageholder
"""
@app.route("/uploadComplexSketchMap", methods=["POST", "GET"])
def uploadComplexSketchMap():
global MODIF_DIR_PATH
global UPLOADED_DIR_PATH
global INPUT_RASTER_COMPLEX_SKETCH
global REDUCED_RASTER_COMPLEX_SKETCH
global SMARTSKEMA_PATH
project_files_path = path_to_project(request.form)
imageFileName = request.form.get('fileName')
imageContent = request.form.get('imageContent')
imageContent = imageContent.replace("data:image/png;base64,", "")
imageContent = imageContent.encode('utf-8')
upload_filepath = os.path.join(project_files_path, UPLOADED_DIR_PATH, INPUT_RASTER_COMPLEX_SKETCH)
modified_filepath = os.path.join(project_files_path, MODIF_DIR_PATH, REDUCED_RASTER_COMPLEX_SKETCH)
try:
if os.path.exists(upload_filepath):
os.remove(upload_filepath)
os.makedirs(os.path.dirname(upload_filepath), exist_ok=True)
with open(upload_filepath, "wb") as f:
f.write(base64.decodebytes(imageContent))
f.close()
w = 800
img = cv2.imread(upload_filepath, -1)
if img is not None:
height, width, depth = img.shape
imgScale = w/width
newX, newY = img.shape[1] * imgScale, img.shape[0] * imgScale
resized_image = cv2.resize(img, (int(newX), int(newY)))
cv2.imwrite(modified_filepath, resized_image)
else:
newX = 500
newY = 500
#img_path = Path(modified_filepath)
with open(modified_filepath, "wb") as f:
f.write(base64.decodebytes(imageContent))
modified_filepath_relative = os.path.relpath(modified_filepath, SMARTSKEMA_PATH)
img_path = Path(modified_filepath_relative)
#img_path = Path(upload_filepath)
return json.dumps({"imgPath": img_path.as_posix(), "imgHeight": newY, "imgWidth": newX})
except IOError:
print("couldn't write data\n", IOError)
return json.dumps({"error": IOError.__module__})
"""
- resize image to load in the imageholder
"""
@app.route("/uploadSketchMap", methods=["POST", "GET"])
def uploadSketchMap():
global MODIF_DIR_PATH
global UPLOADED_DIR_PATH
global INPUT_RASTER_SKETCH
global REDUCED_RASTER_SKETCH
global SMARTSKEMA_PATH
project_files_path = path_to_project(request.form)
imageFileName = request.form.get('fileName')
imageContent = request.form.get('imageContent')
imageContent = imageContent.replace("data:image/png;base64,", "")
imageContent = imageContent.encode('utf-8')
#print("here image contants",imageContent)
upload_filepath = os.path.join(project_files_path, UPLOADED_DIR_PATH, INPUT_RASTER_SKETCH)
modified_filepath = os.path.join(project_files_path, MODIF_DIR_PATH, REDUCED_RASTER_SKETCH)
try:
""" comment out if using full alignment in debug mode
if app.debug:
#copy folder with fileName to currentUserSession/projectType
preRunFiles = os.path.join("preRunSessions", imageFileName)
try:
#print("copying from preRun", project_files_path)
shutil.rmtree(project_files_path, ignore_errors=False, onerror=None)
shutil.copytree(preRunFiles, project_files_path)
# Directories are the same
except shutil.Error as e:
print('Directory not copied. Error: %s' % e)
# Any error saying that the directory doesn't exist
except OSError as e:
print('Directory not copied. Error: %s' % e)
"""
#else:
if os.path.exists(upload_filepath):
os.remove(upload_filepath)
# f = open(upload_filepath, "wb")
# f.write(base64.decodebytes(imageContent))
# f.close()
os.makedirs(os.path.dirname(upload_filepath), exist_ok=True)
with open(upload_filepath, "wb") as f:
f.write(base64.decodebytes(imageContent))
f.close()
w = 800
img = cv2.imread(upload_filepath, -1)
if img is not None:
height, width, depth = img.shape
imgScale = w/width
newX, newY = img.shape[1] * imgScale, img.shape[0] * imgScale
resized_image = cv2.resize(img, (int(newX), int(newY)))
#make path relativ
#img_path = Path(modified_filepath)
cv2.imwrite(modified_filepath, resized_image)
else:
newX = 800
newY = 565.686
#img_path = Path(modified_filepath)
with open(modified_filepath, "wb") as f:
f.write(base64.decodebytes(imageContent))
"""
- docker container requires relative path for front end
- SketchMap_path gives rel path
- get relative and pass to front end
"""
modified_filepath_relative = os.path.relpath(modified_filepath, SMARTSKEMA_PATH)
#print("modified_filepath:",modified_filepath)
#print("modified_filepath_relative:",modified_filepath_relative)
img_path = Path(modified_filepath_relative)
#print("here you go the relative path:", img_path.as_posix())
return json.dumps({"imgPath": img_path.as_posix(), "imgHeight": newY, "imgWidth": newX})
except IOError:
print("couldn't write data\n", IOError)
return json.dumps({"error": IOError.__module__})
"""
- resize base map if necessary
- and create geojson file in the uploaded and modified DIRs.
"""
@app.route("/uploadBaseMap", methods=["POST"])
def uploadBaseMap():
global MODIF_DIR_PATH
global UPLOADED_DIR_PATH
global VECTOR_BASEMAP
global USER_SESSIONS_DIR
project_files_path = path_to_project(request.form)
upload_filepath = os.path.join(project_files_path, UPLOADED_DIR_PATH, VECTOR_BASEMAP)
modified_filepath = os.path.join(project_files_path, MODIF_DIR_PATH, VECTOR_BASEMAP)
json_content = request.form.get('mapContent')
json_content = json.loads(json_content)
try:
if os.path.exists(upload_filepath):
os.remove(upload_filepath)
f = open(upload_filepath, "w")
f.write(json.dumps(json_content, indent=4))
f.close()
if os.path.exists(modified_filepath):
os.remove(modified_filepath)
f = open(modified_filepath, "w")
f.write(json.dumps(json_content, indent=4))
f.close()
except IOError:
return json.dumps({"error": IOError})
return ""
"""
- process sketch map
- Christian Code under here
"""
@app.route("/processSketchMap", methods=["GET"])
def processSketchMap():
global UPLOADED_DIR_PATH
global OUTPUT_DIR_PATH
global INPUT_RASTER_SKETCH
global VECTORIZED_SKETCH
global SMARTSKEMA_PATH
project_files_path = path_to_project(request.args)
uploaded_filepath = os.path.join(project_files_path, UPLOADED_DIR_PATH, INPUT_RASTER_SKETCH)
output_file_path = os.path.join(project_files_path, OUTPUT_DIR_PATH, VECTORIZED_SKETCH)
modified_filepath = os.path.join(project_files_path, MODIF_DIR_PATH, VECTORIZED_SKETCH)
#comment out if using full alignment in debug mode
"""
if app.debug:
svg = svgutils.transform.fromfile(modified_filepath)
#print(svg)
#print(("height and width...:",svg.height, svg.width))
modified_filepath_relative = os.path.relpath(modified_filepath, SMARTSKEMA_PATH)
return json.dumps({'svgPath': Path(modified_filepath_relative).as_posix(), 'svgHeight': float(svg.height), 'svgWidth': float(svg.width)})
"""
try:
""" load image from uploaded folder"""
img2 = cv2.imread(uploaded_filepath)
"""Save the recognized objects as svg in the output and modified folders"""
print("Object Detection STARTED...")
classified_strokes = cc.completeClassification(img2, output_file_path)
svgstring = cc.strokesToSVG(classified_strokes,"abc", img2, output_file_path)
#print("svgString...:",svgstring)
print("Object Detection END")
svg = svgutils.transform.fromstring(svgstring)
""" write the SVG to modified_filepath as well as in the output_file_path """
svg.save(modified_filepath)
svg.save(output_file_path)
# originalSVG = svgutils.compose.SVG(svg_file_path)
# originalSVG.move(0, 0)
h = int(svg.height)
w = int(svg.width)
# scaleFact = 800/w
# print (scaleFact)
# scaledSVG = originalSVG.scale(scaleFact)
# newY = float(scaleFact*float(svg.height))
# newX = float(scaleFact*float(svg.width))
# figure = svgutils.compose.Figure(newY, newX, originalSVG)
#print("h and w of svg..:",h,w)
#newY = 6586
#newX = 10023
# modifiy the path to relative path for front-end
modified_filepath_relative = os.path.relpath(modified_filepath, SMARTSKEMA_PATH)
return json.dumps({'svgPath': Path(modified_filepath_relative).as_posix(), 'svgHeight': h, 'svgWidth': w})
except IOError as ioe:
print("problem in Reading original Image from loaded DIR function: /processSketchMap..\n", ioe)
return json.dumps({"error": ioe.__dict__})
"""
- return alignment results
"""
@app.route("/align_plain", methods =["POST"])
def align_plain_sketch_map():
global OUTPUT_DIR_PATH
global MODIF_DIR_PATH
global VECTORIZED_SKETCH
global VECTOR_BASEMAP
global MATCHED_FEATURES
global SKETCH_MAP_QCN
global BASEMAP_QCN
project_files_path = path_to_project(request.form)
matches_file_path = os.path.join(project_files_path, OUTPUT_DIR_PATH, MATCHED_FEATURES)
#print(matches_file_path)
""" comment out if using full alignment in debug mode """
#if app.debug:
# return debug_align_plain_sketch(matches_file_path)
svg_file_path = os.path.join(project_files_path, MODIF_DIR_PATH, VECTORIZED_SKETCH)
geojson_file_path = os.path.join(project_files_path, MODIF_DIR_PATH, VECTOR_BASEMAP)
qualified_sketch_map_file_path = os.path.join(project_files_path, OUTPUT_DIR_PATH, SKETCH_MAP_QCN)
qualified_metric_map_file_path = os.path.join(project_files_path, OUTPUT_DIR_PATH, BASEMAP_QCN)
#print ("here i am ")
sketchid = "_".join(("sketch", request.form.get("sessID"), request.form.get("projectType")))
metricid = "_".join(("metric", request.form.get("sessID"), request.form.get("projectType")))
loadedSketch, loadedMetric = None, None
try:
loadedSketch = str(request.form.get('svgData'))
#print("loadedSketch: ",loadedSketch)
except KeyError:
pass
try:
loadedMetric = str(request.form.get('geojsonData'))
#print("loadedMetric",loadedMetric)
except KeyError:
pass
#print(loadedMetric, "\n\n", loadedSketch)
qualified_sketch_map = 0 # load qualitative representation here
qualified_metric_map = 0 # load qualitative representation here
# write incoming map data to modified
try:
if (loadedSketch is not None):
if os.path.exists(svg_file_path):
os.remove(svg_file_path)
with io.open(svg_file_path, 'w', encoding='utf8') as file:
file.write(loadedSketch)
file.close()
#qualified_sketch_map = load_map_qualify(sketchid, read_map_data_from_string(loadedSketch,
# "svg"), "svg", "sketch_map")
#print("qualified_sketch_map..:",qualified_sketch_map)
else:
print("else")
qualified_sketch_map = load_map_qualify(sketchid, read_map_data_from_path(svg_file_path,
"svg"), "svg", "sketch_map")
#print("SM_QCN...:", qualified_sketch_map)
if os.path.exists(qualified_sketch_map_file_path):
os.remove(qualified_sketch_map_file_path)
with io.open(qualified_sketch_map_file_path, 'w', encoding='utf8') as file: