File: ScriptAlgorithm.py

package info (click to toggle)
qgis 2.14.11%2Bdfsg-3%2Bdeb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 991,448 kB
  • ctags: 73,105
  • sloc: cpp: 535,362; python: 162,580; xml: 16,494; ansic: 8,031; sh: 1,788; perl: 1,559; sql: 727; yacc: 319; lex: 269; makefile: 251
file content (364 lines) | stat: -rw-r--r-- 14,564 bytes parent folder | download | duplicates (2)
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
# -*- coding: utf-8 -*-

"""
***************************************************************************
    ScriptAlgorithm.py
    ---------------------
    Date                 : August 2012
    Copyright            : (C) 2012 by Victor Olaya
    Email                : volayaf at gmail dot 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.                                   *
*                                                                         *
***************************************************************************
"""

__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'

# This will get replaced with a git SHA1 when you do a git archive

__revision__ = '$Format:%H$'

import os
from PyQt4 import QtGui
import re
import json
from processing.core.GeoAlgorithm import GeoAlgorithm
from processing.gui.Help2Html import getHtmlFromHelpFile
from processing.core.parameters import ParameterRaster
from processing.core.parameters import ParameterTable
from processing.core.parameters import ParameterVector
from processing.core.parameters import ParameterMultipleInput
from processing.core.parameters import ParameterString
from processing.core.parameters import ParameterCrs
from processing.core.parameters import ParameterNumber
from processing.core.parameters import ParameterBoolean
from processing.core.parameters import ParameterSelection
from processing.core.parameters import ParameterTableField
from processing.core.parameters import ParameterExtent
from processing.core.parameters import ParameterFile
from processing.core.parameters import getParameterFromString
from processing.core.outputs import OutputTable
from processing.core.outputs import OutputVector
from processing.core.outputs import OutputRaster
from processing.core.outputs import OutputNumber
from processing.core.outputs import OutputString
from processing.core.outputs import OutputHTML
from processing.core.outputs import OutputFile
from processing.core.outputs import OutputDirectory
from processing.core.outputs import getOutputFromString
from processing.script.WrongScriptException import WrongScriptException

pluginPath = os.path.split(os.path.dirname(__file__))[0]


