wms_base.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. """!
  2. @brief Preparation of parameters for drivers, which download it, and managing downloaded data.
  3. List of classes:
  4. - wms_base::WMSBase
  5. - wms_base::GRASSImporter
  6. - wms_base::WMSDriversInfo
  7. (C) 2012-2016 by the GRASS Development Team
  8. This program is free software under the GNU General Public License
  9. (>=v2). Read the file COPYING that comes with GRASS for details.
  10. @author Stepan Turek <stepan.turek seznam.cz> (Mentor: Martin Landa)
  11. """
  12. import os
  13. from math import ceil
  14. import base64
  15. try:
  16. from urllib2 import Request, urlopen, HTTPError
  17. from httplib import HTTPException
  18. except ImportError:
  19. from urllib.request import Request, urlopen
  20. from urllib.error import HTTPError
  21. from http.client import HTTPException
  22. import grass.script as grass
  23. from grass.exceptions import CalledModuleError
  24. # i18N
  25. import gettext
  26. gettext.install('grassmods', os.path.join(os.getenv("GISBASE"), 'locale'))
  27. class WMSBase:
  28. def __init__(self):
  29. # these variables are information for destructor
  30. self.temp_files_to_cleanup = []
  31. self.params = {}
  32. self.tile_size = {'bbox': None}
  33. self.temp_map = None
  34. self.temp_warpmap = None
  35. def __del__(self):
  36. # tries to remove temporary files, all files should be
  37. # removed before, implemented just in case of unexpected
  38. # stop of module
  39. for temp_file in self.temp_files_to_cleanup:
  40. grass.try_remove(temp_file)
  41. def _debug(self, fn, msg):
  42. grass.debug("%s.%s: %s" %
  43. (self.__class__.__name__, fn, msg))
  44. def _initializeParameters(self, options, flags):
  45. self._debug("_initialize_parameters", "started")
  46. # initialization of module parameters (options, flags)
  47. self.params['driver'] = options['driver']
  48. drv_info = WMSDriversInfo()
  49. driver_props = drv_info.GetDrvProperties(options['driver'])
  50. self._checkIgnoeredParams(options, flags, driver_props)
  51. self.params['capfile'] = options['capfile'].strip()
  52. for key in ['url', 'layers', 'styles', 'method']:
  53. self.params[key] = options[key].strip()
  54. self.flags = flags
  55. if self.flags['o']:
  56. self.params['transparent'] = 'FALSE'
  57. else:
  58. self.params['transparent'] = 'TRUE'
  59. for key in ['password', 'username', 'urlparams']:
  60. self.params[key] = options[key]
  61. if (self.params ['password'] and self.params ['username'] == '') or \
  62. (self.params['password'] == '' and self.params['username']):
  63. grass.fatal(_("Please insert both %s and %s parameters or none of them." %
  64. ('password', 'username')))
  65. self.params['bgcolor'] = options['bgcolor'].strip()
  66. if options['format'] == "jpeg" and \
  67. not 'format' in driver_props['ignored_params']:
  68. if not flags['o'] and \
  69. 'WMS' in self.params['driver']:
  70. grass.warning(_("JPEG format does not support transparency"))
  71. self.params['format'] = drv_info.GetFormat(options['format'])
  72. if not self.params['format']:
  73. self.params['format'] = self.params['format']
  74. # TODO: get srs from Tile Service file in OnEarth_GRASS driver
  75. self.params['srs'] = int(options['srs'])
  76. if self.params['srs'] <= 0 and not 'srs' in driver_props['ignored_params']:
  77. grass.fatal(_("Invalid EPSG code %d") % self.params['srs'])
  78. self.params['wms_version'] = options['wms_version']
  79. if "CRS" in GetSRSParamVal(self.params['srs']) and self.params['wms_version'] == "1.1.1":
  80. self.params['wms_version'] = "1.3.0"
  81. grass.warning(
  82. _("WMS version <1.3.0> will be used, because version <1.1.1> does not support <%s>projection") %
  83. GetSRSParamVal(
  84. self.params['srs']))
  85. if self.params['wms_version'] == "1.3.0":
  86. self.params['proj_name'] = "CRS"
  87. else:
  88. self.params['proj_name'] = "SRS"
  89. # read projection info
  90. self.proj_location = grass.read_command('g.proj',
  91. flags='jf').rstrip('\n')
  92. self.proj_location = self._modifyProj(self.proj_location)
  93. if self.params['srs'] in [3857, 900913]:
  94. # HACK: epsg 3857 def: http://spatialreference.org/ref/sr-org/7483/
  95. # g.proj can return: ...+a=6378137 +rf=298.257223563... (WGS84 elipsoid def instead of sphere), it can make 20km shift in Y, when raster is transformed
  96. # needed to be tested on more servers
  97. self.proj_srs = '+proj=merc +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +no_defs +a=6378137 +b=6378137 +nadgrids=@null +to_meter=1'
  98. else:
  99. self.proj_srs = grass.read_command('g.proj',
  100. flags='jf',
  101. epsg=str(GetEpsg(self.params['srs'])))
  102. self.proj_srs = self.proj_srs.rstrip('\n')
  103. self.proj_srs = self._modifyProj(self.proj_srs)
  104. if not self.proj_srs or not self.proj_location:
  105. grass.fatal(_("Unable to get projection info"))
  106. self.region = options['region']
  107. min_tile_size = 100
  108. maxcols = int(options['maxcols'])
  109. if maxcols <= min_tile_size:
  110. grass.fatal(_("Maxcols must be greater than 100"))
  111. maxrows = int(options['maxrows'])
  112. if maxrows <= min_tile_size:
  113. grass.fatal(_("Maxrows must be greater than 100"))
  114. # setting optimal tile size according to maxcols and maxrows constraint
  115. # and region cols and rows
  116. self.tile_size['cols'] = int(
  117. self.region['cols'] /
  118. ceil(
  119. self.region['cols'] /
  120. float(maxcols)))
  121. self.tile_size['rows'] = int(
  122. self.region['rows'] /
  123. ceil(
  124. self.region['rows'] /
  125. float(maxrows)))
  126. # default format for GDAL library
  127. self.gdal_drv_format = "GTiff"
  128. self._debug("_initialize_parameters", "finished")
  129. def _modifyProj(self, proj):
  130. """!Modify proj.4 string for usage in this module"""
  131. # add +wktext parameter to avoid droping of +nadgrids parameter (if presented) in gdalwarp
  132. if '+nadgrids=' in proj and ' +wktext' not in proj:
  133. proj += ' +wktext'
  134. return proj
  135. def _checkIgnoeredParams(self, options, flags, driver_props):
  136. """!Write warnings for set parameters and flags, which chosen driver does not use."""
  137. not_relevant_params = []
  138. for i_param in driver_props['ignored_params']:
  139. if i_param in options and \
  140. options[i_param] and \
  141. i_param not in ['srs', 'wms_version', 'format']: # params with default value
  142. not_relevant_params.append('<' + i_param + '>')
  143. if len(not_relevant_params) > 0:
  144. grass.warning(_("These parameter are ignored: %s\n\
  145. %s driver does not support the parameters." %
  146. (','.join(not_relevant_params), options['driver'])))
  147. not_relevant_flags = []
  148. for i_flag in driver_props['ignored_flags']:
  149. if flags[i_flag]:
  150. not_relevant_flags.append('<' + i_flag + '>')
  151. if len(not_relevant_flags) > 0:
  152. grass.warning(_("These flags are ignored: %s\n\
  153. %s driver does not support the flags." %
  154. (','.join(not_relevant_flags), options['driver'])))
  155. def GetMap(self, options, flags):
  156. """!Download data from WMS server."""
  157. self._initializeParameters(options, flags)
  158. self.bbox = self._computeBbox()
  159. self.temp_map = self._download()
  160. if not self.temp_map:
  161. return
  162. self._reprojectMap()
  163. return self.temp_warpmap
  164. def _fetchCapabilities(self, options):
  165. """!Download capabilities from WMS server
  166. """
  167. cap_url = options['url'].strip()
  168. if "?" in cap_url:
  169. cap_url += "&"
  170. else:
  171. cap_url += "?"
  172. if 'WMTS' in options['driver']:
  173. cap_url += "SERVICE=WMTS&REQUEST=GetCapabilities&VERSION=1.0.0"
  174. elif 'OnEarth' in options['driver']:
  175. cap_url += "REQUEST=GetTileService"
  176. else:
  177. cap_url += "SERVICE=WMS&REQUEST=GetCapabilities&VERSION=" + options['wms_version']
  178. if options['urlparams']:
  179. cap_url += "&" + options['urlparams']
  180. grass.debug('Fetching capabilities file.\n%s' % cap_url)
  181. try:
  182. cap = self._fetchDataFromServer(cap_url, options['username'], options['password'])
  183. except (IOError, HTTPException) as e:
  184. if isinstance(e, HTTPError) and e.code == 401:
  185. grass.fatal(
  186. _("Authorization failed to <%s> when fetching capabilities") %
  187. options['url'])
  188. else:
  189. msg = _("Unable to fetch capabilities from <{0}>. Reason: ").format(
  190. options['url'])
  191. if hasattr(e, 'reason'):
  192. msg += '{0}'.format(e.reason)
  193. else:
  194. msg += '{0}'.format(e)
  195. grass.fatal(msg)
  196. grass.debug('Fetching capabilities OK')
  197. return cap
  198. def _fetchDataFromServer(self, url, username=None, password=None):
  199. """!Fetch data from server
  200. """
  201. request = Request(url)
  202. if username and password:
  203. base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
  204. request.add_header("Authorization", "Basic %s" % base64string)
  205. try:
  206. return urlopen(request)
  207. except ValueError as error:
  208. grass.fatal("%s" % error)
  209. def GetCapabilities(self, options):
  210. """!Get capabilities from WMS server
  211. """
  212. cap = self._fetchCapabilities(options)
  213. capfile_output = options['capfile_output'].strip()
  214. # save to file
  215. if capfile_output:
  216. try:
  217. temp = open(capfile_output, "w")
  218. temp.write(cap.read())
  219. temp.close()
  220. return
  221. except IOError as error:
  222. grass.fatal(_("Unabble to open file '%s'.\n%s\n" % (cap_file, error)))
  223. # print to output
  224. cap_lines = cap.readlines()
  225. for line in cap_lines:
  226. print(line.rstrip())
  227. def _computeBbox(self):
  228. """!Get region extent for WMS query (bbox)
  229. """
  230. self._debug("_computeBbox", "started")
  231. bbox_region_items = {'maxy': 'n', 'miny': 's', 'maxx': 'e', 'minx': 'w'}
  232. bbox = {}
  233. if self.proj_srs == self.proj_location: # TODO: do it better
  234. for bbox_item, region_item in bbox_region_items.items():
  235. bbox[bbox_item] = self.region[region_item]
  236. # if location projection and wms query projection are
  237. # different, corner points of region are transformed into wms
  238. # projection and then bbox is created from extreme coordinates
  239. # of the transformed points
  240. else:
  241. for bbox_item, region_item in bbox_region_items.items():
  242. bbox[bbox_item] = None
  243. temp_region = self._tempfile()
  244. try:
  245. temp_region_opened = open(temp_region, 'w')
  246. temp_region_opened.write("%f %f\n%f %f\n%f %f\n%f %f\n" %
  247. (self.region['e'], self.region['n'],
  248. self.region['w'], self.region['n'],
  249. self.region['w'], self.region['s'],
  250. self.region['e'], self.region['s']))
  251. except IOError:
  252. grass.fatal(_("Unable to write data into tempfile"))
  253. finally:
  254. temp_region_opened.close()
  255. points = grass.read_command('m.proj', flags='d',
  256. proj_out=self.proj_srs,
  257. proj_in=self.proj_location,
  258. input=temp_region,
  259. quiet=True) # TODO: stdin
  260. grass.try_remove(temp_region)
  261. if not points:
  262. grass.fatal(_("Unable to determine region, %s failed") % 'm.proj')
  263. points = points.splitlines()
  264. if len(points) != 4:
  265. grass.fatal(_("Region definition: 4 points required"))
  266. for point in points:
  267. try:
  268. point = list(map(float, point.split("|")))
  269. except ValueError:
  270. grass.fatal(_('Reprojection of region using m.proj failed.'))
  271. if not bbox['maxy']:
  272. bbox['maxy'] = point[1]
  273. bbox['miny'] = point[1]
  274. bbox['maxx'] = point[0]
  275. bbox['minx'] = point[0]
  276. continue
  277. if bbox['maxy'] < point[1]:
  278. bbox['maxy'] = point[1]
  279. elif bbox['miny'] > point[1]:
  280. bbox['miny'] = point[1]
  281. if bbox['maxx'] < point[0]:
  282. bbox['maxx'] = point[0]
  283. elif bbox['minx'] > point[0]:
  284. bbox['minx'] = point[0]
  285. self._debug("_computeBbox", "finished -> %s" % bbox)
  286. # Ordering of coordinates axis of geographic coordinate
  287. # systems in WMS 1.3.0 is flipped. If self.tile_size['flip_coords'] is
  288. # True, coords in bbox need to be flipped in WMS query.
  289. return bbox
  290. def _reprojectMap(self):
  291. """!Reproject data using gdalwarp if needed
  292. """
  293. # reprojection of raster
  294. if self.proj_srs != self.proj_location: # TODO: do it better
  295. grass.message(_("Reprojecting raster..."))
  296. self.temp_warpmap = grass.tempfile()
  297. if int(os.getenv('GRASS_VERBOSE', '2')) <= 2:
  298. nuldev = open(os.devnull, 'w+')
  299. else:
  300. nuldev = None
  301. if self.params['method'] == "nearest":
  302. gdal_method = "near"
  303. elif self.params['method'] == "linear":
  304. gdal_method = "bilinear"
  305. else:
  306. gdal_method = self.params['method']
  307. #"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs"
  308. # RGB rasters - alpha layer is added for cropping edges of projected raster
  309. try:
  310. if self.temp_map_bands_num == 3:
  311. ps = grass.Popen(['gdalwarp',
  312. '-s_srs', '%s' % self.proj_srs,
  313. '-t_srs', '%s' % self.proj_location,
  314. '-r', gdal_method, '-dstalpha',
  315. self.temp_map, self.temp_warpmap], stdout=nuldev)
  316. # RGBA rasters
  317. else:
  318. ps = grass.Popen(['gdalwarp',
  319. '-s_srs', '%s' % self.proj_srs,
  320. '-t_srs', '%s' % self.proj_location,
  321. '-r', gdal_method,
  322. self.temp_map, self.temp_warpmap], stdout=nuldev)
  323. ps.wait()
  324. except OSError as e:
  325. grass.fatal('%s \nThis can be caused by missing %s utility. ' % (e, 'gdalwarp'))
  326. if nuldev:
  327. nuldev.close()
  328. if ps.returncode != 0:
  329. grass.fatal(_('%s failed') % 'gdalwarp')
  330. grass.try_remove(self.temp_map)
  331. # raster projection is same as projection of location
  332. else:
  333. self.temp_warpmap = self.temp_map
  334. self.temp_files_to_cleanup.remove(self.temp_map)
  335. return self.temp_warpmap
  336. def _tempfile(self):
  337. """!Create temp_file and append list self.temp_files_to_cleanup
  338. with path of file
  339. @return string path to temp_file
  340. """
  341. temp_file = grass.tempfile()
  342. if temp_file is None:
  343. grass.fatal(_("Unable to create temporary files"))
  344. # list of created tempfiles for destructor
  345. self.temp_files_to_cleanup.append(temp_file)
  346. return temp_file
  347. class GRASSImporter:
  348. def __init__(self, opt_output):
  349. self.cleanup_mask = False
  350. self.cleanup_layers = False
  351. # output map name
  352. self.opt_output = opt_output
  353. # suffix for existing mask (during overriding will be saved
  354. # into raster named:self.opt_output + this suffix)
  355. self.original_mask_suffix = "_temp_MASK"
  356. # check names of temporary rasters, which module may create
  357. maps = []
  358. for suffix in ('.red', '.green', '.blue', '.alpha', self.original_mask_suffix):
  359. rast = self.opt_output + suffix
  360. if grass.find_file(rast, element='cell', mapset='.')['file']:
  361. maps.append(rast)
  362. if len(maps) != 0:
  363. grass.fatal(_("Please change output name, or change names of these rasters: %s, "
  364. "module needs to create this temporary maps during execution.") % ",".join(maps))
  365. def __del__(self):
  366. # removes temporary mask, used for import transparent or warped temp_map
  367. if self.cleanup_mask:
  368. # clear temporary mask, which was set by module
  369. try:
  370. grass.run_command('r.mask', quiet=True, flags='r')
  371. except CalledModuleError:
  372. grass.fatal(_('%s failed') % 'r.mask')
  373. # restore original mask, if exists
  374. if grass.find_file(self.opt_output + self.original_mask_suffix,
  375. element='cell', mapset='.')['name']:
  376. try:
  377. mask_copy = self.opt_output + self.original_mask_suffix
  378. grass.run_command('g.copy', quiet=True,
  379. raster=mask_copy + ',MASK')
  380. except CalledModuleError:
  381. grass.fatal(_('%s failed') % 'g.copy')
  382. # remove temporary created rasters
  383. if self.cleanup_layers:
  384. maps = []
  385. for suffix in ('.red', '.green', '.blue', '.alpha', self.original_mask_suffix):
  386. rast = self.opt_output + suffix
  387. if grass.find_file(rast, element='cell', mapset='.')['file']:
  388. maps.append(rast)
  389. if maps:
  390. grass.run_command('g.remove',
  391. quiet=True,
  392. flags='fb',
  393. type='raster',
  394. name=','.join(maps))
  395. # delete environmental variable which overrides region
  396. if 'GRASS_REGION' in os.environ.keys():
  397. os.environ.pop('GRASS_REGION')
  398. def ImportMapIntoGRASS(self, raster):
  399. """!Import raster into GRASS.
  400. """
  401. # importing temp_map into GRASS
  402. try:
  403. grass.run_command('r.in.gdal',
  404. quiet=True, overwrite=True,
  405. input=raster, output=self.opt_output)
  406. except CalledModuleError:
  407. grass.fatal(_('%s failed') % 'r.in.gdal')
  408. # information for destructor to cleanup temp_layers, created
  409. # with r.in.gdal
  410. self.cleanup_layers = True
  411. # setting region for full extend of imported raster
  412. if grass.find_file(self.opt_output + '.red', element='cell', mapset='.')['file']:
  413. region_map = self.opt_output + '.red'
  414. else:
  415. region_map = self.opt_output
  416. os.environ['GRASS_REGION'] = grass.region_env(rast=region_map)
  417. # mask created from alpha layer, which describes real extend
  418. # of warped layer (may not be a rectangle), also mask contains
  419. # transparent parts of raster
  420. if grass.find_file(self.opt_output + '.alpha', element='cell', mapset='.')['name']:
  421. # saving current mask (if exists) into temp raster
  422. if grass.find_file('MASK', element='cell', mapset='.')['name']:
  423. try:
  424. mask_copy = self.opt_output + self.original_mask_suffix
  425. grass.run_command('g.copy', quiet=True,
  426. raster='MASK,' + mask_copy)
  427. except CalledModuleError:
  428. grass.fatal(_('%s failed') % 'g.copy')
  429. # info for destructor
  430. self.cleanup_mask = True
  431. try:
  432. grass.run_command('r.mask',
  433. quiet=True, overwrite=True,
  434. maskcats="0",
  435. flags='i',
  436. raster=self.opt_output + '.alpha')
  437. except CalledModuleError:
  438. grass.fatal(_('%s failed') % 'r.mask')
  439. # TODO one band + alpha band?
  440. if grass.find_file(self.opt_output + '.red', element='cell', mapset='.')['file']:
  441. try:
  442. grass.run_command('r.composite',
  443. quiet=True, overwrite=True,
  444. red=self.opt_output + '.red',
  445. green=self.opt_output + '.green',
  446. blue=self.opt_output + '.blue',
  447. output=self.opt_output)
  448. except CalledModuleError:
  449. grass.fatal(_('%s failed') % 'r.composite')
  450. grass.message(_('<%s> created.') % self.opt_output)
  451. class WMSDriversInfo:
  452. def __init__(self):
  453. """!Provides information about driver parameters.
  454. """
  455. # format labels
  456. self.f_labels = ["geotiff", "tiff", "png", "jpeg", "gif", "png8"]
  457. # form for request
  458. self.formats = [
  459. "image/geotiff",
  460. "image/tiff",
  461. "image/png",
  462. "image/jpeg",
  463. "image/gif",
  464. "image/png8"]
  465. self.srs = ("epsg", "crs")
  466. def GetDrvProperties(self, driver):
  467. """!Get information about driver parameters.
  468. """
  469. if driver == 'WMS_GDAL':
  470. return self._GDALDrvProperties()
  471. if 'WMS' in driver:
  472. return self._WMSProperties()
  473. if 'WMTS' in driver:
  474. return self._WMTSProperties()
  475. if 'OnEarth' in driver:
  476. return self._OnEarthProperties()
  477. def _OnEarthProperties(self):
  478. props = {}
  479. props['ignored_flags'] = ['o']
  480. props['ignored_params'] = ['bgcolor', 'styles', 'capfile_output',
  481. 'format', 'srs', 'wms_version']
  482. props['req_multiple_layers'] = False
  483. return props
  484. def _WMSProperties(self):
  485. props = {}
  486. props['ignored_params'] = ['capfile']
  487. props['ignored_flags'] = []
  488. props['req_multiple_layers'] = True
  489. return props
  490. def _WMTSProperties(self):
  491. props = {}
  492. props['ignored_flags'] = ['o']
  493. props['ignored_params'] = ['urlparams', 'bgcolor', 'wms_version']
  494. props['req_multiple_layers'] = False
  495. return props
  496. def _GDALDrvProperties(self):
  497. props = {}
  498. props['ignored_flags'] = []
  499. props['ignored_params'] = ['urlparams', 'bgcolor', 'capfile', 'capfile_output',
  500. 'username', 'password']
  501. props['req_multiple_layers'] = True
  502. return props
  503. def GetFormatLabel(self, format):
  504. """!Convert format request form to value in parameter 'format'.
  505. """
  506. if format in self.formats:
  507. return self.f_labels[self.formats.index(format)]
  508. return None
  509. def GetFormat(self, label):
  510. """!Convert value in parameter 'format' to format request form.
  511. """
  512. if label in self.f_labels:
  513. return self.formats[self.f_labels.index(label)]
  514. return None
  515. def GetSrs(self):
  516. """!Get supported srs prefixes (e.g. epsg/crs)
  517. @todo filter according to version and driver params
  518. """
  519. return self.srs
  520. # TODO move to utils?
  521. def GetSRSParamVal(srs):
  522. """!Decides whether to use CRS or EPSG prefix according to srs number.
  523. """
  524. if srs in [84, 83, 27]:
  525. return "CRS:%d" % srs
  526. else:
  527. return "EPSG:%d" % srs
  528. def GetEpsg(srs):
  529. """
  530. @return EPSG number
  531. If srs is CRS number, return EPSG number which corresponds to CRS number.
  532. """
  533. if srs == 84:
  534. return 4326
  535. if srs == 83:
  536. return 4269
  537. if srs == 27:
  538. return 4267
  539. return srs