-
Notifications
You must be signed in to change notification settings - Fork 1
/
qgis_fgi_plugin.py
1144 lines (970 loc) · 43.5 KB
/
qgis_fgi_plugin.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 -*-
"""
/***************************************************************************
QGISFGIPlugin
A QGIS plugin
This plugin is for classifying samples of pastures areas.
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2022-06-20
git sha : $Format:%H$
copyright : (C) 2022 by Tharles de Sousa Andrade | LAPIG - UFG
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
import gc
import os
import json
import time
from datetime import datetime
from os.path import expanduser, exists
from functools import partial
import requests as req
from qgis.core import (
Qgis,
QgsFillSymbol,
QgsProject,
QgsRasterLayer,
QgsVectorLayer,
QgsField,
QgsFields,
QgsFeature,
QgsProject,
QgsGeometry,
QgsVectorDataProvider,
QgsVectorFileWriter
)
from qgis.PyQt.QtCore import QCoreApplication, QSettings, Qt, QTranslator, QEvent, QObject, QVariant
from qgis.PyQt.QtGui import QIcon, QPixmap
from qgis.PyQt.QtWidgets import (
QAbstractScrollArea,
QAction,
QApplication,
QFileDialog,
QMessageBox,
QScrollArea,
QVBoxLayout,
QPlainTextEdit,
QProgressBar,
QHBoxLayout,
QLabel,
QWidget,
QPushButton
)
from qgis import utils
from .qgis_fgi_plugin_dockwidget import QGISFGIPluginDockWidget
# Initialize Qt resources from file resources.py
from .resources import *
from .sources import connections
from .src.inspections import InspectionController
from .src.models.config_db import init_db, reset_config, set_config, get_config
from .src.ui.date_time_edit import NoScrollOrArrowKeyFilter
class QGISFGIPlugin(QObject):
"""QGIS Plugin Implementation."""
def __init__(self, iface):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
try:
super(QGISFGIPlugin, self).__init__()
# Save reference to the QGIS interface
self.iface = iface
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# initialize locale
locale = QSettings().value('locale/userLocale')[0:2]
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'QGISFGIPlugin_{}.qm'.format(locale),
)
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
# Declare instance attributes
self.actions = []
self.menu = self.tr('&QGIS Fast Grid Inspection')
# TODO: We are going to let the user set this up in a future iteration
self.toolbar = self.iface.addToolBar('QGISFGIPlugin')
self.toolbar.setObjectName('QGISFGIPlugin')
# print "** INITIALIZING QGISFGIPlugin"
self.plugin_is_active = False
self.dock_widget = None
self.scroll_area = None
self.tiles_layer = None
self.work_dir = None
self.canvas = None
self.root = None
self.group = None
self.tiles = None
self.type_inspection = None
self.current_tile_index = 0
self.selected_class_bing = None
self.selected_class_google = None
self.current_pixels_layer = None
self.inspection_controller = None
self.campaigns_config = None
self.layer_bing = None
self.layer_google = None
self.config = init_db()
self.scroll = None
self.show_imports_buttons = None
self.load_config_from = 'local'
self.layers_plugin = []
self.reset_button = None
self.reload_button = None
self.progress_message_bar = None
self.progress_bar = None
except Exception as e:
print("Error during initialization:", str(e))
# noinspection PyMethodMayBeStatic
def tr(self, message):
"""Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate('QGISFGIPlugin', message)
def add_action(
self,
icon_path,
text,
callback,
enabled_flag=True,
add_to_menu=True,
add_to_toolbar=True,
status_tip=None,
whats_this=None,
parent=None,
):
"""Add a toolbar icon to the toolbar.
:param icon_path: Path to the icon for this action. Can be a resource
path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
:type icon_path: str
:param text: Text that should be shown in menu items for this action.
:type text: str
:param callback: Function to be called when the action is triggered.
:type callback: function
:param enabled_flag: A flag indicating if the action should be enabled
by default. Defaults to True.
:type enabled_flag: bool
:param add_to_menu: Flag indicating whether the action should also
be added to the menu. Defaults to True.
:type add_to_menu: bool
:param add_to_toolbar: Flag indicating whether the action should also
be added to the toolbar. Defaults to True.
:type add_to_toolbar: bool
:param status_tip: Optional text to show in a popup when mouse pointer
hovers over the action.
:type status_tip: str
:param parent: Parent widget for the new action. Defaults None.
:type parent: QWidget
:param whats_this: Optional text to show in the status bar when the
mouse pointer hovers over the action.
:returns: The action that was created. Note that the action is also
added to self.actions list.
:rtype: QAction
"""
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
if add_to_toolbar:
self.toolbar.addAction(action)
if add_to_menu:
self.iface.addPluginToMenu(self.menu, action)
self.actions.append(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
icon_path = os.path.join(os.path.dirname(__file__), 'icon.png')
self.add_action(
icon_path,
text=self.tr('Fast Grid Inspection'),
callback=self.run,
parent=self.iface.mainWindow(),
)
self.reload_button = QPushButton("")
self.reload_button.setToolTip("Click here to reload the plugin QGIS Fast Grid")
reload_icon_path = os.path.join(os.path.dirname(__file__), 'img', 'reload.png')
reload_icon = QIcon(reload_icon_path)
self.reload_button.setIcon(reload_icon)
self.reload_button.clicked.connect(self.reload_plugin)
self.toolbar.addWidget(self.reload_button)
# --------------------------------------------------------------------------
def onClosePlugin(self):
if hasattr(self, 'dock_widget'):
if hasattr(self.dock_widget, 'localConfig'):
self.dock_widget.localConfig.removeEventFilter(self)
self.reset_plugin_instance(reset=False)
# disconnects
if hasattr(self, 'dock_widget'):
if hasattr(self.dock_widget, 'closingPlugin'):
self.dock_widget.closingPlugin.disconnect(self.onClosePlugin)
self.reset_button = None
self.reload_button = None
if hasattr(self, 'toolbar') and self.toolbar:
# Remove the actions from the toolbar
self.toolbar.removeAction(self.reset_button)
self.toolbar.removeAction(self.reload_button)
self.remove_datasource()
self.dock_widget = None
self.plugin_is_active = False
QgsProject.instance().removeMapLayers(self.list_layers())
QApplication.instance().setOverrideCursor(Qt.ArrowCursor)
gc.collect()
def remove_path(self, path):
def safe_remove(_path, retries=8, delay=1):
for _ in range(retries):
try:
os.remove(_path)
break
except PermissionError:
time.sleep(delay)
if os.path.exists(path):
safe_remove(path)
def remove_files_with_extension(self, directory, extension):
self.start_processing()
directory = os.path.dirname(__file__) + directory
total_files = len([name for name in os.listdir(directory)])
processed_files = 0
for filename in os.listdir(directory):
self.update_progress(10)
if 'default_tiles.gpkg' not in filename:
if filename.endswith(extension):
file_path = os.path.join(directory, filename)
self.remove_path(file_path)
processed_files += 1
progress = (processed_files / total_files) * 100
self.update_progress(progress)
self.finish_progress()
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
# print "** UNLOAD QGISFGIPlugin"
for action in self.actions:
self.iface.removePluginMenu(self.tr('&Fast Grid Inspection'), action)
self.iface.removeToolBarIcon(action)
# remove the toolbar
del self.toolbar
# --------------------------------------------------------------------------
@staticmethod
def is_valid_json(text):
try:
json.loads(text)
return True
except json.JSONDecodeError:
return False
def eventFilter(self, obj, event):
if hasattr(self, 'dock_widget') and self.dock_widget is not None:
if obj == self.dock_widget.localConfig and event.type() == QEvent.FocusOut:
content = self.dock_widget.localConfig.toPlainText()
color = '#e6fff2'
if not self.is_valid_json(content):
color = "#ffcccc"
self.iface.messageBar().pushMessage(
'LOCAL CONFIG',
'The provided configuration has syntax errors for the JSON format, please correct them.',
level=Qgis.Critical,
duration=10,
)
self.dock_widget.localConfig.setStyleSheet("QPlainTextEdit { background-color:" + color + "; }")
return True # event was handled
return super(QGISFGIPlugin, self).eventFilter(obj, event)
def open_google_satellite(self):
url = 'https://mt1.google.com/vt/lyrs=s&x=%7Bx%7D&y=%7By%7D&z=%7Bz%7D'
service_url = url.replace('=', '%3D').replace('&', '%26')
qgis_tms_uri = 'type=xyz&zmin={0}&zmax={1}&url={2}'.format(
0, 19, service_url
)
layer = QgsRasterLayer(qgis_tms_uri, 'Google', 'wms')
self.layer_google = layer
self.add_layer(layer.id())
if layer.isValid():
QgsProject.instance().addMapLayer(layer)
QgsProject.instance().layerTreeRoot().findLayer(
layer.id()
).setItemVisibilityChecked(False)
else:
print('Layer failed to load!')
def add_layer(self, layer_id: str):
"""Add a layer ID to the list if it's not already present."""
if layer_id not in self.layers_plugin:
self.layers_plugin.append(layer_id)
def remove_layer(self, layer_id: str):
"""Remove a layer ID from the list if it exists."""
if layer_id in self.layers_plugin:
self.layers_plugin.remove(layer_id)
def list_layers(self):
"""Return the list of layer IDs."""
return self.layers_plugin
def open_bing_satellite(self):
url = 'http://ecn.t3.tiles.virtualearth.net/tiles/a{q}.jpeg?g=1'
qgis_tms_uri = 'type=xyz&zmin={0}&zmax={1}&url={2}'.format(0, 19, url)
layer = QgsRasterLayer(qgis_tms_uri, 'Bing', 'wms')
self.layer_bing = layer
self.add_layer(layer.id())
if layer.isValid():
QgsProject.instance().addMapLayer(layer)
QgsProject.instance().layerTreeRoot().findLayer(
layer.id()
).setItemVisibilityChecked(True)
else:
print('Layer failed to load!')
# def get_config(self, key):
# """Load config file and get value of key"""
# if key is 'inspectionConfig':
# return self.config.get_inspection_config()
#
# return getattr(self.config, key)
#
def get_config(self, key):
"""Load config file and get value of key"""
return get_config(key)
def set_config(self, key, value):
"""Write config in config file"""
set_config(key, value)
# def set_config(self, key, value):
# """Write config in config file"""
# with db.atomic() as transaction: # Start a new transaction
# try:
# setattr(self.config, key, value)
# # if key is 'inspectionConfig':
# # print('inspectionConfig', value)
# self.config.save()
# except Exception as e:
# logger.exception(e)
# print(f"Error setting config for key: {key}, value: {value}. Error: {e}")
# transaction.rollback() # Rollback the transaction if there's an error
def clear_config(self):
self.config = reset_config()
def handle_remote_url(self, config):
if "cell_size" not in config:
config['cell_size'] = 10
for _class in config['classes']:
if "rgba" not in _class:
_class['rgba'] = _class['rgb']
return config
def load_type_inspections(self):
"""Load campaigns from service: https://ows.lapig.iesa.ufg.br/api/global-pasture/campaigns"""
if self.load_config_from == 'url':
url = self.dock_widget.configURL.text()
if url is not None:
resp = req.get(
url
)
# self.campaigns_config = self.handle_remote_url(resp.json()[0])
self.campaigns_config = resp.json()[0]
self.set_config(key='configURL', value=url)
self.update_progress(30)
else:
self.iface.messageBar().pushMessage(
'ERROR',
'It was not possible to load the settings from the provided URL.',
level=Qgis.Critical,
duration=5,
)
else:
self.update_progress(30)
local_config = json.loads(self.dock_widget.localConfig.toPlainText())
self.campaigns_config = local_config
self.set_config(key='inspectionConfig', value=self.campaigns_config)
self.show_config_url(False)
self.show_local_config(False)
self.enable_config_buttons(False)
def config_tiles(self):
self.current_pixels_layer = None
self.update_progress(30)
try:
tile = self.tiles[self.current_tile_index]
self.dock_widget.tileInfoBing.setText(
f'Tile {self.current_tile_index + 1} of {len(self.tiles)}'
)
self.dock_widget.tileInfoGoogle.setText(
f'Tile {self.current_tile_index + 1} of {len(self.tiles)}'
)
self.update_progress(50)
self.inspection_controller.create_grid_pixels(tile)
self.update_progress(90)
self.dock_widget.lblSearch.setVisible(True)
self.dock_widget.spinSearch.setVisible(True)
self.dock_widget.btnSearch.setVisible(True)
self.dock_widget.btnNewInspection.setVisible(True)
self.dock_widget.zoom.setVisible(True)
self.dock_widget.btnSkip.setVisible(True)
self.dock_widget.spinSearch.setMaximum(999999999)
self.update_progress(100)
self.finish_progress()
except Exception as e:
self.iface.messageBar().pushMessage(
'CONFIG_TILES',
str(e),
level=Qgis.Critical,
duration=5,
)
self.finish_progress()
print(e)
def load_tiles(self):
QApplication.instance().setOverrideCursor(Qt.BusyCursor)
"""Load tiles from layer"""
instance = QgsProject.instance()
open_layers = [layer for layer in instance.mapLayers().values()]
for layer in open_layers:
if layer.name() == 'tiles':
self.tiles = [f.attributes() for f in layer.getFeatures()]
QApplication.instance().setOverrideCursor(Qt.ArrowCursor)
def find_first_valid_date(self, layer, date_field):
for feature in layer.getFeatures():
date_value = feature[date_field]
if date_value and date_value != '2000-01-01':
return date_value
return '2000-01-01'
def create_and_populate_tiles_review_layer(self, files):
# Create an empty memory layer with the required fields
fields = QgsFields()
fields.append(QgsField('fid', QVariant.Int))
fields.append(QgsField("name_file", QVariant.String))
fields.append(QgsField("path", QVariant.String))
fields.append(QgsField("bing_start", QVariant.String))
fields.append(QgsField("bing_end", QVariant.String))
fields.append(QgsField("google_start", QVariant.String))
fields.append(QgsField("google_end", QVariant.String))
tiles_review = QgsVectorLayer("Polygon?crs=EPSG:3857", "tiles_review", "memory")
provider = tiles_review.dataProvider()
provider.addAttributes(fields)
tiles_review.updateFields()
# For each file, load it, extract data and add a new feature with those attributes to the memory layer
for file_path in files:
layer = QgsVectorLayer(file_path, os.path.basename(file_path), "ogr")
if not layer.isValid():
print(f"Layer failed to load: {file_path}")
continue
bing_image_start_date = self.find_first_valid_date(layer, 'bing_image_start_date')
bing_image_end_date = self.find_first_valid_date(layer, 'bing_image_end_date')
google_image_start_date = self.find_first_valid_date(layer, 'google_image_start_date')
google_image_end_date = self.find_first_valid_date(layer, 'google_image_end_date')
# Add a feature with these attributes to the memory layer
fid = int(os.path.basename(file_path).split('_')[0])
new_feature = QgsFeature()
new_feature.setFields(tiles_review.fields())
new_feature.setGeometry(QgsGeometry.fromRect(layer.extent()))
new_feature['fid'] = fid
new_feature['name_file'] = os.path.basename(file_path)
new_feature['path'] = file_path
new_feature['bing_start'] = bing_image_start_date
new_feature['bing_end'] = bing_image_end_date
new_feature['google_start'] = google_image_start_date
new_feature['google_end'] = google_image_end_date
provider.addFeature(new_feature)
work_dir = os.path.expanduser("~")
output_file_path = f"{work_dir}/tiles_review_{datetime.now().strftime('%Y-%m-%d').replace('-', '_')}.gpkg"
writer = QgsVectorFileWriter.writeAsVectorFormat(
tiles_review,
output_file_path,
"utf-8",
tiles_review.crs(),
"GPKG"
)
if writer[0] == QgsVectorFileWriter.NoError:
print(f"Successfully saved to {output_file_path}")
else:
print("Failed to save:", writer[1])
return output_file_path
def create_tiles_file_from_dir(self):
directory = QFileDialog.getExistingDirectory(
self.dock_widget,
'Choose the directory with the files containing the tiles',
expanduser('~'),
QFileDialog.ShowDirsOnly,
)
# If user doesn't select any directory, just return an empty list
if not directory:
return []
# Get all files in the directory
files = [os.path.join(directory, f) for f in os.listdir(directory) if
os.path.isfile(os.path.join(directory, f))]
return self.create_and_populate_tiles_review_layer(files)
def open_tiles_file(self, from_config=False):
QApplication.instance().setOverrideCursor(Qt.BusyCursor)
"""Open Tiles file Dialog"""
selected_mode = self.dock_widget.comboMode.currentText()
interpreter_name = self.dock_widget.interpreterName.text()
if interpreter_name != '':
self.set_config(
key='interpreterName', value=interpreter_name.upper()
)
if from_config:
layer_path = self.get_config('filePath')
self.dock_widget.tabWidget.setCurrentIndex(1)
self.current_tile_index = self.get_config('currentTileIndex')
else:
if selected_mode == 'INSPECT':
layer_path = str(
QFileDialog.getOpenFileName(
caption='Choose the file with the tiles',
filter='Geopackage (*gpkg)',
)[0]
)
else:
layer_path = self.create_tiles_file_from_dir()
if layer_path != '' and exists(layer_path):
self.tiles_layer = QgsVectorLayer(layer_path, 'tiles', 'ogr')
symbol = QgsFillSymbol.createSimple(
{
'color': '0,0,0,0',
'color_border': 'red',
'width_border': '0.7'
}
)
fill_layer = symbol.symbolLayer(0)
fill_layer.setStrokeStyle(Qt.DashLine)
self.tiles_layer.renderer().setSymbol(symbol)
self.dock_widget.fieldFileName.setText(layer_path)
QgsProject.instance().addMapLayer(self.tiles_layer)
self.add_layer(self.tiles_layer.id())
self.iface.setActiveLayer(self.tiles_layer)
self.iface.zoomToActiveLayer()
self.load_tiles()
self.set_config(key='filePath', value=layer_path)
if from_config:
self.config_tiles()
QApplication.instance().setOverrideCursor(Qt.ArrowCursor)
return True
else:
self.iface.messageBar().pushMessage(
'ERROR READ FILE',
'Tiles GPKG not found',
level=Qgis.Critical,
duration=5,
)
QApplication.instance().setOverrideCursor(Qt.ArrowCursor)
return False
def get_dir_path(self, from_config=False):
if from_config:
directory = self.get_config('workingDirectory')
else:
directory = QFileDialog.getExistingDirectory(
self.dock_widget,
'Select Directory',
expanduser('~'),
QFileDialog.ShowDirsOnly,
)
self.dock_widget.btnInitInspections.setVisible(True)
self.dock_widget.fieldWorkingDirectory.setText(directory)
self.set_config(key='workingDirectory', value=directory)
def load_classes(self):
image_date = self.dock_widget.imageDate.date()
if not self.inspection_controller.date_is_valid(
image_date.toString('yyyy-MM-dd')
):
image_date = None
if not image_date:
msg = QMessageBox()
msg.setIcon(QMessageBox.Question)
msg.setText('The image date is required to classify this tile!')
msg.setInformativeText(
'If the image date was not found, the tile would be ignored. Do you confirm the missing date of the image?'
)
msg.setWindowTitle('INSPECTION TILES')
msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
retval = msg.exec_()
if retval == 16384:
self.inspection_controller.init_inspection_tile(
no_image_date=True
)
else:
if self.get_config('imageSource') == 'BING':
self.dock_widget.labelClassBing.setVisible(True)
self.dock_widget.selectedClassBing.setVisible(True)
else:
self.dock_widget.btnNext.setVisible(True)
if self.dock_widget.btnShowYes.isChecked():
self.dock_widget.importBingClassification.setVisible(True)
self.dock_widget.labelClassGoogle.setVisible(True)
self.dock_widget.selectedClassGoogle.setVisible(True)
self.inspection_controller.init_inspection_tile()
def init_inspections(self):
self.start_processing()
self.update_progress(10)
interpreter_name = self.dock_widget.interpreterName.text()
if interpreter_name != '':
QApplication.instance().setOverrideCursor(Qt.BusyCursor)
self.load_type_inspections()
self.config_tiles()
self.set_config(
key='interpreterName', value=interpreter_name.upper()
)
self.dock_widget.btnInitInspections.setVisible(False)
if self.get_config('imageSource') == 'BING':
self.dock_widget.tabWidget.setTabEnabled(1, True)
self.dock_widget.tabWidget.setCurrentIndex(1)
else:
self.dock_widget.tabWidget.setTabEnabled(2, True)
self.dock_widget.tabWidget.setCurrentIndex(2)
else:
self.iface.messageBar().pushMessage(
'',
f'The name of interpreter is required!',
level=Qgis.Critical,
duration=5,
)
def show_local_config(self, show=False):
sh = not show
self.dock_widget.localConfig.setReadOnly(sh)
color = "#e6e6e6"
if not sh:
color = '#fafafa'
self.dock_widget.localConfig.setStyleSheet("QPlainTextEdit { background-color:" + color + "; }")
def show_config_url(self, show=False):
self.dock_widget.configURL.setEnabled(show)
def enable_config_buttons(self, enable=False):
self.dock_widget.btnConfigLocal.setEnabled(enable)
self.dock_widget.btnConfigURL.setEnabled(enable)
self.dock_widget.btnShowYes.setEnabled(enable)
self.dock_widget.btnShowNo.setEnabled(enable)
self.dock_widget.comboMode.setEnabled(enable)
def on_config_buttons_toggled(self, button):
actions = {
'Yes': lambda: setattr(self, 'show_imports_buttons', True),
'No': lambda: setattr(self, 'show_imports_buttons', False),
'Local': lambda: setattr(self, 'load_config_from', 'local'),
'URL': lambda: setattr(self, 'load_config_from', 'url')
}
action = actions.get(button)
if action:
action()
if self.show_imports_buttons:
self.set_config(key='showImportsButtons', value=self.show_imports_buttons)
if self.load_config_from:
self.set_config(key='loadConfigFrom', value=self.load_config_from)
if self.load_config_from == 'local':
self.show_local_config(True)
else:
self.show_local_config(False)
if self.load_config_from == 'url':
self.show_config_url(True)
else:
self.show_config_url(False)
def reset_content(self):
self.plugin_actions(connect=False)
self.dock_widget.btnFile.setEnabled(True)
self.dock_widget.btnWorkingDirectory.setEnabled(True)
self.dock_widget.interpreterName.setEnabled(True)
self.dock_widget.tabWidget.setCurrentIndex(0)
self.clear_config()
self.plugin_actions(connect=True)
self.dock_widget.spinSearch.setMaximum(999999999)
def continue_inspecting(self):
self.start_processing()
self.get_dir_path(from_config=True)
if not self.open_tiles_file(from_config=True):
return
self.load_config_from = self.get_config('loadConfigFrom')
self.load_campaign_conf()
self.show_imports_buttons = self.get_config('showImportsButtons')
self.dock_widget.interpreterName.setText(
self.get_config('interpreterName').upper()
)
if self.show_imports_buttons:
self.dock_widget.btnShowNo.setChecked(False)
self.dock_widget.btnShowYes.setChecked(True)
else:
self.dock_widget.btnShowNo.setChecked(True)
self.dock_widget.btnShowYes.setChecked(False)
self.start_processing()
self.update_progress(10)
self.load_type_inspections()
self.dock_widget.tabWidget.setTabEnabled(1, True)
self.dock_widget.tabWidget.setTabEnabled(2, True)
self.set_config(key='imageSource', value='BING')
self.update_progress(30)
self.inspection_controller.on_change_tab(1)
self.show_config_url(False)
self.show_local_config(False)
self.enable_config_buttons(False)
self.dock_widget.interpreterName.setEnabled(False)
self.dock_widget.btnFile.setEnabled(False)
self.dock_widget.btnWorkingDirectory.setEnabled(False)
self.dock_widget.btnInitInspections.setVisible(False)
self.update_progress(60)
self.plugin_actions()
self.update_progress(100)
self.finish_progress()
def zoom_to_tile_layer(self):
self.iface.setActiveLayer(self.current_pixels_layer)
self.iface.zoomToActiveLayer()
def plugin_actions(self, connect=True):
# Define all connections in a list of tuples
connections = [
(self.dock_widget.btnFile.clicked, self.open_tiles_file),
(self.dock_widget.btnWorkingDirectory.clicked, self.get_dir_path),
(self.dock_widget.btnClearSelectionBing.clicked, self.inspection_controller.remove_selection),
(self.dock_widget.btnClearSelectionGoogle.clicked, self.inspection_controller.remove_selection),
(self.dock_widget.btnInitInspections.clicked, self.init_inspections),
(self.dock_widget.btnLoadClasses.clicked, self.load_classes),
(self.dock_widget.btnFinishBing.clicked, self.inspection_controller.start_inspection_google),
(self.dock_widget.tabWidget.currentChanged, self.inspection_controller.on_change_tab),
(self.dock_widget.sameImage.clicked, self.inspection_controller.set_same_image),
(self.dock_widget.importBingClassification.clicked, self.inspection_controller.import_classes_bing),
(self.dock_widget.btnConfigLocal.clicked, partial(self.on_config_buttons_toggled, 'Local')),
(self.dock_widget.btnConfigURL.clicked, partial(self.on_config_buttons_toggled, 'URL')),
(self.dock_widget.btnShowYes.clicked, partial(self.on_config_buttons_toggled, 'Yes')),
(self.dock_widget.btnShowNo.clicked, partial(self.on_config_buttons_toggled, 'No')),
(self.dock_widget.btnNewInspection.clicked, self.new_inspection),
(self.dock_widget.zoom.clicked, self.zoom_to_tile_layer),
(self.dock_widget.btnSkip.clicked, self.inspection_controller.skip_tile),
(self.dock_widget.comboMode.currentIndexChanged, self.on_mode_change)
]
# If connecting
if connect:
for signal, slot in connections:
signal.connect(slot)
# If disconnecting
else:
for signal, slot in connections:
try:
signal.disconnect(slot)
except TypeError as e:
pass
def reset_screen(self):
self.dock_widget.btnInitInspections.setVisible(False)
self.dock_widget.btnClearSelectionBing.setVisible(False)
self.dock_widget.btnClearSelectionGoogle.setVisible(False)
self.dock_widget.btnLoadClasses.setVisible(False)
self.dock_widget.tabWidget.setTabEnabled(1, False)
self.dock_widget.tabWidget.setTabEnabled(2, False)
self.dock_widget.tabWidget.setTabEnabled(3, False)
self.dock_widget.labelClassBing.setVisible(False)
self.dock_widget.labelClassGoogle.setVisible(False)
self.dock_widget.selectedClassBing.setVisible(False)
self.dock_widget.selectedClassGoogle.setVisible(False)
self.dock_widget.classesBing.setVisible(False)
self.dock_widget.classesGoogle.setVisible(False)
self.dock_widget.importBingClassification.setVisible(False)
self.dock_widget.btnFinishBing.setVisible(False)
self.dock_widget.bingStartDate.setEnabled(False)
self.dock_widget.btnNext.setVisible(False)
self.dock_widget.btnNext.setEnabled(False)
self.dock_widget.bingEndDate.setEnabled(False)
self.dock_widget.imageDate.setMaximumDateTime(datetime.now())
self.dock_widget.lblSearch.setVisible(False)
self.dock_widget.spinSearch.setVisible(False)
self.dock_widget.btnSearch.setVisible(False)
self.dock_widget.btnNewInspection.setVisible(False)
self.dock_widget.zoom.setVisible(False)
self.dock_widget.btnSkip.setVisible(False)
self.show_config_url(False)
self.dock_widget.btnConfigLocal.setChecked(True)
self.dock_widget.btnShowNo.setChecked(True)
self.dock_widget.comboMode.setEnabled(True)
self.dock_widget.btnNext.setToolTip("Generate GPKG of the inspected and classified tile.")
self.dock_widget.spinSearch.setToolTip("Type the FID that you want to search.")
self.dock_widget.btnSearch.setToolTip("Run search of tile by FID")
self.dock_widget.btnNewInspection.setToolTip("Create new Inspection")
self.dock_widget.zoom.setToolTip("Zoom in on the current layer of tiles being inspected.")
self.dock_widget.btnSkip.setToolTip("Skip the current tile.")
def remove_datasource(self):
for extension in ['.gpkg-shm', '.gpkg-wal', 'gpkg']:
self.remove_files_with_extension('/datasource', extension)
def reset_plugin_instance(self, reset=True):
if reset:
QgsProject.instance().clear()
self.iface.mainWindow().statusBar().hide()
if hasattr(self, 'dock_widget'):
if hasattr(self.dock_widget, 'fieldFileName'):
self.dock_widget.fieldFileName.setText('')
if hasattr(self.dock_widget, 'interpreterName'):
self.dock_widget.interpreterName.setText('')
if hasattr(self.dock_widget, 'fieldWorkingDirectory'):
self.dock_widget.fieldWorkingDirectory.setText('')
if hasattr(self.dock_widget, 'imageDate'):
self.dock_widget.imageDate.clear()
self.iface.actionPan().trigger()
self.remove_datasource()
def new_inspection(self):
msg = QMessageBox()
msg.setIcon(QMessageBox.Question)
msg.setText('Do you want to start a new inspection?')
msg.setWindowTitle('INSPECTION TILES')
msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
QApplication.instance().setOverrideCursor(Qt.ArrowCursor)
retval = msg.exec_()
# 65536 -> No | 16384 -> Yes
if retval == 16384:
self.reset_content()
self.reset_screen()
self.reset_plugin_instance()
self.open_google_satellite()
self.open_bing_satellite()
self.enable_config_buttons(enable=True)
self.show_local_config(show=True)
self.iface.actionZoomToSelected().trigger()
self.current_tile_index = 0
self.current_pixels_layer = None
def load_campaign_conf(self):
if self.load_config_from == 'local':
self.dock_widget.btnConfigLocal.setChecked(True)
self.dock_widget.btnConfigURL.setChecked(False)
inspection_config = self.get_config('inspectionConfig')
self.campaigns_config = inspection_config
self.dock_widget.localConfig.setPlainText(
json.dumps(inspection_config, indent=4)
)
else:
self.dock_widget.btnConfigLocal.setChecked(False)
self.dock_widget.btnConfigURL.setChecked(True)
self.dock_widget.configURL.setText(
self.get_config('configURL')
)
def start_processing(self):
# Remove existing progress bar if any
if self.progress_message_bar:
self.finish_progress()
self.progress_message_bar = self.iface.messageBar().createMessage("")
self.progress_bar = QProgressBar()
self.progress_bar.setMaximum(100)
# Create a QWidget to hold the progress bar
container = QWidget()
layout = QHBoxLayout(container)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(QLabel("Processing..."))
layout.addWidget(self.progress_bar)
container.setLayout(layout)
self.progress_message_bar.layout().addWidget(container)
self.iface.messageBar().pushWidget(self.progress_message_bar, Qgis.Info)
def update_progress(self, value):
if self.progress_bar:
self.progress_bar.setValue(value)
else:
self.start_processing()