from qgis.core import QgsApplication, QgsField, QgsProject, \ QgsProcessingFeedback, QgsVectorLayer, QgsVectorDataProvider, \ QgsExpressionContext, QgsExpressionContextUtils from qgis.analysis import QgsNativeAlgorithms import processing class ScrubLayer: def __init__(self, qgis_path, layer_path, layer_name): # Set the path to QGIS installation QgsApplication.setPrefixPath(qgis_path, True) # Initialize QGIS application qgs = QgsApplication([], False) qgs.initQgis() self.layer_path = layer_path self.layer_name = layer_name self.layer = self.load_layer() def load_layer(self): the_layer = QgsVectorLayer(self.layer_path, self.layer_name, 'ogr') if not the_layer.isValid(): raise ValueError(f'Failed to load layer {self.layer_name} from {self.layer_path}') else: QgsProject.instance().addMapLayer(the_layer) return the_layer def fix_geometries(self, fixed_layer): QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) fix_geometries_params = { 'INPUT': self.layer, 'METHOD': 0, 'OUTPUT': fixed_layer } processing.run("native:fixgeometries", fix_geometries_params) def create_spatial_index(self): QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) create_spatial_index_params = { 'INPUT': self.layer, 'OUTPUT': 'Output' } processing.run("native:createspatialindex", create_spatial_index_params) print(f'Creating spatial index for {self.layer_name} is completed.') def clip_layer(self, overlay_layer, clipped_layer): QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) clip_layer_params = { 'INPUT': self.layer_path, 'OVERLAY': overlay_layer, 'FILTER_EXPRESSION': '', 'FILTER_EXTENT': None, 'OUTPUT': clipped_layer } processing.run("native:clip", clip_layer_params) print(f'Clipping of {self.layer_name} is completed.') @staticmethod def cleanup(): QgsApplication.exitQgis()