code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def Resolution(self, zoom): '''Resolution (arc/pixel) for given zoom level (measured at Equator)''' return self.resFact / 2 ** zoom # return 180 / float( 1 << (8+zoom) )
Resolution (arc/pixel) for given zoom level (measured at Equator)
Resolution
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def ZoomForPixelSize(self, pixelSize): '''Maximal scaledown zoom of the pyramid closest to the pixelSize.''' for i in range(MAXZOOMLEVEL): if pixelSize > self.Resolution(i): if i != 0: return i - 1 else: return 0 # We ...
Maximal scaledown zoom of the pyramid closest to the pixelSize.
ZoomForPixelSize
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def TileBounds( self, tx, ty, zoom, ): '''Returns bounds of the given tile''' res = self.resFact / 2 ** zoom return (tx * self.tileSize * res - 180, ty * self.tileSize * res - 90, (tx + 1) * self.tileSize * res - 180, (ty +...
Returns bounds of the given tile
TileBounds
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def TileLatLonBounds( self, tx, ty, zoom, ): '''Returns bounds of the given tile in the SWNE form''' b = self.TileBounds(tx, ty, zoom) return (b[1], b[0], b[3], b[2])
Returns bounds of the given tile in the SWNE form
TileLatLonBounds
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def __init__( self, width, height, tilesize=256, tileformat='jpg', ): """Initialization of the Zoomify tile tree""" self.tilesize = tilesize self.tileformat = tileformat imagesize = (width, height) tiles = (math.ceil(width / tilesi...
Initialization of the Zoomify tile tree
__init__
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def tilefilename( self, x, y, z, ): """Returns filename for tile with given coordinates""" tileIndex = x + y * self.tierSizeInTiles[z][0] \ + self.tileCountUpToTier[z] return os.path.join('TileGroup%.0f' % math.floor(tileIndex ...
Returns filename for tile with given coordinates
tilefilename
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def process(self): """The main processing function, runs all the main steps of processing""" # Opening and preprocessing of the input file self.open_input() # Generation of main metadata files and HTML viewers self.generate_metadata() # Generation of the lowest tiles...
The main processing function, runs all the main steps of processing
process
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def error(self, msg, details=''): """Print an error message and stop the processing""" if details: self.parser.error(msg + ''' ''' + details) else: self.parser.error(msg)
Print an error message and stop the processing
error
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def optparse_init(self): """Prepare the option parser for input (argv)""" from optparse import OptionParser, OptionGroup usage = 'Usage: %prog [options] input_file(s) [output]' p = OptionParser(usage, version='%prog ' + __version__) p.add_option( '-p', '-...
Prepare the option parser for input (argv)
optparse_init
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def open_input(self): """Initialization of the input raster, reprojection if necessary""" gdal.UseExceptions() gdal.AllRegister() if not self.options.verbose: gdal.PushErrorHandler('CPLQuietErrorHandler') # Initialize necessary GDAL drivers self.out_drv = g...
Initialization of the input raster, reprojection if necessary
open_input
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def generate_metadata(self): """Generation of main metadata files and HTML viewers (metadata related to particular tiles are generated during the tile processing).""" if not os.path.exists(self.output): os.makedirs(self.output) if self.options.profile == 'mercator': (s...
Generation of main metadata files and HTML viewers (metadata related to particular tiles are generated during the tile processing).
generate_metadata
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def generate_base_tiles(self, cpu): """Generation of the base tiles (the lowest in the pyramid) directly from the input raster""" if self.options.verbose: # mx, my = self.out_gt[0], self.out_gt[3] # OriginX, OriginY # px, py = self.mercator.MetersToPixels( mx, my, self.tmaxz) ...
Generation of the base tiles (the lowest in the pyramid) directly from the input raster
generate_base_tiles
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def generate_overview_tiles(self, cpu, tz): """Generation of the overview tiles (higher in the pyramid) based on existing tiles""" tilebands = self.dataBandsCount + 1 # Usage of existing tiles: from 4 underlying tiles generate one as overview. tcount = 0 for z in range(self.tm...
Generation of the overview tiles (higher in the pyramid) based on existing tiles
generate_overview_tiles
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def geo_query( self, ds, ulx, uly, lrx, lry, querysize=0, ): """For given dataset and query in cartographic coordinates returns parameters for ReadRaster() in raster coordinates and x/y shifts (for border tiles). If the querysize is...
For given dataset and query in cartographic coordinates returns parameters for ReadRaster() in raster coordinates and x/y shifts (for border tiles). If the querysize is not given, the extent is returned in the native resolution of dataset ds.
geo_query
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def scale_query_to_tile( self, dsquery, dstile, tilefilename='', ): """Scales down query dataset to the tile dataset""" querysize = dsquery.RasterXSize tilesize = dstile.RasterXSize tilebands = dstile.RasterCount if self.options.resamplin...
Scales down query dataset to the tile dataset
scale_query_to_tile
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def generate_tilemapresource(self): """ Template for tilemapresource.xml. Returns filled string. Expected variables: title, north, south, east, west, isepsg4326, projection, publishurl, zoompixels, tilesize, tileformat, profile """ args = {} args['title'] = s...
Template for tilemapresource.xml. Returns filled string. Expected variables: title, north, south, east, west, isepsg4326, projection, publishurl, zoompixels, tilesize, tileformat, profile
generate_tilemapresource
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def generate_kml( self, tx, ty, tz, children=[], **args ): """ Template for the KML. Returns filled string. """ (args['tx'], args['ty'], args['tz']) = (tx, ty, tz) args['tileformat'] = self.tileext if 'tilesize' not...
Template for the KML. Returns filled string.
generate_kml
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def generate_googlemaps(self): """ Template for googlemaps.html implementing Overlay of tiles for 'mercator' profile. It returns filled string. Expected variables: title, googlemapskey, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl """ args...
Template for googlemaps.html implementing Overlay of tiles for 'mercator' profile. It returns filled string. Expected variables: title, googlemapskey, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl
generate_googlemaps
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def generate_openlayers(self): """ Template for openlayers.html implementing overlay of available Spherical Mercator layers. It returns filled string. Expected variables: title, bingkey, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl """ ar...
Template for openlayers.html implementing overlay of available Spherical Mercator layers. It returns filled string. Expected variables: title, bingkey, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl
generate_openlayers
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def __init__(self, tileSize=256): '''Initialize the TMS Global Mercator pyramid''' self.tileSize = tileSize self.initialResolution = 2 * math.pi * 6378137 / self.tileSize # 156543.03392804062 for tileSize 256 pixels self.originShift = 2 * math.pi * 6378137 / 2.0 # 200...
Initialize the TMS Global Mercator pyramid
__init__
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def LatLonToMeters(self, lat, lon): '''Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913''' mx = lon * self.originShift / 180.0 my = math.log(math.tan((90 + lat) * math.pi / 360.0)) \ / (math.pi / 180.0) my = my * self.originShift / 180.0 ...
Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913
LatLonToMeters
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def MetersToLatLon(self, mx, my): '''Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum''' lon = mx / self.originShift * 180.0 lat = my / self.originShift * 180.0 lat = 180 / math.pi * (2 * math.atan(math.exp(lat * math.pi / 1...
Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum
MetersToLatLon
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def PixelsToMeters( self, px, py, zoom, ): '''Converts pixel coordinates in given zoom level of pyramid to EPSG:900913''' res = self.Resolution(zoom) mx = px * res - self.originShift my = py * res - self.originShift return (mx, my)
Converts pixel coordinates in given zoom level of pyramid to EPSG:900913
PixelsToMeters
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def MetersToPixels( self, mx, my, zoom, ): '''Converts EPSG:900913 to pyramid pixel coordinates in given zoom level''' res = self.Resolution(zoom) px = (mx + self.originShift) / res py = (my + self.originShift) / res return (px, py)
Converts EPSG:900913 to pyramid pixel coordinates in given zoom level
MetersToPixels
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def PixelsToTile(self, px, py): '''Returns a tile covering region in given pixel coordinates''' tx = int(math.ceil(px / float(self.tileSize)) - 1) ty = int(math.ceil(py / float(self.tileSize)) - 1) return (tx, ty)
Returns a tile covering region in given pixel coordinates
PixelsToTile
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def PixelsToRaster( self, px, py, zoom, ): '''Move the origin of pixel coordinates to top-left corner''' mapSize = self.tileSize << zoom return (px, mapSize - py)
Move the origin of pixel coordinates to top-left corner
PixelsToRaster
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def MetersToTile( self, mx, my, zoom, ): '''Returns tile for given mercator coordinates''' (px, py) = self.MetersToPixels(mx, my, zoom) return self.PixelsToTile(px, py)
Returns tile for given mercator coordinates
MetersToTile
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def TileBounds( self, tx, ty, zoom, ): '''Returns bounds of the given tile in EPSG:900913 coordinates''' (minx, miny) = self.PixelsToMeters(tx * self.tileSize, ty * self.tileSize, zoom) (maxx, maxy) = self.PixelsToMeters((tx + 1) * self.ti...
Returns bounds of the given tile in EPSG:900913 coordinates
TileBounds
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def TileLatLonBounds( self, tx, ty, zoom, ): '''Returns bounds of the given tile in latutude/longitude using WGS84 datum''' bounds = self.TileBounds(tx, ty, zoom) (minLat, minLon) = self.MetersToLatLon(bounds[0], bounds[1]) (maxLat, maxLon) = self...
Returns bounds of the given tile in latutude/longitude using WGS84 datum
TileLatLonBounds
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def Resolution(self, zoom): '''Resolution (meters/pixel) for given zoom level (measured at Equator)''' # return (2 * math.pi * 6378137) / (self.tileSize * 2**zoom) return self.initialResolution / 2 ** zoom
Resolution (meters/pixel) for given zoom level (measured at Equator)
Resolution
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def ZoomForPixelSize(self, pixelSize): '''Maximal scaledown zoom of the pyramid closest to the pixelSize.''' for i in range(MAXZOOMLEVEL): if pixelSize > self.Resolution(i): if i != 0: return i - 1 else: return 0 # We ...
Maximal scaledown zoom of the pyramid closest to the pixelSize.
ZoomForPixelSize
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def GoogleTile( self, tx, ty, zoom, ): '''Converts TMS tile coordinates to Google Tile coordinates''' # coordinate origin is moved from bottom-left to top-left corner of the extent return (tx, 2 ** zoom - 1 - ty)
Converts TMS tile coordinates to Google Tile coordinates
GoogleTile
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def QuadTree( self, tx, ty, zoom, ): '''Converts TMS tile coordinates to Microsoft QuadTree''' quadKey = '' ty = 2 ** zoom - 1 - ty for i in range(zoom, 0, -1): digit = 0 mask = 1 << i - 1 if tx & mask != 0: ...
Converts TMS tile coordinates to Microsoft QuadTree
QuadTree
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def LonLatToPixels( self, lon, lat, zoom, ): '''Converts lon/lat to pixel coordinates in given zoom of the EPSG:4326 pyramid''' res = self.resFact / 2 ** zoom px = (180 + lon) / res py = (90 + lat) / res return (px, py)
Converts lon/lat to pixel coordinates in given zoom of the EPSG:4326 pyramid
LonLatToPixels
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def PixelsToTile(self, px, py): '''Returns coordinates of the tile covering region in pixel coordinates''' tx = int(math.ceil(px / float(self.tileSize)) - 1) ty = int(math.ceil(py / float(self.tileSize)) - 1) return (tx, ty)
Returns coordinates of the tile covering region in pixel coordinates
PixelsToTile
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def LonLatToTile( self, lon, lat, zoom, ): '''Returns the tile for zoom which covers given lon/lat coordinates''' (px, py) = self.LonLatToPixels(lon, lat, zoom) return self.PixelsToTile(px, py)
Returns the tile for zoom which covers given lon/lat coordinates
LonLatToTile
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def Resolution(self, zoom): '''Resolution (arc/pixel) for given zoom level (measured at Equator)''' return self.resFact / 2 ** zoom # return 180 / float( 1 << (8+zoom) )
Resolution (arc/pixel) for given zoom level (measured at Equator)
Resolution
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def ZoomForPixelSize(self, pixelSize): '''Maximal scaledown zoom of the pyramid closest to the pixelSize.''' for i in range(MAXZOOMLEVEL): if pixelSize > self.Resolution(i): if i != 0: return i - 1 else: return 0 # We ...
Maximal scaledown zoom of the pyramid closest to the pixelSize.
ZoomForPixelSize
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def TileBounds( self, tx, ty, zoom, ): '''Returns bounds of the given tile''' res = self.resFact / 2 ** zoom return (tx * self.tileSize * res - 180, ty * self.tileSize * res - 90, (tx + 1) * self.tileSize * res - 180, (ty +...
Returns bounds of the given tile
TileBounds
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def TileLatLonBounds( self, tx, ty, zoom, ): '''Returns bounds of the given tile in the SWNE form''' b = self.TileBounds(tx, ty, zoom) return (b[1], b[0], b[3], b[2])
Returns bounds of the given tile in the SWNE form
TileLatLonBounds
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def __init__( self, width, height, tilesize=256, tileformat='jpg', ): """Initialization of the Zoomify tile tree""" self.tilesize = tilesize self.tileformat = tileformat imagesize = (width, height) tiles = (math.ceil(width / tilesi...
Initialization of the Zoomify tile tree
__init__
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def tilefilename( self, x, y, z, ): """Returns filename for tile with given coordinates""" tileIndex = x + y * self.tierSizeInTiles[z][0] \ + self.tileCountUpToTier[z] return os.path.join('TileGroup%.0f' % math.floor(tileIndex ...
Returns filename for tile with given coordinates
tilefilename
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def process(self): """The main processing function, runs all the main steps of processing""" # Opening and preprocessing of the input file self.open_input() # Generation of main metadata files and HTML viewers self.generate_metadata() # Generation of the lowest tiles...
The main processing function, runs all the main steps of processing
process
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def error(self, msg, details=''): """Print an error message and stop the processing""" if details: self.parser.error(msg + ''' ''' + details) else: self.parser.error(msg)
Print an error message and stop the processing
error
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def optparse_init(self): """Prepare the option parser for input (argv)""" from optparse import OptionParser, OptionGroup usage = 'Usage: %prog [options] input_file(s) [output]' p = OptionParser(usage, version='%prog ' + __version__) p.add_option( '-p', '-...
Prepare the option parser for input (argv)
optparse_init
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def open_input(self): """Initialization of the input raster, reprojection if necessary""" gdal.AllRegister() # Initialize necessary GDAL drivers self.out_drv = gdal.GetDriverByName(self.tiledriver) self.mem_drv = gdal.GetDriverByName('MEM') if not self.out_drv: ...
Initialization of the input raster, reprojection if necessary
open_input
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def generate_metadata(self): """Generation of main metadata files and HTML viewers (metadata related to particular tiles are generated during the tile processing).""" if not os.path.exists(self.output): os.makedirs(self.output) if self.options.profile == 'mercator': (s...
Generation of main metadata files and HTML viewers (metadata related to particular tiles are generated during the tile processing).
generate_metadata
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def generate_base_tiles(self): """Generation of the base tiles (the lowest in the pyramid) directly from the input raster""" print('Generating Base Tiles:') if self.options.verbose: # mx, my = self.out_gt[0], self.out_gt[3] # OriginX, OriginY # px, py = self.mercator.M...
Generation of the base tiles (the lowest in the pyramid) directly from the input raster
generate_base_tiles
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def generate_overview_tiles(self): """Generation of the overview tiles (higher in the pyramid) based on existing tiles""" print('Generating Overview Tiles:') tilebands = self.dataBandsCount + 1 # Usage of existing tiles: from 4 underlying tiles generate one as overview. tcoun...
Generation of the overview tiles (higher in the pyramid) based on existing tiles
generate_overview_tiles
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def geo_query( self, ds, ulx, uly, lrx, lry, querysize=0, ): """For given dataset and query in cartographic coordinates returns parameters for ReadRaster() in raster coordinates and x/y shifts (for border tiles). If the querysize is...
For given dataset and query in cartographic coordinates returns parameters for ReadRaster() in raster coordinates and x/y shifts (for border tiles). If the querysize is not given, the extent is returned in the native resolution of dataset ds.
geo_query
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def scale_query_to_tile( self, dsquery, dstile, tilefilename='', ): """Scales down query dataset to the tile dataset""" querysize = dsquery.RasterXSize tilesize = dstile.RasterXSize tilebands = dstile.RasterCount if self.options.resamplin...
Scales down query dataset to the tile dataset
scale_query_to_tile
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def generate_tilemapresource(self): """ Template for tilemapresource.xml. Returns filled string. Expected variables: title, north, south, east, west, isepsg4326, projection, publishurl, zoompixels, tilesize, tileformat, profile """ args = {} args['title'] = s...
Template for tilemapresource.xml. Returns filled string. Expected variables: title, north, south, east, west, isepsg4326, projection, publishurl, zoompixels, tilesize, tileformat, profile
generate_tilemapresource
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def generate_kml( self, tx, ty, tz, children=[], **args ): """ Template for the KML. Returns filled string. """ (args['tx'], args['ty'], args['tz']) = (tx, ty, tz) args['tileformat'] = self.tileext if 'tilesize' not...
Template for the KML. Returns filled string.
generate_kml
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def generate_googlemaps(self): """ Template for googlemaps.html implementing Overlay of tiles for 'mercator' profile. It returns filled string. Expected variables: title, googlemapskey, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl """ args...
Template for googlemaps.html implementing Overlay of tiles for 'mercator' profile. It returns filled string. Expected variables: title, googlemapskey, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl
generate_googlemaps
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def generate_openlayers(self): """ Template for openlayers.html implementing overlay of available Spherical Mercator layers. It returns filled string. Expected variables: title, bingkey, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl """ ar...
Template for openlayers.html implementing overlay of available Spherical Mercator layers. It returns filled string. Expected variables: title, bingkey, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl
generate_openlayers
python
commenthol/gdal2tiles-leaflet
gdal2tiles.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles.py
MIT
def build_dataset(tokenizer, config): ''' We assume that we have preprocessed the dataset appropriately such that the sample is organized as follows: {"positive": prompt + answer_positive, "negative": prompt + answer_negative}, where the positive response is preferred. ''' def tokenize(sample): ...
We assume that we have preprocessed the dataset appropriately such that the sample is organized as follows: {"positive": prompt + answer_positive, "negative": prompt + answer_negative}, where the positive response is preferred.
build_dataset
python
OptimalScale/LMFlow
contrib/rlhflow/reward_modeling.py
https://github.com/OptimalScale/LMFlow/blob/master/contrib/rlhflow/reward_modeling.py
Apache-2.0
def tokenize( self, dataset, add_special_tokens=True, *args, **kwargs ) -> Dataset: """ Tokenize the full dataset. Parameters ------------ dataset : lmflow.datasets.Dataset. args : Optional. Positional argu...
Tokenize the full dataset. Parameters ------------ dataset : lmflow.datasets.Dataset. args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. Returns ------------ tokenized_d...
tokenize
python
OptimalScale/LMFlow
contrib/tool-finetune/function_call_finetune.py
https://github.com/OptimalScale/LMFlow/blob/master/contrib/tool-finetune/function_call_finetune.py
Apache-2.0
def update_ema(target_params, source_params, rate=0.99): """ Update target parameters to be closer to those of source parameters using an exponential moving average. :param target_params: the target parameter sequence. :param source_params: the source parameter sequence. :param rate: the EMA ra...
Update target parameters to be closer to those of source parameters using an exponential moving average. :param target_params: the target parameter sequence. :param source_params: the source parameter sequence. :param rate: the EMA rate (closer to 1 means slower).
update_ema
python
OptimalScale/LMFlow
experimental/LISA-diffusion/diffusion_dpo/train_diffusion_dpo_lisa.py
https://github.com/OptimalScale/LMFlow/blob/master/experimental/LISA-diffusion/diffusion_dpo/train_diffusion_dpo_lisa.py
Apache-2.0
def group_by_keys_nothrow(data, keys=base_plus_ext, lcase=True, suffixes=None, handler=None): """Return function over iterator that groups key, value pairs into samples. :param keys: function that splits the key into key and extension (base_plus_ext) :param lcase: convert suffixes to lower case (Default va...
Return function over iterator that groups key, value pairs into samples. :param keys: function that splits the key into key and extension (base_plus_ext) :param lcase: convert suffixes to lower case (Default value = True)
group_by_keys_nothrow
python
OptimalScale/LMFlow
experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lisa.py
https://github.com/OptimalScale/LMFlow/blob/master/experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lisa.py
Apache-2.0
def guidance_scale_embedding(w, embedding_dim=512, dtype=torch.float32): """ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 Args: timesteps (`torch.Tensor`): generate embedding vectors at these timesteps embedding_dim (...
See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 Args: timesteps (`torch.Tensor`): generate embedding vectors at these timesteps embedding_dim (`int`, *optional*, defaults to 512): dimension of the embeddings to ...
guidance_scale_embedding
python
OptimalScale/LMFlow
experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lisa.py
https://github.com/OptimalScale/LMFlow/blob/master/experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lisa.py
Apache-2.0
def append_dims(x, target_dims): """Appends dimensions to the end of a tensor until it has target_dims dimensions.""" dims_to_append = target_dims - x.ndim if dims_to_append < 0: raise ValueError(f"input has {x.ndim} dims but target_dims is {target_dims}, which is less") return x[(...,) + (None,...
Appends dimensions to the end of a tensor until it has target_dims dimensions.
append_dims
python
OptimalScale/LMFlow
experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lisa.py
https://github.com/OptimalScale/LMFlow/blob/master/experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lisa.py
Apache-2.0
def update_ema(target_params, source_params, rate=0.99): """ Update target parameters to be closer to those of source parameters using an exponential moving average. :param target_params: the target parameter sequence. :param source_params: the source parameter sequence. :param rate: the EMA ra...
Update target parameters to be closer to those of source parameters using an exponential moving average. :param target_params: the target parameter sequence. :param source_params: the source parameter sequence. :param rate: the EMA rate (closer to 1 means slower).
update_ema
python
OptimalScale/LMFlow
experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lisa.py
https://github.com/OptimalScale/LMFlow/blob/master/experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lisa.py
Apache-2.0
def group_by_keys_nothrow(data, keys=base_plus_ext, lcase=True, suffixes=None, handler=None): """Return function over iterator that groups key, value pairs into samples. :param keys: function that splits the key into key and extension (base_plus_ext) :param lcase: convert suffixes to lower case (Default va...
Return function over iterator that groups key, value pairs into samples. :param keys: function that splits the key into key and extension (base_plus_ext) :param lcase: convert suffixes to lower case (Default value = True)
group_by_keys_nothrow
python
OptimalScale/LMFlow
experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lora.py
https://github.com/OptimalScale/LMFlow/blob/master/experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lora.py
Apache-2.0
def guidance_scale_embedding(w, embedding_dim=512, dtype=torch.float32): """ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 Args: timesteps (`torch.Tensor`): generate embedding vectors at these timesteps embedding_dim (...
See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 Args: timesteps (`torch.Tensor`): generate embedding vectors at these timesteps embedding_dim (`int`, *optional*, defaults to 512): dimension of the embeddings to ...
guidance_scale_embedding
python
OptimalScale/LMFlow
experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lora.py
https://github.com/OptimalScale/LMFlow/blob/master/experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lora.py
Apache-2.0
def append_dims(x, target_dims): """Appends dimensions to the end of a tensor until it has target_dims dimensions.""" dims_to_append = target_dims - x.ndim if dims_to_append < 0: raise ValueError(f"input has {x.ndim} dims but target_dims is {target_dims}, which is less") return x[(...,) + (None,...
Appends dimensions to the end of a tensor until it has target_dims dimensions.
append_dims
python
OptimalScale/LMFlow
experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lora.py
https://github.com/OptimalScale/LMFlow/blob/master/experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lora.py
Apache-2.0
def update_ema(target_params, source_params, rate=0.99): """ Update target parameters to be closer to those of source parameters using an exponential moving average. :param target_params: the target parameter sequence. :param source_params: the source parameter sequence. :param rate: the EMA ra...
Update target parameters to be closer to those of source parameters using an exponential moving average. :param target_params: the target parameter sequence. :param source_params: the source parameter sequence. :param rate: the EMA rate (closer to 1 means slower).
update_ema
python
OptimalScale/LMFlow
experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lora.py
https://github.com/OptimalScale/LMFlow/blob/master/experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lora.py
Apache-2.0
def parse_argument(sys_argv): """Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '-...
Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '--input', 'a.txt', '--num', '10']) ...
parse_argument
python
OptimalScale/LMFlow
scripts/data_preprocess/add_end_mark.py
https://github.com/OptimalScale/LMFlow/blob/master/scripts/data_preprocess/add_end_mark.py
Apache-2.0
def parse_argument(sys_argv): """Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '-...
Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '--input', 'a.txt', '--num', '10']) ...
parse_argument
python
OptimalScale/LMFlow
scripts/data_preprocess/add_prompt.py
https://github.com/OptimalScale/LMFlow/blob/master/scripts/data_preprocess/add_prompt.py
Apache-2.0
def parse_argument(sys_argv): """Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '-...
Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '--input', 'a.txt', '--num', '10']) ...
parse_argument
python
OptimalScale/LMFlow
scripts/data_preprocess/concat.py
https://github.com/OptimalScale/LMFlow/blob/master/scripts/data_preprocess/concat.py
Apache-2.0
def parse_argument(sys_argv): """Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '-...
Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '--input', 'a.txt', '--num', '10']) ...
parse_argument
python
OptimalScale/LMFlow
scripts/data_preprocess/concat_shuffle_split.py
https://github.com/OptimalScale/LMFlow/blob/master/scripts/data_preprocess/concat_shuffle_split.py
Apache-2.0
def parse_argument(sys_argv): """Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '-...
Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '--input', 'a.txt', '--num', '10']) ...
parse_argument
python
OptimalScale/LMFlow
scripts/data_preprocess/count.py
https://github.com/OptimalScale/LMFlow/blob/master/scripts/data_preprocess/count.py
Apache-2.0
def parse_argument(sys_argv): """Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '-...
Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '--input', 'a.txt', '--num', '10']) ...
parse_argument
python
OptimalScale/LMFlow
scripts/data_preprocess/merge.py
https://github.com/OptimalScale/LMFlow/blob/master/scripts/data_preprocess/merge.py
Apache-2.0
def parse_argument(sys_argv): """Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '-...
Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '--input', 'a.txt', '--num', '10']) ...
parse_argument
python
OptimalScale/LMFlow
scripts/data_preprocess/raw2textonly.py
https://github.com/OptimalScale/LMFlow/blob/master/scripts/data_preprocess/raw2textonly.py
Apache-2.0
def raw2textonly(fin): """ Converts raw text to text-only format. Args: fin: the input file description of the raw text file. Returns: a dict with "text-only" format. """ data_dict = { "type": "text_only", "instances": [ { "text": line.strip() } for line in fin ]...
Converts raw text to text-only format. Args: fin: the input file description of the raw text file. Returns: a dict with "text-only" format.
raw2textonly
python
OptimalScale/LMFlow
scripts/data_preprocess/raw2textonly.py
https://github.com/OptimalScale/LMFlow/blob/master/scripts/data_preprocess/raw2textonly.py
Apache-2.0
def parse_argument(sys_argv): """Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '-...
Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '--input', 'a.txt', '--num', '10']) ...
parse_argument
python
OptimalScale/LMFlow
scripts/data_preprocess/sample.py
https://github.com/OptimalScale/LMFlow/blob/master/scripts/data_preprocess/sample.py
Apache-2.0
def parse_argument(sys_argv): """Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '-...
Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '--input', 'a.txt', '--num', '10']) ...
parse_argument
python
OptimalScale/LMFlow
scripts/data_preprocess/shuffle.py
https://github.com/OptimalScale/LMFlow/blob/master/scripts/data_preprocess/shuffle.py
Apache-2.0
def _check_instance_format(self): """ Checks if data (instances) have required fields. Raises messages with hints if not matched. """ fields = self.backend_dataset.features correct_fields = INSTANCE_FIELDS_MAP[self.type] if not set(correct_fields).issubset(set(fi...
Checks if data (instances) have required fields. Raises messages with hints if not matched.
_check_instance_format
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def from_dict(self, dict_obj: dict, *args, **kwargs): r""" Create a Dataset object from a dictionary. Return a Dataset given a dict with format: { "type": TYPE, "instances": [ { "key_1": VALUE_1.1, ...
Create a Dataset object from a dictionary. Return a Dataset given a dict with format: { "type": TYPE, "instances": [ { "key_1": VALUE_1.1, "key_2": VALUE_1.2, ... ...
from_dict
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def create_from_dict(cls, dict_obj, *args, **kwargs): r""" Returns -------- Returns a Dataset object given a dict. """ empty_data_args = DatasetArguments(dataset_path=None) dataset = Dataset(empty_data_args) return dataset.from_dict(dict_obj)
Returns -------- Returns a Dataset object given a dict.
create_from_dict
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def to_dict(self): r""" Returns --------- Return a dict represents the dataset: { "type": TYPE, "instances": [ { "key_1": VALUE_1.1, "key_2": VALUE_1.2, ...
Returns --------- Return a dict represents the dataset: { "type": TYPE, "instances": [ { "key_1": VALUE_1.1, "key_2": VALUE_1.2, ... }, ...
to_dict
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def map(self, *args, **kwargs): r""" Parameters ------------ args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. Returns --------- self : Dataset object. """ # If the dataset uses ...
Parameters ------------ args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. Returns --------- self : Dataset object.
map
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def save( self, file_path: str, format: str="json" ): r""" Save the dataset to a json file. Parameters ------------ file_path : str. The path to the file where the dataset will be saved. """ if format == "json": ...
Save the dataset to a json file. Parameters ------------ file_path : str. The path to the file where the dataset will be saved.
save
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def sample(self, n: int, seed: int=42): r""" Sample n instances from the dataset. Parameters ------------ n : int. The number of instances to sample from the dataset. Returns --------- sample_dataset : Dataset object. A new datas...
Sample n instances from the dataset. Parameters ------------ n : int. The number of instances to sample from the dataset. Returns --------- sample_dataset : Dataset object. A new dataset object containing the sampled instances.
sample
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def train_test_split(self, test_size: float=0.2, shuffle: bool=True, seed: int=42): r""" Split the dataset into training and testing sets. Parameters ------------ test_size : float, default=0.2. The proportion of the dataset that will be used for testing. Re...
Split the dataset into training and testing sets. Parameters ------------ test_size : float, default=0.2. The proportion of the dataset that will be used for testing. Returns --------- train_dataset : Dataset object. A new dataset objec...
train_test_split
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def drop_instances(self, indices: list): r""" Drop instances from the dataset. Parameters ------------ indices : list. A list of indices of the instances to drop from the dataset. """ if self.backend == "huggingface": self.backend_dataset ...
Drop instances from the dataset. Parameters ------------ indices : list. A list of indices of the instances to drop from the dataset.
drop_instances
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def sanity_check( self, drop_invalid: bool=True, ): r""" Perform a sanity check on the dataset. """ if self.backend == "huggingface": self.hf_dataset_sanity_check(drop_invalid) else: raise NotImplementedError( f'Current...
Perform a sanity check on the dataset.
sanity_check
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def hf_dataset_sanity_check( self, drop_invalid: bool=True, ): r""" Perform a sanity check on the HuggingFace dataset. """ if self.backend_dataset is None or len(self.backend_dataset) == 0: raise ValueError("Dataset is empty.") if self.type == 'te...
Perform a sanity check on the HuggingFace dataset.
hf_dataset_sanity_check
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def preprocess_llama_from_llava_plain( sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False): """ This function just add the image in the front of text. And don't add any prompt. Args: sources: The input data with text and image. tokenizer: The tokeni...
This function just add the image in the front of text. And don't add any prompt. Args: sources: The input data with text and image. tokenizer: The tokenizer to process text. has_image: Whether the input data has image. Returns: The input_ids and labels for the model. ...
preprocess_llama_from_llava_plain
python
OptimalScale/LMFlow
src/lmflow/datasets/multi_modal_dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/multi_modal_dataset.py
Apache-2.0
def preprocess_llama_from_llava_v1( sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False): """ This function add the prompt and then put the image after the prompt. So it needs additional code to generate the target label. Args: sources: The input data with t...
This function add the prompt and then put the image after the prompt. So it needs additional code to generate the target label. Args: sources: The input data with text and image. tokenizer: The tokenizer to process text. has_image: Whether the input data has image. Returns: ...
preprocess_llama_from_llava_v1
python
OptimalScale/LMFlow
src/lmflow/datasets/multi_modal_dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/multi_modal_dataset.py
Apache-2.0
def __init__( self, model_args, tune_strategy='normal', ds_config=None, device="gpu", use_accelerator=False, *args, **kwargs ): """ Initializes a HFDecoderModel instance. :param model_args: dictionary with model arguments such a...
Initializes a HFDecoderModel instance. :param model_args: dictionary with model arguments such as model name, path, revision, etc. :param tune_strategy: tuning strategy: normal, none, lora or adapter :param ds_config: deepspeed configuration for distributed training
__init__
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def tokenize( self, dataset: Dataset, add_special_tokens=True, *args, **kwargs ) -> Dataset: """ Tokenize the full dataset. Parameters ------------ dataset : lmflow.datasets.Dataset. args : Optional. Positi...
Tokenize the full dataset. Parameters ------------ dataset : lmflow.datasets.Dataset. args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. Returns ------------ tokenized_d...
tokenize
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def encode(self, input: Union[str, List[str]], *args, **kwargs ) -> Union[List[int], List[List[int]]]: """ Perform encoding process of the tokenizer. Parameters ------------ inputs : str or list. The text sequence. args : Optional. ...
Perform encoding process of the tokenizer. Parameters ------------ inputs : str or list. The text sequence. args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. Re...
encode
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def decode(self, input, *args, **kwargs ) -> Union[str, List[str]]: """ Perform decoding process of the tokenizer. Parameters ------------ inputs : list or tensor. The token sequence. args : Optional. Positional arguments. ...
Perform decoding process of the tokenizer. Parameters ------------ inputs : list or tensor. The token sequence. args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. ...
decode
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def inference( self, inputs, release_gpu: bool = False, use_vllm: bool = False, **kwargs ): """ Perform generation process of the model. Parameters ------------ inputs : The sequence used as a prompt for the generatio...
Perform generation process of the model. Parameters ------------ inputs : The sequence used as a prompt for the generation or as model inputs to the model. When using vllm inference, this should be a string or a list of strings. When using normal...
inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def __inference(self, inputs, *args, **kwargs): """ Perform generation process of the model. Parameters ------------ inputs : The **tokenized** sequence used as a prompt for the generation or as model inputs to the model. args : Optional. ...
Perform generation process of the model. Parameters ------------ inputs : The **tokenized** sequence used as a prompt for the generation or as model inputs to the model. args : Optional. Positional arguments. kwargs : Op...
__inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def __vllm_inference( self, inputs: Union[str, List[str]], sampling_params: Optional['SamplingParams'] = None, **kwargs, ) -> List[VLLMInferenceResultWithInput]: """Perform VLLM inference process of the model. Parameters ---------- inputs : Union[str...
Perform VLLM inference process of the model. Parameters ---------- inputs : Union[str, List[str]] Prompt(s), string or a list of strings. sampling_params : Optional[SamplingParams], optional vllm SamplingParams object, by default None. Returns --...
__vllm_inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def prepare_inputs_for_inference( self, dataset: Dataset, apply_chat_template: bool = True, enable_distributed_inference: bool = False, use_vllm: bool = False, **kwargs, ) -> Union[List[str], "ray.data.Dataset", Dict[str, torch.Tensor]]: """ Prepare in...
Prepare inputs for inference. Parameters ------------ dataset : lmflow.datasets.Dataset. The dataset used for inference. args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. ...
prepare_inputs_for_inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def save(self, dir, save_full_model=False, *args, **kwargs): """ Perform generation process of the model. Parameters ------------ dir : The directory to save model and tokenizer save_full_model : Optional. Whether to save full mod...
Perform generation process of the model. Parameters ------------ dir : The directory to save model and tokenizer save_full_model : Optional. Whether to save full model. kwargs : Optional. Keyword arguments. ...
save
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def __init__( self, model_args, tune_strategy='normal', ds_config=None, device="gpu", use_accelerator=False, custom_model=False, with_deepspeed=True, pipeline_args=None, *args, **kwargs ): """ Initializes a HFDec...
Initializes a HFDecoderModel instance. :param model_args: dictionary with model arguments such as model name, path, revision, etc. :param tune_strategy: tuning strategy: normal, none, lora or adapter :param ds_config: deepspeed configuration for distributed training
__init__
python
OptimalScale/LMFlow
src/lmflow/models/hf_encoder_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_encoder_decoder_model.py
Apache-2.0
def encode(self, input: Union[str, List[str]], *args, **kwargs ) -> Union[List[int], List[List[int]]]: """ Perform encoding process of the tokenizer. Parameters ------------ inputs : str or list. The text sequence. args : Optional. Positional arg...
Perform encoding process of the tokenizer. Parameters ------------ inputs : str or list. The text sequence. args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. Returns ------------ o...
encode
python
OptimalScale/LMFlow
src/lmflow/models/hf_encoder_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_encoder_decoder_model.py
Apache-2.0