id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
26,200 | tensorflow/datasets | tensorflow_datasets/scripts/document_datasets.py | schema_org | def schema_org(builder):
# pylint: disable=line-too-long
"""Builds schema.org microdata for DatasetSearch from DatasetBuilder.
Markup spec: https://developers.google.com/search/docs/data-types/dataset#dataset
Testing tool: https://search.google.com/structured-data/testing-tool
For Google Dataset Search: http... | python | def schema_org(builder):
# pylint: disable=line-too-long
"""Builds schema.org microdata for DatasetSearch from DatasetBuilder.
Markup spec: https://developers.google.com/search/docs/data-types/dataset#dataset
Testing tool: https://search.google.com/structured-data/testing-tool
For Google Dataset Search: http... | [
"def",
"schema_org",
"(",
"builder",
")",
":",
"# pylint: disable=line-too-long",
"# pylint: enable=line-too-long",
"properties",
"=",
"[",
"(",
"lambda",
"x",
":",
"x",
".",
"name",
",",
"SCHEMA_ORG_NAME",
")",
",",
"(",
"lambda",
"x",
":",
"x",
".",
"descrip... | Builds schema.org microdata for DatasetSearch from DatasetBuilder.
Markup spec: https://developers.google.com/search/docs/data-types/dataset#dataset
Testing tool: https://search.google.com/structured-data/testing-tool
For Google Dataset Search: https://toolbox.google.com/datasetsearch
Microdata format was cho... | [
"Builds",
"schema",
".",
"org",
"microdata",
"for",
"DatasetSearch",
"from",
"DatasetBuilder",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/scripts/document_datasets.py#L414-L449 |
26,201 | tensorflow/datasets | tensorflow_datasets/image/corruptions.py | disk | def disk(radius, alias_blur=0.1, dtype=np.float32):
"""Generating a Gaussian blurring kernel with disk shape.
Generating a Gaussian blurring kernel with disk shape using cv2 API.
Args:
radius: integer, radius of blurring kernel.
alias_blur: float, standard deviation of Gaussian blurring.
dtype: data... | python | def disk(radius, alias_blur=0.1, dtype=np.float32):
"""Generating a Gaussian blurring kernel with disk shape.
Generating a Gaussian blurring kernel with disk shape using cv2 API.
Args:
radius: integer, radius of blurring kernel.
alias_blur: float, standard deviation of Gaussian blurring.
dtype: data... | [
"def",
"disk",
"(",
"radius",
",",
"alias_blur",
"=",
"0.1",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
":",
"if",
"radius",
"<=",
"8",
":",
"length",
"=",
"np",
".",
"arange",
"(",
"-",
"8",
",",
"8",
"+",
"1",
")",
"ksize",
"=",
"(",
"3"... | Generating a Gaussian blurring kernel with disk shape.
Generating a Gaussian blurring kernel with disk shape using cv2 API.
Args:
radius: integer, radius of blurring kernel.
alias_blur: float, standard deviation of Gaussian blurring.
dtype: data type of kernel
Returns:
cv2 object of the Gaussia... | [
"Generating",
"a",
"Gaussian",
"blurring",
"kernel",
"with",
"disk",
"shape",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/corruptions.py#L46-L70 |
26,202 | tensorflow/datasets | tensorflow_datasets/image/corruptions.py | clipped_zoom | def clipped_zoom(img, zoom_factor):
"""Zoom image with clipping.
Zoom the central part of the image and clip extra pixels.
Args:
img: numpy array, uncorrupted image.
zoom_factor: numpy array, a sequence of float numbers for zoom factor.
Returns:
numpy array, zoomed image after clipping.
"""
h... | python | def clipped_zoom(img, zoom_factor):
"""Zoom image with clipping.
Zoom the central part of the image and clip extra pixels.
Args:
img: numpy array, uncorrupted image.
zoom_factor: numpy array, a sequence of float numbers for zoom factor.
Returns:
numpy array, zoomed image after clipping.
"""
h... | [
"def",
"clipped_zoom",
"(",
"img",
",",
"zoom_factor",
")",
":",
"h",
"=",
"img",
".",
"shape",
"[",
"0",
"]",
"ch",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"h",
"/",
"float",
"(",
"zoom_factor",
")",
")",
")",
"top_h",
"=",
"(",
"h",
"-",
"... | Zoom image with clipping.
Zoom the central part of the image and clip extra pixels.
Args:
img: numpy array, uncorrupted image.
zoom_factor: numpy array, a sequence of float numbers for zoom factor.
Returns:
numpy array, zoomed image after clipping. | [
"Zoom",
"image",
"with",
"clipping",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/corruptions.py#L73-L101 |
26,203 | tensorflow/datasets | tensorflow_datasets/image/corruptions.py | plasma_fractal | def plasma_fractal(mapsize=512, wibbledecay=3):
"""Generate a heightmap using diamond-square algorithm.
Modification of the algorithm in
https://github.com/FLHerne/mapgen/blob/master/diamondsquare.py
Args:
mapsize: side length of the heightmap, must be a power of two.
wibbledecay: integer, decay facto... | python | def plasma_fractal(mapsize=512, wibbledecay=3):
"""Generate a heightmap using diamond-square algorithm.
Modification of the algorithm in
https://github.com/FLHerne/mapgen/blob/master/diamondsquare.py
Args:
mapsize: side length of the heightmap, must be a power of two.
wibbledecay: integer, decay facto... | [
"def",
"plasma_fractal",
"(",
"mapsize",
"=",
"512",
",",
"wibbledecay",
"=",
"3",
")",
":",
"if",
"mapsize",
"&",
"(",
"mapsize",
"-",
"1",
")",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"'mapsize must be a power of two.'",
")",
"maparray",
"=",
"np",
... | Generate a heightmap using diamond-square algorithm.
Modification of the algorithm in
https://github.com/FLHerne/mapgen/blob/master/diamondsquare.py
Args:
mapsize: side length of the heightmap, must be a power of two.
wibbledecay: integer, decay factor.
Returns:
numpy 2d array, side length 'mapsi... | [
"Generate",
"a",
"heightmap",
"using",
"diamond",
"-",
"square",
"algorithm",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/corruptions.py#L104-L159 |
26,204 | tensorflow/datasets | tensorflow_datasets/image/corruptions.py | gaussian_noise | def gaussian_noise(x, severity=1):
"""Gaussian noise corruption to images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Added Gaussian noise.
"""
c = [.08, .12... | python | def gaussian_noise(x, severity=1):
"""Gaussian noise corruption to images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Added Gaussian noise.
"""
c = [.08, .12... | [
"def",
"gaussian_noise",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
".08",
",",
".12",
",",
"0.18",
",",
"0.26",
",",
"0.38",
"]",
"[",
"severity",
"-",
"1",
"]",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"/",
"255.",
... | Gaussian noise corruption to images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Added Gaussian noise. | [
"Gaussian",
"noise",
"corruption",
"to",
"images",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/corruptions.py#L167-L180 |
26,205 | tensorflow/datasets | tensorflow_datasets/image/corruptions.py | shot_noise | def shot_noise(x, severity=1):
"""Shot noise corruption to images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Added shot noise.
"""
c = [60, 25, 12, 5, 3][se... | python | def shot_noise(x, severity=1):
"""Shot noise corruption to images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Added shot noise.
"""
c = [60, 25, 12, 5, 3][se... | [
"def",
"shot_noise",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
"60",
",",
"25",
",",
"12",
",",
"5",
",",
"3",
"]",
"[",
"severity",
"-",
"1",
"]",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"/",
"255.",
"x_clip",
"=... | Shot noise corruption to images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Added shot noise. | [
"Shot",
"noise",
"corruption",
"to",
"images",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/corruptions.py#L183-L196 |
26,206 | tensorflow/datasets | tensorflow_datasets/image/corruptions.py | impulse_noise | def impulse_noise(x, severity=1):
"""Impulse noise corruption to images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Added impulse noise.
"""
c = [.03, .06, .... | python | def impulse_noise(x, severity=1):
"""Impulse noise corruption to images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Added impulse noise.
"""
c = [.03, .06, .... | [
"def",
"impulse_noise",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
".03",
",",
".06",
",",
".09",
",",
"0.17",
",",
"0.27",
"]",
"[",
"severity",
"-",
"1",
"]",
"x",
"=",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"skimag... | Impulse noise corruption to images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Added impulse noise. | [
"Impulse",
"noise",
"corruption",
"to",
"images",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/corruptions.py#L199-L213 |
26,207 | tensorflow/datasets | tensorflow_datasets/image/corruptions.py | defocus_blur | def defocus_blur(x, severity=1):
"""Defocus blurring to images.
Apply defocus blurring to images using Gaussian kernel.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,2... | python | def defocus_blur(x, severity=1):
"""Defocus blurring to images.
Apply defocus blurring to images using Gaussian kernel.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,2... | [
"def",
"defocus_blur",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
"(",
"3",
",",
"0.1",
")",
",",
"(",
"4",
",",
"0.5",
")",
",",
"(",
"6",
",",
"0.5",
")",
",",
"(",
"8",
",",
"0.5",
")",
",",
"(",
"10",
",",
"0.5",
... | Defocus blurring to images.
Apply defocus blurring to images using Gaussian kernel.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Applied defocus blur. | [
"Defocus",
"blurring",
"to",
"images",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/corruptions.py#L216-L236 |
26,208 | tensorflow/datasets | tensorflow_datasets/image/corruptions.py | frosted_glass_blur | def frosted_glass_blur(x, severity=1):
"""Frosted glass blurring to images.
Apply frosted glass blurring to images by shuffling pixels locally.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image w... | python | def frosted_glass_blur(x, severity=1):
"""Frosted glass blurring to images.
Apply frosted glass blurring to images by shuffling pixels locally.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image w... | [
"def",
"frosted_glass_blur",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"# sigma, max_delta, iterations",
"c",
"=",
"[",
"(",
"0.7",
",",
"1",
",",
"2",
")",
",",
"(",
"0.9",
",",
"2",
",",
"1",
")",
",",
"(",
"1",
",",
"2",
",",
"3",
")",
... | Frosted glass blurring to images.
Apply frosted glass blurring to images by shuffling pixels locally.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Applied frosted... | [
"Frosted",
"glass",
"blurring",
"to",
"images",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/corruptions.py#L239-L270 |
26,209 | tensorflow/datasets | tensorflow_datasets/image/corruptions.py | zoom_blur | def zoom_blur(x, severity=1):
"""Zoom blurring to images.
Applying zoom blurring to images by zooming the central part of the images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 ... | python | def zoom_blur(x, severity=1):
"""Zoom blurring to images.
Applying zoom blurring to images by zooming the central part of the images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 ... | [
"def",
"zoom_blur",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
"np",
".",
"arange",
"(",
"1",
",",
"1.11",
",",
"0.01",
")",
",",
"np",
".",
"arange",
"(",
"1",
",",
"1.16",
",",
"0.01",
")",
",",
"np",
".",
"arange",
"("... | Zoom blurring to images.
Applying zoom blurring to images by zooming the central part of the images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Applied zoom blu... | [
"Zoom",
"blurring",
"to",
"images",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/corruptions.py#L273-L298 |
26,210 | tensorflow/datasets | tensorflow_datasets/image/corruptions.py | fog | def fog(x, severity=1):
"""Fog corruption to images.
Adding fog to images. Fog is generated by diamond-square algorithm.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,... | python | def fog(x, severity=1):
"""Fog corruption to images.
Adding fog to images. Fog is generated by diamond-square algorithm.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,... | [
"def",
"fog",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
"(",
"1.5",
",",
"2",
")",
",",
"(",
"2.",
",",
"2",
")",
",",
"(",
"2.5",
",",
"1.7",
")",
",",
"(",
"2.5",
",",
"1.5",
")",
",",
"(",
"3.",
",",
"1.4",
")",... | Fog corruption to images.
Adding fog to images. Fog is generated by diamond-square algorithm.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Added fog. | [
"Fog",
"corruption",
"to",
"images",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/corruptions.py#L301-L326 |
26,211 | tensorflow/datasets | tensorflow_datasets/image/corruptions.py | brightness | def brightness(x, severity=1):
"""Change brightness of images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Changed brightness.
"""
c = [.1, .2, .3, .4, .5][se... | python | def brightness(x, severity=1):
"""Change brightness of images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Changed brightness.
"""
c = [.1, .2, .3, .4, .5][se... | [
"def",
"brightness",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
".1",
",",
".2",
",",
".3",
",",
".4",
",",
".5",
"]",
"[",
"severity",
"-",
"1",
"]",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"/",
"255.",
"x",
"=",
... | Change brightness of images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Changed brightness. | [
"Change",
"brightness",
"of",
"images",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/corruptions.py#L329-L346 |
26,212 | tensorflow/datasets | tensorflow_datasets/image/corruptions.py | contrast | def contrast(x, severity=1):
"""Change contrast of images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Changed contrast.
"""
c = [0.4, .3, .2, .1, .05][severi... | python | def contrast(x, severity=1):
"""Change contrast of images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Changed contrast.
"""
c = [0.4, .3, .2, .1, .05][severi... | [
"def",
"contrast",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
"0.4",
",",
".3",
",",
".2",
",",
".1",
",",
".05",
"]",
"[",
"severity",
"-",
"1",
"]",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"/",
"255.",
"means",
"... | Change contrast of images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Changed contrast. | [
"Change",
"contrast",
"of",
"images",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/corruptions.py#L349-L364 |
26,213 | tensorflow/datasets | tensorflow_datasets/image/corruptions.py | pixelate | def pixelate(x, severity=1):
"""Pixelate images.
Conduct pixelating corruptions to images by first shrinking the images and
then resizing to original size.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy ... | python | def pixelate(x, severity=1):
"""Pixelate images.
Conduct pixelating corruptions to images by first shrinking the images and
then resizing to original size.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy ... | [
"def",
"pixelate",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
"0.6",
",",
"0.5",
",",
"0.4",
",",
"0.3",
",",
"0.25",
"]",
"[",
"severity",
"-",
"1",
"]",
"shape",
"=",
"x",
".",
"shape",
"x",
"=",
"tfds",
".",
"core",
".... | Pixelate images.
Conduct pixelating corruptions to images by first shrinking the images and
then resizing to original size.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in ... | [
"Pixelate",
"images",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/corruptions.py#L428-L447 |
26,214 | tensorflow/datasets | tensorflow_datasets/image/corruptions.py | jpeg_compression | def jpeg_compression(x, severity=1):
"""Conduct jpeg compression to images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Applied jpeg compression.
"""
c = [25,... | python | def jpeg_compression(x, severity=1):
"""Conduct jpeg compression to images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Applied jpeg compression.
"""
c = [25,... | [
"def",
"jpeg_compression",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
"25",
",",
"18",
",",
"15",
",",
"10",
",",
"7",
"]",
"[",
"severity",
"-",
"1",
"]",
"x",
"=",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"PIL_Image",... | Conduct jpeg compression to images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Applied jpeg compression. | [
"Conduct",
"jpeg",
"compression",
"to",
"images",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/corruptions.py#L450-L466 |
26,215 | tensorflow/datasets | tensorflow_datasets/core/utils/py_utils.py | temporary_assignment | def temporary_assignment(obj, attr, value):
"""Temporarily assign obj.attr to value."""
original = getattr(obj, attr, None)
setattr(obj, attr, value)
yield
setattr(obj, attr, original) | python | def temporary_assignment(obj, attr, value):
"""Temporarily assign obj.attr to value."""
original = getattr(obj, attr, None)
setattr(obj, attr, value)
yield
setattr(obj, attr, original) | [
"def",
"temporary_assignment",
"(",
"obj",
",",
"attr",
",",
"value",
")",
":",
"original",
"=",
"getattr",
"(",
"obj",
",",
"attr",
",",
"None",
")",
"setattr",
"(",
"obj",
",",
"attr",
",",
"value",
")",
"yield",
"setattr",
"(",
"obj",
",",
"attr",... | Temporarily assign obj.attr to value. | [
"Temporarily",
"assign",
"obj",
".",
"attr",
"to",
"value",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/py_utils.py#L55-L60 |
26,216 | tensorflow/datasets | tensorflow_datasets/core/utils/py_utils.py | zip_dict | def zip_dict(*dicts):
"""Iterate over items of dictionaries grouped by their keys."""
for key in set(itertools.chain(*dicts)): # set merge all keys
# Will raise KeyError if the dict don't have the same keys
yield key, tuple(d[key] for d in dicts) | python | def zip_dict(*dicts):
"""Iterate over items of dictionaries grouped by their keys."""
for key in set(itertools.chain(*dicts)): # set merge all keys
# Will raise KeyError if the dict don't have the same keys
yield key, tuple(d[key] for d in dicts) | [
"def",
"zip_dict",
"(",
"*",
"dicts",
")",
":",
"for",
"key",
"in",
"set",
"(",
"itertools",
".",
"chain",
"(",
"*",
"dicts",
")",
")",
":",
"# set merge all keys",
"# Will raise KeyError if the dict don't have the same keys",
"yield",
"key",
",",
"tuple",
"(",
... | Iterate over items of dictionaries grouped by their keys. | [
"Iterate",
"over",
"items",
"of",
"dictionaries",
"grouped",
"by",
"their",
"keys",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/py_utils.py#L63-L67 |
26,217 | tensorflow/datasets | tensorflow_datasets/core/utils/py_utils.py | map_nested | def map_nested(function, data_struct, dict_only=False, map_tuple=False):
"""Apply a function recursively to each element of a nested data struct."""
# Could add support for more exotic data_struct, like OrderedDict
if isinstance(data_struct, dict):
return {
k: map_nested(function, v, dict_only, map_t... | python | def map_nested(function, data_struct, dict_only=False, map_tuple=False):
"""Apply a function recursively to each element of a nested data struct."""
# Could add support for more exotic data_struct, like OrderedDict
if isinstance(data_struct, dict):
return {
k: map_nested(function, v, dict_only, map_t... | [
"def",
"map_nested",
"(",
"function",
",",
"data_struct",
",",
"dict_only",
"=",
"False",
",",
"map_tuple",
"=",
"False",
")",
":",
"# Could add support for more exotic data_struct, like OrderedDict",
"if",
"isinstance",
"(",
"data_struct",
",",
"dict",
")",
":",
"r... | Apply a function recursively to each element of a nested data struct. | [
"Apply",
"a",
"function",
"recursively",
"to",
"each",
"element",
"of",
"a",
"nested",
"data",
"struct",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/py_utils.py#L122-L143 |
26,218 | tensorflow/datasets | tensorflow_datasets/core/utils/py_utils.py | zip_nested | def zip_nested(arg0, *args, **kwargs):
"""Zip data struct together and return a data struct with the same shape."""
# Python 2 do not support kwargs only arguments
dict_only = kwargs.pop("dict_only", False)
assert not kwargs
# Could add support for more exotic data_struct, like OrderedDict
if isinstance(ar... | python | def zip_nested(arg0, *args, **kwargs):
"""Zip data struct together and return a data struct with the same shape."""
# Python 2 do not support kwargs only arguments
dict_only = kwargs.pop("dict_only", False)
assert not kwargs
# Could add support for more exotic data_struct, like OrderedDict
if isinstance(ar... | [
"def",
"zip_nested",
"(",
"arg0",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Python 2 do not support kwargs only arguments",
"dict_only",
"=",
"kwargs",
".",
"pop",
"(",
"\"dict_only\"",
",",
"False",
")",
"assert",
"not",
"kwargs",
"# Could add sup... | Zip data struct together and return a data struct with the same shape. | [
"Zip",
"data",
"struct",
"together",
"and",
"return",
"a",
"data",
"struct",
"with",
"the",
"same",
"shape",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/py_utils.py#L146-L161 |
26,219 | tensorflow/datasets | tensorflow_datasets/core/utils/py_utils.py | as_proto_cls | def as_proto_cls(proto_cls):
"""Simulate proto inheritance.
By default, protobuf do not support direct inheritance, so this decorator
simulates inheritance to the class to which it is applied.
Example:
```
@as_proto_class(proto.MyProto)
class A(object):
def custom_method(self):
return self.pr... | python | def as_proto_cls(proto_cls):
"""Simulate proto inheritance.
By default, protobuf do not support direct inheritance, so this decorator
simulates inheritance to the class to which it is applied.
Example:
```
@as_proto_class(proto.MyProto)
class A(object):
def custom_method(self):
return self.pr... | [
"def",
"as_proto_cls",
"(",
"proto_cls",
")",
":",
"def",
"decorator",
"(",
"cls",
")",
":",
"\"\"\"Decorator applied to the class.\"\"\"",
"class",
"ProtoCls",
"(",
"object",
")",
":",
"\"\"\"Base class simulating the protobuf.\"\"\"",
"def",
"__init__",
"(",
"self",
... | Simulate proto inheritance.
By default, protobuf do not support direct inheritance, so this decorator
simulates inheritance to the class to which it is applied.
Example:
```
@as_proto_class(proto.MyProto)
class A(object):
def custom_method(self):
return self.proto_field * 10
p = proto.MyProt... | [
"Simulate",
"proto",
"inheritance",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/py_utils.py#L164-L229 |
26,220 | tensorflow/datasets | tensorflow_datasets/core/utils/py_utils.py | tfds_dir | def tfds_dir():
"""Path to tensorflow_datasets directory."""
return os.path.dirname(os.path.dirname(os.path.dirname(__file__))) | python | def tfds_dir():
"""Path to tensorflow_datasets directory."""
return os.path.dirname(os.path.dirname(os.path.dirname(__file__))) | [
"def",
"tfds_dir",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
")"
] | Path to tensorflow_datasets directory. | [
"Path",
"to",
"tensorflow_datasets",
"directory",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/py_utils.py#L232-L234 |
26,221 | tensorflow/datasets | tensorflow_datasets/core/utils/py_utils.py | atomic_write | def atomic_write(path, mode):
"""Writes to path atomically, by writing to temp file and renaming it."""
tmp_path = "%s%s_%s" % (path, constants.INCOMPLETE_SUFFIX, uuid.uuid4().hex)
with tf.io.gfile.GFile(tmp_path, mode) as file_:
yield file_
tf.io.gfile.rename(tmp_path, path, overwrite=True) | python | def atomic_write(path, mode):
"""Writes to path atomically, by writing to temp file and renaming it."""
tmp_path = "%s%s_%s" % (path, constants.INCOMPLETE_SUFFIX, uuid.uuid4().hex)
with tf.io.gfile.GFile(tmp_path, mode) as file_:
yield file_
tf.io.gfile.rename(tmp_path, path, overwrite=True) | [
"def",
"atomic_write",
"(",
"path",
",",
"mode",
")",
":",
"tmp_path",
"=",
"\"%s%s_%s\"",
"%",
"(",
"path",
",",
"constants",
".",
"INCOMPLETE_SUFFIX",
",",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
")",
"with",
"tf",
".",
"io",
".",
"gfile",
".",... | Writes to path atomically, by writing to temp file and renaming it. | [
"Writes",
"to",
"path",
"atomically",
"by",
"writing",
"to",
"temp",
"file",
"and",
"renaming",
"it",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/py_utils.py#L238-L243 |
26,222 | tensorflow/datasets | tensorflow_datasets/core/utils/py_utils.py | read_checksum_digest | def read_checksum_digest(path, checksum_cls=hashlib.sha256):
"""Given a hash constructor, returns checksum digest and size of file."""
checksum = checksum_cls()
size = 0
with tf.io.gfile.GFile(path, "rb") as f:
while True:
block = f.read(io.DEFAULT_BUFFER_SIZE)
size += len(block)
if not bl... | python | def read_checksum_digest(path, checksum_cls=hashlib.sha256):
"""Given a hash constructor, returns checksum digest and size of file."""
checksum = checksum_cls()
size = 0
with tf.io.gfile.GFile(path, "rb") as f:
while True:
block = f.read(io.DEFAULT_BUFFER_SIZE)
size += len(block)
if not bl... | [
"def",
"read_checksum_digest",
"(",
"path",
",",
"checksum_cls",
"=",
"hashlib",
".",
"sha256",
")",
":",
"checksum",
"=",
"checksum_cls",
"(",
")",
"size",
"=",
"0",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"path",
",",
"\"rb\"",
")",... | Given a hash constructor, returns checksum digest and size of file. | [
"Given",
"a",
"hash",
"constructor",
"returns",
"checksum",
"digest",
"and",
"size",
"of",
"file",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/py_utils.py#L262-L273 |
26,223 | tensorflow/datasets | tensorflow_datasets/core/utils/py_utils.py | reraise | def reraise(additional_msg):
"""Reraise an exception with an additional message."""
exc_type, exc_value, exc_traceback = sys.exc_info()
msg = str(exc_value) + "\n" + additional_msg
six.reraise(exc_type, exc_type(msg), exc_traceback) | python | def reraise(additional_msg):
"""Reraise an exception with an additional message."""
exc_type, exc_value, exc_traceback = sys.exc_info()
msg = str(exc_value) + "\n" + additional_msg
six.reraise(exc_type, exc_type(msg), exc_traceback) | [
"def",
"reraise",
"(",
"additional_msg",
")",
":",
"exc_type",
",",
"exc_value",
",",
"exc_traceback",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"str",
"(",
"exc_value",
")",
"+",
"\"\\n\"",
"+",
"additional_msg",
"six",
".",
"reraise",
"(",
"ex... | Reraise an exception with an additional message. | [
"Reraise",
"an",
"exception",
"with",
"an",
"additional",
"message",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/py_utils.py#L276-L280 |
26,224 | tensorflow/datasets | tensorflow_datasets/core/utils/py_utils.py | rgetattr | def rgetattr(obj, attr, *args):
"""Get attr that handles dots in attr name."""
def _getattr(obj, attr):
return getattr(obj, attr, *args)
return functools.reduce(_getattr, [obj] + attr.split(".")) | python | def rgetattr(obj, attr, *args):
"""Get attr that handles dots in attr name."""
def _getattr(obj, attr):
return getattr(obj, attr, *args)
return functools.reduce(_getattr, [obj] + attr.split(".")) | [
"def",
"rgetattr",
"(",
"obj",
",",
"attr",
",",
"*",
"args",
")",
":",
"def",
"_getattr",
"(",
"obj",
",",
"attr",
")",
":",
"return",
"getattr",
"(",
"obj",
",",
"attr",
",",
"*",
"args",
")",
"return",
"functools",
".",
"reduce",
"(",
"_getattr"... | Get attr that handles dots in attr name. | [
"Get",
"attr",
"that",
"handles",
"dots",
"in",
"attr",
"name",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/py_utils.py#L283-L287 |
26,225 | tensorflow/datasets | tensorflow_datasets/core/features/image_feature.py | Image.set_encoding_format | def set_encoding_format(self, encoding_format):
"""Update the encoding format."""
supported = ENCODE_FN.keys()
if encoding_format not in supported:
raise ValueError('`encoding_format` must be one of %s.' % supported)
self._encoding_format = encoding_format | python | def set_encoding_format(self, encoding_format):
"""Update the encoding format."""
supported = ENCODE_FN.keys()
if encoding_format not in supported:
raise ValueError('`encoding_format` must be one of %s.' % supported)
self._encoding_format = encoding_format | [
"def",
"set_encoding_format",
"(",
"self",
",",
"encoding_format",
")",
":",
"supported",
"=",
"ENCODE_FN",
".",
"keys",
"(",
")",
"if",
"encoding_format",
"not",
"in",
"supported",
":",
"raise",
"ValueError",
"(",
"'`encoding_format` must be one of %s.'",
"%",
"s... | Update the encoding format. | [
"Update",
"the",
"encoding",
"format",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/image_feature.py#L97-L102 |
26,226 | tensorflow/datasets | tensorflow_datasets/core/features/image_feature.py | Image.set_shape | def set_shape(self, shape):
"""Update the shape."""
channels = shape[-1]
acceptable_channels = ACCEPTABLE_CHANNELS[self._encoding_format]
if channels not in acceptable_channels:
raise ValueError('Acceptable `channels` for %s: %s (was %s)' % (
self._encoding_format, acceptable_channels, c... | python | def set_shape(self, shape):
"""Update the shape."""
channels = shape[-1]
acceptable_channels = ACCEPTABLE_CHANNELS[self._encoding_format]
if channels not in acceptable_channels:
raise ValueError('Acceptable `channels` for %s: %s (was %s)' % (
self._encoding_format, acceptable_channels, c... | [
"def",
"set_shape",
"(",
"self",
",",
"shape",
")",
":",
"channels",
"=",
"shape",
"[",
"-",
"1",
"]",
"acceptable_channels",
"=",
"ACCEPTABLE_CHANNELS",
"[",
"self",
".",
"_encoding_format",
"]",
"if",
"channels",
"not",
"in",
"acceptable_channels",
":",
"r... | Update the shape. | [
"Update",
"the",
"shape",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/image_feature.py#L104-L111 |
26,227 | tensorflow/datasets | tensorflow_datasets/core/features/image_feature.py | Image._encode_image | def _encode_image(self, np_image):
"""Returns np_image encoded as jpeg or png."""
if np_image.dtype != np.uint8:
raise ValueError('Image should be uint8. Detected: %s.' % np_image.dtype)
utils.assert_shape_match(np_image.shape, self._shape)
return self._runner.run(ENCODE_FN[self._encoding_format],... | python | def _encode_image(self, np_image):
"""Returns np_image encoded as jpeg or png."""
if np_image.dtype != np.uint8:
raise ValueError('Image should be uint8. Detected: %s.' % np_image.dtype)
utils.assert_shape_match(np_image.shape, self._shape)
return self._runner.run(ENCODE_FN[self._encoding_format],... | [
"def",
"_encode_image",
"(",
"self",
",",
"np_image",
")",
":",
"if",
"np_image",
".",
"dtype",
"!=",
"np",
".",
"uint8",
":",
"raise",
"ValueError",
"(",
"'Image should be uint8. Detected: %s.'",
"%",
"np_image",
".",
"dtype",
")",
"utils",
".",
"assert_shape... | Returns np_image encoded as jpeg or png. | [
"Returns",
"np_image",
"encoded",
"as",
"jpeg",
"or",
"png",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/image_feature.py#L128-L133 |
26,228 | tensorflow/datasets | tensorflow_datasets/core/features/image_feature.py | Image.encode_example | def encode_example(self, image_or_path_or_fobj):
"""Convert the given image into a dict convertible to tf example."""
if isinstance(image_or_path_or_fobj, np.ndarray):
encoded_image = self._encode_image(image_or_path_or_fobj)
elif isinstance(image_or_path_or_fobj, six.string_types):
with tf.io.g... | python | def encode_example(self, image_or_path_or_fobj):
"""Convert the given image into a dict convertible to tf example."""
if isinstance(image_or_path_or_fobj, np.ndarray):
encoded_image = self._encode_image(image_or_path_or_fobj)
elif isinstance(image_or_path_or_fobj, six.string_types):
with tf.io.g... | [
"def",
"encode_example",
"(",
"self",
",",
"image_or_path_or_fobj",
")",
":",
"if",
"isinstance",
"(",
"image_or_path_or_fobj",
",",
"np",
".",
"ndarray",
")",
":",
"encoded_image",
"=",
"self",
".",
"_encode_image",
"(",
"image_or_path_or_fobj",
")",
"elif",
"i... | Convert the given image into a dict convertible to tf example. | [
"Convert",
"the",
"given",
"image",
"into",
"a",
"dict",
"convertible",
"to",
"tf",
"example",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/image_feature.py#L135-L144 |
26,229 | tensorflow/datasets | tensorflow_datasets/core/features/image_feature.py | Image.decode_example | def decode_example(self, example):
"""Reconstruct the image from the tf example."""
img = tf.image.decode_image(
example, channels=self._shape[-1], dtype=tf.uint8)
img.set_shape(self._shape)
return img | python | def decode_example(self, example):
"""Reconstruct the image from the tf example."""
img = tf.image.decode_image(
example, channels=self._shape[-1], dtype=tf.uint8)
img.set_shape(self._shape)
return img | [
"def",
"decode_example",
"(",
"self",
",",
"example",
")",
":",
"img",
"=",
"tf",
".",
"image",
".",
"decode_image",
"(",
"example",
",",
"channels",
"=",
"self",
".",
"_shape",
"[",
"-",
"1",
"]",
",",
"dtype",
"=",
"tf",
".",
"uint8",
")",
"img",... | Reconstruct the image from the tf example. | [
"Reconstruct",
"the",
"image",
"from",
"the",
"tf",
"example",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/image_feature.py#L146-L151 |
26,230 | tensorflow/datasets | tensorflow_datasets/video/moving_sequence.py | _create_moving_sequence | def _create_moving_sequence(image, pad_lefts, total_padding):
"""Create a moving image sequence from the given image a left padding values.
Args:
image: [in_h, in_w, n_channels] uint8 array
pad_lefts: [sequence_length, 2] int32 array of left padding values
total_padding: tensor of padding values, (pad_... | python | def _create_moving_sequence(image, pad_lefts, total_padding):
"""Create a moving image sequence from the given image a left padding values.
Args:
image: [in_h, in_w, n_channels] uint8 array
pad_lefts: [sequence_length, 2] int32 array of left padding values
total_padding: tensor of padding values, (pad_... | [
"def",
"_create_moving_sequence",
"(",
"image",
",",
"pad_lefts",
",",
"total_padding",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"moving_sequence\"",
")",
":",
"def",
"get_padded_image",
"(",
"args",
")",
":",
"pad_left",
",",
"=",
"args",
"pad_right"... | Create a moving image sequence from the given image a left padding values.
Args:
image: [in_h, in_w, n_channels] uint8 array
pad_lefts: [sequence_length, 2] int32 array of left padding values
total_padding: tensor of padding values, (pad_h, pad_w)
Returns:
[sequence_length, out_h, out_w, n_channel... | [
"Create",
"a",
"moving",
"image",
"sequence",
"from",
"the",
"given",
"image",
"a",
"left",
"padding",
"values",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/video/moving_sequence.py#L27-L53 |
26,231 | tensorflow/datasets | tensorflow_datasets/video/moving_sequence.py | _get_linear_trajectory | def _get_linear_trajectory(x0, velocity, t):
"""Construct a linear trajectory from x0.
Args:
x0: N-D float tensor.
velocity: N-D float tensor
t: [sequence_length]-length float tensor
Returns:
x: [sequence_length, ndims] float tensor.
"""
x0 = tf.convert_to_tensor(x0)
velocity = tf.convert_... | python | def _get_linear_trajectory(x0, velocity, t):
"""Construct a linear trajectory from x0.
Args:
x0: N-D float tensor.
velocity: N-D float tensor
t: [sequence_length]-length float tensor
Returns:
x: [sequence_length, ndims] float tensor.
"""
x0 = tf.convert_to_tensor(x0)
velocity = tf.convert_... | [
"def",
"_get_linear_trajectory",
"(",
"x0",
",",
"velocity",
",",
"t",
")",
":",
"x0",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"x0",
")",
"velocity",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"velocity",
")",
"t",
"=",
"tf",
".",
"convert_to_tensor",
"... | Construct a linear trajectory from x0.
Args:
x0: N-D float tensor.
velocity: N-D float tensor
t: [sequence_length]-length float tensor
Returns:
x: [sequence_length, ndims] float tensor. | [
"Construct",
"a",
"linear",
"trajectory",
"from",
"x0",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/video/moving_sequence.py#L56-L82 |
26,232 | tensorflow/datasets | tensorflow_datasets/video/moving_sequence.py | image_as_moving_sequence | def image_as_moving_sequence(
image, sequence_length=20, output_size=(64, 64), velocity=0.1,
start_position=None):
"""Turn simple static images into sequences of the originals bouncing around.
Adapted from Srivastava et al.
http://www.cs.toronto.edu/~nitish/unsupervised_video/
Example usage:
```pyth... | python | def image_as_moving_sequence(
image, sequence_length=20, output_size=(64, 64), velocity=0.1,
start_position=None):
"""Turn simple static images into sequences of the originals bouncing around.
Adapted from Srivastava et al.
http://www.cs.toronto.edu/~nitish/unsupervised_video/
Example usage:
```pyth... | [
"def",
"image_as_moving_sequence",
"(",
"image",
",",
"sequence_length",
"=",
"20",
",",
"output_size",
"=",
"(",
"64",
",",
"64",
")",
",",
"velocity",
"=",
"0.1",
",",
"start_position",
"=",
"None",
")",
":",
"ndims",
"=",
"2",
"image",
"=",
"tf",
".... | Turn simple static images into sequences of the originals bouncing around.
Adapted from Srivastava et al.
http://www.cs.toronto.edu/~nitish/unsupervised_video/
Example usage:
```python
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow_datasets.video import moving_sequence
tf.c... | [
"Turn",
"simple",
"static",
"images",
"into",
"sequences",
"of",
"the",
"originals",
"bouncing",
"around",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/video/moving_sequence.py#L115-L234 |
26,233 | tensorflow/datasets | tensorflow_datasets/core/utils/version.py | Version.match | def match(self, other_version):
"""Returns True if other_version matches.
Args:
other_version: string, of the form "x[.y[.x]]" where {x,y,z} can be a
number or a wildcard.
"""
major, minor, patch = _str_to_version(other_version, allow_wildcard=True)
return (major in [self.major, "*"] ... | python | def match(self, other_version):
"""Returns True if other_version matches.
Args:
other_version: string, of the form "x[.y[.x]]" where {x,y,z} can be a
number or a wildcard.
"""
major, minor, patch = _str_to_version(other_version, allow_wildcard=True)
return (major in [self.major, "*"] ... | [
"def",
"match",
"(",
"self",
",",
"other_version",
")",
":",
"major",
",",
"minor",
",",
"patch",
"=",
"_str_to_version",
"(",
"other_version",
",",
"allow_wildcard",
"=",
"True",
")",
"return",
"(",
"major",
"in",
"[",
"self",
".",
"major",
",",
"\"*\""... | Returns True if other_version matches.
Args:
other_version: string, of the form "x[.y[.x]]" where {x,y,z} can be a
number or a wildcard. | [
"Returns",
"True",
"if",
"other_version",
"matches",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/version.py#L58-L67 |
26,234 | tensorflow/datasets | tensorflow_datasets/image/imagenet.py | Imagenet2012._get_validation_labels | def _get_validation_labels(val_path):
"""Returns labels for validation.
Args:
val_path: path to TAR file containing validation images. It is used to
retrieve the name of pictures and associate them to labels.
Returns:
dict, mapping from image name (str) to label (str).
"""
labels... | python | def _get_validation_labels(val_path):
"""Returns labels for validation.
Args:
val_path: path to TAR file containing validation images. It is used to
retrieve the name of pictures and associate them to labels.
Returns:
dict, mapping from image name (str) to label (str).
"""
labels... | [
"def",
"_get_validation_labels",
"(",
"val_path",
")",
":",
"labels_path",
"=",
"tfds",
".",
"core",
".",
"get_tfds_path",
"(",
"_VALIDATION_LABELS_FNAME",
")",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"labels_path",
")",
"as",
"labels_f",
"... | Returns labels for validation.
Args:
val_path: path to TAR file containing validation images. It is used to
retrieve the name of pictures and associate them to labels.
Returns:
dict, mapping from image name (str) to label (str). | [
"Returns",
"labels",
"for",
"validation",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/imagenet.py#L86-L102 |
26,235 | tensorflow/datasets | tensorflow_datasets/core/file_format_adapter.py | do_files_exist | def do_files_exist(filenames):
"""Whether any of the filenames exist."""
preexisting = [tf.io.gfile.exists(f) for f in filenames]
return any(preexisting) | python | def do_files_exist(filenames):
"""Whether any of the filenames exist."""
preexisting = [tf.io.gfile.exists(f) for f in filenames]
return any(preexisting) | [
"def",
"do_files_exist",
"(",
"filenames",
")",
":",
"preexisting",
"=",
"[",
"tf",
".",
"io",
".",
"gfile",
".",
"exists",
"(",
"f",
")",
"for",
"f",
"in",
"filenames",
"]",
"return",
"any",
"(",
"preexisting",
")"
] | Whether any of the filenames exist. | [
"Whether",
"any",
"of",
"the",
"filenames",
"exist",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/file_format_adapter.py#L194-L197 |
26,236 | tensorflow/datasets | tensorflow_datasets/core/file_format_adapter.py | get_incomplete_path | def get_incomplete_path(filename):
"""Returns a temporary filename based on filename."""
random_suffix = "".join(
random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
return filename + ".incomplete" + random_suffix | python | def get_incomplete_path(filename):
"""Returns a temporary filename based on filename."""
random_suffix = "".join(
random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
return filename + ".incomplete" + random_suffix | [
"def",
"get_incomplete_path",
"(",
"filename",
")",
":",
"random_suffix",
"=",
"\"\"",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"string",
".",
"ascii_uppercase",
"+",
"string",
".",
"digits",
")",
"for",
"_",
"in",
"range",
"(",
"6",
")",
")",
"... | Returns a temporary filename based on filename. | [
"Returns",
"a",
"temporary",
"filename",
"based",
"on",
"filename",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/file_format_adapter.py#L210-L214 |
26,237 | tensorflow/datasets | tensorflow_datasets/core/file_format_adapter.py | _incomplete_files | def _incomplete_files(filenames):
"""Create temporary files for filenames and rename on exit."""
tmp_files = [get_incomplete_path(f) for f in filenames]
try:
yield tmp_files
for tmp, output in zip(tmp_files, filenames):
tf.io.gfile.rename(tmp, output)
finally:
for tmp in tmp_files:
if tf... | python | def _incomplete_files(filenames):
"""Create temporary files for filenames and rename on exit."""
tmp_files = [get_incomplete_path(f) for f in filenames]
try:
yield tmp_files
for tmp, output in zip(tmp_files, filenames):
tf.io.gfile.rename(tmp, output)
finally:
for tmp in tmp_files:
if tf... | [
"def",
"_incomplete_files",
"(",
"filenames",
")",
":",
"tmp_files",
"=",
"[",
"get_incomplete_path",
"(",
"f",
")",
"for",
"f",
"in",
"filenames",
"]",
"try",
":",
"yield",
"tmp_files",
"for",
"tmp",
",",
"output",
"in",
"zip",
"(",
"tmp_files",
",",
"f... | Create temporary files for filenames and rename on exit. | [
"Create",
"temporary",
"files",
"for",
"filenames",
"and",
"rename",
"on",
"exit",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/file_format_adapter.py#L218-L228 |
26,238 | tensorflow/datasets | tensorflow_datasets/core/file_format_adapter.py | incomplete_dir | def incomplete_dir(dirname):
"""Create temporary dir for dirname and rename on exit."""
tmp_dir = get_incomplete_path(dirname)
tf.io.gfile.makedirs(tmp_dir)
try:
yield tmp_dir
tf.io.gfile.rename(tmp_dir, dirname)
finally:
if tf.io.gfile.exists(tmp_dir):
tf.io.gfile.rmtree(tmp_dir) | python | def incomplete_dir(dirname):
"""Create temporary dir for dirname and rename on exit."""
tmp_dir = get_incomplete_path(dirname)
tf.io.gfile.makedirs(tmp_dir)
try:
yield tmp_dir
tf.io.gfile.rename(tmp_dir, dirname)
finally:
if tf.io.gfile.exists(tmp_dir):
tf.io.gfile.rmtree(tmp_dir) | [
"def",
"incomplete_dir",
"(",
"dirname",
")",
":",
"tmp_dir",
"=",
"get_incomplete_path",
"(",
"dirname",
")",
"tf",
".",
"io",
".",
"gfile",
".",
"makedirs",
"(",
"tmp_dir",
")",
"try",
":",
"yield",
"tmp_dir",
"tf",
".",
"io",
".",
"gfile",
".",
"ren... | Create temporary dir for dirname and rename on exit. | [
"Create",
"temporary",
"dir",
"for",
"dirname",
"and",
"rename",
"on",
"exit",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/file_format_adapter.py#L232-L241 |
26,239 | tensorflow/datasets | tensorflow_datasets/core/file_format_adapter.py | _shuffle_tfrecord | def _shuffle_tfrecord(path, random_gen):
"""Shuffle a single record file in memory."""
# Read all records
record_iter = tf.compat.v1.io.tf_record_iterator(path)
all_records = [
r for r in utils.tqdm(
record_iter, desc="Reading...", unit=" examples", leave=False)
]
# Shuffling in memory
ran... | python | def _shuffle_tfrecord(path, random_gen):
"""Shuffle a single record file in memory."""
# Read all records
record_iter = tf.compat.v1.io.tf_record_iterator(path)
all_records = [
r for r in utils.tqdm(
record_iter, desc="Reading...", unit=" examples", leave=False)
]
# Shuffling in memory
ran... | [
"def",
"_shuffle_tfrecord",
"(",
"path",
",",
"random_gen",
")",
":",
"# Read all records",
"record_iter",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"io",
".",
"tf_record_iterator",
"(",
"path",
")",
"all_records",
"=",
"[",
"r",
"for",
"r",
"in",
"utils",... | Shuffle a single record file in memory. | [
"Shuffle",
"a",
"single",
"record",
"file",
"in",
"memory",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/file_format_adapter.py#L244-L258 |
26,240 | tensorflow/datasets | tensorflow_datasets/core/file_format_adapter.py | _write_tfrecords_from_generator | def _write_tfrecords_from_generator(generator, output_files, shuffle=True):
"""Writes generated str records to output_files in round-robin order."""
if do_files_exist(output_files):
raise ValueError(
"Pre-processed files already exists: {}.".format(output_files))
with _incomplete_files(output_files) ... | python | def _write_tfrecords_from_generator(generator, output_files, shuffle=True):
"""Writes generated str records to output_files in round-robin order."""
if do_files_exist(output_files):
raise ValueError(
"Pre-processed files already exists: {}.".format(output_files))
with _incomplete_files(output_files) ... | [
"def",
"_write_tfrecords_from_generator",
"(",
"generator",
",",
"output_files",
",",
"shuffle",
"=",
"True",
")",
":",
"if",
"do_files_exist",
"(",
"output_files",
")",
":",
"raise",
"ValueError",
"(",
"\"Pre-processed files already exists: {}.\"",
".",
"format",
"("... | Writes generated str records to output_files in round-robin order. | [
"Writes",
"generated",
"str",
"records",
"to",
"output_files",
"in",
"round",
"-",
"robin",
"order",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/file_format_adapter.py#L261-L281 |
26,241 | tensorflow/datasets | tensorflow_datasets/core/file_format_adapter.py | _round_robin_write | def _round_robin_write(writers, generator):
"""Write records from generator round-robin across writers."""
for i, example in enumerate(utils.tqdm(
generator, unit=" examples", leave=False)):
writers[i % len(writers)].write(example) | python | def _round_robin_write(writers, generator):
"""Write records from generator round-robin across writers."""
for i, example in enumerate(utils.tqdm(
generator, unit=" examples", leave=False)):
writers[i % len(writers)].write(example) | [
"def",
"_round_robin_write",
"(",
"writers",
",",
"generator",
")",
":",
"for",
"i",
",",
"example",
"in",
"enumerate",
"(",
"utils",
".",
"tqdm",
"(",
"generator",
",",
"unit",
"=",
"\" examples\"",
",",
"leave",
"=",
"False",
")",
")",
":",
"writers",
... | Write records from generator round-robin across writers. | [
"Write",
"records",
"from",
"generator",
"round",
"-",
"robin",
"across",
"writers",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/file_format_adapter.py#L284-L288 |
26,242 | tensorflow/datasets | tensorflow_datasets/core/file_format_adapter.py | _item_to_tf_feature | def _item_to_tf_feature(item, key_name):
"""Single item to a tf.train.Feature."""
v = item
if isinstance(v, (list, tuple)) and not v:
raise ValueError(
"Feature {} received an empty list value, so is unable to infer the "
"feature type to record. To support empty value, the corresponding "
... | python | def _item_to_tf_feature(item, key_name):
"""Single item to a tf.train.Feature."""
v = item
if isinstance(v, (list, tuple)) and not v:
raise ValueError(
"Feature {} received an empty list value, so is unable to infer the "
"feature type to record. To support empty value, the corresponding "
... | [
"def",
"_item_to_tf_feature",
"(",
"item",
",",
"key_name",
")",
":",
"v",
"=",
"item",
"if",
"isinstance",
"(",
"v",
",",
"(",
"list",
",",
"tuple",
")",
")",
"and",
"not",
"v",
":",
"raise",
"ValueError",
"(",
"\"Feature {} received an empty list value, so... | Single item to a tf.train.Feature. | [
"Single",
"item",
"to",
"a",
"tf",
".",
"train",
".",
"Feature",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/file_format_adapter.py#L307-L344 |
26,243 | tensorflow/datasets | tensorflow_datasets/core/utils/tqdm_utils.py | _async_tqdm | def _async_tqdm(*args, **kwargs):
"""Wrapper around Tqdm which can be updated in threads.
Usage:
```
with utils.async_tqdm(...) as pbar:
# pbar can then be modified inside a thread
# pbar.update_total(3)
# pbar.update()
```
Args:
*args: args of tqdm
**kwargs: kwargs of tqdm
Yields:... | python | def _async_tqdm(*args, **kwargs):
"""Wrapper around Tqdm which can be updated in threads.
Usage:
```
with utils.async_tqdm(...) as pbar:
# pbar can then be modified inside a thread
# pbar.update_total(3)
# pbar.update()
```
Args:
*args: args of tqdm
**kwargs: kwargs of tqdm
Yields:... | [
"def",
"_async_tqdm",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"tqdm_lib",
".",
"tqdm",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"as",
"pbar",
":",
"pbar",
"=",
"_TqdmPbarAsync",
"(",
"pbar",
")",
"yield",
"pbar",
"pbar",... | Wrapper around Tqdm which can be updated in threads.
Usage:
```
with utils.async_tqdm(...) as pbar:
# pbar can then be modified inside a thread
# pbar.update_total(3)
# pbar.update()
```
Args:
*args: args of tqdm
**kwargs: kwargs of tqdm
Yields:
pbar: Async pbar which can be shar... | [
"Wrapper",
"around",
"Tqdm",
"which",
"can",
"be",
"updated",
"in",
"threads",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/tqdm_utils.py#L79-L102 |
26,244 | tensorflow/datasets | tensorflow_datasets/core/utils/tqdm_utils.py | _TqdmPbarAsync.update_total | def update_total(self, n=1):
"""Increment total pbar value."""
with self._lock:
self._pbar.total += n
self.refresh() | python | def update_total(self, n=1):
"""Increment total pbar value."""
with self._lock:
self._pbar.total += n
self.refresh() | [
"def",
"update_total",
"(",
"self",
",",
"n",
"=",
"1",
")",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_pbar",
".",
"total",
"+=",
"n",
"self",
".",
"refresh",
"(",
")"
] | Increment total pbar value. | [
"Increment",
"total",
"pbar",
"value",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/tqdm_utils.py#L114-L118 |
26,245 | tensorflow/datasets | tensorflow_datasets/core/utils/tqdm_utils.py | _TqdmPbarAsync.update | def update(self, n=1):
"""Increment current value."""
with self._lock:
self._pbar.update(n)
self.refresh() | python | def update(self, n=1):
"""Increment current value."""
with self._lock:
self._pbar.update(n)
self.refresh() | [
"def",
"update",
"(",
"self",
",",
"n",
"=",
"1",
")",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_pbar",
".",
"update",
"(",
"n",
")",
"self",
".",
"refresh",
"(",
")"
] | Increment current value. | [
"Increment",
"current",
"value",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/tqdm_utils.py#L120-L124 |
26,246 | tensorflow/datasets | tensorflow_datasets/core/download/extractor.py | _copy | def _copy(src_file, dest_path):
"""Copy data read from src file obj to new file in dest_path."""
tf.io.gfile.makedirs(os.path.dirname(dest_path))
with tf.io.gfile.GFile(dest_path, 'wb') as dest_file:
while True:
data = src_file.read(io.DEFAULT_BUFFER_SIZE)
if not data:
break
dest_fil... | python | def _copy(src_file, dest_path):
"""Copy data read from src file obj to new file in dest_path."""
tf.io.gfile.makedirs(os.path.dirname(dest_path))
with tf.io.gfile.GFile(dest_path, 'wb') as dest_file:
while True:
data = src_file.read(io.DEFAULT_BUFFER_SIZE)
if not data:
break
dest_fil... | [
"def",
"_copy",
"(",
"src_file",
",",
"dest_path",
")",
":",
"tf",
".",
"io",
".",
"gfile",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"dest_path",
")",
")",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"dest_path",
... | Copy data read from src file obj to new file in dest_path. | [
"Copy",
"data",
"read",
"from",
"src",
"file",
"obj",
"to",
"new",
"file",
"in",
"dest_path",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/extractor.py#L103-L111 |
26,247 | tensorflow/datasets | tensorflow_datasets/core/download/extractor.py | _Extractor.tqdm | def tqdm(self):
"""Add a progression bar for the current extraction."""
with utils.async_tqdm(
total=0, desc='Extraction completed...', unit=' file') as pbar_path:
self._pbar_path = pbar_path
yield | python | def tqdm(self):
"""Add a progression bar for the current extraction."""
with utils.async_tqdm(
total=0, desc='Extraction completed...', unit=' file') as pbar_path:
self._pbar_path = pbar_path
yield | [
"def",
"tqdm",
"(",
"self",
")",
":",
"with",
"utils",
".",
"async_tqdm",
"(",
"total",
"=",
"0",
",",
"desc",
"=",
"'Extraction completed...'",
",",
"unit",
"=",
"' file'",
")",
"as",
"pbar_path",
":",
"self",
".",
"_pbar_path",
"=",
"pbar_path",
"yield... | Add a progression bar for the current extraction. | [
"Add",
"a",
"progression",
"bar",
"for",
"the",
"current",
"extraction",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/extractor.py#L68-L73 |
26,248 | tensorflow/datasets | tensorflow_datasets/core/download/extractor.py | _Extractor.extract | def extract(self, path, extract_method, to_path):
"""Returns `promise.Promise` => to_path."""
self._pbar_path.update_total(1)
if extract_method not in _EXTRACT_METHODS:
raise ValueError('Unknown extraction method "%s".' % extract_method)
future = self._executor.submit(self._sync_extract,
... | python | def extract(self, path, extract_method, to_path):
"""Returns `promise.Promise` => to_path."""
self._pbar_path.update_total(1)
if extract_method not in _EXTRACT_METHODS:
raise ValueError('Unknown extraction method "%s".' % extract_method)
future = self._executor.submit(self._sync_extract,
... | [
"def",
"extract",
"(",
"self",
",",
"path",
",",
"extract_method",
",",
"to_path",
")",
":",
"self",
".",
"_pbar_path",
".",
"update_total",
"(",
"1",
")",
"if",
"extract_method",
"not",
"in",
"_EXTRACT_METHODS",
":",
"raise",
"ValueError",
"(",
"'Unknown ex... | Returns `promise.Promise` => to_path. | [
"Returns",
"promise",
".",
"Promise",
"=",
">",
"to_path",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/extractor.py#L75-L82 |
26,249 | tensorflow/datasets | tensorflow_datasets/core/download/extractor.py | _Extractor._sync_extract | def _sync_extract(self, from_path, method, to_path):
"""Returns `to_path` once resource has been extracted there."""
to_path_tmp = '%s%s_%s' % (to_path, constants.INCOMPLETE_SUFFIX,
uuid.uuid4().hex)
try:
for path, handle in iter_archive(from_path, method):
_copy... | python | def _sync_extract(self, from_path, method, to_path):
"""Returns `to_path` once resource has been extracted there."""
to_path_tmp = '%s%s_%s' % (to_path, constants.INCOMPLETE_SUFFIX,
uuid.uuid4().hex)
try:
for path, handle in iter_archive(from_path, method):
_copy... | [
"def",
"_sync_extract",
"(",
"self",
",",
"from_path",
",",
"method",
",",
"to_path",
")",
":",
"to_path_tmp",
"=",
"'%s%s_%s'",
"%",
"(",
"to_path",
",",
"constants",
".",
"INCOMPLETE_SUFFIX",
",",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
")",
"try",... | Returns `to_path` once resource has been extracted there. | [
"Returns",
"to_path",
"once",
"resource",
"has",
"been",
"extracted",
"there",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/extractor.py#L84-L100 |
26,250 | tensorflow/datasets | tensorflow_datasets/core/features/feature.py | to_serialized_field | def to_serialized_field(tensor_info):
"""Convert a `TensorInfo` object into a feature proto object."""
# Select the type
dtype = tensor_info.dtype
# TODO(b/119937875): TF Examples proto only support int64, float32 and string
# This create limitation like float64 downsampled to float32, bool converted
# to ... | python | def to_serialized_field(tensor_info):
"""Convert a `TensorInfo` object into a feature proto object."""
# Select the type
dtype = tensor_info.dtype
# TODO(b/119937875): TF Examples proto only support int64, float32 and string
# This create limitation like float64 downsampled to float32, bool converted
# to ... | [
"def",
"to_serialized_field",
"(",
"tensor_info",
")",
":",
"# Select the type",
"dtype",
"=",
"tensor_info",
".",
"dtype",
"# TODO(b/119937875): TF Examples proto only support int64, float32 and string",
"# This create limitation like float64 downsampled to float32, bool converted",
"# ... | Convert a `TensorInfo` object into a feature proto object. | [
"Convert",
"a",
"TensorInfo",
"object",
"into",
"a",
"feature",
"proto",
"object",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/feature.py#L576-L612 |
26,251 | tensorflow/datasets | tensorflow_datasets/core/features/feature.py | to_feature | def to_feature(value):
"""Convert the given value to Feature if necessary."""
if isinstance(value, FeatureConnector):
return value
elif utils.is_dtype(value): # tf.int32, tf.string,...
return Tensor(shape=(), dtype=tf.as_dtype(value))
elif isinstance(value, dict):
return FeaturesDict(value)
else:... | python | def to_feature(value):
"""Convert the given value to Feature if necessary."""
if isinstance(value, FeatureConnector):
return value
elif utils.is_dtype(value): # tf.int32, tf.string,...
return Tensor(shape=(), dtype=tf.as_dtype(value))
elif isinstance(value, dict):
return FeaturesDict(value)
else:... | [
"def",
"to_feature",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"FeatureConnector",
")",
":",
"return",
"value",
"elif",
"utils",
".",
"is_dtype",
"(",
"value",
")",
":",
"# tf.int32, tf.string,...",
"return",
"Tensor",
"(",
"shape",
"=",... | Convert the given value to Feature if necessary. | [
"Convert",
"the",
"given",
"value",
"to",
"Feature",
"if",
"necessary",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/feature.py#L615-L624 |
26,252 | tensorflow/datasets | tensorflow_datasets/core/features/feature.py | decode_single_feature_from_dict | def decode_single_feature_from_dict(
feature_k,
feature,
tfexample_dict):
"""Decode the given feature from the tfexample_dict.
Args:
feature_k (str): Feature key in the tfexample_dict
feature (FeatureConnector): Connector object to use to decode the field
tfexample_dict (dict): Dict contain... | python | def decode_single_feature_from_dict(
feature_k,
feature,
tfexample_dict):
"""Decode the given feature from the tfexample_dict.
Args:
feature_k (str): Feature key in the tfexample_dict
feature (FeatureConnector): Connector object to use to decode the field
tfexample_dict (dict): Dict contain... | [
"def",
"decode_single_feature_from_dict",
"(",
"feature_k",
",",
"feature",
",",
"tfexample_dict",
")",
":",
"# Singleton case",
"if",
"not",
"feature",
".",
"serialized_keys",
":",
"data_to_decode",
"=",
"tfexample_dict",
"[",
"feature_k",
"]",
"# Feature contains sub ... | Decode the given feature from the tfexample_dict.
Args:
feature_k (str): Feature key in the tfexample_dict
feature (FeatureConnector): Connector object to use to decode the field
tfexample_dict (dict): Dict containing the data to decode.
Returns:
decoded_feature: The output of the feature.decode_e... | [
"Decode",
"the",
"given",
"feature",
"from",
"the",
"tfexample_dict",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/feature.py#L627-L651 |
26,253 | tensorflow/datasets | tensorflow_datasets/core/features/feature.py | _assert_keys_match | def _assert_keys_match(keys1, keys2):
"""Ensure the two list of keys matches."""
if set(keys1) != set(keys2):
raise ValueError('{} {}'.format(list(keys1), list(keys2))) | python | def _assert_keys_match(keys1, keys2):
"""Ensure the two list of keys matches."""
if set(keys1) != set(keys2):
raise ValueError('{} {}'.format(list(keys1), list(keys2))) | [
"def",
"_assert_keys_match",
"(",
"keys1",
",",
"keys2",
")",
":",
"if",
"set",
"(",
"keys1",
")",
"!=",
"set",
"(",
"keys2",
")",
":",
"raise",
"ValueError",
"(",
"'{} {}'",
".",
"format",
"(",
"list",
"(",
"keys1",
")",
",",
"list",
"(",
"keys2",
... | Ensure the two list of keys matches. | [
"Ensure",
"the",
"two",
"list",
"of",
"keys",
"matches",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/feature.py#L654-L657 |
26,254 | tensorflow/datasets | tensorflow_datasets/image/celeba.py | CelebA._process_celeba_config_file | def _process_celeba_config_file(self, file_path):
"""Unpack the celeba config file.
The file starts with the number of lines, and a header.
Afterwards, there is a configuration for each file: one per line.
Args:
file_path: Path to the file with the configuration.
Returns:
keys: names ... | python | def _process_celeba_config_file(self, file_path):
"""Unpack the celeba config file.
The file starts with the number of lines, and a header.
Afterwards, there is a configuration for each file: one per line.
Args:
file_path: Path to the file with the configuration.
Returns:
keys: names ... | [
"def",
"_process_celeba_config_file",
"(",
"self",
",",
"file_path",
")",
":",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"file_path",
")",
"as",
"f",
":",
"data_raw",
"=",
"f",
".",
"read",
"(",
")",
"lines",
"=",
"data_raw",
".",
"sp... | Unpack the celeba config file.
The file starts with the number of lines, and a header.
Afterwards, there is a configuration for each file: one per line.
Args:
file_path: Path to the file with the configuration.
Returns:
keys: names of the attributes
values: map from the file name to... | [
"Unpack",
"the",
"celeba",
"config",
"file",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/celeba.py#L150-L175 |
26,255 | tensorflow/datasets | tensorflow_datasets/image/quickdraw.py | QuickdrawBitmap._generate_examples | def _generate_examples(self, file_paths):
"""Generate QuickDraw bitmap examples.
Given a list of file paths with data for each class label, generate examples
in a random order.
Args:
file_paths: (dict of {str: str}) the paths to files containing the data,
indexed by label.
... | python | def _generate_examples(self, file_paths):
"""Generate QuickDraw bitmap examples.
Given a list of file paths with data for each class label, generate examples
in a random order.
Args:
file_paths: (dict of {str: str}) the paths to files containing the data,
indexed by label.
... | [
"def",
"_generate_examples",
"(",
"self",
",",
"file_paths",
")",
":",
"for",
"label",
",",
"path",
"in",
"sorted",
"(",
"file_paths",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
":",
"with",
"tf",
".",
"... | Generate QuickDraw bitmap examples.
Given a list of file paths with data for each class label, generate examples
in a random order.
Args:
file_paths: (dict of {str: str}) the paths to files containing the data,
indexed by label.
Yields:
The QuickDraw examples, as defined... | [
"Generate",
"QuickDraw",
"bitmap",
"examples",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/quickdraw.py#L97-L117 |
26,256 | tensorflow/datasets | tensorflow_datasets/core/tf_compat.py | ensure_tf_install | def ensure_tf_install(): # pylint: disable=g-statement-before-imports
"""Attempt to import tensorflow, and ensure its version is sufficient.
Raises:
ImportError: if either tensorflow is not importable or its version is
inadequate.
"""
try:
import tensorflow as tf
except ImportError:
# Print ... | python | def ensure_tf_install(): # pylint: disable=g-statement-before-imports
"""Attempt to import tensorflow, and ensure its version is sufficient.
Raises:
ImportError: if either tensorflow is not importable or its version is
inadequate.
"""
try:
import tensorflow as tf
except ImportError:
# Print ... | [
"def",
"ensure_tf_install",
"(",
")",
":",
"# pylint: disable=g-statement-before-imports",
"try",
":",
"import",
"tensorflow",
"as",
"tf",
"except",
"ImportError",
":",
"# Print more informative error message, then reraise.",
"print",
"(",
"\"\\n\\nFailed to import TensorFlow. Pl... | Attempt to import tensorflow, and ensure its version is sufficient.
Raises:
ImportError: if either tensorflow is not importable or its version is
inadequate. | [
"Attempt",
"to",
"import",
"tensorflow",
"and",
"ensure",
"its",
"version",
"is",
"sufficient",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/tf_compat.py#L39-L67 |
26,257 | tensorflow/datasets | tensorflow_datasets/core/tf_compat.py | _patch_tf | def _patch_tf(tf):
"""Patch TF to maintain compatibility across versions."""
global TF_PATCH
if TF_PATCH:
return
v_1_12 = distutils.version.LooseVersion("1.12.0")
v_1_13 = distutils.version.LooseVersion("1.13.0")
v_2 = distutils.version.LooseVersion("2.0.0")
tf_version = distutils.version.LooseVersio... | python | def _patch_tf(tf):
"""Patch TF to maintain compatibility across versions."""
global TF_PATCH
if TF_PATCH:
return
v_1_12 = distutils.version.LooseVersion("1.12.0")
v_1_13 = distutils.version.LooseVersion("1.13.0")
v_2 = distutils.version.LooseVersion("2.0.0")
tf_version = distutils.version.LooseVersio... | [
"def",
"_patch_tf",
"(",
"tf",
")",
":",
"global",
"TF_PATCH",
"if",
"TF_PATCH",
":",
"return",
"v_1_12",
"=",
"distutils",
".",
"version",
".",
"LooseVersion",
"(",
"\"1.12.0\"",
")",
"v_1_13",
"=",
"distutils",
".",
"version",
".",
"LooseVersion",
"(",
"... | Patch TF to maintain compatibility across versions. | [
"Patch",
"TF",
"to",
"maintain",
"compatibility",
"across",
"versions",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/tf_compat.py#L70-L89 |
26,258 | tensorflow/datasets | tensorflow_datasets/core/tf_compat.py | _patch_for_tf1_12 | def _patch_for_tf1_12(tf):
"""Monkey patch tf 1.12 so tfds can use it."""
tf.io.gfile = tf.gfile
tf.io.gfile.copy = tf.gfile.Copy
tf.io.gfile.exists = tf.gfile.Exists
tf.io.gfile.glob = tf.gfile.Glob
tf.io.gfile.isdir = tf.gfile.IsDirectory
tf.io.gfile.listdir = tf.gfile.ListDirectory
tf.io.gfile.makedi... | python | def _patch_for_tf1_12(tf):
"""Monkey patch tf 1.12 so tfds can use it."""
tf.io.gfile = tf.gfile
tf.io.gfile.copy = tf.gfile.Copy
tf.io.gfile.exists = tf.gfile.Exists
tf.io.gfile.glob = tf.gfile.Glob
tf.io.gfile.isdir = tf.gfile.IsDirectory
tf.io.gfile.listdir = tf.gfile.ListDirectory
tf.io.gfile.makedi... | [
"def",
"_patch_for_tf1_12",
"(",
"tf",
")",
":",
"tf",
".",
"io",
".",
"gfile",
"=",
"tf",
".",
"gfile",
"tf",
".",
"io",
".",
"gfile",
".",
"copy",
"=",
"tf",
".",
"gfile",
".",
"Copy",
"tf",
".",
"io",
".",
"gfile",
".",
"exists",
"=",
"tf",
... | Monkey patch tf 1.12 so tfds can use it. | [
"Monkey",
"patch",
"tf",
"1",
".",
"12",
"so",
"tfds",
"can",
"use",
"it",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/tf_compat.py#L100-L132 |
26,259 | tensorflow/datasets | tensorflow_datasets/core/tf_compat.py | _patch_for_tf1_13 | def _patch_for_tf1_13(tf):
"""Monkey patch tf 1.13 so tfds can use it."""
if not hasattr(tf.io.gfile, "GFile"):
tf.io.gfile.GFile = tf.gfile.GFile
if not hasattr(tf, "nest"):
tf.nest = tf.contrib.framework.nest
if not hasattr(tf.compat, "v2"):
tf.compat.v2 = types.ModuleType("tf.compat.v2")
tf.c... | python | def _patch_for_tf1_13(tf):
"""Monkey patch tf 1.13 so tfds can use it."""
if not hasattr(tf.io.gfile, "GFile"):
tf.io.gfile.GFile = tf.gfile.GFile
if not hasattr(tf, "nest"):
tf.nest = tf.contrib.framework.nest
if not hasattr(tf.compat, "v2"):
tf.compat.v2 = types.ModuleType("tf.compat.v2")
tf.c... | [
"def",
"_patch_for_tf1_13",
"(",
"tf",
")",
":",
"if",
"not",
"hasattr",
"(",
"tf",
".",
"io",
".",
"gfile",
",",
"\"GFile\"",
")",
":",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"=",
"tf",
".",
"gfile",
".",
"GFile",
"if",
"not",
"hasattr",
"... | Monkey patch tf 1.13 so tfds can use it. | [
"Monkey",
"patch",
"tf",
"1",
".",
"13",
"so",
"tfds",
"can",
"use",
"it",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/tf_compat.py#L135-L152 |
26,260 | tensorflow/datasets | tensorflow_datasets/core/tf_compat.py | is_dataset | def is_dataset(ds):
"""Whether ds is a Dataset. Compatible across TF versions."""
import tensorflow as tf
from tensorflow_datasets.core.utils import py_utils
dataset_types = [tf.data.Dataset]
v1_ds = py_utils.rgetattr(tf, "compat.v1.data.Dataset", None)
v2_ds = py_utils.rgetattr(tf, "compat.v2.data.Dataset"... | python | def is_dataset(ds):
"""Whether ds is a Dataset. Compatible across TF versions."""
import tensorflow as tf
from tensorflow_datasets.core.utils import py_utils
dataset_types = [tf.data.Dataset]
v1_ds = py_utils.rgetattr(tf, "compat.v1.data.Dataset", None)
v2_ds = py_utils.rgetattr(tf, "compat.v2.data.Dataset"... | [
"def",
"is_dataset",
"(",
"ds",
")",
":",
"import",
"tensorflow",
"as",
"tf",
"from",
"tensorflow_datasets",
".",
"core",
".",
"utils",
"import",
"py_utils",
"dataset_types",
"=",
"[",
"tf",
".",
"data",
".",
"Dataset",
"]",
"v1_ds",
"=",
"py_utils",
".",
... | Whether ds is a Dataset. Compatible across TF versions. | [
"Whether",
"ds",
"is",
"a",
"Dataset",
".",
"Compatible",
"across",
"TF",
"versions",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/tf_compat.py#L155-L166 |
26,261 | tensorflow/datasets | tensorflow_datasets/image/image_folder.py | ImageLabelFolder._split_generators | def _split_generators(self, dl_manager):
"""Returns SplitGenerators from the folder names."""
# At data creation time, parse the folder to deduce number of splits,
# labels, image size,
# The splits correspond to the high level folders
split_names = list_folders(dl_manager.manual_dir)
# Extrac... | python | def _split_generators(self, dl_manager):
"""Returns SplitGenerators from the folder names."""
# At data creation time, parse the folder to deduce number of splits,
# labels, image size,
# The splits correspond to the high level folders
split_names = list_folders(dl_manager.manual_dir)
# Extrac... | [
"def",
"_split_generators",
"(",
"self",
",",
"dl_manager",
")",
":",
"# At data creation time, parse the folder to deduce number of splits,",
"# labels, image size,",
"# The splits correspond to the high level folders",
"split_names",
"=",
"list_folders",
"(",
"dl_manager",
".",
"... | Returns SplitGenerators from the folder names. | [
"Returns",
"SplitGenerators",
"from",
"the",
"folder",
"names",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/image_folder.py#L103-L154 |
26,262 | tensorflow/datasets | tensorflow_datasets/image/image_folder.py | ImageLabelFolder._generate_examples | def _generate_examples(self, label_images):
"""Generate example for each image in the dict."""
for label, image_paths in label_images.items():
for image_path in image_paths:
yield {
"image": image_path,
"label": label,
} | python | def _generate_examples(self, label_images):
"""Generate example for each image in the dict."""
for label, image_paths in label_images.items():
for image_path in image_paths:
yield {
"image": image_path,
"label": label,
} | [
"def",
"_generate_examples",
"(",
"self",
",",
"label_images",
")",
":",
"for",
"label",
",",
"image_paths",
"in",
"label_images",
".",
"items",
"(",
")",
":",
"for",
"image_path",
"in",
"image_paths",
":",
"yield",
"{",
"\"image\"",
":",
"image_path",
",",
... | Generate example for each image in the dict. | [
"Generate",
"example",
"for",
"each",
"image",
"in",
"the",
"dict",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/image_folder.py#L156-L164 |
26,263 | tensorflow/datasets | tensorflow_datasets/scripts/create_new_dataset.py | create_dataset_file | def create_dataset_file(root_dir, data):
"""Create a new dataset from a template."""
file_path = os.path.join(root_dir, '{dataset_type}', '{dataset_name}.py')
context = (
_HEADER + _DATASET_DEFAULT_IMPORTS + _CITATION
+ _DESCRIPTION + _DATASET_DEFAULTS
)
with gfile.GFile(file_path.format(**data),... | python | def create_dataset_file(root_dir, data):
"""Create a new dataset from a template."""
file_path = os.path.join(root_dir, '{dataset_type}', '{dataset_name}.py')
context = (
_HEADER + _DATASET_DEFAULT_IMPORTS + _CITATION
+ _DESCRIPTION + _DATASET_DEFAULTS
)
with gfile.GFile(file_path.format(**data),... | [
"def",
"create_dataset_file",
"(",
"root_dir",
",",
"data",
")",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root_dir",
",",
"'{dataset_type}'",
",",
"'{dataset_name}.py'",
")",
"context",
"=",
"(",
"_HEADER",
"+",
"_DATASET_DEFAULT_IMPORTS",
... | Create a new dataset from a template. | [
"Create",
"a",
"new",
"dataset",
"from",
"a",
"template",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/scripts/create_new_dataset.py#L155-L164 |
26,264 | tensorflow/datasets | tensorflow_datasets/image/imagenet2012_corrupted.py | Imagenet2012Corrupted._split_generators | def _split_generators(self, dl_manager):
"""Return the validation split of ImageNet2012.
Args:
dl_manager: download manager object.
Returns:
validation split.
"""
splits = super(Imagenet2012Corrupted, self)._split_generators(dl_manager)
validation = splits[1]
return [validation... | python | def _split_generators(self, dl_manager):
"""Return the validation split of ImageNet2012.
Args:
dl_manager: download manager object.
Returns:
validation split.
"""
splits = super(Imagenet2012Corrupted, self)._split_generators(dl_manager)
validation = splits[1]
return [validation... | [
"def",
"_split_generators",
"(",
"self",
",",
"dl_manager",
")",
":",
"splits",
"=",
"super",
"(",
"Imagenet2012Corrupted",
",",
"self",
")",
".",
"_split_generators",
"(",
"dl_manager",
")",
"validation",
"=",
"splits",
"[",
"1",
"]",
"return",
"[",
"valida... | Return the validation split of ImageNet2012.
Args:
dl_manager: download manager object.
Returns:
validation split. | [
"Return",
"the",
"validation",
"split",
"of",
"ImageNet2012",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/imagenet2012_corrupted.py#L134-L145 |
26,265 | tensorflow/datasets | tensorflow_datasets/image/imagenet2012_corrupted.py | Imagenet2012Corrupted._generate_examples_validation | def _generate_examples_validation(self, archive, labels):
"""Generate corrupted imagenet validation data.
Apply corruptions to the raw images according to self.corruption_type.
Args:
archive: an iterator for the raw dataset.
labels: a dictionary that maps the file names to imagenet labels.
... | python | def _generate_examples_validation(self, archive, labels):
"""Generate corrupted imagenet validation data.
Apply corruptions to the raw images according to self.corruption_type.
Args:
archive: an iterator for the raw dataset.
labels: a dictionary that maps the file names to imagenet labels.
... | [
"def",
"_generate_examples_validation",
"(",
"self",
",",
"archive",
",",
"labels",
")",
":",
"# Get the current random seeds.",
"numpy_st0",
"=",
"np",
".",
"random",
".",
"get_state",
"(",
")",
"# Set new random seeds.",
"np",
".",
"random",
".",
"seed",
"(",
... | Generate corrupted imagenet validation data.
Apply corruptions to the raw images according to self.corruption_type.
Args:
archive: an iterator for the raw dataset.
labels: a dictionary that maps the file names to imagenet labels.
Yields:
dictionary with the file name, an image file obje... | [
"Generate",
"corrupted",
"imagenet",
"validation",
"data",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/imagenet2012_corrupted.py#L147-L175 |
26,266 | tensorflow/datasets | tensorflow_datasets/image/imagenet2012_corrupted.py | Imagenet2012Corrupted._get_corrupted_example | def _get_corrupted_example(self, x):
"""Return corrupted images.
Args:
x: numpy array, uncorrupted image.
Returns:
numpy array, corrupted images.
"""
corruption_type = self.builder_config.corruption_type
severity = self.builder_config.severity
return {
'gaussian_noise'... | python | def _get_corrupted_example(self, x):
"""Return corrupted images.
Args:
x: numpy array, uncorrupted image.
Returns:
numpy array, corrupted images.
"""
corruption_type = self.builder_config.corruption_type
severity = self.builder_config.severity
return {
'gaussian_noise'... | [
"def",
"_get_corrupted_example",
"(",
"self",
",",
"x",
")",
":",
"corruption_type",
"=",
"self",
".",
"builder_config",
".",
"corruption_type",
"severity",
"=",
"self",
".",
"builder_config",
".",
"severity",
"return",
"{",
"'gaussian_noise'",
":",
"corruptions",... | Return corrupted images.
Args:
x: numpy array, uncorrupted image.
Returns:
numpy array, corrupted images. | [
"Return",
"corrupted",
"images",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/imagenet2012_corrupted.py#L177-L202 |
26,267 | tensorflow/datasets | tensorflow_datasets/core/utils/tf_utils.py | assert_shape_match | def assert_shape_match(shape1, shape2):
"""Ensure the shape1 match the pattern given by shape2.
Ex:
assert_shape_match((64, 64, 3), (None, None, 3))
Args:
shape1 (tuple): Static shape
shape2 (tuple): Dynamic shape (can contain None)
"""
shape1 = tf.TensorShape(shape1)
shape2 = tf.TensorShape(s... | python | def assert_shape_match(shape1, shape2):
"""Ensure the shape1 match the pattern given by shape2.
Ex:
assert_shape_match((64, 64, 3), (None, None, 3))
Args:
shape1 (tuple): Static shape
shape2 (tuple): Dynamic shape (can contain None)
"""
shape1 = tf.TensorShape(shape1)
shape2 = tf.TensorShape(s... | [
"def",
"assert_shape_match",
"(",
"shape1",
",",
"shape2",
")",
":",
"shape1",
"=",
"tf",
".",
"TensorShape",
"(",
"shape1",
")",
"shape2",
"=",
"tf",
".",
"TensorShape",
"(",
"shape2",
")",
"if",
"shape1",
".",
"ndims",
"is",
"None",
"or",
"shape2",
"... | Ensure the shape1 match the pattern given by shape2.
Ex:
assert_shape_match((64, 64, 3), (None, None, 3))
Args:
shape1 (tuple): Static shape
shape2 (tuple): Dynamic shape (can contain None) | [
"Ensure",
"the",
"shape1",
"match",
"the",
"pattern",
"given",
"by",
"shape2",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/tf_utils.py#L132-L148 |
26,268 | tensorflow/datasets | tensorflow_datasets/core/utils/tf_utils.py | raw_nogpu_session | def raw_nogpu_session(graph=None):
"""tf.Session, hiding GPUs."""
config = tf.compat.v1.ConfigProto(device_count={'GPU': 0})
return tf.compat.v1.Session(config=config, graph=graph) | python | def raw_nogpu_session(graph=None):
"""tf.Session, hiding GPUs."""
config = tf.compat.v1.ConfigProto(device_count={'GPU': 0})
return tf.compat.v1.Session(config=config, graph=graph) | [
"def",
"raw_nogpu_session",
"(",
"graph",
"=",
"None",
")",
":",
"config",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"ConfigProto",
"(",
"device_count",
"=",
"{",
"'GPU'",
":",
"0",
"}",
")",
"return",
"tf",
".",
"compat",
".",
"v1",
".",
"Session",
... | tf.Session, hiding GPUs. | [
"tf",
".",
"Session",
"hiding",
"GPUs",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/tf_utils.py#L161-L164 |
26,269 | tensorflow/datasets | tensorflow_datasets/core/utils/tf_utils.py | TFGraphRunner.run | def run(self, fct, input_):
"""Execute the given TensorFlow function."""
# TF 2.0
if tf.executing_eagerly():
return fct(input_).numpy()
# TF 1.0
else:
# Should compile the function if this is the first time encountered
if not isinstance(input_, np.ndarray):
input_ = np.arra... | python | def run(self, fct, input_):
"""Execute the given TensorFlow function."""
# TF 2.0
if tf.executing_eagerly():
return fct(input_).numpy()
# TF 1.0
else:
# Should compile the function if this is the first time encountered
if not isinstance(input_, np.ndarray):
input_ = np.arra... | [
"def",
"run",
"(",
"self",
",",
"fct",
",",
"input_",
")",
":",
"# TF 2.0",
"if",
"tf",
".",
"executing_eagerly",
"(",
")",
":",
"return",
"fct",
"(",
"input_",
")",
".",
"numpy",
"(",
")",
"# TF 1.0",
"else",
":",
"# Should compile the function if this is... | Execute the given TensorFlow function. | [
"Execute",
"the",
"given",
"TensorFlow",
"function",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/tf_utils.py#L70-L92 |
26,270 | tensorflow/datasets | tensorflow_datasets/core/utils/tf_utils.py | TFGraphRunner._build_graph_run | def _build_graph_run(self, run_args):
"""Create a new graph for the given args."""
# Could try to use tfe.py_func(fct) but this would require knowing
# information about the signature of the function.
# Create a new graph:
with tf.Graph().as_default() as g:
# Create placeholder
input_ =... | python | def _build_graph_run(self, run_args):
"""Create a new graph for the given args."""
# Could try to use tfe.py_func(fct) but this would require knowing
# information about the signature of the function.
# Create a new graph:
with tf.Graph().as_default() as g:
# Create placeholder
input_ =... | [
"def",
"_build_graph_run",
"(",
"self",
",",
"run_args",
")",
":",
"# Could try to use tfe.py_func(fct) but this would require knowing",
"# information about the signature of the function.",
"# Create a new graph:",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
... | Create a new graph for the given args. | [
"Create",
"a",
"new",
"graph",
"for",
"the",
"given",
"args",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/utils/tf_utils.py#L94-L111 |
26,271 | tensorflow/datasets | tensorflow_datasets/core/features/video_feature.py | Video.encode_example | def encode_example(self, video_or_path_or_fobj):
"""Converts the given image into a dict convertible to tf example."""
if isinstance(video_or_path_or_fobj, six.string_types):
if not os.path.isfile(video_or_path_or_fobj):
_, video_temp_path = tempfile.mkstemp()
try:
tf.gfile.Copy(... | python | def encode_example(self, video_or_path_or_fobj):
"""Converts the given image into a dict convertible to tf example."""
if isinstance(video_or_path_or_fobj, six.string_types):
if not os.path.isfile(video_or_path_or_fobj):
_, video_temp_path = tempfile.mkstemp()
try:
tf.gfile.Copy(... | [
"def",
"encode_example",
"(",
"self",
",",
"video_or_path_or_fobj",
")",
":",
"if",
"isinstance",
"(",
"video_or_path_or_fobj",
",",
"six",
".",
"string_types",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"video_or_path_or_fobj",
")",
":",
... | Converts the given image into a dict convertible to tf example. | [
"Converts",
"the",
"given",
"image",
"into",
"a",
"dict",
"convertible",
"to",
"tf",
"example",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/video_feature.py#L148-L164 |
26,272 | tensorflow/datasets | tensorflow_datasets/image/rock_paper_scissors.py | RockPaperScissors._generate_examples | def _generate_examples(self, archive):
"""Generate rock, paper or scissors images and labels given the directory path.
Args:
archive: object that iterates over the zip.
Yields:
The image path and its corresponding label.
"""
for fname, fobj in archive:
res = _NAME_RE.match(fname... | python | def _generate_examples(self, archive):
"""Generate rock, paper or scissors images and labels given the directory path.
Args:
archive: object that iterates over the zip.
Yields:
The image path and its corresponding label.
"""
for fname, fobj in archive:
res = _NAME_RE.match(fname... | [
"def",
"_generate_examples",
"(",
"self",
",",
"archive",
")",
":",
"for",
"fname",
",",
"fobj",
"in",
"archive",
":",
"res",
"=",
"_NAME_RE",
".",
"match",
"(",
"fname",
")",
"if",
"not",
"res",
":",
"# if anything other than .png; skip",
"continue",
"label... | Generate rock, paper or scissors images and labels given the directory path.
Args:
archive: object that iterates over the zip.
Yields:
The image path and its corresponding label. | [
"Generate",
"rock",
"paper",
"or",
"scissors",
"images",
"and",
"labels",
"given",
"the",
"directory",
"path",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/rock_paper_scissors.py#L82-L100 |
26,273 | tensorflow/datasets | tensorflow_datasets/structured/titanic.py | Titanic._generate_examples | def _generate_examples(self, file_path):
"""Generate features and target given the directory path.
Args:
file_path: path where the csv file is stored
Yields:
The features and the target
"""
with tf.io.gfile.GFile(file_path) as f:
raw_data = csv.DictReader(f)
for row in raw... | python | def _generate_examples(self, file_path):
"""Generate features and target given the directory path.
Args:
file_path: path where the csv file is stored
Yields:
The features and the target
"""
with tf.io.gfile.GFile(file_path) as f:
raw_data = csv.DictReader(f)
for row in raw... | [
"def",
"_generate_examples",
"(",
"self",
",",
"file_path",
")",
":",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"file_path",
")",
"as",
"f",
":",
"raw_data",
"=",
"csv",
".",
"DictReader",
"(",
"f",
")",
"for",
"row",
"in",
"raw_data"... | Generate features and target given the directory path.
Args:
file_path: path where the csv file is stored
Yields:
The features and the target | [
"Generate",
"features",
"and",
"target",
"given",
"the",
"directory",
"path",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/structured/titanic.py#L130-L150 |
26,274 | tensorflow/datasets | tensorflow_datasets/core/features/text/text_encoder.py | pad_decr | def pad_decr(ids):
"""Strip ID 0 and decrement ids by 1."""
if len(ids) < 1:
return list(ids)
if not any(ids):
return [] # all padding.
idx = -1
while not ids[idx]:
idx -= 1
if idx == -1:
ids = ids
else:
ids = ids[:idx + 1]
return [i - 1 for i in ids] | python | def pad_decr(ids):
"""Strip ID 0 and decrement ids by 1."""
if len(ids) < 1:
return list(ids)
if not any(ids):
return [] # all padding.
idx = -1
while not ids[idx]:
idx -= 1
if idx == -1:
ids = ids
else:
ids = ids[:idx + 1]
return [i - 1 for i in ids] | [
"def",
"pad_decr",
"(",
"ids",
")",
":",
"if",
"len",
"(",
"ids",
")",
"<",
"1",
":",
"return",
"list",
"(",
"ids",
")",
"if",
"not",
"any",
"(",
"ids",
")",
":",
"return",
"[",
"]",
"# all padding.",
"idx",
"=",
"-",
"1",
"while",
"not",
"ids"... | Strip ID 0 and decrement ids by 1. | [
"Strip",
"ID",
"0",
"and",
"decrement",
"ids",
"by",
"1",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text/text_encoder.py#L426-L439 |
26,275 | tensorflow/datasets | tensorflow_datasets/core/features/text/text_encoder.py | _prepare_reserved_tokens | def _prepare_reserved_tokens(reserved_tokens):
"""Prepare reserved tokens and a regex for splitting them out of strings."""
reserved_tokens = [tf.compat.as_text(tok) for tok in reserved_tokens or []]
dups = _find_duplicates(reserved_tokens)
if dups:
raise ValueError("Duplicates found in tokens: %s" % dups)
... | python | def _prepare_reserved_tokens(reserved_tokens):
"""Prepare reserved tokens and a regex for splitting them out of strings."""
reserved_tokens = [tf.compat.as_text(tok) for tok in reserved_tokens or []]
dups = _find_duplicates(reserved_tokens)
if dups:
raise ValueError("Duplicates found in tokens: %s" % dups)
... | [
"def",
"_prepare_reserved_tokens",
"(",
"reserved_tokens",
")",
":",
"reserved_tokens",
"=",
"[",
"tf",
".",
"compat",
".",
"as_text",
"(",
"tok",
")",
"for",
"tok",
"in",
"reserved_tokens",
"or",
"[",
"]",
"]",
"dups",
"=",
"_find_duplicates",
"(",
"reserve... | Prepare reserved tokens and a regex for splitting them out of strings. | [
"Prepare",
"reserved",
"tokens",
"and",
"a",
"regex",
"for",
"splitting",
"them",
"out",
"of",
"strings",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text/text_encoder.py#L447-L454 |
26,276 | tensorflow/datasets | tensorflow_datasets/core/features/text/text_encoder.py | _make_reserved_tokens_re | def _make_reserved_tokens_re(reserved_tokens):
"""Constructs compiled regex to parse out reserved tokens."""
if not reserved_tokens:
return None
escaped_tokens = [_re_escape(rt) for rt in reserved_tokens]
pattern = "(%s)" % "|".join(escaped_tokens)
reserved_tokens_re = _re_compile(pattern)
return reserv... | python | def _make_reserved_tokens_re(reserved_tokens):
"""Constructs compiled regex to parse out reserved tokens."""
if not reserved_tokens:
return None
escaped_tokens = [_re_escape(rt) for rt in reserved_tokens]
pattern = "(%s)" % "|".join(escaped_tokens)
reserved_tokens_re = _re_compile(pattern)
return reserv... | [
"def",
"_make_reserved_tokens_re",
"(",
"reserved_tokens",
")",
":",
"if",
"not",
"reserved_tokens",
":",
"return",
"None",
"escaped_tokens",
"=",
"[",
"_re_escape",
"(",
"rt",
")",
"for",
"rt",
"in",
"reserved_tokens",
"]",
"pattern",
"=",
"\"(%s)\"",
"%",
"\... | Constructs compiled regex to parse out reserved tokens. | [
"Constructs",
"compiled",
"regex",
"to",
"parse",
"out",
"reserved",
"tokens",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text/text_encoder.py#L463-L470 |
26,277 | tensorflow/datasets | tensorflow_datasets/core/features/text/text_encoder.py | write_lines_to_file | def write_lines_to_file(cls_name, filename, lines, metadata_dict):
"""Writes lines to file prepended by header and metadata."""
metadata_dict = metadata_dict or {}
header_line = "%s%s" % (_HEADER_PREFIX, cls_name)
metadata_line = "%s%s" % (_METADATA_PREFIX,
json.dumps(metadata_dict, ... | python | def write_lines_to_file(cls_name, filename, lines, metadata_dict):
"""Writes lines to file prepended by header and metadata."""
metadata_dict = metadata_dict or {}
header_line = "%s%s" % (_HEADER_PREFIX, cls_name)
metadata_line = "%s%s" % (_METADATA_PREFIX,
json.dumps(metadata_dict, ... | [
"def",
"write_lines_to_file",
"(",
"cls_name",
",",
"filename",
",",
"lines",
",",
"metadata_dict",
")",
":",
"metadata_dict",
"=",
"metadata_dict",
"or",
"{",
"}",
"header_line",
"=",
"\"%s%s\"",
"%",
"(",
"_HEADER_PREFIX",
",",
"cls_name",
")",
"metadata_line"... | Writes lines to file prepended by header and metadata. | [
"Writes",
"lines",
"to",
"file",
"prepended",
"by",
"header",
"and",
"metadata",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text/text_encoder.py#L492-L504 |
26,278 | tensorflow/datasets | tensorflow_datasets/core/features/text/text_encoder.py | read_lines_from_file | def read_lines_from_file(cls_name, filename):
"""Read lines from file, parsing out header and metadata."""
with tf.io.gfile.GFile(filename, "rb") as f:
lines = [tf.compat.as_text(line)[:-1] for line in f]
header_line = "%s%s" % (_HEADER_PREFIX, cls_name)
if lines[0] != header_line:
raise ValueError("Fil... | python | def read_lines_from_file(cls_name, filename):
"""Read lines from file, parsing out header and metadata."""
with tf.io.gfile.GFile(filename, "rb") as f:
lines = [tf.compat.as_text(line)[:-1] for line in f]
header_line = "%s%s" % (_HEADER_PREFIX, cls_name)
if lines[0] != header_line:
raise ValueError("Fil... | [
"def",
"read_lines_from_file",
"(",
"cls_name",
",",
"filename",
")",
":",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"f",
":",
"lines",
"=",
"[",
"tf",
".",
"compat",
".",
"as_text",
"(",
"line",
... | Read lines from file, parsing out header and metadata. | [
"Read",
"lines",
"from",
"file",
"parsing",
"out",
"header",
"and",
"metadata",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text/text_encoder.py#L507-L517 |
26,279 | tensorflow/datasets | tensorflow_datasets/core/features/text/text_encoder.py | Tokenizer.tokenize | def tokenize(self, s):
"""Splits a string into tokens."""
s = tf.compat.as_text(s)
if self.reserved_tokens:
# First split out the reserved tokens
substrs = self._reserved_tokens_re.split(s)
else:
substrs = [s]
toks = []
for substr in substrs:
if substr in self.reserved_... | python | def tokenize(self, s):
"""Splits a string into tokens."""
s = tf.compat.as_text(s)
if self.reserved_tokens:
# First split out the reserved tokens
substrs = self._reserved_tokens_re.split(s)
else:
substrs = [s]
toks = []
for substr in substrs:
if substr in self.reserved_... | [
"def",
"tokenize",
"(",
"self",
",",
"s",
")",
":",
"s",
"=",
"tf",
".",
"compat",
".",
"as_text",
"(",
"s",
")",
"if",
"self",
".",
"reserved_tokens",
":",
"# First split out the reserved tokens",
"substrs",
"=",
"self",
".",
"_reserved_tokens_re",
".",
"... | Splits a string into tokens. | [
"Splits",
"a",
"string",
"into",
"tokens",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text/text_encoder.py#L378-L397 |
26,280 | tensorflow/datasets | tensorflow_datasets/core/splits.py | get_shard_id2num_examples | def get_shard_id2num_examples(num_shards, total_num_examples):
"""Return the mapping shard_id=>num_examples, assuming round-robin."""
# TODO(b/130353071): This has the strong assumption that the shards have
# been written in a round-robin fashion. This assumption does not hold, for
# instance, with Beam generat... | python | def get_shard_id2num_examples(num_shards, total_num_examples):
"""Return the mapping shard_id=>num_examples, assuming round-robin."""
# TODO(b/130353071): This has the strong assumption that the shards have
# been written in a round-robin fashion. This assumption does not hold, for
# instance, with Beam generat... | [
"def",
"get_shard_id2num_examples",
"(",
"num_shards",
",",
"total_num_examples",
")",
":",
"# TODO(b/130353071): This has the strong assumption that the shards have",
"# been written in a round-robin fashion. This assumption does not hold, for",
"# instance, with Beam generation. The mapping sh... | Return the mapping shard_id=>num_examples, assuming round-robin. | [
"Return",
"the",
"mapping",
"shard_id",
"=",
">",
"num_examples",
"assuming",
"round",
"-",
"robin",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/splits.py#L489-L502 |
26,281 | tensorflow/datasets | tensorflow_datasets/core/splits.py | compute_mask_offsets | def compute_mask_offsets(shard_id2num_examples):
"""Return the list of offsets associated with each shards.
Args:
shard_id2num_examples: `list[int]`, mapping shard_id=>num_examples
Returns:
mask_offsets: `list[int]`, offset to skip for each of the shard
"""
total_num_examples = sum(shard_id2num_exam... | python | def compute_mask_offsets(shard_id2num_examples):
"""Return the list of offsets associated with each shards.
Args:
shard_id2num_examples: `list[int]`, mapping shard_id=>num_examples
Returns:
mask_offsets: `list[int]`, offset to skip for each of the shard
"""
total_num_examples = sum(shard_id2num_exam... | [
"def",
"compute_mask_offsets",
"(",
"shard_id2num_examples",
")",
":",
"total_num_examples",
"=",
"sum",
"(",
"shard_id2num_examples",
")",
"mask_offsets",
"=",
"[",
"]",
"total_num_examples",
"=",
"0",
"for",
"num_examples_in_shard",
"in",
"shard_id2num_examples",
":",... | Return the list of offsets associated with each shards.
Args:
shard_id2num_examples: `list[int]`, mapping shard_id=>num_examples
Returns:
mask_offsets: `list[int]`, offset to skip for each of the shard | [
"Return",
"the",
"list",
"of",
"offsets",
"associated",
"with",
"each",
"shards",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/splits.py#L505-L524 |
26,282 | tensorflow/datasets | tensorflow_datasets/core/splits.py | check_splits_equals | def check_splits_equals(splits1, splits2):
"""Check that the two split dicts have the same names and num_shards."""
if set(splits1) ^ set(splits2): # Name intersection should be null
return False
for _, (split1, split2) in utils.zip_dict(splits1, splits2):
if split1.num_shards != split2.num_shards:
... | python | def check_splits_equals(splits1, splits2):
"""Check that the two split dicts have the same names and num_shards."""
if set(splits1) ^ set(splits2): # Name intersection should be null
return False
for _, (split1, split2) in utils.zip_dict(splits1, splits2):
if split1.num_shards != split2.num_shards:
... | [
"def",
"check_splits_equals",
"(",
"splits1",
",",
"splits2",
")",
":",
"if",
"set",
"(",
"splits1",
")",
"^",
"set",
"(",
"splits2",
")",
":",
"# Name intersection should be null",
"return",
"False",
"for",
"_",
",",
"(",
"split1",
",",
"split2",
")",
"in... | Check that the two split dicts have the same names and num_shards. | [
"Check",
"that",
"the",
"two",
"split",
"dicts",
"have",
"the",
"same",
"names",
"and",
"num_shards",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/splits.py#L573-L580 |
26,283 | tensorflow/datasets | tensorflow_datasets/core/splits.py | SplitDict.add | def add(self, split_info):
"""Add the split info."""
if split_info.name in self:
raise ValueError("Split {} already present".format(split_info.name))
# TODO(epot): Make sure this works with Named splits correctly.
super(SplitDict, self).__setitem__(split_info.name, split_info) | python | def add(self, split_info):
"""Add the split info."""
if split_info.name in self:
raise ValueError("Split {} already present".format(split_info.name))
# TODO(epot): Make sure this works with Named splits correctly.
super(SplitDict, self).__setitem__(split_info.name, split_info) | [
"def",
"add",
"(",
"self",
",",
"split_info",
")",
":",
"if",
"split_info",
".",
"name",
"in",
"self",
":",
"raise",
"ValueError",
"(",
"\"Split {} already present\"",
".",
"format",
"(",
"split_info",
".",
"name",
")",
")",
"# TODO(epot): Make sure this works w... | Add the split info. | [
"Add",
"the",
"split",
"info",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/splits.py#L542-L547 |
26,284 | tensorflow/datasets | tensorflow_datasets/core/splits.py | SplitDict.from_proto | def from_proto(cls, repeated_split_infos):
"""Returns a new SplitDict initialized from the `repeated_split_infos`."""
split_dict = cls()
for split_info_proto in repeated_split_infos:
split_info = SplitInfo()
split_info.CopyFrom(split_info_proto)
split_dict.add(split_info)
return split_... | python | def from_proto(cls, repeated_split_infos):
"""Returns a new SplitDict initialized from the `repeated_split_infos`."""
split_dict = cls()
for split_info_proto in repeated_split_infos:
split_info = SplitInfo()
split_info.CopyFrom(split_info_proto)
split_dict.add(split_info)
return split_... | [
"def",
"from_proto",
"(",
"cls",
",",
"repeated_split_infos",
")",
":",
"split_dict",
"=",
"cls",
"(",
")",
"for",
"split_info_proto",
"in",
"repeated_split_infos",
":",
"split_info",
"=",
"SplitInfo",
"(",
")",
"split_info",
".",
"CopyFrom",
"(",
"split_info_pr... | Returns a new SplitDict initialized from the `repeated_split_infos`. | [
"Returns",
"a",
"new",
"SplitDict",
"initialized",
"from",
"the",
"repeated_split_infos",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/splits.py#L550-L557 |
26,285 | tensorflow/datasets | tensorflow_datasets/core/splits.py | SplitDict.to_proto | def to_proto(self):
"""Returns a list of SplitInfo protos that we have."""
# Return the proto.SplitInfo, sorted by name
return sorted((s.get_proto() for s in self.values()), key=lambda s: s.name) | python | def to_proto(self):
"""Returns a list of SplitInfo protos that we have."""
# Return the proto.SplitInfo, sorted by name
return sorted((s.get_proto() for s in self.values()), key=lambda s: s.name) | [
"def",
"to_proto",
"(",
"self",
")",
":",
"# Return the proto.SplitInfo, sorted by name",
"return",
"sorted",
"(",
"(",
"s",
".",
"get_proto",
"(",
")",
"for",
"s",
"in",
"self",
".",
"values",
"(",
")",
")",
",",
"key",
"=",
"lambda",
"s",
":",
"s",
"... | Returns a list of SplitInfo protos that we have. | [
"Returns",
"a",
"list",
"of",
"SplitInfo",
"protos",
"that",
"we",
"have",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/splits.py#L559-L562 |
26,286 | tensorflow/datasets | tensorflow_datasets/core/download/util.py | build_synchronize_decorator | def build_synchronize_decorator():
"""Returns a decorator which prevents concurrent calls to functions.
Usage:
synchronized = build_synchronize_decorator()
@synchronized
def read_value():
...
@synchronized
def write_value(x):
...
Returns:
make_threadsafe (fct): The decorato... | python | def build_synchronize_decorator():
"""Returns a decorator which prevents concurrent calls to functions.
Usage:
synchronized = build_synchronize_decorator()
@synchronized
def read_value():
...
@synchronized
def write_value(x):
...
Returns:
make_threadsafe (fct): The decorato... | [
"def",
"build_synchronize_decorator",
"(",
")",
":",
"lock",
"=",
"threading",
".",
"Lock",
"(",
")",
"def",
"lock_decorator",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"lock_decorated",
"(",
"*",
"args",
",",
"*",
"*"... | Returns a decorator which prevents concurrent calls to functions.
Usage:
synchronized = build_synchronize_decorator()
@synchronized
def read_value():
...
@synchronized
def write_value(x):
...
Returns:
make_threadsafe (fct): The decorator which lock all functions to which it
... | [
"Returns",
"a",
"decorator",
"which",
"prevents",
"concurrent",
"calls",
"to",
"functions",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/util.py#L72-L101 |
26,287 | tensorflow/datasets | tensorflow_datasets/core/download/util.py | get_file_name | def get_file_name(url):
"""Returns file name of file at given url."""
return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name' | python | def get_file_name(url):
"""Returns file name of file at given url."""
return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name' | [
"def",
"get_file_name",
"(",
"url",
")",
":",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
".",
"path",
")",
"or",
"'unknown_name'"
] | Returns file name of file at given url. | [
"Returns",
"file",
"name",
"of",
"file",
"at",
"given",
"url",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/util.py#L104-L106 |
26,288 | tensorflow/datasets | tensorflow_datasets/audio/librispeech.py | _make_builder_configs | def _make_builder_configs():
"""Make built-in Librispeech BuilderConfigs.
Uses 4 text encodings (plain text, bytes, subwords with 8k vocab, subwords
with 32k vocab) crossed with the data subsets (clean100, clean360, all).
Returns:
`list<tfds.audio.LibrispeechConfig>`
"""
text_encoder_configs = [
... | python | def _make_builder_configs():
"""Make built-in Librispeech BuilderConfigs.
Uses 4 text encodings (plain text, bytes, subwords with 8k vocab, subwords
with 32k vocab) crossed with the data subsets (clean100, clean360, all).
Returns:
`list<tfds.audio.LibrispeechConfig>`
"""
text_encoder_configs = [
... | [
"def",
"_make_builder_configs",
"(",
")",
":",
"text_encoder_configs",
"=",
"[",
"None",
",",
"tfds",
".",
"features",
".",
"text",
".",
"TextEncoderConfig",
"(",
"name",
"=",
"\"bytes\"",
",",
"encoder",
"=",
"tfds",
".",
"features",
".",
"text",
".",
"By... | Make built-in Librispeech BuilderConfigs.
Uses 4 text encodings (plain text, bytes, subwords with 8k vocab, subwords
with 32k vocab) crossed with the data subsets (clean100, clean360, all).
Returns:
`list<tfds.audio.LibrispeechConfig>` | [
"Make",
"built",
"-",
"in",
"Librispeech",
"BuilderConfigs",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/audio/librispeech.py#L130-L159 |
26,289 | tensorflow/datasets | tensorflow_datasets/audio/librispeech.py | _walk_librispeech_dir | def _walk_librispeech_dir(directory):
"""Walk a Librispeech directory and yield examples."""
directory = os.path.join(directory, "LibriSpeech")
for path, _, files in tf.io.gfile.walk(directory):
if not files:
continue
transcript_file = [f for f in files if f.endswith(".txt")]
if not transcript_... | python | def _walk_librispeech_dir(directory):
"""Walk a Librispeech directory and yield examples."""
directory = os.path.join(directory, "LibriSpeech")
for path, _, files in tf.io.gfile.walk(directory):
if not files:
continue
transcript_file = [f for f in files if f.endswith(".txt")]
if not transcript_... | [
"def",
"_walk_librispeech_dir",
"(",
"directory",
")",
":",
"directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"\"LibriSpeech\"",
")",
"for",
"path",
",",
"_",
",",
"files",
"in",
"tf",
".",
"io",
".",
"gfile",
".",
"walk",
"(",
... | Walk a Librispeech directory and yield examples. | [
"Walk",
"a",
"Librispeech",
"directory",
"and",
"yield",
"examples",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/audio/librispeech.py#L237-L265 |
26,290 | tensorflow/datasets | tensorflow_datasets/audio/librispeech.py | LibrispeechConfig.download_urls | def download_urls(self):
"""Returns download urls for this config."""
urls = {
tfds.Split.TRAIN: ["train_clean100"],
tfds.Split.VALIDATION: ["dev_clean"],
tfds.Split.TEST: ["test_clean"],
}
if self.data in ["all", "clean360"]:
urls[tfds.Split.TRAIN].append("train_clean360")... | python | def download_urls(self):
"""Returns download urls for this config."""
urls = {
tfds.Split.TRAIN: ["train_clean100"],
tfds.Split.VALIDATION: ["dev_clean"],
tfds.Split.TEST: ["test_clean"],
}
if self.data in ["all", "clean360"]:
urls[tfds.Split.TRAIN].append("train_clean360")... | [
"def",
"download_urls",
"(",
"self",
")",
":",
"urls",
"=",
"{",
"tfds",
".",
"Split",
".",
"TRAIN",
":",
"[",
"\"train_clean100\"",
"]",
",",
"tfds",
".",
"Split",
".",
"VALIDATION",
":",
"[",
"\"dev_clean\"",
"]",
",",
"tfds",
".",
"Split",
".",
"T... | Returns download urls for this config. | [
"Returns",
"download",
"urls",
"for",
"this",
"config",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/audio/librispeech.py#L109-L127 |
26,291 | tensorflow/datasets | tensorflow_datasets/core/features/class_label_feature.py | ClassLabel.str2int | def str2int(self, str_value):
"""Conversion class name string => integer."""
str_value = tf.compat.as_text(str_value)
if self._str2int:
return self._str2int[str_value]
# No names provided, try to integerize
failed_parse = False
try:
int_value = int(str_value)
except ValueError:
... | python | def str2int(self, str_value):
"""Conversion class name string => integer."""
str_value = tf.compat.as_text(str_value)
if self._str2int:
return self._str2int[str_value]
# No names provided, try to integerize
failed_parse = False
try:
int_value = int(str_value)
except ValueError:
... | [
"def",
"str2int",
"(",
"self",
",",
"str_value",
")",
":",
"str_value",
"=",
"tf",
".",
"compat",
".",
"as_text",
"(",
"str_value",
")",
"if",
"self",
".",
"_str2int",
":",
"return",
"self",
".",
"_str2int",
"[",
"str_value",
"]",
"# No names provided, try... | Conversion class name string => integer. | [
"Conversion",
"class",
"name",
"string",
"=",
">",
"integer",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/class_label_feature.py#L99-L113 |
26,292 | tensorflow/datasets | tensorflow_datasets/core/features/class_label_feature.py | ClassLabel.int2str | def int2str(self, int_value):
"""Conversion integer => class name string."""
if self._int2str:
# Maybe should support batched np array/eager tensors, to allow things
# like
# out_ids = model(inputs)
# labels = cifar10.info.features['label'].int2str(out_ids)
return self._int2str[int... | python | def int2str(self, int_value):
"""Conversion integer => class name string."""
if self._int2str:
# Maybe should support batched np array/eager tensors, to allow things
# like
# out_ids = model(inputs)
# labels = cifar10.info.features['label'].int2str(out_ids)
return self._int2str[int... | [
"def",
"int2str",
"(",
"self",
",",
"int_value",
")",
":",
"if",
"self",
".",
"_int2str",
":",
"# Maybe should support batched np array/eager tensors, to allow things",
"# like",
"# out_ids = model(inputs)",
"# labels = cifar10.info.features['label'].int2str(out_ids)",
"return",
... | Conversion integer => class name string. | [
"Conversion",
"integer",
"=",
">",
"class",
"name",
"string",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/class_label_feature.py#L115-L127 |
26,293 | tensorflow/datasets | tensorflow_datasets/core/features/text/subword_text_encoder.py | _token_counts_from_generator | def _token_counts_from_generator(generator, max_chars, reserved_tokens):
"""Builds token counts from generator."""
reserved_tokens = list(reserved_tokens) + [_UNDERSCORE_REPLACEMENT]
tokenizer = text_encoder.Tokenizer(
alphanum_only=False, reserved_tokens=reserved_tokens)
num_chars = 0
token_counts = co... | python | def _token_counts_from_generator(generator, max_chars, reserved_tokens):
"""Builds token counts from generator."""
reserved_tokens = list(reserved_tokens) + [_UNDERSCORE_REPLACEMENT]
tokenizer = text_encoder.Tokenizer(
alphanum_only=False, reserved_tokens=reserved_tokens)
num_chars = 0
token_counts = co... | [
"def",
"_token_counts_from_generator",
"(",
"generator",
",",
"max_chars",
",",
"reserved_tokens",
")",
":",
"reserved_tokens",
"=",
"list",
"(",
"reserved_tokens",
")",
"+",
"[",
"_UNDERSCORE_REPLACEMENT",
"]",
"tokenizer",
"=",
"text_encoder",
".",
"Tokenizer",
"(... | Builds token counts from generator. | [
"Builds",
"token",
"counts",
"from",
"generator",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text/subword_text_encoder.py#L388-L407 |
26,294 | tensorflow/datasets | tensorflow_datasets/core/features/text/subword_text_encoder.py | _validate_build_arguments | def _validate_build_arguments(max_subword_length, reserved_tokens,
target_vocab_size):
"""Validate arguments for SubwordTextEncoder.build_from_corpus."""
if max_subword_length <= 0:
raise ValueError(
"max_subword_length must be > 0. Note that memory and compute for "
... | python | def _validate_build_arguments(max_subword_length, reserved_tokens,
target_vocab_size):
"""Validate arguments for SubwordTextEncoder.build_from_corpus."""
if max_subword_length <= 0:
raise ValueError(
"max_subword_length must be > 0. Note that memory and compute for "
... | [
"def",
"_validate_build_arguments",
"(",
"max_subword_length",
",",
"reserved_tokens",
",",
"target_vocab_size",
")",
":",
"if",
"max_subword_length",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"max_subword_length must be > 0. Note that memory and compute for \"",
"\"buildin... | Validate arguments for SubwordTextEncoder.build_from_corpus. | [
"Validate",
"arguments",
"for",
"SubwordTextEncoder",
".",
"build_from_corpus",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text/subword_text_encoder.py#L410-L428 |
26,295 | tensorflow/datasets | tensorflow_datasets/core/features/text/subword_text_encoder.py | _prepare_tokens_for_encode | def _prepare_tokens_for_encode(tokens):
"""Prepare tokens for encoding.
Tokens followed by a single space have "_" appended and the single space token
is dropped.
If a token is _UNDERSCORE_REPLACEMENT, it is broken up into 2 tokens.
Args:
tokens: `list<str>`, tokens to prepare.
Returns:
`list<st... | python | def _prepare_tokens_for_encode(tokens):
"""Prepare tokens for encoding.
Tokens followed by a single space have "_" appended and the single space token
is dropped.
If a token is _UNDERSCORE_REPLACEMENT, it is broken up into 2 tokens.
Args:
tokens: `list<str>`, tokens to prepare.
Returns:
`list<st... | [
"def",
"_prepare_tokens_for_encode",
"(",
"tokens",
")",
":",
"prepared_tokens",
"=",
"[",
"]",
"def",
"_prepare_token",
"(",
"t",
",",
"next_t",
")",
":",
"skip_next",
"=",
"False",
"t",
"=",
"_escape",
"(",
"t",
")",
"# If next token is a single space, add _ s... | Prepare tokens for encoding.
Tokens followed by a single space have "_" appended and the single space token
is dropped.
If a token is _UNDERSCORE_REPLACEMENT, it is broken up into 2 tokens.
Args:
tokens: `list<str>`, tokens to prepare.
Returns:
`list<str>` prepared tokens. | [
"Prepare",
"tokens",
"for",
"encoding",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text/subword_text_encoder.py#L451-L496 |
26,296 | tensorflow/datasets | tensorflow_datasets/core/features/text/subword_text_encoder.py | SubwordTextEncoder.encode | def encode(self, s):
"""Encodes text into a list of integers."""
s = tf.compat.as_text(s)
tokens = self._tokenizer.tokenize(s)
tokens = _prepare_tokens_for_encode(tokens)
ids = []
for token in tokens:
ids.extend(self._token_to_ids(token))
return text_encoder.pad_incr(ids) | python | def encode(self, s):
"""Encodes text into a list of integers."""
s = tf.compat.as_text(s)
tokens = self._tokenizer.tokenize(s)
tokens = _prepare_tokens_for_encode(tokens)
ids = []
for token in tokens:
ids.extend(self._token_to_ids(token))
return text_encoder.pad_incr(ids) | [
"def",
"encode",
"(",
"self",
",",
"s",
")",
":",
"s",
"=",
"tf",
".",
"compat",
".",
"as_text",
"(",
"s",
")",
"tokens",
"=",
"self",
".",
"_tokenizer",
".",
"tokenize",
"(",
"s",
")",
"tokens",
"=",
"_prepare_tokens_for_encode",
"(",
"tokens",
")",... | Encodes text into a list of integers. | [
"Encodes",
"text",
"into",
"a",
"list",
"of",
"integers",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text/subword_text_encoder.py#L80-L88 |
26,297 | tensorflow/datasets | tensorflow_datasets/core/features/text/subword_text_encoder.py | SubwordTextEncoder.decode | def decode(self, ids):
"""Decodes a list of integers into text."""
ids = text_encoder.pad_decr(ids)
subword_ids = ids
del ids
subwords = []
# Some ids correspond to bytes. Because unicode characters are composed of
# possibly multiple bytes, we attempt to decode contiguous lists of bytes
... | python | def decode(self, ids):
"""Decodes a list of integers into text."""
ids = text_encoder.pad_decr(ids)
subword_ids = ids
del ids
subwords = []
# Some ids correspond to bytes. Because unicode characters are composed of
# possibly multiple bytes, we attempt to decode contiguous lists of bytes
... | [
"def",
"decode",
"(",
"self",
",",
"ids",
")",
":",
"ids",
"=",
"text_encoder",
".",
"pad_decr",
"(",
"ids",
")",
"subword_ids",
"=",
"ids",
"del",
"ids",
"subwords",
"=",
"[",
"]",
"# Some ids correspond to bytes. Because unicode characters are composed of",
"# p... | Decodes a list of integers into text. | [
"Decodes",
"a",
"list",
"of",
"integers",
"into",
"text",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text/subword_text_encoder.py#L90-L126 |
26,298 | tensorflow/datasets | tensorflow_datasets/core/features/text/subword_text_encoder.py | SubwordTextEncoder._token_to_ids | def _token_to_ids(self, token):
"""Convert a single token to a list of integer ids."""
# Check cache
cache_location = hash(token) % self._cache_size
cache_key, cache_value = self._token_to_ids_cache[cache_location]
if cache_key == token:
return cache_value
subwords = self._token_to_subwor... | python | def _token_to_ids(self, token):
"""Convert a single token to a list of integer ids."""
# Check cache
cache_location = hash(token) % self._cache_size
cache_key, cache_value = self._token_to_ids_cache[cache_location]
if cache_key == token:
return cache_value
subwords = self._token_to_subwor... | [
"def",
"_token_to_ids",
"(",
"self",
",",
"token",
")",
":",
"# Check cache",
"cache_location",
"=",
"hash",
"(",
"token",
")",
"%",
"self",
".",
"_cache_size",
"cache_key",
",",
"cache_value",
"=",
"self",
".",
"_token_to_ids_cache",
"[",
"cache_location",
"]... | Convert a single token to a list of integer ids. | [
"Convert",
"a",
"single",
"token",
"to",
"a",
"list",
"of",
"integer",
"ids",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text/subword_text_encoder.py#L140-L164 |
26,299 | tensorflow/datasets | tensorflow_datasets/core/features/text/subword_text_encoder.py | SubwordTextEncoder._byte_encode | def _byte_encode(self, token):
"""Encode a single token byte-wise into integer ids."""
# Vocab ids for all bytes follow ids for the subwords
offset = len(self._subwords)
if token == "_":
return [len(self._subwords) + ord(" ")]
return [i + offset for i in list(bytearray(tf.compat.as_bytes(token... | python | def _byte_encode(self, token):
"""Encode a single token byte-wise into integer ids."""
# Vocab ids for all bytes follow ids for the subwords
offset = len(self._subwords)
if token == "_":
return [len(self._subwords) + ord(" ")]
return [i + offset for i in list(bytearray(tf.compat.as_bytes(token... | [
"def",
"_byte_encode",
"(",
"self",
",",
"token",
")",
":",
"# Vocab ids for all bytes follow ids for the subwords",
"offset",
"=",
"len",
"(",
"self",
".",
"_subwords",
")",
"if",
"token",
"==",
"\"_\"",
":",
"return",
"[",
"len",
"(",
"self",
".",
"_subwords... | Encode a single token byte-wise into integer ids. | [
"Encode",
"a",
"single",
"token",
"byte",
"-",
"wise",
"into",
"integer",
"ids",
"."
] | 46ceb0cf7b4690f38ecbbc689e4d659a903d08dc | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text/subword_text_encoder.py#L166-L172 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.