class ScriptAlgorithm(GeoAlgorithm):

    def __init__(self, descriptionFile, script=None):
        """The script parameter can be used to directly pass the code
        of the script without a file.

        This is to be used from the script edition dialog, but should
        not be used in other cases.
        """

        GeoAlgorithm.__init__(self)
        self._icon = QtGui.QIcon(os.path.join(pluginPath, 'images', 'script.png'))

        self.script = script
        self.allowEdit = True
        self.noCRSWarning = False
        self.descriptionFile = descriptionFile
        if script is not None:
            self.defineCharacteristicsFromScript()
        if descriptionFile is not None:
            self.defineCharacteristicsFromFile()

    def getCopy(self):
        newone = ScriptAlgorithm(self.descriptionFile)
        newone.provider = self.provider
        return newone

    def getIcon(self):
        return self._icon

    def defineCharacteristicsFromFile(self):
        self.script = ''
        self.silentOutputs = []
        filename = os.path.basename(self.descriptionFile)
        self.name = filename[:filename.rfind('.')].replace('_', ' ')
        self.group = self.tr('User scripts', 'ScriptAlgorithm')
        lines = open(self.descriptionFile)
        line = lines.readline()
        while line != '':
            if line.startswith('##'):
                try:
                    self.processParameterLine(line.strip('\n'))
                except:
                    raise WrongScriptException(
                        self.tr('Could not load script: %s\n'
                                'Problem with line: %s', 'ScriptAlgorithm') % (self.descriptionFile, line))
            self.script += line
            line = lines.readline()
        lines.close()
        if self.group == self.tr('[Test scripts]', 'ScriptAlgorithm'):
            self.showInModeler = False
            self.showInToolbox = False

    def defineCharacteristicsFromScript(self):
        lines = self.script.split('\n')
        self.silentOutputs = []
        self.name, self.i18n_name = self.trAlgorithm('[Unnamed algorithm]', 'ScriptAlgorithm')
        self.group, self.i18n_group = self.trAlgorithm('User scripts', 'ScriptAlgorithm')
        for line in lines:
            if line.startswith('##'):
                try:
                    self.processParameterLine(line.strip('\n'))
                except:
                    pass

    def checkInputCRS(self):
        if self.noCRSWarning:
            return True
        else:
            return GeoAlgorithm.checkInputCRS(self)

    def createDescriptiveName(self, s):
        return s.replace('_', ' ')

    def processParameterLine(self, line):
        param = None
        out = None
        line = line.replace('#', '')

        # If the line is in the format of the text description files for
        # normal algorithms, then process it using parameter and output
        # factories
        if '|' in line:
            self.processDescriptionParameterLine(line)
            return
        if line == "nomodeler":
            self.showInModeler = False
            return
        if line == "nocrswarning":
            self.noCRSWarning = True
            return
        tokens = line.split('=', 1)
        desc = self.createDescriptiveName(tokens[0])
        if tokens[1].lower().strip() == 'group':
            self.group = self.i18n_group = tokens[0]
            return
        if tokens[1].lower().strip() == 'name':
            self.name = self.i18n_name = tokens[0]
            return

        if tokens[1].lower().strip().startswith('output'):
            outToken = tokens[1].strip()[len('output') + 1:]
            out = self.processOutputParameterToken(outToken)

        elif tokens[1].lower().strip().startswith('optional'):
            optToken = tokens[1].strip()[len('optional') + 1:]
            param = self.processInputParameterToken(optToken, tokens[0])
            if param:
                param.optional = True

        else:
            param = self.processInputParameterToken(tokens[1], tokens[0])

        if param is not None:
            self.addParameter(param)
        elif out is not None:
            out.name = tokens[0]
            out.description = desc
            self.addOutput(out)
        else:
            raise WrongScriptException(
                self.tr('Could not load script: %s.\n'
                        'Problem with line "%s"', 'ScriptAlgorithm') % (self.descriptionFile or '', line))

    def processInputParameterToken(self, token, name):
        param = None

        descName = self.createDescriptiveName(name)

        if token.lower().strip() == 'raster':
            param = ParameterRaster(name, descName, False)
        elif token.lower().strip() == 'vector':
            param = ParameterVector(name, descName,
                                    [ParameterVector.VECTOR_TYPE_ANY])
        elif token.lower().strip() == 'vector point':
            param = ParameterVector(name, descName,
                                    [ParameterVector.VECTOR_TYPE_POINT])
        elif token.lower().strip() == 'vector line':
            param = ParameterVector(name, descName,
                                    [ParameterVector.VECTOR_TYPE_LINE])
        elif token.lower().strip() == 'vector polygon':
            param = ParameterVector(name, descName,
                                    [ParameterVector.VECTOR_TYPE_POLYGON])
        elif token.lower().strip() == 'table':
            param = ParameterTable(name, descName, False)
        elif token.lower().strip() == 'multiple raster':
            param = ParameterMultipleInput(name, descName,
                                           ParameterMultipleInput.TYPE_RASTER)
            param.optional = False
        elif token.lower().strip() == 'multiple vector':
            param = ParameterMultipleInput(name, descName,
                                           ParameterMultipleInput.TYPE_VECTOR_ANY)
            param.optional = False
        elif token.lower().strip().startswith('selectionfromfile'):
            options = token.strip()[len('selectionfromfile '):].split(';')
            param = ParameterSelection(name, descName, options, isSource=True)
        elif token.lower().strip().startswith('selection'):
            options = token.strip()[len('selection '):].split(';')
            param = ParameterSelection(name, descName, options)
        elif token.lower().strip().startswith('boolean'):
            default = token.strip()[len('boolean') + 1:]
            if default:
                param = ParameterBoolean(name, descName, default)
            else:
                param = ParameterBoolean(name, descName)
        elif token.lower().strip() == 'extent':
            param = ParameterExtent(name, descName)
        elif token.lower().strip() == 'file':
            param = ParameterFile(name, descName, False)
        elif token.lower().strip() == 'folder':
            param = ParameterFile(name, descName, True)
        elif token.lower().strip().startswith('number'):
            default = token.strip()[len('number') + 1:]
            if default:
                param = ParameterNumber(name, descName, default=default)
            else:
                param = ParameterNumber(name, descName)
        elif token.lower().strip().startswith('field'):
            field = token.strip()[len('field') + 1:]
            found = False
            for p in self.parameters:
                if p.name == field:
                    found = True
                    break
            if found:
                param = ParameterTableField(name, descName, field)
        elif token.lower().strip().startswith('string'):
            default = token.strip()[len('string') + 1:]
            if default:
                param = ParameterString(name, descName, default)
            else:
                param = ParameterString(name, descName)
        elif token.lower().strip().startswith('longstring'):
            default = token.strip()[len('longstring') + 1:]
            if default:
                param = ParameterString(name, descName, default, multiline=True)
            else:
                param = ParameterString(name, descName, multiline=True)
        elif token.lower().strip().startswith('crs'):
            default = token.strip()[len('crs') + 1:]
            if default:
                param = ParameterCrs(name, descName, default)
            else:
                param = ParameterCrs(name, descName)

        return param

    def processOutputParameterToken(self, token):
        out = None

        if token.lower().strip().startswith('raster'):
            out = OutputRaster()
        elif token.lower().strip().startswith('vector'):
            out = OutputVector()
        elif token.lower().strip().startswith('table'):
            out = OutputTable()
        elif token.lower().strip().startswith('html'):
            out = OutputHTML()
        elif token.lower().strip().startswith('file'):
            out = OutputFile()
            subtokens = token.split(' ')
            if len(subtokens) > 2:
                out.ext = subtokens[2]
        elif token.lower().strip().startswith('directory'):
            out = OutputDirectory()
        elif token.lower().strip().startswith('number'):
            out = OutputNumber()
        elif token.lower().strip().startswith('string'):
            out = OutputString()

        return out

    def processDescriptionParameterLine(self, line):
        try:
            if line.startswith('Parameter'):
                self.addParameter(getParameterFromString(line))
            elif line.startswith('*Parameter'):
                param = getParameterFromString(line[1:])
                param.isAdvanced = True
                self.addParameter(param)
            else:
                self.addOutput(getOutputFromString(line))
        except Exception:
            raise WrongScriptException(
                self.tr('Could not load script: %s.\n'
                        'Problem with line %d', 'ScriptAlgorithm') % (self.descriptionFile or '', line))

    def processAlgorithm(self, progress):

        script = 'import processing\n'

        ns = {}
        ns['progress'] = progress
        ns['scriptDescriptionFile'] = self.descriptionFile

        for param in self.parameters:
            ns[param.name] = param.value

        for out in self.outputs:
            ns[out.name] = out.value

        script += self.script
        exec((script), ns)
        for out in self.outputs:
            out.setValue(ns[out.name])

    def help(self):
        if self.descriptionFile is None:
            return False, None
        helpfile = self.descriptionFile + '.help'
        if os.path.exists(helpfile):
            return True, getHtmlFromHelpFile(self, helpfile)
        else:
            return False, None

    def shortHelp(self):
        if self.descriptionFile is None:
            return None
        helpFile = unicode(self.descriptionFile) + '.help'
        if os.path.exists(helpFile):
            with open(helpFile) as f:
                try:
                    descriptions = json.load(f)
                    if 'ALG_DESC' in descriptions:
                        return self._formatHelp(unicode(descriptions['ALG_DESC']))
                except:
                    return None
        return None

    def getParameterDescriptions(self):
        descs = {}
        if self.descriptionFile is None:
            return descs
        helpFile = unicode(self.descriptionFile) + '.help'
        if os.path.exists(helpFile):
            with open(helpFile) as f:
                try:
                    descriptions = json.load(f)
                    for param in self.parameters:
                        if param.name in descriptions:
                            descs[param.name] = unicode(descriptions[param.name])
                except:
                    return descs
        return descs