-
Notifications
You must be signed in to change notification settings - Fork 0
/
cbers_explorer_dockwidget.py
221 lines (178 loc) · 9.55 KB
/
cbers_explorer_dockwidget.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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
CbersExplorerDockWidget
A QGIS plugin
CBERS Explorer is a plugin designed to help find images from CBERS-4A/WPM - Multispectral and Panchromatic Bands Fusioned.
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2024-07-18
git sha : $Format:%H$
copyright : (C) 2024 by Tharles de Sousa Andrade
email : irtharles@gmail.com
***************************************************************************/
/***************************************************************************
* *
* 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 os
from qgis.PyQt import QtGui, QtWidgets, uic
from qgis.PyQt.QtCore import pyqtSignal
from PyQt5 import QtWidgets
from PyQt5.QtCore import QCoreApplication, QTranslator, QDate
from PyQt5.QtWidgets import QVBoxLayout, QLabel, QPushButton, QHBoxLayout, QDateEdit, QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox
from qgis.core import QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsProject, QgsRasterLayer
from qgis.utils import iface
from osgeo import gdal
import requests
import tempfile
FORM_CLASS, _ = uic.loadUiType(os.path.join(
os.path.dirname(__file__), 'cbers_explorer_dockwidget_base.ui'))
class CbersExplorerDockWidget(QtWidgets.QDockWidget, FORM_CLASS):
closingPlugin = pyqtSignal()
def __init__(self, parent=None):
"""Constructor."""
super(CbersExplorerDockWidget, self).__init__(parent)
self.translator = QTranslator()
self.load_translations()
self.setWindowTitle(self.tr('CBERS-4A WPM Explorer'))
self.widget = QtWidgets.QWidget()
self.layout = QVBoxLayout(self.widget)
self.bbox_label = QLabel(self.tr('Bounding Box: '))
self.layout.addWidget(self.bbox_label)
self.update_bbox_button = QPushButton(self.tr('Atualizar Bounding Box'))
self.update_bbox_button.clicked.connect(self.update_bbox)
self.layout.addWidget(self.update_bbox_button)
date_layout = QHBoxLayout()
self.start_date_label = QLabel(self.tr('Data de Início:'))
date_layout.addWidget(self.start_date_label)
self.start_date_edit = QDateEdit()
self.start_date_edit.setCalendarPopup(True)
self.start_date_edit.setDate(QDate.currentDate().addYears(-1))
date_layout.addWidget(self.start_date_edit)
self.end_date_label = QLabel(self.tr('Data de Fim:'))
date_layout.addWidget(self.end_date_label)
self.end_date_edit = QDateEdit()
self.end_date_edit.setCalendarPopup(True)
self.end_date_edit.setDate(QDate.currentDate())
date_layout.addWidget(self.end_date_edit)
self.layout.addLayout(date_layout)
self.collection_label = QLabel(self.tr('Coleção: CB4A-WPM-PCA-FUSED-1'))
self.layout.addWidget(self.collection_label)
self.fetch_button = QPushButton(self.tr('Buscar Imagens'))
self.fetch_button.clicked.connect(self.fetch_images)
self.layout.addWidget(self.fetch_button)
self.result_label = QLabel('')
self.layout.addWidget(self.result_label)
self.table_widget = QTableWidget()
self.table_widget.setColumnCount(4)
self.table_widget.setHorizontalHeaderLabels([
self.tr("ID da Imagem"),
self.tr("Data de Criação"),
self.tr("Data de Alteração"),
self.tr("Copiar URL")
])
self.table_widget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
self.table_widget.cellClicked.connect(self.load_selected_image) # Connect cell click to load image
self.layout.addWidget(self.table_widget)
self.setWidget(self.widget)
self.features = []
self.update_bbox() # Initialize bbox
def load_translations(self):
locale = QCoreApplication.instance().property('locale_user')
translation_loaded = False
if locale:
translation_file = os.path.join(os.path.dirname(__file__), 'i18n', f'cbers_explorer_{locale}.qm')
translation_loaded = self.translator.load(translation_file)
if not translation_loaded:
# Load default English translation if specific locale translation is not found
translation_file = os.path.join(os.path.dirname(__file__), 'i18n', 'cbers_explorer_en.qm')
self.translator.load(translation_file)
QCoreApplication.installTranslator(self.translator)
def update_bbox(self):
bbox = self.get_bbox()
self.bbox_label.setText(self.tr('Bounding Box: {bbox}').format(bbox=bbox))
def fetch_images(self):
bbox = self.get_bbox()
start_date = self.start_date_edit.date().toString("yyyy-MM-ddT00:00:00.000Z")
end_date = self.end_date_edit.date().toString("yyyy-MM-ddT23:59:59.999Z")
url = self.build_url(bbox, start_date, end_date)
data = self.consume_service(url)
if 'features' in data and len(data['features']) > 0:
self.update_features(data['features'])
else:
QMessageBox.information(self, self.tr('Informação'), self.tr('Nenhuma imagem encontrada para os parâmetros fornecidos.'))
def get_bbox(self):
canvas = iface.mapCanvas()
extent = canvas.extent()
# Sistema de referência de coordenadas (CRS) de destino
crs_dest = QgsCoordinateReferenceSystem('EPSG:4326')
# CRS da camada atual
crs_src = canvas.mapSettings().destinationCrs()
# Transformação de coordenadas
transform = QgsCoordinateTransform(crs_src, crs_dest, QgsProject.instance())
# Extensão transformada
extent_transformed = transform.transformBoundingBox(extent)
bbox = [extent_transformed.xMinimum(), extent_transformed.yMinimum(), extent_transformed.xMaximum(), extent_transformed.yMaximum()]
return bbox
def build_url(self, bbox, start_date, end_date):
base_url = 'https://data.inpe.br/bdc/stac/v1/search'
collections = 'CB4A-WPM-PCA-FUSED-1'
bbox_str = f'{bbox[0]}%2C{bbox[1]}%2C{bbox[2]}%2C{bbox[3]}'
datetime = f'{start_date}%2F{end_date}'
url = f'{base_url}?datetime={datetime}&bbox={bbox_str}&collections={collections}'
return url
def consume_service(self, url):
headers = {'Accept': 'application/geo+json'}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
raise Exception(self.tr("Erro na requisição: {status_code}, {text}").format(status_code=response.status_code, text=response.text))
def update_features(self, features):
self.features = features
self.table_widget.setRowCount(0)
for feature in features:
row_position = self.table_widget.rowCount()
self.table_widget.insertRow(row_position)
self.table_widget.setItem(row_position, 0, QTableWidgetItem(feature['id']))
self.table_widget.setItem(row_position, 1, QTableWidgetItem(feature['properties']['created']))
self.table_widget.setItem(row_position, 2, QTableWidgetItem(feature['properties']['updated']))
copy_button = QPushButton(self.tr("Copiar URL"))
copy_button.clicked.connect(lambda _, f=feature: self.copy_to_clipboard(f['assets']['tci']['href']))
self.table_widget.setCellWidget(row_position, 3, copy_button)
def load_selected_image(self, row, column):
selected_id = self.table_widget.item(row, 0).text()
for feature in self.features:
if feature['id'] == selected_id:
cog_url = feature['assets']['tci']['href']
id = feature['id']
self.add_cog_to_map(id, cog_url)
break
def build_and_load_vrt(self, urls, label):
vrt_path = tempfile.mktemp(suffix='.vrt')
options = gdal.BuildVRTOptions(separate=False)
gdal.BuildVRT(vrt_path, urls, options=options)
layer = QgsRasterLayer(vrt_path, label)
if layer.isValid():
QgsProject.instance().addMapLayer(layer)
return layer
else:
return None
def add_cog_to_map(self, id, cog_url):
urls = [f"/vsicurl/{cog_url}"]
layer = self.build_and_load_vrt(urls, id)
if layer is None:
QMessageBox.critical(None, self.tr('Erro'), self.tr('Falha ao carregar a imagem no mapa.'))
def copy_to_clipboard(self, text):
clipboard = QCoreApplication.instance().clipboard()
clipboard.setText(text)
QMessageBox.information(self, self.tr("Informação"), self.tr("URL copiada para a área de transferência."))
def closeEvent(self, event):
self.closingPlugin.emit()
event.accept()