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: https://toolbox.google.com/datasetsearch
Microdata format was chosen over JSON-LD due to the fact that Markdown
rendering engines remove all <script> tags.
Args:
builder: `tfds.core.DatasetBuilder`
Returns:
HTML string with microdata
"""
# pylint: enable=line-too-long
properties = [
(lambda x: x.name, SCHEMA_ORG_NAME),
(lambda x: x.description, SCHEMA_ORG_DESC),
(lambda x: x.name, SCHEMA_ORG_URL),
(lambda x: (x.urls and x.urls[0]) or "", SCHEMA_ORG_SAMEAS)
]
info = builder.info
out_str = SCHEMA_ORG_PRE
for extractor, template in properties:
val = extractor(info)
if val:
# We are using cgi module instead of html due to Python 2 compatibility
out_str += template.format(val=cgi.escape(val, quote=True).strip())
out_str += SCHEMA_ORG_POST
return out_str | 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: https://toolbox.google.com/datasetsearch
Microdata format was chosen over JSON-LD due to the fact that Markdown
rendering engines remove all <script> tags.
Args:
builder: `tfds.core.DatasetBuilder`
Returns:
HTML string with microdata
"""
# pylint: enable=line-too-long
properties = [
(lambda x: x.name, SCHEMA_ORG_NAME),
(lambda x: x.description, SCHEMA_ORG_DESC),
(lambda x: x.name, SCHEMA_ORG_URL),
(lambda x: (x.urls and x.urls[0]) or "", SCHEMA_ORG_SAMEAS)
]
info = builder.info
out_str = SCHEMA_ORG_PRE
for extractor, template in properties:
val = extractor(info)
if val:
# We are using cgi module instead of html due to Python 2 compatibility
out_str += template.format(val=cgi.escape(val, quote=True).strip())
out_str += SCHEMA_ORG_POST
return out_str | [
"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",
".",
"description",
",",
"SCHEMA_ORG_DESC",
")",
",",
"(",
"lambda",
"x",
":",
"x",
".",
"name",
",",
"SCHEMA_ORG_URL",
")",
",",
"(",
"lambda",
"x",
":",
"(",
"x",
".",
"urls",
"and",
"x",
".",
"urls",
"[",
"0",
"]",
")",
"or",
"\"\"",
",",
"SCHEMA_ORG_SAMEAS",
")",
"]",
"info",
"=",
"builder",
".",
"info",
"out_str",
"=",
"SCHEMA_ORG_PRE",
"for",
"extractor",
",",
"template",
"in",
"properties",
":",
"val",
"=",
"extractor",
"(",
"info",
")",
"if",
"val",
":",
"# We are using cgi module instead of html due to Python 2 compatibility",
"out_str",
"+=",
"template",
".",
"format",
"(",
"val",
"=",
"cgi",
".",
"escape",
"(",
"val",
",",
"quote",
"=",
"True",
")",
".",
"strip",
"(",
")",
")",
"out_str",
"+=",
"SCHEMA_ORG_POST",
"return",
"out_str"
] | 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 chosen over JSON-LD due to the fact that Markdown
rendering engines remove all <script> tags.
Args:
builder: `tfds.core.DatasetBuilder`
Returns:
HTML string with microdata | [
"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 type of kernel
Returns:
cv2 object of the Gaussian blurring kernel.
"""
if radius <= 8:
length = np.arange(-8, 8 + 1)
ksize = (3, 3)
else:
length = np.arange(-radius, radius + 1)
ksize = (5, 5)
x_axis, y_axis = np.meshgrid(length, length)
aliased_disk = np.array((x_axis**2 + y_axis**2) <= radius**2, dtype=dtype)
aliased_disk /= np.sum(aliased_disk)
# supersample disk to antialias
return tfds.core.lazy_imports.cv2.GaussianBlur(
aliased_disk, ksize=ksize, sigmaX=alias_blur) | 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 type of kernel
Returns:
cv2 object of the Gaussian blurring kernel.
"""
if radius <= 8:
length = np.arange(-8, 8 + 1)
ksize = (3, 3)
else:
length = np.arange(-radius, radius + 1)
ksize = (5, 5)
x_axis, y_axis = np.meshgrid(length, length)
aliased_disk = np.array((x_axis**2 + y_axis**2) <= radius**2, dtype=dtype)
aliased_disk /= np.sum(aliased_disk)
# supersample disk to antialias
return tfds.core.lazy_imports.cv2.GaussianBlur(
aliased_disk, ksize=ksize, sigmaX=alias_blur) | [
"def",
"disk",
"(",
"radius",
",",
"alias_blur",
"=",
"0.1",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
":",
"if",
"radius",
"<=",
"8",
":",
"length",
"=",
"np",
".",
"arange",
"(",
"-",
"8",
",",
"8",
"+",
"1",
")",
"ksize",
"=",
"(",
"3",
",",
"3",
")",
"else",
":",
"length",
"=",
"np",
".",
"arange",
"(",
"-",
"radius",
",",
"radius",
"+",
"1",
")",
"ksize",
"=",
"(",
"5",
",",
"5",
")",
"x_axis",
",",
"y_axis",
"=",
"np",
".",
"meshgrid",
"(",
"length",
",",
"length",
")",
"aliased_disk",
"=",
"np",
".",
"array",
"(",
"(",
"x_axis",
"**",
"2",
"+",
"y_axis",
"**",
"2",
")",
"<=",
"radius",
"**",
"2",
",",
"dtype",
"=",
"dtype",
")",
"aliased_disk",
"/=",
"np",
".",
"sum",
"(",
"aliased_disk",
")",
"# supersample disk to antialias",
"return",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"cv2",
".",
"GaussianBlur",
"(",
"aliased_disk",
",",
"ksize",
"=",
"ksize",
",",
"sigmaX",
"=",
"alias_blur",
")"
] | 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 Gaussian blurring kernel. | [
"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 = img.shape[0]
ch = int(np.ceil(h / float(zoom_factor)))
top_h = (h - ch) // 2
w = img.shape[1]
cw = int(np.ceil(w / float(zoom_factor)))
top_w = (w - cw) // 2
img = tfds.core.lazy_imports.scipy.ndimage.zoom(
img[top_h:top_h + ch, top_w:top_w + cw], (zoom_factor, zoom_factor, 1),
order=1)
# trim off any extra pixels
trim_top_h = (img.shape[0] - h) // 2
trim_top_w = (img.shape[1] - w) // 2
return img[trim_top_h:trim_top_h + h, trim_top_w:trim_top_w + w] | 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 = img.shape[0]
ch = int(np.ceil(h / float(zoom_factor)))
top_h = (h - ch) // 2
w = img.shape[1]
cw = int(np.ceil(w / float(zoom_factor)))
top_w = (w - cw) // 2
img = tfds.core.lazy_imports.scipy.ndimage.zoom(
img[top_h:top_h + ch, top_w:top_w + cw], (zoom_factor, zoom_factor, 1),
order=1)
# trim off any extra pixels
trim_top_h = (img.shape[0] - h) // 2
trim_top_w = (img.shape[1] - w) // 2
return img[trim_top_h:trim_top_h + h, trim_top_w:trim_top_w + w] | [
"def",
"clipped_zoom",
"(",
"img",
",",
"zoom_factor",
")",
":",
"h",
"=",
"img",
".",
"shape",
"[",
"0",
"]",
"ch",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"h",
"/",
"float",
"(",
"zoom_factor",
")",
")",
")",
"top_h",
"=",
"(",
"h",
"-",
"ch",
")",
"//",
"2",
"w",
"=",
"img",
".",
"shape",
"[",
"1",
"]",
"cw",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"w",
"/",
"float",
"(",
"zoom_factor",
")",
")",
")",
"top_w",
"=",
"(",
"w",
"-",
"cw",
")",
"//",
"2",
"img",
"=",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"scipy",
".",
"ndimage",
".",
"zoom",
"(",
"img",
"[",
"top_h",
":",
"top_h",
"+",
"ch",
",",
"top_w",
":",
"top_w",
"+",
"cw",
"]",
",",
"(",
"zoom_factor",
",",
"zoom_factor",
",",
"1",
")",
",",
"order",
"=",
"1",
")",
"# trim off any extra pixels",
"trim_top_h",
"=",
"(",
"img",
".",
"shape",
"[",
"0",
"]",
"-",
"h",
")",
"//",
"2",
"trim_top_w",
"=",
"(",
"img",
".",
"shape",
"[",
"1",
"]",
"-",
"w",
")",
"//",
"2",
"return",
"img",
"[",
"trim_top_h",
":",
"trim_top_h",
"+",
"h",
",",
"trim_top_w",
":",
"trim_top_w",
"+",
"w",
"]"
] | 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 factor.
Returns:
numpy 2d array, side length 'mapsize', of floats in [0,255].
"""
if mapsize & (mapsize - 1) != 0:
raise ValueError('mapsize must be a power of two.')
maparray = np.empty((mapsize, mapsize), dtype=np.float_)
maparray[0, 0] = 0
stepsize = mapsize
wibble = 100
def wibbledmean(array):
return array / 4 + wibble * np.random.uniform(-wibble, wibble, array.shape)
def fillsquares():
"""For each square, calculate middle value as mean of points + wibble."""
cornerref = maparray[0:mapsize:stepsize, 0:mapsize:stepsize]
squareaccum = cornerref + np.roll(cornerref, shift=-1, axis=0)
squareaccum += np.roll(squareaccum, shift=-1, axis=1)
maparray[stepsize // 2:mapsize:stepsize, stepsize //
2:mapsize:stepsize] = wibbledmean(squareaccum)
def filldiamonds():
"""For each diamond, calculate middle value as meanof points + wibble."""
mapsize = maparray.shape[0]
drgrid = maparray[stepsize // 2:mapsize:stepsize, stepsize //
2:mapsize:stepsize]
ulgrid = maparray[0:mapsize:stepsize, 0:mapsize:stepsize]
ldrsum = drgrid + np.roll(drgrid, 1, axis=0)
lulsum = ulgrid + np.roll(ulgrid, -1, axis=1)
ltsum = ldrsum + lulsum
maparray[0:mapsize:stepsize, stepsize //
2:mapsize:stepsize] = wibbledmean(ltsum)
tdrsum = drgrid + np.roll(drgrid, 1, axis=1)
tulsum = ulgrid + np.roll(ulgrid, -1, axis=0)
ttsum = tdrsum + tulsum
maparray[stepsize //
2:mapsize:stepsize, 0:mapsize:stepsize] = wibbledmean(ttsum)
while stepsize >= 2:
fillsquares()
filldiamonds()
stepsize //= 2
wibble /= wibbledecay
maparray -= maparray.min()
return maparray / maparray.max() | 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 factor.
Returns:
numpy 2d array, side length 'mapsize', of floats in [0,255].
"""
if mapsize & (mapsize - 1) != 0:
raise ValueError('mapsize must be a power of two.')
maparray = np.empty((mapsize, mapsize), dtype=np.float_)
maparray[0, 0] = 0
stepsize = mapsize
wibble = 100
def wibbledmean(array):
return array / 4 + wibble * np.random.uniform(-wibble, wibble, array.shape)
def fillsquares():
"""For each square, calculate middle value as mean of points + wibble."""
cornerref = maparray[0:mapsize:stepsize, 0:mapsize:stepsize]
squareaccum = cornerref + np.roll(cornerref, shift=-1, axis=0)
squareaccum += np.roll(squareaccum, shift=-1, axis=1)
maparray[stepsize // 2:mapsize:stepsize, stepsize //
2:mapsize:stepsize] = wibbledmean(squareaccum)
def filldiamonds():
"""For each diamond, calculate middle value as meanof points + wibble."""
mapsize = maparray.shape[0]
drgrid = maparray[stepsize // 2:mapsize:stepsize, stepsize //
2:mapsize:stepsize]
ulgrid = maparray[0:mapsize:stepsize, 0:mapsize:stepsize]
ldrsum = drgrid + np.roll(drgrid, 1, axis=0)
lulsum = ulgrid + np.roll(ulgrid, -1, axis=1)
ltsum = ldrsum + lulsum
maparray[0:mapsize:stepsize, stepsize //
2:mapsize:stepsize] = wibbledmean(ltsum)
tdrsum = drgrid + np.roll(drgrid, 1, axis=1)
tulsum = ulgrid + np.roll(ulgrid, -1, axis=0)
ttsum = tdrsum + tulsum
maparray[stepsize //
2:mapsize:stepsize, 0:mapsize:stepsize] = wibbledmean(ttsum)
while stepsize >= 2:
fillsquares()
filldiamonds()
stepsize //= 2
wibble /= wibbledecay
maparray -= maparray.min()
return maparray / maparray.max() | [
"def",
"plasma_fractal",
"(",
"mapsize",
"=",
"512",
",",
"wibbledecay",
"=",
"3",
")",
":",
"if",
"mapsize",
"&",
"(",
"mapsize",
"-",
"1",
")",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"'mapsize must be a power of two.'",
")",
"maparray",
"=",
"np",
".",
"empty",
"(",
"(",
"mapsize",
",",
"mapsize",
")",
",",
"dtype",
"=",
"np",
".",
"float_",
")",
"maparray",
"[",
"0",
",",
"0",
"]",
"=",
"0",
"stepsize",
"=",
"mapsize",
"wibble",
"=",
"100",
"def",
"wibbledmean",
"(",
"array",
")",
":",
"return",
"array",
"/",
"4",
"+",
"wibble",
"*",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"wibble",
",",
"wibble",
",",
"array",
".",
"shape",
")",
"def",
"fillsquares",
"(",
")",
":",
"\"\"\"For each square, calculate middle value as mean of points + wibble.\"\"\"",
"cornerref",
"=",
"maparray",
"[",
"0",
":",
"mapsize",
":",
"stepsize",
",",
"0",
":",
"mapsize",
":",
"stepsize",
"]",
"squareaccum",
"=",
"cornerref",
"+",
"np",
".",
"roll",
"(",
"cornerref",
",",
"shift",
"=",
"-",
"1",
",",
"axis",
"=",
"0",
")",
"squareaccum",
"+=",
"np",
".",
"roll",
"(",
"squareaccum",
",",
"shift",
"=",
"-",
"1",
",",
"axis",
"=",
"1",
")",
"maparray",
"[",
"stepsize",
"//",
"2",
":",
"mapsize",
":",
"stepsize",
",",
"stepsize",
"//",
"2",
":",
"mapsize",
":",
"stepsize",
"]",
"=",
"wibbledmean",
"(",
"squareaccum",
")",
"def",
"filldiamonds",
"(",
")",
":",
"\"\"\"For each diamond, calculate middle value as meanof points + wibble.\"\"\"",
"mapsize",
"=",
"maparray",
".",
"shape",
"[",
"0",
"]",
"drgrid",
"=",
"maparray",
"[",
"stepsize",
"//",
"2",
":",
"mapsize",
":",
"stepsize",
",",
"stepsize",
"//",
"2",
":",
"mapsize",
":",
"stepsize",
"]",
"ulgrid",
"=",
"maparray",
"[",
"0",
":",
"mapsize",
":",
"stepsize",
",",
"0",
":",
"mapsize",
":",
"stepsize",
"]",
"ldrsum",
"=",
"drgrid",
"+",
"np",
".",
"roll",
"(",
"drgrid",
",",
"1",
",",
"axis",
"=",
"0",
")",
"lulsum",
"=",
"ulgrid",
"+",
"np",
".",
"roll",
"(",
"ulgrid",
",",
"-",
"1",
",",
"axis",
"=",
"1",
")",
"ltsum",
"=",
"ldrsum",
"+",
"lulsum",
"maparray",
"[",
"0",
":",
"mapsize",
":",
"stepsize",
",",
"stepsize",
"//",
"2",
":",
"mapsize",
":",
"stepsize",
"]",
"=",
"wibbledmean",
"(",
"ltsum",
")",
"tdrsum",
"=",
"drgrid",
"+",
"np",
".",
"roll",
"(",
"drgrid",
",",
"1",
",",
"axis",
"=",
"1",
")",
"tulsum",
"=",
"ulgrid",
"+",
"np",
".",
"roll",
"(",
"ulgrid",
",",
"-",
"1",
",",
"axis",
"=",
"0",
")",
"ttsum",
"=",
"tdrsum",
"+",
"tulsum",
"maparray",
"[",
"stepsize",
"//",
"2",
":",
"mapsize",
":",
"stepsize",
",",
"0",
":",
"mapsize",
":",
"stepsize",
"]",
"=",
"wibbledmean",
"(",
"ttsum",
")",
"while",
"stepsize",
">=",
"2",
":",
"fillsquares",
"(",
")",
"filldiamonds",
"(",
")",
"stepsize",
"//=",
"2",
"wibble",
"/=",
"wibbledecay",
"maparray",
"-=",
"maparray",
".",
"min",
"(",
")",
"return",
"maparray",
"/",
"maparray",
".",
"max",
"(",
")"
] | 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 'mapsize', of floats in [0,255]. | [
"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, 0.18, 0.26, 0.38][severity - 1]
x = np.array(x) / 255.
x_clip = np.clip(x + np.random.normal(size=x.shape, scale=c), 0, 1) * 255
return around_and_astype(x_clip) | 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, 0.18, 0.26, 0.38][severity - 1]
x = np.array(x) / 255.
x_clip = np.clip(x + np.random.normal(size=x.shape, scale=c), 0, 1) * 255
return around_and_astype(x_clip) | [
"def",
"gaussian_noise",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
".08",
",",
".12",
",",
"0.18",
",",
"0.26",
",",
"0.38",
"]",
"[",
"severity",
"-",
"1",
"]",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"/",
"255.",
"x_clip",
"=",
"np",
".",
"clip",
"(",
"x",
"+",
"np",
".",
"random",
".",
"normal",
"(",
"size",
"=",
"x",
".",
"shape",
",",
"scale",
"=",
"c",
")",
",",
"0",
",",
"1",
")",
"*",
"255",
"return",
"around_and_astype",
"(",
"x_clip",
")"
] | 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][severity - 1]
x = np.array(x) / 255.
x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255
return around_and_astype(x_clip) | 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][severity - 1]
x = np.array(x) / 255.
x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255
return around_and_astype(x_clip) | [
"def",
"shot_noise",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
"60",
",",
"25",
",",
"12",
",",
"5",
",",
"3",
"]",
"[",
"severity",
"-",
"1",
"]",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"/",
"255.",
"x_clip",
"=",
"np",
".",
"clip",
"(",
"np",
".",
"random",
".",
"poisson",
"(",
"x",
"*",
"c",
")",
"/",
"float",
"(",
"c",
")",
",",
"0",
",",
"1",
")",
"*",
"255",
"return",
"around_and_astype",
"(",
"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, .09, 0.17, 0.27][severity - 1]
x = tfds.core.lazy_imports.skimage.util.random_noise(
np.array(x) / 255., mode='s&p', amount=c)
x_clip = np.clip(x, 0, 1) * 255
return around_and_astype(x_clip) | 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, .09, 0.17, 0.27][severity - 1]
x = tfds.core.lazy_imports.skimage.util.random_noise(
np.array(x) / 255., mode='s&p', amount=c)
x_clip = np.clip(x, 0, 1) * 255
return around_and_astype(x_clip) | [
"def",
"impulse_noise",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
".03",
",",
".06",
",",
".09",
",",
"0.17",
",",
"0.27",
"]",
"[",
"severity",
"-",
"1",
"]",
"x",
"=",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"skimage",
".",
"util",
".",
"random_noise",
"(",
"np",
".",
"array",
"(",
"x",
")",
"/",
"255.",
",",
"mode",
"=",
"'s&p'",
",",
"amount",
"=",
"c",
")",
"x_clip",
"=",
"np",
".",
"clip",
"(",
"x",
",",
"0",
",",
"1",
")",
"*",
"255",
"return",
"around_and_astype",
"(",
"x_clip",
")"
] | 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,255]. Applied defocus blur.
"""
c = [(3, 0.1), (4, 0.5), (6, 0.5), (8, 0.5), (10, 0.5)][severity - 1]
x = np.array(x) / 255.
kernel = disk(radius=c[0], alias_blur=c[1])
channels = []
for d in range(3):
channels.append(tfds.core.lazy_imports.cv2.filter2D(x[:, :, d], -1, kernel))
channels = np.array(channels).transpose((1, 2, 0)) # 3x224x224 -> 224x224x3
x_clip = np.clip(channels, 0, 1) * 255
return around_and_astype(x_clip) | 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,255]. Applied defocus blur.
"""
c = [(3, 0.1), (4, 0.5), (6, 0.5), (8, 0.5), (10, 0.5)][severity - 1]
x = np.array(x) / 255.
kernel = disk(radius=c[0], alias_blur=c[1])
channels = []
for d in range(3):
channels.append(tfds.core.lazy_imports.cv2.filter2D(x[:, :, d], -1, kernel))
channels = np.array(channels).transpose((1, 2, 0)) # 3x224x224 -> 224x224x3
x_clip = np.clip(channels, 0, 1) * 255
return around_and_astype(x_clip) | [
"def",
"defocus_blur",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
"(",
"3",
",",
"0.1",
")",
",",
"(",
"4",
",",
"0.5",
")",
",",
"(",
"6",
",",
"0.5",
")",
",",
"(",
"8",
",",
"0.5",
")",
",",
"(",
"10",
",",
"0.5",
")",
"]",
"[",
"severity",
"-",
"1",
"]",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"/",
"255.",
"kernel",
"=",
"disk",
"(",
"radius",
"=",
"c",
"[",
"0",
"]",
",",
"alias_blur",
"=",
"c",
"[",
"1",
"]",
")",
"channels",
"=",
"[",
"]",
"for",
"d",
"in",
"range",
"(",
"3",
")",
":",
"channels",
".",
"append",
"(",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"cv2",
".",
"filter2D",
"(",
"x",
"[",
":",
",",
":",
",",
"d",
"]",
",",
"-",
"1",
",",
"kernel",
")",
")",
"channels",
"=",
"np",
".",
"array",
"(",
"channels",
")",
".",
"transpose",
"(",
"(",
"1",
",",
"2",
",",
"0",
")",
")",
"# 3x224x224 -> 224x224x3",
"x_clip",
"=",
"np",
".",
"clip",
"(",
"channels",
",",
"0",
",",
"1",
")",
"*",
"255",
"return",
"around_and_astype",
"(",
"x_clip",
")"
] | 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 with uint8 pixels in [0,255]. Applied frosted glass blur.
"""
# sigma, max_delta, iterations
c = [(0.7, 1, 2), (0.9, 2, 1), (1, 2, 3), (1.1, 3, 2), (1.5, 4,
2)][severity - 1]
x = np.uint8(
tfds.core.lazy_imports.skimage.filters.gaussian(
np.array(x) / 255., sigma=c[0], multichannel=True) * 255)
# locally shuffle pixels
for _ in range(c[2]):
for h in range(x.shape[0] - c[1], c[1], -1):
for w in range(x.shape[1] - c[1], c[1], -1):
dx, dy = np.random.randint(-c[1], c[1], size=(2,))
h_prime, w_prime = h + dy, w + dx
# swap
x[h, w], x[h_prime, w_prime] = x[h_prime, w_prime], x[h, w]
x_clip = np.clip(
tfds.core.lazy_imports.skimage.filters.gaussian(
x / 255., sigma=c[0], multichannel=True), 0, 1)
x_clip *= 255
return around_and_astype(x_clip) | 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 with uint8 pixels in [0,255]. Applied frosted glass blur.
"""
# sigma, max_delta, iterations
c = [(0.7, 1, 2), (0.9, 2, 1), (1, 2, 3), (1.1, 3, 2), (1.5, 4,
2)][severity - 1]
x = np.uint8(
tfds.core.lazy_imports.skimage.filters.gaussian(
np.array(x) / 255., sigma=c[0], multichannel=True) * 255)
# locally shuffle pixels
for _ in range(c[2]):
for h in range(x.shape[0] - c[1], c[1], -1):
for w in range(x.shape[1] - c[1], c[1], -1):
dx, dy = np.random.randint(-c[1], c[1], size=(2,))
h_prime, w_prime = h + dy, w + dx
# swap
x[h, w], x[h_prime, w_prime] = x[h_prime, w_prime], x[h, w]
x_clip = np.clip(
tfds.core.lazy_imports.skimage.filters.gaussian(
x / 255., sigma=c[0], multichannel=True), 0, 1)
x_clip *= 255
return around_and_astype(x_clip) | [
"def",
"frosted_glass_blur",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"# sigma, max_delta, iterations",
"c",
"=",
"[",
"(",
"0.7",
",",
"1",
",",
"2",
")",
",",
"(",
"0.9",
",",
"2",
",",
"1",
")",
",",
"(",
"1",
",",
"2",
",",
"3",
")",
",",
"(",
"1.1",
",",
"3",
",",
"2",
")",
",",
"(",
"1.5",
",",
"4",
",",
"2",
")",
"]",
"[",
"severity",
"-",
"1",
"]",
"x",
"=",
"np",
".",
"uint8",
"(",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"skimage",
".",
"filters",
".",
"gaussian",
"(",
"np",
".",
"array",
"(",
"x",
")",
"/",
"255.",
",",
"sigma",
"=",
"c",
"[",
"0",
"]",
",",
"multichannel",
"=",
"True",
")",
"*",
"255",
")",
"# locally shuffle pixels",
"for",
"_",
"in",
"range",
"(",
"c",
"[",
"2",
"]",
")",
":",
"for",
"h",
"in",
"range",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
"-",
"c",
"[",
"1",
"]",
",",
"c",
"[",
"1",
"]",
",",
"-",
"1",
")",
":",
"for",
"w",
"in",
"range",
"(",
"x",
".",
"shape",
"[",
"1",
"]",
"-",
"c",
"[",
"1",
"]",
",",
"c",
"[",
"1",
"]",
",",
"-",
"1",
")",
":",
"dx",
",",
"dy",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"-",
"c",
"[",
"1",
"]",
",",
"c",
"[",
"1",
"]",
",",
"size",
"=",
"(",
"2",
",",
")",
")",
"h_prime",
",",
"w_prime",
"=",
"h",
"+",
"dy",
",",
"w",
"+",
"dx",
"# swap",
"x",
"[",
"h",
",",
"w",
"]",
",",
"x",
"[",
"h_prime",
",",
"w_prime",
"]",
"=",
"x",
"[",
"h_prime",
",",
"w_prime",
"]",
",",
"x",
"[",
"h",
",",
"w",
"]",
"x_clip",
"=",
"np",
".",
"clip",
"(",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"skimage",
".",
"filters",
".",
"gaussian",
"(",
"x",
"/",
"255.",
",",
"sigma",
"=",
"c",
"[",
"0",
"]",
",",
"multichannel",
"=",
"True",
")",
",",
"0",
",",
"1",
")",
"x_clip",
"*=",
"255",
"return",
"around_and_astype",
"(",
"x_clip",
")"
] | 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 glass blur. | [
"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 pixels in [0,255]. Applied zoom blur.
"""
c = [
np.arange(1, 1.11, 0.01),
np.arange(1, 1.16, 0.01),
np.arange(1, 1.21, 0.02),
np.arange(1, 1.26, 0.02),
np.arange(1, 1.31, 0.03)
][severity - 1]
x = (np.array(x) / 255.).astype(np.float32)
out = np.zeros_like(x)
for zoom_factor in c:
out += clipped_zoom(x, zoom_factor)
x = (x + out) / (len(c) + 1)
x_clip = np.clip(x, 0, 1) * 255
return around_and_astype(x_clip) | 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 pixels in [0,255]. Applied zoom blur.
"""
c = [
np.arange(1, 1.11, 0.01),
np.arange(1, 1.16, 0.01),
np.arange(1, 1.21, 0.02),
np.arange(1, 1.26, 0.02),
np.arange(1, 1.31, 0.03)
][severity - 1]
x = (np.array(x) / 255.).astype(np.float32)
out = np.zeros_like(x)
for zoom_factor in c:
out += clipped_zoom(x, zoom_factor)
x = (x + out) / (len(c) + 1)
x_clip = np.clip(x, 0, 1) * 255
return around_and_astype(x_clip) | [
"def",
"zoom_blur",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
"np",
".",
"arange",
"(",
"1",
",",
"1.11",
",",
"0.01",
")",
",",
"np",
".",
"arange",
"(",
"1",
",",
"1.16",
",",
"0.01",
")",
",",
"np",
".",
"arange",
"(",
"1",
",",
"1.21",
",",
"0.02",
")",
",",
"np",
".",
"arange",
"(",
"1",
",",
"1.26",
",",
"0.02",
")",
",",
"np",
".",
"arange",
"(",
"1",
",",
"1.31",
",",
"0.03",
")",
"]",
"[",
"severity",
"-",
"1",
"]",
"x",
"=",
"(",
"np",
".",
"array",
"(",
"x",
")",
"/",
"255.",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"out",
"=",
"np",
".",
"zeros_like",
"(",
"x",
")",
"for",
"zoom_factor",
"in",
"c",
":",
"out",
"+=",
"clipped_zoom",
"(",
"x",
",",
"zoom_factor",
")",
"x",
"=",
"(",
"x",
"+",
"out",
")",
"/",
"(",
"len",
"(",
"c",
")",
"+",
"1",
")",
"x_clip",
"=",
"np",
".",
"clip",
"(",
"x",
",",
"0",
",",
"1",
")",
"*",
"255",
"return",
"around_and_astype",
"(",
"x_clip",
")"
] | 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 blur. | [
"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,255]. Added fog.
"""
c = [(1.5, 2), (2., 2), (2.5, 1.7), (2.5, 1.5), (3., 1.4)][severity - 1]
x = np.array(x) / 255.
max_val = x.max()
mapsize = 512
shape = x.shape
max_length = max(shape[0], shape[1])
if max_length > mapsize:
mapsize = 2**int(np.ceil(np.log2(float(max_length))))
tmp = plasma_fractal(mapsize=mapsize, wibbledecay=c[1])
tmp = tmp[:x.shape[0], :x.shape[1]]
tmp = tmp[..., np.newaxis]
x += c[0] * tmp
x_clip = np.clip(x * max_val / (max_val + c[0]), 0, 1) * 255
return around_and_astype(x_clip) | 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,255]. Added fog.
"""
c = [(1.5, 2), (2., 2), (2.5, 1.7), (2.5, 1.5), (3., 1.4)][severity - 1]
x = np.array(x) / 255.
max_val = x.max()
mapsize = 512
shape = x.shape
max_length = max(shape[0], shape[1])
if max_length > mapsize:
mapsize = 2**int(np.ceil(np.log2(float(max_length))))
tmp = plasma_fractal(mapsize=mapsize, wibbledecay=c[1])
tmp = tmp[:x.shape[0], :x.shape[1]]
tmp = tmp[..., np.newaxis]
x += c[0] * tmp
x_clip = np.clip(x * max_val / (max_val + c[0]), 0, 1) * 255
return around_and_astype(x_clip) | [
"def",
"fog",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
"(",
"1.5",
",",
"2",
")",
",",
"(",
"2.",
",",
"2",
")",
",",
"(",
"2.5",
",",
"1.7",
")",
",",
"(",
"2.5",
",",
"1.5",
")",
",",
"(",
"3.",
",",
"1.4",
")",
"]",
"[",
"severity",
"-",
"1",
"]",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"/",
"255.",
"max_val",
"=",
"x",
".",
"max",
"(",
")",
"mapsize",
"=",
"512",
"shape",
"=",
"x",
".",
"shape",
"max_length",
"=",
"max",
"(",
"shape",
"[",
"0",
"]",
",",
"shape",
"[",
"1",
"]",
")",
"if",
"max_length",
">",
"mapsize",
":",
"mapsize",
"=",
"2",
"**",
"int",
"(",
"np",
".",
"ceil",
"(",
"np",
".",
"log2",
"(",
"float",
"(",
"max_length",
")",
")",
")",
")",
"tmp",
"=",
"plasma_fractal",
"(",
"mapsize",
"=",
"mapsize",
",",
"wibbledecay",
"=",
"c",
"[",
"1",
"]",
")",
"tmp",
"=",
"tmp",
"[",
":",
"x",
".",
"shape",
"[",
"0",
"]",
",",
":",
"x",
".",
"shape",
"[",
"1",
"]",
"]",
"tmp",
"=",
"tmp",
"[",
"...",
",",
"np",
".",
"newaxis",
"]",
"x",
"+=",
"c",
"[",
"0",
"]",
"*",
"tmp",
"x_clip",
"=",
"np",
".",
"clip",
"(",
"x",
"*",
"max_val",
"/",
"(",
"max_val",
"+",
"c",
"[",
"0",
"]",
")",
",",
"0",
",",
"1",
")",
"*",
"255",
"return",
"around_and_astype",
"(",
"x_clip",
")"
] | 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][severity - 1]
x = np.array(x) / 255.
x = tfds.core.lazy_imports.skimage.color.rgb2hsv(x)
x[:, :, 2] = np.clip(x[:, :, 2] + c, 0, 1)
x = tfds.core.lazy_imports.skimage.color.hsv2rgb(x)
x_clip = np.clip(x, 0, 1) * 255
return around_and_astype(x_clip) | 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][severity - 1]
x = np.array(x) / 255.
x = tfds.core.lazy_imports.skimage.color.rgb2hsv(x)
x[:, :, 2] = np.clip(x[:, :, 2] + c, 0, 1)
x = tfds.core.lazy_imports.skimage.color.hsv2rgb(x)
x_clip = np.clip(x, 0, 1) * 255
return around_and_astype(x_clip) | [
"def",
"brightness",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
".1",
",",
".2",
",",
".3",
",",
".4",
",",
".5",
"]",
"[",
"severity",
"-",
"1",
"]",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"/",
"255.",
"x",
"=",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"skimage",
".",
"color",
".",
"rgb2hsv",
"(",
"x",
")",
"x",
"[",
":",
",",
":",
",",
"2",
"]",
"=",
"np",
".",
"clip",
"(",
"x",
"[",
":",
",",
":",
",",
"2",
"]",
"+",
"c",
",",
"0",
",",
"1",
")",
"x",
"=",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"skimage",
".",
"color",
".",
"hsv2rgb",
"(",
"x",
")",
"x_clip",
"=",
"np",
".",
"clip",
"(",
"x",
",",
"0",
",",
"1",
")",
"*",
"255",
"return",
"around_and_astype",
"(",
"x_clip",
")"
] | 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][severity - 1]
x = np.array(x) / 255.
means = np.mean(x, axis=(0, 1), keepdims=True)
x_clip = np.clip((x - means) * c + means, 0, 1) * 255
return around_and_astype(x_clip) | 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][severity - 1]
x = np.array(x) / 255.
means = np.mean(x, axis=(0, 1), keepdims=True)
x_clip = np.clip((x - means) * c + means, 0, 1) * 255
return around_and_astype(x_clip) | [
"def",
"contrast",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
"0.4",
",",
".3",
",",
".2",
",",
".1",
",",
".05",
"]",
"[",
"severity",
"-",
"1",
"]",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"/",
"255.",
"means",
"=",
"np",
".",
"mean",
"(",
"x",
",",
"axis",
"=",
"(",
"0",
",",
"1",
")",
",",
"keepdims",
"=",
"True",
")",
"x_clip",
"=",
"np",
".",
"clip",
"(",
"(",
"x",
"-",
"means",
")",
"*",
"c",
"+",
"means",
",",
"0",
",",
"1",
")",
"*",
"255",
"return",
"around_and_astype",
"(",
"x_clip",
")"
] | 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 array, image with uint8 pixels in [0,255]. Applied pixelating
corruption.
"""
c = [0.6, 0.5, 0.4, 0.3, 0.25][severity - 1]
shape = x.shape
x = tfds.core.lazy_imports.PIL_Image.fromarray(x.astype(np.uint8))
x = x.resize((int(shape[1] * c), int(shape[0] * c)))
x = x.resize((shape[1], shape[0]))
return np.asarray(x) | 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 array, image with uint8 pixels in [0,255]. Applied pixelating
corruption.
"""
c = [0.6, 0.5, 0.4, 0.3, 0.25][severity - 1]
shape = x.shape
x = tfds.core.lazy_imports.PIL_Image.fromarray(x.astype(np.uint8))
x = x.resize((int(shape[1] * c), int(shape[0] * c)))
x = x.resize((shape[1], shape[0]))
return np.asarray(x) | [
"def",
"pixelate",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
"0.6",
",",
"0.5",
",",
"0.4",
",",
"0.3",
",",
"0.25",
"]",
"[",
"severity",
"-",
"1",
"]",
"shape",
"=",
"x",
".",
"shape",
"x",
"=",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"PIL_Image",
".",
"fromarray",
"(",
"x",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
")",
"x",
"=",
"x",
".",
"resize",
"(",
"(",
"int",
"(",
"shape",
"[",
"1",
"]",
"*",
"c",
")",
",",
"int",
"(",
"shape",
"[",
"0",
"]",
"*",
"c",
")",
")",
")",
"x",
"=",
"x",
".",
"resize",
"(",
"(",
"shape",
"[",
"1",
"]",
",",
"shape",
"[",
"0",
"]",
")",
")",
"return",
"np",
".",
"asarray",
"(",
"x",
")"
] | 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 [0,255]. Applied pixelating
corruption. | [
"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, 18, 15, 10, 7][severity - 1]
x = tfds.core.lazy_imports.PIL_Image.fromarray(x.astype(np.uint8))
output = io.BytesIO()
x.save(output, 'JPEG', quality=c)
output.seek(0)
x = tfds.core.lazy_imports.PIL_Image.open(output)
return np.asarray(x) | 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, 18, 15, 10, 7][severity - 1]
x = tfds.core.lazy_imports.PIL_Image.fromarray(x.astype(np.uint8))
output = io.BytesIO()
x.save(output, 'JPEG', quality=c)
output.seek(0)
x = tfds.core.lazy_imports.PIL_Image.open(output)
return np.asarray(x) | [
"def",
"jpeg_compression",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
"25",
",",
"18",
",",
"15",
",",
"10",
",",
"7",
"]",
"[",
"severity",
"-",
"1",
"]",
"x",
"=",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"PIL_Image",
".",
"fromarray",
"(",
"x",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
")",
"output",
"=",
"io",
".",
"BytesIO",
"(",
")",
"x",
".",
"save",
"(",
"output",
",",
"'JPEG'",
",",
"quality",
"=",
"c",
")",
"output",
".",
"seek",
"(",
"0",
")",
"x",
"=",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"PIL_Image",
".",
"open",
"(",
"output",
")",
"return",
"np",
".",
"asarray",
"(",
"x",
")"
] | 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",
",",
"original",
")"
] | 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",
"(",
"d",
"[",
"key",
"]",
"for",
"d",
"in",
"dicts",
")"
] | 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_tuple)
for k, v in data_struct.items()
}
elif not dict_only:
types = [list]
if map_tuple:
types.append(tuple)
if isinstance(data_struct, tuple(types)):
mapped = [map_nested(function, v, dict_only, map_tuple)
for v in data_struct]
if isinstance(data_struct, list):
return mapped
else:
return tuple(mapped)
# Singleton
return function(data_struct) | 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_tuple)
for k, v in data_struct.items()
}
elif not dict_only:
types = [list]
if map_tuple:
types.append(tuple)
if isinstance(data_struct, tuple(types)):
mapped = [map_nested(function, v, dict_only, map_tuple)
for v in data_struct]
if isinstance(data_struct, list):
return mapped
else:
return tuple(mapped)
# Singleton
return function(data_struct) | [
"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",
")",
":",
"return",
"{",
"k",
":",
"map_nested",
"(",
"function",
",",
"v",
",",
"dict_only",
",",
"map_tuple",
")",
"for",
"k",
",",
"v",
"in",
"data_struct",
".",
"items",
"(",
")",
"}",
"elif",
"not",
"dict_only",
":",
"types",
"=",
"[",
"list",
"]",
"if",
"map_tuple",
":",
"types",
".",
"append",
"(",
"tuple",
")",
"if",
"isinstance",
"(",
"data_struct",
",",
"tuple",
"(",
"types",
")",
")",
":",
"mapped",
"=",
"[",
"map_nested",
"(",
"function",
",",
"v",
",",
"dict_only",
",",
"map_tuple",
")",
"for",
"v",
"in",
"data_struct",
"]",
"if",
"isinstance",
"(",
"data_struct",
",",
"list",
")",
":",
"return",
"mapped",
"else",
":",
"return",
"tuple",
"(",
"mapped",
")",
"# Singleton",
"return",
"function",
"(",
"data_struct",
")"
] | 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(arg0, dict):
return {
k: zip_nested(*a, dict_only=dict_only) for k, a in zip_dict(arg0, *args)
}
elif not dict_only:
if isinstance(arg0, list):
return [zip_nested(*a, dict_only=dict_only) for a in zip(arg0, *args)]
# Singleton
return (arg0,) + args | 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(arg0, dict):
return {
k: zip_nested(*a, dict_only=dict_only) for k, a in zip_dict(arg0, *args)
}
elif not dict_only:
if isinstance(arg0, list):
return [zip_nested(*a, dict_only=dict_only) for a in zip(arg0, *args)]
# Singleton
return (arg0,) + args | [
"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 support for more exotic data_struct, like OrderedDict",
"if",
"isinstance",
"(",
"arg0",
",",
"dict",
")",
":",
"return",
"{",
"k",
":",
"zip_nested",
"(",
"*",
"a",
",",
"dict_only",
"=",
"dict_only",
")",
"for",
"k",
",",
"a",
"in",
"zip_dict",
"(",
"arg0",
",",
"*",
"args",
")",
"}",
"elif",
"not",
"dict_only",
":",
"if",
"isinstance",
"(",
"arg0",
",",
"list",
")",
":",
"return",
"[",
"zip_nested",
"(",
"*",
"a",
",",
"dict_only",
"=",
"dict_only",
")",
"for",
"a",
"in",
"zip",
"(",
"arg0",
",",
"*",
"args",
")",
"]",
"# Singleton",
"return",
"(",
"arg0",
",",
")",
"+",
"args"
] | 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.proto_field * 10
p = proto.MyProto(proto_field=123)
a = A()
a.CopyFrom(p) # a is like a proto object
assert a.proto_field == 123
a.custom_method() # But has additional methods
```
Args:
proto_cls: The protobuf class to inherit from
Returns:
decorated_cls: The decorated class
"""
def decorator(cls):
"""Decorator applied to the class."""
class ProtoCls(object):
"""Base class simulating the protobuf."""
def __init__(self, *args, **kwargs):
super(ProtoCls, self).__setattr__(
"_ProtoCls__proto",
proto_cls(*args, **kwargs),
)
def __getattr__(self, attr_name):
return getattr(self.__proto, attr_name)
def __setattr__(self, attr_name, new_value):
try:
return setattr(self.__proto, attr_name, new_value)
except AttributeError:
return super(ProtoCls, self).__setattr__(attr_name, new_value)
def __eq__(self, other):
return self.__proto, other.get_proto()
def get_proto(self):
return self.__proto
def __repr__(self):
return "<{cls_name}\n{proto_repr}\n>".format(
cls_name=cls.__name__, proto_repr=repr(self.__proto))
decorator_cls = type(cls.__name__, (cls, ProtoCls), {
"__doc__": cls.__doc__,
})
return decorator_cls
return decorator | 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.proto_field * 10
p = proto.MyProto(proto_field=123)
a = A()
a.CopyFrom(p) # a is like a proto object
assert a.proto_field == 123
a.custom_method() # But has additional methods
```
Args:
proto_cls: The protobuf class to inherit from
Returns:
decorated_cls: The decorated class
"""
def decorator(cls):
"""Decorator applied to the class."""
class ProtoCls(object):
"""Base class simulating the protobuf."""
def __init__(self, *args, **kwargs):
super(ProtoCls, self).__setattr__(
"_ProtoCls__proto",
proto_cls(*args, **kwargs),
)
def __getattr__(self, attr_name):
return getattr(self.__proto, attr_name)
def __setattr__(self, attr_name, new_value):
try:
return setattr(self.__proto, attr_name, new_value)
except AttributeError:
return super(ProtoCls, self).__setattr__(attr_name, new_value)
def __eq__(self, other):
return self.__proto, other.get_proto()
def get_proto(self):
return self.__proto
def __repr__(self):
return "<{cls_name}\n{proto_repr}\n>".format(
cls_name=cls.__name__, proto_repr=repr(self.__proto))
decorator_cls = type(cls.__name__, (cls, ProtoCls), {
"__doc__": cls.__doc__,
})
return decorator_cls
return decorator | [
"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",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"ProtoCls",
",",
"self",
")",
".",
"__setattr__",
"(",
"\"_ProtoCls__proto\"",
",",
"proto_cls",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
",",
")",
"def",
"__getattr__",
"(",
"self",
",",
"attr_name",
")",
":",
"return",
"getattr",
"(",
"self",
".",
"__proto",
",",
"attr_name",
")",
"def",
"__setattr__",
"(",
"self",
",",
"attr_name",
",",
"new_value",
")",
":",
"try",
":",
"return",
"setattr",
"(",
"self",
".",
"__proto",
",",
"attr_name",
",",
"new_value",
")",
"except",
"AttributeError",
":",
"return",
"super",
"(",
"ProtoCls",
",",
"self",
")",
".",
"__setattr__",
"(",
"attr_name",
",",
"new_value",
")",
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"__proto",
",",
"other",
".",
"get_proto",
"(",
")",
"def",
"get_proto",
"(",
"self",
")",
":",
"return",
"self",
".",
"__proto",
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"\"<{cls_name}\\n{proto_repr}\\n>\"",
".",
"format",
"(",
"cls_name",
"=",
"cls",
".",
"__name__",
",",
"proto_repr",
"=",
"repr",
"(",
"self",
".",
"__proto",
")",
")",
"decorator_cls",
"=",
"type",
"(",
"cls",
".",
"__name__",
",",
"(",
"cls",
",",
"ProtoCls",
")",
",",
"{",
"\"__doc__\"",
":",
"cls",
".",
"__doc__",
",",
"}",
")",
"return",
"decorator_cls",
"return",
"decorator"
] | 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.MyProto(proto_field=123)
a = A()
a.CopyFrom(p) # a is like a proto object
assert a.proto_field == 123
a.custom_method() # But has additional methods
```
Args:
proto_cls: The protobuf class to inherit from
Returns:
decorated_cls: The decorated class | [
"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",
".",
"GFile",
"(",
"tmp_path",
",",
"mode",
")",
"as",
"file_",
":",
"yield",
"file_",
"tf",
".",
"io",
".",
"gfile",
".",
"rename",
"(",
"tmp_path",
",",
"path",
",",
"overwrite",
"=",
"True",
")"
] | 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 block:
break
checksum.update(block)
return checksum.hexdigest(), size | 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 block:
break
checksum.update(block)
return checksum.hexdigest(), size | [
"def",
"read_checksum_digest",
"(",
"path",
",",
"checksum_cls",
"=",
"hashlib",
".",
"sha256",
")",
":",
"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",
"block",
":",
"break",
"checksum",
".",
"update",
"(",
"block",
")",
"return",
"checksum",
".",
"hexdigest",
"(",
")",
",",
"size"
] | 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",
"(",
"exc_type",
",",
"exc_type",
"(",
"msg",
")",
",",
"exc_traceback",
")"
] | 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",
",",
"[",
"obj",
"]",
"+",
"attr",
".",
"split",
"(",
"\".\"",
")",
")"
] | 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.'",
"%",
"supported",
")",
"self",
".",
"_encoding_format",
"=",
"encoding_format"
] | 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, channels))
self._shape = tuple(shape) | 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, channels))
self._shape = tuple(shape) | [
"def",
"set_shape",
"(",
"self",
",",
"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",
",",
"channels",
")",
")",
"self",
".",
"_shape",
"=",
"tuple",
"(",
"shape",
")"
] | 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], np_image) | 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], np_image) | [
"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_match",
"(",
"np_image",
".",
"shape",
",",
"self",
".",
"_shape",
")",
"return",
"self",
".",
"_runner",
".",
"run",
"(",
"ENCODE_FN",
"[",
"self",
".",
"_encoding_format",
"]",
",",
"np_image",
")"
] | 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.gfile.GFile(image_or_path_or_fobj, 'rb') as image_f:
encoded_image = image_f.read()
else:
encoded_image = image_or_path_or_fobj.read()
return encoded_image | 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.gfile.GFile(image_or_path_or_fobj, 'rb') as image_f:
encoded_image = image_f.read()
else:
encoded_image = image_or_path_or_fobj.read()
return encoded_image | [
"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",
"isinstance",
"(",
"image_or_path_or_fobj",
",",
"six",
".",
"string_types",
")",
":",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"image_or_path_or_fobj",
",",
"'rb'",
")",
"as",
"image_f",
":",
"encoded_image",
"=",
"image_f",
".",
"read",
"(",
")",
"else",
":",
"encoded_image",
"=",
"image_or_path_or_fobj",
".",
"read",
"(",
")",
"return",
"encoded_image"
] | 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",
".",
"set_shape",
"(",
"self",
".",
"_shape",
")",
"return",
"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_h, pad_w)
Returns:
[sequence_length, out_h, out_w, n_channels] uint8 image sequence, where
out_h = in_h + pad_h, out_w = in_w + out_w
"""
with tf.name_scope("moving_sequence"):
def get_padded_image(args):
pad_left, = args
pad_right = total_padding - pad_left
padding = tf.stack([pad_left, pad_right], axis=-1)
z = tf.zeros((1, 2), dtype=pad_left.dtype)
padding = tf.concat([padding, z], axis=0)
return tf.pad(image, padding)
padded_images = tf.map_fn(
get_padded_image, [pad_lefts], dtype=tf.uint8, infer_shape=False,
back_prop=False)
return padded_images | 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_h, pad_w)
Returns:
[sequence_length, out_h, out_w, n_channels] uint8 image sequence, where
out_h = in_h + pad_h, out_w = in_w + out_w
"""
with tf.name_scope("moving_sequence"):
def get_padded_image(args):
pad_left, = args
pad_right = total_padding - pad_left
padding = tf.stack([pad_left, pad_right], axis=-1)
z = tf.zeros((1, 2), dtype=pad_left.dtype)
padding = tf.concat([padding, z], axis=0)
return tf.pad(image, padding)
padded_images = tf.map_fn(
get_padded_image, [pad_lefts], dtype=tf.uint8, infer_shape=False,
back_prop=False)
return padded_images | [
"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",
"=",
"total_padding",
"-",
"pad_left",
"padding",
"=",
"tf",
".",
"stack",
"(",
"[",
"pad_left",
",",
"pad_right",
"]",
",",
"axis",
"=",
"-",
"1",
")",
"z",
"=",
"tf",
".",
"zeros",
"(",
"(",
"1",
",",
"2",
")",
",",
"dtype",
"=",
"pad_left",
".",
"dtype",
")",
"padding",
"=",
"tf",
".",
"concat",
"(",
"[",
"padding",
",",
"z",
"]",
",",
"axis",
"=",
"0",
")",
"return",
"tf",
".",
"pad",
"(",
"image",
",",
"padding",
")",
"padded_images",
"=",
"tf",
".",
"map_fn",
"(",
"get_padded_image",
",",
"[",
"pad_lefts",
"]",
",",
"dtype",
"=",
"tf",
".",
"uint8",
",",
"infer_shape",
"=",
"False",
",",
"back_prop",
"=",
"False",
")",
"return",
"padded_images"
] | 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_channels] uint8 image sequence, where
out_h = in_h + pad_h, out_w = in_w + out_w | [
"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_to_tensor(velocity)
t = tf.convert_to_tensor(t)
if x0.shape.ndims != 1:
raise ValueError("x0 must be a rank 1 tensor")
if velocity.shape.ndims != 1:
raise ValueError("velocity must be a rank 1 tensor")
if t.shape.ndims != 1:
raise ValueError("t must be a rank 1 tensor")
x0 = tf.expand_dims(x0, axis=0)
velocity = tf.expand_dims(velocity, axis=0)
dx = velocity * tf.expand_dims(t, axis=-1)
linear_trajectories = x0 + dx
assert linear_trajectories.shape.ndims == 2, \
"linear_trajectories should be a rank 2 tensor"
return linear_trajectories | 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_to_tensor(velocity)
t = tf.convert_to_tensor(t)
if x0.shape.ndims != 1:
raise ValueError("x0 must be a rank 1 tensor")
if velocity.shape.ndims != 1:
raise ValueError("velocity must be a rank 1 tensor")
if t.shape.ndims != 1:
raise ValueError("t must be a rank 1 tensor")
x0 = tf.expand_dims(x0, axis=0)
velocity = tf.expand_dims(velocity, axis=0)
dx = velocity * tf.expand_dims(t, axis=-1)
linear_trajectories = x0 + dx
assert linear_trajectories.shape.ndims == 2, \
"linear_trajectories should be a rank 2 tensor"
return linear_trajectories | [
"def",
"_get_linear_trajectory",
"(",
"x0",
",",
"velocity",
",",
"t",
")",
":",
"x0",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"x0",
")",
"velocity",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"velocity",
")",
"t",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"t",
")",
"if",
"x0",
".",
"shape",
".",
"ndims",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"x0 must be a rank 1 tensor\"",
")",
"if",
"velocity",
".",
"shape",
".",
"ndims",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"velocity must be a rank 1 tensor\"",
")",
"if",
"t",
".",
"shape",
".",
"ndims",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"t must be a rank 1 tensor\"",
")",
"x0",
"=",
"tf",
".",
"expand_dims",
"(",
"x0",
",",
"axis",
"=",
"0",
")",
"velocity",
"=",
"tf",
".",
"expand_dims",
"(",
"velocity",
",",
"axis",
"=",
"0",
")",
"dx",
"=",
"velocity",
"*",
"tf",
".",
"expand_dims",
"(",
"t",
",",
"axis",
"=",
"-",
"1",
")",
"linear_trajectories",
"=",
"x0",
"+",
"dx",
"assert",
"linear_trajectories",
".",
"shape",
".",
"ndims",
"==",
"2",
",",
"\"linear_trajectories should be a rank 2 tensor\"",
"return",
"linear_trajectories"
] | 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:
```python
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow_datasets.video import moving_sequence
tf.compat.v1.enable_eager_execution()
def animate(sequence):
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
sequence = np.squeeze(sequence, axis=-1)
fig = plt.figure()
plt.axis("off")
ims = [[plt.imshow(im, cmap="gray", animated=True)] for im in sequence]
# don't remove `anim =` as linter may suggets
# weird behaviour, plot will freeze on last frame
anim = animation.ArtistAnimation(
fig, ims, interval=50, blit=True, repeat_delay=100)
plt.show()
plt.close()
tf.enable_eager_execution()
mnist_ds = tfds.load("mnist", split=tfds.Split.TRAIN, as_supervised=True)
mnist_ds = mnist_ds.repeat().shuffle(1024)
def map_fn(image, label):
sequence = moving_sequence.image_as_moving_sequence(
image, sequence_length=20)
return sequence.image_sequence
moving_mnist_ds = mnist_ds.map(map_fn).batch(2).map(
lambda x: dict(image_sequence=tf.reduce_max(x, axis=0)))
# # for comparison with test data provided by original authors
# moving_mnist_ds = tfds.load("moving_mnist", split=tfds.Split.TEST)
for seq in moving_mnist_ds:
animate(seq["image_sequence"].numpy())
```
Args:
image: [in_h, in_w, n_channels] tensor defining the sub-image to be bouncing
around.
sequence_length: int, length of sequence.
output_size: (out_h, out_w) size returned images.
velocity: scalar speed or 2D velocity of image. If scalar, the 2D
velocity is randomly generated with this magnitude. This is the
normalized distance moved each time step by the sub-image, where
normalization occurs over the feasible distance the sub-image can move
e.g if the input image is [10 x 10] and the output image is [60 x 60],
a speed of 0.1 means the sub-image moves (60 - 10) * 0.1 = 5 pixels per
time step.
start_position: 2D float32 normalized initial position of each
image in [0, 1]. Randomized uniformly if not given.
Returns:
`MovingSequence` namedtuple containing:
`image_sequence`:
[sequence_length, out_h, out_w, n_channels] image at each time step.
padded values are all zero. Same dtype as input image.
`trajectory`: [sequence_length, 2] float32 in [0, 1]
2D normalized coordinates of the image at every time step.
`start_position`: 2D float32 initial position in [0, 1].
2D normalized initial position of image. Same as input if provided,
otherwise the randomly value generated.
`velocity`: 2D float32 normalized velocity. Same as input velocity
if provided as a 2D tensor, otherwise the random velocity generated.
"""
ndims = 2
image = tf.convert_to_tensor(image)
if image.shape.ndims != 3:
raise ValueError("image must be rank 3, got %s" % str(image))
output_size = tf.TensorShape(output_size)
if len(output_size) != ndims:
raise ValueError("output_size must have exactly %d elements, got %s"
% (ndims, output_size))
image_shape = tf.shape(image)
if start_position is None:
start_position = tf.random.uniform((ndims,), dtype=tf.float32)
elif start_position.shape != (ndims,):
raise ValueError("start_positions must (%d,)" % ndims)
velocity = tf.convert_to_tensor(velocity, dtype=tf.float32)
if velocity.shape.ndims == 0:
velocity = _get_random_unit_vector(ndims, tf.float32) * velocity
elif velocity.shape.ndims != 1:
raise ValueError("velocity must be rank 0 or rank 1, got %s" % velocity)
t = tf.range(sequence_length, dtype=tf.float32)
trajectory = _get_linear_trajectory(start_position, velocity, t)
trajectory = _bounce_to_bbox(trajectory)
total_padding = output_size - image_shape[:2]
if not tf.executing_eagerly():
cond = tf.compat.v1.assert_greater(total_padding, -1)
with tf.control_dependencies([cond]):
total_padding = tf.identity(total_padding)
sequence_pad_lefts = tf.cast(
tf.math.round(trajectory * tf.cast(total_padding, tf.float32)), tf.int32)
sequence = _create_moving_sequence(image, sequence_pad_lefts, total_padding)
sequence.set_shape(
[sequence_length] + output_size.as_list() + [image.shape[-1]])
return MovingSequence(
image_sequence=sequence,
trajectory=trajectory,
start_position=start_position,
velocity=velocity) | 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:
```python
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow_datasets.video import moving_sequence
tf.compat.v1.enable_eager_execution()
def animate(sequence):
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
sequence = np.squeeze(sequence, axis=-1)
fig = plt.figure()
plt.axis("off")
ims = [[plt.imshow(im, cmap="gray", animated=True)] for im in sequence]
# don't remove `anim =` as linter may suggets
# weird behaviour, plot will freeze on last frame
anim = animation.ArtistAnimation(
fig, ims, interval=50, blit=True, repeat_delay=100)
plt.show()
plt.close()
tf.enable_eager_execution()
mnist_ds = tfds.load("mnist", split=tfds.Split.TRAIN, as_supervised=True)
mnist_ds = mnist_ds.repeat().shuffle(1024)
def map_fn(image, label):
sequence = moving_sequence.image_as_moving_sequence(
image, sequence_length=20)
return sequence.image_sequence
moving_mnist_ds = mnist_ds.map(map_fn).batch(2).map(
lambda x: dict(image_sequence=tf.reduce_max(x, axis=0)))
# # for comparison with test data provided by original authors
# moving_mnist_ds = tfds.load("moving_mnist", split=tfds.Split.TEST)
for seq in moving_mnist_ds:
animate(seq["image_sequence"].numpy())
```
Args:
image: [in_h, in_w, n_channels] tensor defining the sub-image to be bouncing
around.
sequence_length: int, length of sequence.
output_size: (out_h, out_w) size returned images.
velocity: scalar speed or 2D velocity of image. If scalar, the 2D
velocity is randomly generated with this magnitude. This is the
normalized distance moved each time step by the sub-image, where
normalization occurs over the feasible distance the sub-image can move
e.g if the input image is [10 x 10] and the output image is [60 x 60],
a speed of 0.1 means the sub-image moves (60 - 10) * 0.1 = 5 pixels per
time step.
start_position: 2D float32 normalized initial position of each
image in [0, 1]. Randomized uniformly if not given.
Returns:
`MovingSequence` namedtuple containing:
`image_sequence`:
[sequence_length, out_h, out_w, n_channels] image at each time step.
padded values are all zero. Same dtype as input image.
`trajectory`: [sequence_length, 2] float32 in [0, 1]
2D normalized coordinates of the image at every time step.
`start_position`: 2D float32 initial position in [0, 1].
2D normalized initial position of image. Same as input if provided,
otherwise the randomly value generated.
`velocity`: 2D float32 normalized velocity. Same as input velocity
if provided as a 2D tensor, otherwise the random velocity generated.
"""
ndims = 2
image = tf.convert_to_tensor(image)
if image.shape.ndims != 3:
raise ValueError("image must be rank 3, got %s" % str(image))
output_size = tf.TensorShape(output_size)
if len(output_size) != ndims:
raise ValueError("output_size must have exactly %d elements, got %s"
% (ndims, output_size))
image_shape = tf.shape(image)
if start_position is None:
start_position = tf.random.uniform((ndims,), dtype=tf.float32)
elif start_position.shape != (ndims,):
raise ValueError("start_positions must (%d,)" % ndims)
velocity = tf.convert_to_tensor(velocity, dtype=tf.float32)
if velocity.shape.ndims == 0:
velocity = _get_random_unit_vector(ndims, tf.float32) * velocity
elif velocity.shape.ndims != 1:
raise ValueError("velocity must be rank 0 or rank 1, got %s" % velocity)
t = tf.range(sequence_length, dtype=tf.float32)
trajectory = _get_linear_trajectory(start_position, velocity, t)
trajectory = _bounce_to_bbox(trajectory)
total_padding = output_size - image_shape[:2]
if not tf.executing_eagerly():
cond = tf.compat.v1.assert_greater(total_padding, -1)
with tf.control_dependencies([cond]):
total_padding = tf.identity(total_padding)
sequence_pad_lefts = tf.cast(
tf.math.round(trajectory * tf.cast(total_padding, tf.float32)), tf.int32)
sequence = _create_moving_sequence(image, sequence_pad_lefts, total_padding)
sequence.set_shape(
[sequence_length] + output_size.as_list() + [image.shape[-1]])
return MovingSequence(
image_sequence=sequence,
trajectory=trajectory,
start_position=start_position,
velocity=velocity) | [
"def",
"image_as_moving_sequence",
"(",
"image",
",",
"sequence_length",
"=",
"20",
",",
"output_size",
"=",
"(",
"64",
",",
"64",
")",
",",
"velocity",
"=",
"0.1",
",",
"start_position",
"=",
"None",
")",
":",
"ndims",
"=",
"2",
"image",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"image",
")",
"if",
"image",
".",
"shape",
".",
"ndims",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"\"image must be rank 3, got %s\"",
"%",
"str",
"(",
"image",
")",
")",
"output_size",
"=",
"tf",
".",
"TensorShape",
"(",
"output_size",
")",
"if",
"len",
"(",
"output_size",
")",
"!=",
"ndims",
":",
"raise",
"ValueError",
"(",
"\"output_size must have exactly %d elements, got %s\"",
"%",
"(",
"ndims",
",",
"output_size",
")",
")",
"image_shape",
"=",
"tf",
".",
"shape",
"(",
"image",
")",
"if",
"start_position",
"is",
"None",
":",
"start_position",
"=",
"tf",
".",
"random",
".",
"uniform",
"(",
"(",
"ndims",
",",
")",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
"elif",
"start_position",
".",
"shape",
"!=",
"(",
"ndims",
",",
")",
":",
"raise",
"ValueError",
"(",
"\"start_positions must (%d,)\"",
"%",
"ndims",
")",
"velocity",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"velocity",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
"if",
"velocity",
".",
"shape",
".",
"ndims",
"==",
"0",
":",
"velocity",
"=",
"_get_random_unit_vector",
"(",
"ndims",
",",
"tf",
".",
"float32",
")",
"*",
"velocity",
"elif",
"velocity",
".",
"shape",
".",
"ndims",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"velocity must be rank 0 or rank 1, got %s\"",
"%",
"velocity",
")",
"t",
"=",
"tf",
".",
"range",
"(",
"sequence_length",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
"trajectory",
"=",
"_get_linear_trajectory",
"(",
"start_position",
",",
"velocity",
",",
"t",
")",
"trajectory",
"=",
"_bounce_to_bbox",
"(",
"trajectory",
")",
"total_padding",
"=",
"output_size",
"-",
"image_shape",
"[",
":",
"2",
"]",
"if",
"not",
"tf",
".",
"executing_eagerly",
"(",
")",
":",
"cond",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"assert_greater",
"(",
"total_padding",
",",
"-",
"1",
")",
"with",
"tf",
".",
"control_dependencies",
"(",
"[",
"cond",
"]",
")",
":",
"total_padding",
"=",
"tf",
".",
"identity",
"(",
"total_padding",
")",
"sequence_pad_lefts",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"math",
".",
"round",
"(",
"trajectory",
"*",
"tf",
".",
"cast",
"(",
"total_padding",
",",
"tf",
".",
"float32",
")",
")",
",",
"tf",
".",
"int32",
")",
"sequence",
"=",
"_create_moving_sequence",
"(",
"image",
",",
"sequence_pad_lefts",
",",
"total_padding",
")",
"sequence",
".",
"set_shape",
"(",
"[",
"sequence_length",
"]",
"+",
"output_size",
".",
"as_list",
"(",
")",
"+",
"[",
"image",
".",
"shape",
"[",
"-",
"1",
"]",
"]",
")",
"return",
"MovingSequence",
"(",
"image_sequence",
"=",
"sequence",
",",
"trajectory",
"=",
"trajectory",
",",
"start_position",
"=",
"start_position",
",",
"velocity",
"=",
"velocity",
")"
] | 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.compat.v1.enable_eager_execution()
def animate(sequence):
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
sequence = np.squeeze(sequence, axis=-1)
fig = plt.figure()
plt.axis("off")
ims = [[plt.imshow(im, cmap="gray", animated=True)] for im in sequence]
# don't remove `anim =` as linter may suggets
# weird behaviour, plot will freeze on last frame
anim = animation.ArtistAnimation(
fig, ims, interval=50, blit=True, repeat_delay=100)
plt.show()
plt.close()
tf.enable_eager_execution()
mnist_ds = tfds.load("mnist", split=tfds.Split.TRAIN, as_supervised=True)
mnist_ds = mnist_ds.repeat().shuffle(1024)
def map_fn(image, label):
sequence = moving_sequence.image_as_moving_sequence(
image, sequence_length=20)
return sequence.image_sequence
moving_mnist_ds = mnist_ds.map(map_fn).batch(2).map(
lambda x: dict(image_sequence=tf.reduce_max(x, axis=0)))
# # for comparison with test data provided by original authors
# moving_mnist_ds = tfds.load("moving_mnist", split=tfds.Split.TEST)
for seq in moving_mnist_ds:
animate(seq["image_sequence"].numpy())
```
Args:
image: [in_h, in_w, n_channels] tensor defining the sub-image to be bouncing
around.
sequence_length: int, length of sequence.
output_size: (out_h, out_w) size returned images.
velocity: scalar speed or 2D velocity of image. If scalar, the 2D
velocity is randomly generated with this magnitude. This is the
normalized distance moved each time step by the sub-image, where
normalization occurs over the feasible distance the sub-image can move
e.g if the input image is [10 x 10] and the output image is [60 x 60],
a speed of 0.1 means the sub-image moves (60 - 10) * 0.1 = 5 pixels per
time step.
start_position: 2D float32 normalized initial position of each
image in [0, 1]. Randomized uniformly if not given.
Returns:
`MovingSequence` namedtuple containing:
`image_sequence`:
[sequence_length, out_h, out_w, n_channels] image at each time step.
padded values are all zero. Same dtype as input image.
`trajectory`: [sequence_length, 2] float32 in [0, 1]
2D normalized coordinates of the image at every time step.
`start_position`: 2D float32 initial position in [0, 1].
2D normalized initial position of image. Same as input if provided,
otherwise the randomly value generated.
`velocity`: 2D float32 normalized velocity. Same as input velocity
if provided as a 2D tensor, otherwise the random velocity generated. | [
"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, "*"] and minor in [self.minor, "*"]
and patch in [self.patch, "*"]) | 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, "*"] and minor in [self.minor, "*"]
and patch in [self.patch, "*"]) | [
"def",
"match",
"(",
"self",
",",
"other_version",
")",
":",
"major",
",",
"minor",
",",
"patch",
"=",
"_str_to_version",
"(",
"other_version",
",",
"allow_wildcard",
"=",
"True",
")",
"return",
"(",
"major",
"in",
"[",
"self",
".",
"major",
",",
"\"*\"",
"]",
"and",
"minor",
"in",
"[",
"self",
".",
"minor",
",",
"\"*\"",
"]",
"and",
"patch",
"in",
"[",
"self",
".",
"patch",
",",
"\"*\"",
"]",
")"
] | 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_path = tfds.core.get_tfds_path(_VALIDATION_LABELS_FNAME)
with tf.io.gfile.GFile(labels_path) as labels_f:
labels = labels_f.read().strip().split('\n')
with tf.io.gfile.GFile(val_path, 'rb') as tar_f_obj:
tar = tarfile.open(mode='r:', fileobj=tar_f_obj)
images = sorted(tar.getnames())
return dict(zip(images, 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_path = tfds.core.get_tfds_path(_VALIDATION_LABELS_FNAME)
with tf.io.gfile.GFile(labels_path) as labels_f:
labels = labels_f.read().strip().split('\n')
with tf.io.gfile.GFile(val_path, 'rb') as tar_f_obj:
tar = tarfile.open(mode='r:', fileobj=tar_f_obj)
images = sorted(tar.getnames())
return dict(zip(images, 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",
":",
"labels",
"=",
"labels_f",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"val_path",
",",
"'rb'",
")",
"as",
"tar_f_obj",
":",
"tar",
"=",
"tarfile",
".",
"open",
"(",
"mode",
"=",
"'r:'",
",",
"fileobj",
"=",
"tar_f_obj",
")",
"images",
"=",
"sorted",
"(",
"tar",
".",
"getnames",
"(",
")",
")",
"return",
"dict",
"(",
"zip",
"(",
"images",
",",
"labels",
")",
")"
] | 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",
")",
")",
"return",
"filename",
"+",
"\".incomplete\"",
"+",
"random_suffix"
] | 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.io.gfile.exists(tmp):
tf.io.gfile.remove(tmp) | 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.io.gfile.exists(tmp):
tf.io.gfile.remove(tmp) | [
"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",
",",
"filenames",
")",
":",
"tf",
".",
"io",
".",
"gfile",
".",
"rename",
"(",
"tmp",
",",
"output",
")",
"finally",
":",
"for",
"tmp",
"in",
"tmp_files",
":",
"if",
"tf",
".",
"io",
".",
"gfile",
".",
"exists",
"(",
"tmp",
")",
":",
"tf",
".",
"io",
".",
"gfile",
".",
"remove",
"(",
"tmp",
")"
] | 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",
".",
"rename",
"(",
"tmp_dir",
",",
"dirname",
")",
"finally",
":",
"if",
"tf",
".",
"io",
".",
"gfile",
".",
"exists",
"(",
"tmp_dir",
")",
":",
"tf",
".",
"io",
".",
"gfile",
".",
"rmtree",
"(",
"tmp_dir",
")"
] | 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
random_gen.shuffle(all_records)
# Write all record back
with tf.io.TFRecordWriter(path) as writer:
for record in utils.tqdm(
all_records, desc="Writing...", unit=" examples", leave=False):
writer.write(record) | 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
random_gen.shuffle(all_records)
# Write all record back
with tf.io.TFRecordWriter(path) as writer:
for record in utils.tqdm(
all_records, desc="Writing...", unit=" examples", leave=False):
writer.write(record) | [
"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",
".",
"tqdm",
"(",
"record_iter",
",",
"desc",
"=",
"\"Reading...\"",
",",
"unit",
"=",
"\" examples\"",
",",
"leave",
"=",
"False",
")",
"]",
"# Shuffling in memory",
"random_gen",
".",
"shuffle",
"(",
"all_records",
")",
"# Write all record back",
"with",
"tf",
".",
"io",
".",
"TFRecordWriter",
"(",
"path",
")",
"as",
"writer",
":",
"for",
"record",
"in",
"utils",
".",
"tqdm",
"(",
"all_records",
",",
"desc",
"=",
"\"Writing...\"",
",",
"unit",
"=",
"\" examples\"",
",",
"leave",
"=",
"False",
")",
":",
"writer",
".",
"write",
"(",
"record",
")"
] | 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) as tmp_files:
# Write all shards
writers = [tf.io.TFRecordWriter(fname) for fname in tmp_files]
with _close_on_exit(writers) as writers:
logging.info("Writing TFRecords")
_round_robin_write(writers, generator)
# Shuffle each shard
if shuffle:
# WARNING: Using np instead of Python random because Python random
# produce different values between Python 2 and 3 and between
# architectures
random_gen = np.random.RandomState(42)
for path in utils.tqdm(
tmp_files, desc="Shuffling...", unit=" shard", leave=False):
_shuffle_tfrecord(path, random_gen=random_gen) | 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) as tmp_files:
# Write all shards
writers = [tf.io.TFRecordWriter(fname) for fname in tmp_files]
with _close_on_exit(writers) as writers:
logging.info("Writing TFRecords")
_round_robin_write(writers, generator)
# Shuffle each shard
if shuffle:
# WARNING: Using np instead of Python random because Python random
# produce different values between Python 2 and 3 and between
# architectures
random_gen = np.random.RandomState(42)
for path in utils.tqdm(
tmp_files, desc="Shuffling...", unit=" shard", leave=False):
_shuffle_tfrecord(path, random_gen=random_gen) | [
"def",
"_write_tfrecords_from_generator",
"(",
"generator",
",",
"output_files",
",",
"shuffle",
"=",
"True",
")",
":",
"if",
"do_files_exist",
"(",
"output_files",
")",
":",
"raise",
"ValueError",
"(",
"\"Pre-processed files already exists: {}.\"",
".",
"format",
"(",
"output_files",
")",
")",
"with",
"_incomplete_files",
"(",
"output_files",
")",
"as",
"tmp_files",
":",
"# Write all shards",
"writers",
"=",
"[",
"tf",
".",
"io",
".",
"TFRecordWriter",
"(",
"fname",
")",
"for",
"fname",
"in",
"tmp_files",
"]",
"with",
"_close_on_exit",
"(",
"writers",
")",
"as",
"writers",
":",
"logging",
".",
"info",
"(",
"\"Writing TFRecords\"",
")",
"_round_robin_write",
"(",
"writers",
",",
"generator",
")",
"# Shuffle each shard",
"if",
"shuffle",
":",
"# WARNING: Using np instead of Python random because Python random",
"# produce different values between Python 2 and 3 and between",
"# architectures",
"random_gen",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"42",
")",
"for",
"path",
"in",
"utils",
".",
"tqdm",
"(",
"tmp_files",
",",
"desc",
"=",
"\"Shuffling...\"",
",",
"unit",
"=",
"\" shard\"",
",",
"leave",
"=",
"False",
")",
":",
"_shuffle_tfrecord",
"(",
"path",
",",
"random_gen",
"=",
"random_gen",
")"
] | 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",
"[",
"i",
"%",
"len",
"(",
"writers",
")",
"]",
".",
"write",
"(",
"example",
")"
] | 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 "
"FeatureConnector should return a numpy array with the correct dtype "
"instead of a Python list.".format(key_name)
)
# Handle strings/bytes first
if isinstance(v, (six.binary_type, six.string_types)):
v = [tf.compat.as_bytes(v)]
return tf.train.Feature(bytes_list=tf.train.BytesList(value=v))
elif (isinstance(v, (tuple, list)) and
all(isinstance(x, (six.binary_type, six.string_types)) for x in v)):
v = [tf.compat.as_bytes(x) for x in v]
return tf.train.Feature(bytes_list=tf.train.BytesList(value=v))
elif (isinstance(v, np.ndarray) and
(v.dtype.kind in ("U", "S") or v.dtype == object)): # binary or unicode
v = [tf.compat.as_bytes(x) for x in v.flatten()]
return tf.train.Feature(bytes_list=tf.train.BytesList(value=v))
# Use NumPy for numeric types
v = np.array(v).flatten() # Convert v into a 1-d array
if np.issubdtype(v.dtype, np.integer):
return tf.train.Feature(int64_list=tf.train.Int64List(value=v))
elif np.issubdtype(v.dtype, np.floating):
return tf.train.Feature(float_list=tf.train.FloatList(value=v))
else:
raise ValueError(
"Value received: {}.\n"
"tf.train.Feature does not support type {} for feature key {}. "
"This may indicate that one of the FeatureConnectors received an "
"unsupported value as input.".format(repr(v), repr(type(v)), key_name)
) | 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 "
"FeatureConnector should return a numpy array with the correct dtype "
"instead of a Python list.".format(key_name)
)
# Handle strings/bytes first
if isinstance(v, (six.binary_type, six.string_types)):
v = [tf.compat.as_bytes(v)]
return tf.train.Feature(bytes_list=tf.train.BytesList(value=v))
elif (isinstance(v, (tuple, list)) and
all(isinstance(x, (six.binary_type, six.string_types)) for x in v)):
v = [tf.compat.as_bytes(x) for x in v]
return tf.train.Feature(bytes_list=tf.train.BytesList(value=v))
elif (isinstance(v, np.ndarray) and
(v.dtype.kind in ("U", "S") or v.dtype == object)): # binary or unicode
v = [tf.compat.as_bytes(x) for x in v.flatten()]
return tf.train.Feature(bytes_list=tf.train.BytesList(value=v))
# Use NumPy for numeric types
v = np.array(v).flatten() # Convert v into a 1-d array
if np.issubdtype(v.dtype, np.integer):
return tf.train.Feature(int64_list=tf.train.Int64List(value=v))
elif np.issubdtype(v.dtype, np.floating):
return tf.train.Feature(float_list=tf.train.FloatList(value=v))
else:
raise ValueError(
"Value received: {}.\n"
"tf.train.Feature does not support type {} for feature key {}. "
"This may indicate that one of the FeatureConnectors received an "
"unsupported value as input.".format(repr(v), repr(type(v)), key_name)
) | [
"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 is unable to infer the \"",
"\"feature type to record. To support empty value, the corresponding \"",
"\"FeatureConnector should return a numpy array with the correct dtype \"",
"\"instead of a Python list.\"",
".",
"format",
"(",
"key_name",
")",
")",
"# Handle strings/bytes first",
"if",
"isinstance",
"(",
"v",
",",
"(",
"six",
".",
"binary_type",
",",
"six",
".",
"string_types",
")",
")",
":",
"v",
"=",
"[",
"tf",
".",
"compat",
".",
"as_bytes",
"(",
"v",
")",
"]",
"return",
"tf",
".",
"train",
".",
"Feature",
"(",
"bytes_list",
"=",
"tf",
".",
"train",
".",
"BytesList",
"(",
"value",
"=",
"v",
")",
")",
"elif",
"(",
"isinstance",
"(",
"v",
",",
"(",
"tuple",
",",
"list",
")",
")",
"and",
"all",
"(",
"isinstance",
"(",
"x",
",",
"(",
"six",
".",
"binary_type",
",",
"six",
".",
"string_types",
")",
")",
"for",
"x",
"in",
"v",
")",
")",
":",
"v",
"=",
"[",
"tf",
".",
"compat",
".",
"as_bytes",
"(",
"x",
")",
"for",
"x",
"in",
"v",
"]",
"return",
"tf",
".",
"train",
".",
"Feature",
"(",
"bytes_list",
"=",
"tf",
".",
"train",
".",
"BytesList",
"(",
"value",
"=",
"v",
")",
")",
"elif",
"(",
"isinstance",
"(",
"v",
",",
"np",
".",
"ndarray",
")",
"and",
"(",
"v",
".",
"dtype",
".",
"kind",
"in",
"(",
"\"U\"",
",",
"\"S\"",
")",
"or",
"v",
".",
"dtype",
"==",
"object",
")",
")",
":",
"# binary or unicode",
"v",
"=",
"[",
"tf",
".",
"compat",
".",
"as_bytes",
"(",
"x",
")",
"for",
"x",
"in",
"v",
".",
"flatten",
"(",
")",
"]",
"return",
"tf",
".",
"train",
".",
"Feature",
"(",
"bytes_list",
"=",
"tf",
".",
"train",
".",
"BytesList",
"(",
"value",
"=",
"v",
")",
")",
"# Use NumPy for numeric types",
"v",
"=",
"np",
".",
"array",
"(",
"v",
")",
".",
"flatten",
"(",
")",
"# Convert v into a 1-d array",
"if",
"np",
".",
"issubdtype",
"(",
"v",
".",
"dtype",
",",
"np",
".",
"integer",
")",
":",
"return",
"tf",
".",
"train",
".",
"Feature",
"(",
"int64_list",
"=",
"tf",
".",
"train",
".",
"Int64List",
"(",
"value",
"=",
"v",
")",
")",
"elif",
"np",
".",
"issubdtype",
"(",
"v",
".",
"dtype",
",",
"np",
".",
"floating",
")",
":",
"return",
"tf",
".",
"train",
".",
"Feature",
"(",
"float_list",
"=",
"tf",
".",
"train",
".",
"FloatList",
"(",
"value",
"=",
"v",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Value received: {}.\\n\"",
"\"tf.train.Feature does not support type {} for feature key {}. \"",
"\"This may indicate that one of the FeatureConnectors received an \"",
"\"unsupported value as input.\"",
".",
"format",
"(",
"repr",
"(",
"v",
")",
",",
"repr",
"(",
"type",
"(",
"v",
")",
")",
",",
"key_name",
")",
")"
] | 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:
pbar: Async pbar which can be shared between threads.
"""
with tqdm_lib.tqdm(*args, **kwargs) as pbar:
pbar = _TqdmPbarAsync(pbar)
yield pbar
pbar.clear() # pop pbar from the active list of pbar
print() | 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:
pbar: Async pbar which can be shared between threads.
"""
with tqdm_lib.tqdm(*args, **kwargs) as pbar:
pbar = _TqdmPbarAsync(pbar)
yield pbar
pbar.clear() # pop pbar from the active list of pbar
print() | [
"def",
"_async_tqdm",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"tqdm_lib",
".",
"tqdm",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"as",
"pbar",
":",
"pbar",
"=",
"_TqdmPbarAsync",
"(",
"pbar",
")",
"yield",
"pbar",
"pbar",
".",
"clear",
"(",
")",
"# pop pbar from the active list of pbar",
"print",
"(",
")"
] | 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 shared between threads. | [
"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_file.write(data) | 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_file.write(data) | [
"def",
"_copy",
"(",
"src_file",
",",
"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_file",
".",
"write",
"(",
"data",
")"
] | 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,
path, extract_method, to_path)
return promise.Promise.resolve(future) | 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,
path, extract_method, to_path)
return promise.Promise.resolve(future) | [
"def",
"extract",
"(",
"self",
",",
"path",
",",
"extract_method",
",",
"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",
",",
"path",
",",
"extract_method",
",",
"to_path",
")",
"return",
"promise",
".",
"Promise",
".",
"resolve",
"(",
"future",
")"
] | 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(handle, path and os.path.join(to_path_tmp, path) or to_path_tmp)
except BaseException as err:
msg = 'Error while extracting %s to %s : %s' % (from_path, to_path, err)
raise ExtractError(msg)
# `tf.io.gfile.Rename(overwrite=True)` doesn't work for non empty
# directories, so delete destination first, if it already exists.
if tf.io.gfile.exists(to_path):
tf.io.gfile.rmtree(to_path)
tf.io.gfile.rename(to_path_tmp, to_path)
self._pbar_path.update(1)
return to_path | 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(handle, path and os.path.join(to_path_tmp, path) or to_path_tmp)
except BaseException as err:
msg = 'Error while extracting %s to %s : %s' % (from_path, to_path, err)
raise ExtractError(msg)
# `tf.io.gfile.Rename(overwrite=True)` doesn't work for non empty
# directories, so delete destination first, if it already exists.
if tf.io.gfile.exists(to_path):
tf.io.gfile.rmtree(to_path)
tf.io.gfile.rename(to_path_tmp, to_path)
self._pbar_path.update(1)
return to_path | [
"def",
"_sync_extract",
"(",
"self",
",",
"from_path",
",",
"method",
",",
"to_path",
")",
":",
"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",
"(",
"handle",
",",
"path",
"and",
"os",
".",
"path",
".",
"join",
"(",
"to_path_tmp",
",",
"path",
")",
"or",
"to_path_tmp",
")",
"except",
"BaseException",
"as",
"err",
":",
"msg",
"=",
"'Error while extracting %s to %s : %s'",
"%",
"(",
"from_path",
",",
"to_path",
",",
"err",
")",
"raise",
"ExtractError",
"(",
"msg",
")",
"# `tf.io.gfile.Rename(overwrite=True)` doesn't work for non empty",
"# directories, so delete destination first, if it already exists.",
"if",
"tf",
".",
"io",
".",
"gfile",
".",
"exists",
"(",
"to_path",
")",
":",
"tf",
".",
"io",
".",
"gfile",
".",
"rmtree",
"(",
"to_path",
")",
"tf",
".",
"io",
".",
"gfile",
".",
"rename",
"(",
"to_path_tmp",
",",
"to_path",
")",
"self",
".",
"_pbar_path",
".",
"update",
"(",
"1",
")",
"return",
"to_path"
] | 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 int64 which is space ineficient, no support for complexes or quantized
if tensor_info.dtype.is_integer or tensor_info.dtype.is_bool:
dtype = tf.int64
elif tensor_info.dtype.is_floating:
dtype = tf.float32
# It seems quite space inefficient to convert bool to int64
# We may want to add support for complex, quantize dtype in the future
# TFRecord only support 3 types
if dtype not in (tf.int64, tf.float32, tf.string):
raise NotImplementedError(
'Serialization not implemented for {}'.format(dtype))
# Select the feature proto type in function of the unknown shape
if (tensor_info.shape is not None and # Shape is a sequence (None, ...)
tensor_info.shape.count(None) == 1 and
tensor_info.shape[0] is None):
return tf.io.FixedLenSequenceFeature(
shape=tensor_info.shape[1:],
dtype=dtype,
allow_missing=True,
)
# At least one dimension is undefined
elif tensor_info.shape is None or None in tensor_info.shape:
return tf.io.VarLenFeature(dtype=dtype)
else:
return tf.io.FixedLenFeature(
shape=tensor_info.shape,
dtype=dtype,
) | 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 int64 which is space ineficient, no support for complexes or quantized
if tensor_info.dtype.is_integer or tensor_info.dtype.is_bool:
dtype = tf.int64
elif tensor_info.dtype.is_floating:
dtype = tf.float32
# It seems quite space inefficient to convert bool to int64
# We may want to add support for complex, quantize dtype in the future
# TFRecord only support 3 types
if dtype not in (tf.int64, tf.float32, tf.string):
raise NotImplementedError(
'Serialization not implemented for {}'.format(dtype))
# Select the feature proto type in function of the unknown shape
if (tensor_info.shape is not None and # Shape is a sequence (None, ...)
tensor_info.shape.count(None) == 1 and
tensor_info.shape[0] is None):
return tf.io.FixedLenSequenceFeature(
shape=tensor_info.shape[1:],
dtype=dtype,
allow_missing=True,
)
# At least one dimension is undefined
elif tensor_info.shape is None or None in tensor_info.shape:
return tf.io.VarLenFeature(dtype=dtype)
else:
return tf.io.FixedLenFeature(
shape=tensor_info.shape,
dtype=dtype,
) | [
"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",
"# to int64 which is space ineficient, no support for complexes or quantized",
"if",
"tensor_info",
".",
"dtype",
".",
"is_integer",
"or",
"tensor_info",
".",
"dtype",
".",
"is_bool",
":",
"dtype",
"=",
"tf",
".",
"int64",
"elif",
"tensor_info",
".",
"dtype",
".",
"is_floating",
":",
"dtype",
"=",
"tf",
".",
"float32",
"# It seems quite space inefficient to convert bool to int64",
"# We may want to add support for complex, quantize dtype in the future",
"# TFRecord only support 3 types",
"if",
"dtype",
"not",
"in",
"(",
"tf",
".",
"int64",
",",
"tf",
".",
"float32",
",",
"tf",
".",
"string",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Serialization not implemented for {}'",
".",
"format",
"(",
"dtype",
")",
")",
"# Select the feature proto type in function of the unknown shape",
"if",
"(",
"tensor_info",
".",
"shape",
"is",
"not",
"None",
"and",
"# Shape is a sequence (None, ...)",
"tensor_info",
".",
"shape",
".",
"count",
"(",
"None",
")",
"==",
"1",
"and",
"tensor_info",
".",
"shape",
"[",
"0",
"]",
"is",
"None",
")",
":",
"return",
"tf",
".",
"io",
".",
"FixedLenSequenceFeature",
"(",
"shape",
"=",
"tensor_info",
".",
"shape",
"[",
"1",
":",
"]",
",",
"dtype",
"=",
"dtype",
",",
"allow_missing",
"=",
"True",
",",
")",
"# At least one dimension is undefined",
"elif",
"tensor_info",
".",
"shape",
"is",
"None",
"or",
"None",
"in",
"tensor_info",
".",
"shape",
":",
"return",
"tf",
".",
"io",
".",
"VarLenFeature",
"(",
"dtype",
"=",
"dtype",
")",
"else",
":",
"return",
"tf",
".",
"io",
".",
"FixedLenFeature",
"(",
"shape",
"=",
"tensor_info",
".",
"shape",
",",
"dtype",
"=",
"dtype",
",",
")"
] | 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:
raise ValueError('Feature not supported: {}'.format(value)) | 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:
raise ValueError('Feature not supported: {}'.format(value)) | [
"def",
"to_feature",
"(",
"value",
")",
":",
"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",
":",
"raise",
"ValueError",
"(",
"'Feature not supported: {}'",
".",
"format",
"(",
"value",
")",
")"
] | 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 containing the data to decode.
Returns:
decoded_feature: The output of the feature.decode_example
"""
# Singleton case
if not feature.serialized_keys:
data_to_decode = tfexample_dict[feature_k]
# Feature contains sub features
else:
# Extract the sub-features from the global feature dict
data_to_decode = {
k: tfexample_dict[posixpath.join(feature_k, k)]
for k in feature.serialized_keys
}
return feature.decode_example(data_to_decode) | 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 containing the data to decode.
Returns:
decoded_feature: The output of the feature.decode_example
"""
# Singleton case
if not feature.serialized_keys:
data_to_decode = tfexample_dict[feature_k]
# Feature contains sub features
else:
# Extract the sub-features from the global feature dict
data_to_decode = {
k: tfexample_dict[posixpath.join(feature_k, k)]
for k in feature.serialized_keys
}
return feature.decode_example(data_to_decode) | [
"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 features",
"else",
":",
"# Extract the sub-features from the global feature dict",
"data_to_decode",
"=",
"{",
"k",
":",
"tfexample_dict",
"[",
"posixpath",
".",
"join",
"(",
"feature_k",
",",
"k",
")",
"]",
"for",
"k",
"in",
"feature",
".",
"serialized_keys",
"}",
"return",
"feature",
".",
"decode_example",
"(",
"data_to_decode",
")"
] | 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_example | [
"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 of the attributes
values: map from the file name to the list of attribute values for
this file.
"""
with tf.io.gfile.GFile(file_path) as f:
data_raw = f.read()
lines = data_raw.split("\n")
keys = lines[1].strip().split()
values = {}
# Go over each line (skip the last one, as it is empty).
for line in lines[2:-1]:
row_values = line.strip().split()
# Each row start with the 'file_name' and then space-separated values.
values[row_values[0]] = [int(v) for v in row_values[1:]]
return keys, values | 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 of the attributes
values: map from the file name to the list of attribute values for
this file.
"""
with tf.io.gfile.GFile(file_path) as f:
data_raw = f.read()
lines = data_raw.split("\n")
keys = lines[1].strip().split()
values = {}
# Go over each line (skip the last one, as it is empty).
for line in lines[2:-1]:
row_values = line.strip().split()
# Each row start with the 'file_name' and then space-separated values.
values[row_values[0]] = [int(v) for v in row_values[1:]]
return keys, values | [
"def",
"_process_celeba_config_file",
"(",
"self",
",",
"file_path",
")",
":",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"file_path",
")",
"as",
"f",
":",
"data_raw",
"=",
"f",
".",
"read",
"(",
")",
"lines",
"=",
"data_raw",
".",
"split",
"(",
"\"\\n\"",
")",
"keys",
"=",
"lines",
"[",
"1",
"]",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"values",
"=",
"{",
"}",
"# Go over each line (skip the last one, as it is empty).",
"for",
"line",
"in",
"lines",
"[",
"2",
":",
"-",
"1",
"]",
":",
"row_values",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"# Each row start with the 'file_name' and then space-separated values.",
"values",
"[",
"row_values",
"[",
"0",
"]",
"]",
"=",
"[",
"int",
"(",
"v",
")",
"for",
"v",
"in",
"row_values",
"[",
"1",
":",
"]",
"]",
"return",
"keys",
",",
"values"
] | 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 the list of attribute values for
this file. | [
"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.
Yields:
The QuickDraw examples, as defined in the dataset info features.
"""
for label, path in sorted(file_paths.items(), key=lambda x: x[0]):
with tf.io.gfile.GFile(path, "rb") as f:
class_images = np.load(f)
for np_image in class_images:
yield {
"image": np_image.reshape(_QUICKDRAW_IMAGE_SHAPE),
"label": 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.
Yields:
The QuickDraw examples, as defined in the dataset info features.
"""
for label, path in sorted(file_paths.items(), key=lambda x: x[0]):
with tf.io.gfile.GFile(path, "rb") as f:
class_images = np.load(f)
for np_image in class_images:
yield {
"image": np_image.reshape(_QUICKDRAW_IMAGE_SHAPE),
"label": label,
} | [
"def",
"_generate_examples",
"(",
"self",
",",
"file_paths",
")",
":",
"for",
"label",
",",
"path",
"in",
"sorted",
"(",
"file_paths",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
":",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"class_images",
"=",
"np",
".",
"load",
"(",
"f",
")",
"for",
"np_image",
"in",
"class_images",
":",
"yield",
"{",
"\"image\"",
":",
"np_image",
".",
"reshape",
"(",
"_QUICKDRAW_IMAGE_SHAPE",
")",
",",
"\"label\"",
":",
"label",
",",
"}"
] | 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 in the dataset info features. | [
"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 more informative error message, then reraise.
print("\n\nFailed to import TensorFlow. Please note that TensorFlow is not "
"installed by default when you install TensorFlow Datasets. This is "
"so that users can decide whether to install the GPU-enabled "
"TensorFlow package. To use TensorFlow Datasets, please install the "
"most recent version of TensorFlow, by following instructions at "
"https://tensorflow.org/install.\n\n")
raise
tf_version = distutils.version.LooseVersion(tf.__version__)
v_1_12 = distutils.version.LooseVersion("1.12.0")
if tf_version < v_1_12:
raise ImportError(
"This version of TensorFlow Datasets requires TensorFlow "
"version >= {required}; Detected an installation of version {present}. "
"Please upgrade TensorFlow to proceed.".format(
required="1.12.0",
present=tf.__version__))
_patch_tf(tf) | 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 more informative error message, then reraise.
print("\n\nFailed to import TensorFlow. Please note that TensorFlow is not "
"installed by default when you install TensorFlow Datasets. This is "
"so that users can decide whether to install the GPU-enabled "
"TensorFlow package. To use TensorFlow Datasets, please install the "
"most recent version of TensorFlow, by following instructions at "
"https://tensorflow.org/install.\n\n")
raise
tf_version = distutils.version.LooseVersion(tf.__version__)
v_1_12 = distutils.version.LooseVersion("1.12.0")
if tf_version < v_1_12:
raise ImportError(
"This version of TensorFlow Datasets requires TensorFlow "
"version >= {required}; Detected an installation of version {present}. "
"Please upgrade TensorFlow to proceed.".format(
required="1.12.0",
present=tf.__version__))
_patch_tf(tf) | [
"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. Please note that TensorFlow is not \"",
"\"installed by default when you install TensorFlow Datasets. This is \"",
"\"so that users can decide whether to install the GPU-enabled \"",
"\"TensorFlow package. To use TensorFlow Datasets, please install the \"",
"\"most recent version of TensorFlow, by following instructions at \"",
"\"https://tensorflow.org/install.\\n\\n\"",
")",
"raise",
"tf_version",
"=",
"distutils",
".",
"version",
".",
"LooseVersion",
"(",
"tf",
".",
"__version__",
")",
"v_1_12",
"=",
"distutils",
".",
"version",
".",
"LooseVersion",
"(",
"\"1.12.0\"",
")",
"if",
"tf_version",
"<",
"v_1_12",
":",
"raise",
"ImportError",
"(",
"\"This version of TensorFlow Datasets requires TensorFlow \"",
"\"version >= {required}; Detected an installation of version {present}. \"",
"\"Please upgrade TensorFlow to proceed.\"",
".",
"format",
"(",
"required",
"=",
"\"1.12.0\"",
",",
"present",
"=",
"tf",
".",
"__version__",
")",
")",
"_patch_tf",
"(",
"tf",
")"
] | 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.LooseVersion(tf.__version__)
if v_1_12 <= tf_version < v_1_13:
# TODO(b/123930850): remove when 1.13 is stable.
TF_PATCH = "tf1_12"
_patch_for_tf1_12(tf)
elif v_1_13 <= tf_version < v_2:
TF_PATCH = "tf1_13"
_patch_for_tf1_13(tf)
else:
TF_PATCH = "tf2"
_patch_for_tf2(tf) | 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.LooseVersion(tf.__version__)
if v_1_12 <= tf_version < v_1_13:
# TODO(b/123930850): remove when 1.13 is stable.
TF_PATCH = "tf1_12"
_patch_for_tf1_12(tf)
elif v_1_13 <= tf_version < v_2:
TF_PATCH = "tf1_13"
_patch_for_tf1_13(tf)
else:
TF_PATCH = "tf2"
_patch_for_tf2(tf) | [
"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",
"(",
"\"1.13.0\"",
")",
"v_2",
"=",
"distutils",
".",
"version",
".",
"LooseVersion",
"(",
"\"2.0.0\"",
")",
"tf_version",
"=",
"distutils",
".",
"version",
".",
"LooseVersion",
"(",
"tf",
".",
"__version__",
")",
"if",
"v_1_12",
"<=",
"tf_version",
"<",
"v_1_13",
":",
"# TODO(b/123930850): remove when 1.13 is stable.",
"TF_PATCH",
"=",
"\"tf1_12\"",
"_patch_for_tf1_12",
"(",
"tf",
")",
"elif",
"v_1_13",
"<=",
"tf_version",
"<",
"v_2",
":",
"TF_PATCH",
"=",
"\"tf1_13\"",
"_patch_for_tf1_13",
"(",
"tf",
")",
"else",
":",
"TF_PATCH",
"=",
"\"tf2\"",
"_patch_for_tf2",
"(",
"tf",
")"
] | 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.makedirs = tf.gfile.MakeDirs
tf.io.gfile.mkdir = tf.gfile.MkDir
tf.io.gfile.remove = tf.gfile.Remove
tf.io.gfile.rename = tf.gfile.Rename
tf.io.gfile.rmtree = tf.gfile.DeleteRecursively
tf.io.gfile.stat = tf.gfile.Stat
tf.io.gfile.walk = tf.gfile.Walk
tf.io.gfile.GFile = tf.gfile.GFile
tf.data.experimental = tf.contrib.data
tf.compat.v1 = types.ModuleType("tf.compat.v1")
tf.compat.v1.assert_greater = tf.assert_greater
tf.compat.v1.placeholder = tf.placeholder
tf.compat.v1.ConfigProto = tf.ConfigProto
tf.compat.v1.Session = tf.Session
tf.compat.v1.enable_eager_execution = tf.enable_eager_execution
tf.compat.v1.io = tf.io
tf.compat.v1.data = tf.data
tf.compat.v1.data.Dataset = tf.data.Dataset
tf.compat.v1.data.make_one_shot_iterator = (
lambda ds: ds.make_one_shot_iterator())
tf.compat.v1.train = tf.train
tf.compat.v1.global_variables_initializer = tf.global_variables_initializer
tf.compat.v1.test = tf.test
tf.compat.v1.test.get_temp_dir = tf.test.get_temp_dir
tf.nest = tf.contrib.framework.nest | 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.makedirs = tf.gfile.MakeDirs
tf.io.gfile.mkdir = tf.gfile.MkDir
tf.io.gfile.remove = tf.gfile.Remove
tf.io.gfile.rename = tf.gfile.Rename
tf.io.gfile.rmtree = tf.gfile.DeleteRecursively
tf.io.gfile.stat = tf.gfile.Stat
tf.io.gfile.walk = tf.gfile.Walk
tf.io.gfile.GFile = tf.gfile.GFile
tf.data.experimental = tf.contrib.data
tf.compat.v1 = types.ModuleType("tf.compat.v1")
tf.compat.v1.assert_greater = tf.assert_greater
tf.compat.v1.placeholder = tf.placeholder
tf.compat.v1.ConfigProto = tf.ConfigProto
tf.compat.v1.Session = tf.Session
tf.compat.v1.enable_eager_execution = tf.enable_eager_execution
tf.compat.v1.io = tf.io
tf.compat.v1.data = tf.data
tf.compat.v1.data.Dataset = tf.data.Dataset
tf.compat.v1.data.make_one_shot_iterator = (
lambda ds: ds.make_one_shot_iterator())
tf.compat.v1.train = tf.train
tf.compat.v1.global_variables_initializer = tf.global_variables_initializer
tf.compat.v1.test = tf.test
tf.compat.v1.test.get_temp_dir = tf.test.get_temp_dir
tf.nest = tf.contrib.framework.nest | [
"def",
"_patch_for_tf1_12",
"(",
"tf",
")",
":",
"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",
".",
"makedirs",
"=",
"tf",
".",
"gfile",
".",
"MakeDirs",
"tf",
".",
"io",
".",
"gfile",
".",
"mkdir",
"=",
"tf",
".",
"gfile",
".",
"MkDir",
"tf",
".",
"io",
".",
"gfile",
".",
"remove",
"=",
"tf",
".",
"gfile",
".",
"Remove",
"tf",
".",
"io",
".",
"gfile",
".",
"rename",
"=",
"tf",
".",
"gfile",
".",
"Rename",
"tf",
".",
"io",
".",
"gfile",
".",
"rmtree",
"=",
"tf",
".",
"gfile",
".",
"DeleteRecursively",
"tf",
".",
"io",
".",
"gfile",
".",
"stat",
"=",
"tf",
".",
"gfile",
".",
"Stat",
"tf",
".",
"io",
".",
"gfile",
".",
"walk",
"=",
"tf",
".",
"gfile",
".",
"Walk",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"=",
"tf",
".",
"gfile",
".",
"GFile",
"tf",
".",
"data",
".",
"experimental",
"=",
"tf",
".",
"contrib",
".",
"data",
"tf",
".",
"compat",
".",
"v1",
"=",
"types",
".",
"ModuleType",
"(",
"\"tf.compat.v1\"",
")",
"tf",
".",
"compat",
".",
"v1",
".",
"assert_greater",
"=",
"tf",
".",
"assert_greater",
"tf",
".",
"compat",
".",
"v1",
".",
"placeholder",
"=",
"tf",
".",
"placeholder",
"tf",
".",
"compat",
".",
"v1",
".",
"ConfigProto",
"=",
"tf",
".",
"ConfigProto",
"tf",
".",
"compat",
".",
"v1",
".",
"Session",
"=",
"tf",
".",
"Session",
"tf",
".",
"compat",
".",
"v1",
".",
"enable_eager_execution",
"=",
"tf",
".",
"enable_eager_execution",
"tf",
".",
"compat",
".",
"v1",
".",
"io",
"=",
"tf",
".",
"io",
"tf",
".",
"compat",
".",
"v1",
".",
"data",
"=",
"tf",
".",
"data",
"tf",
".",
"compat",
".",
"v1",
".",
"data",
".",
"Dataset",
"=",
"tf",
".",
"data",
".",
"Dataset",
"tf",
".",
"compat",
".",
"v1",
".",
"data",
".",
"make_one_shot_iterator",
"=",
"(",
"lambda",
"ds",
":",
"ds",
".",
"make_one_shot_iterator",
"(",
")",
")",
"tf",
".",
"compat",
".",
"v1",
".",
"train",
"=",
"tf",
".",
"train",
"tf",
".",
"compat",
".",
"v1",
".",
"global_variables_initializer",
"=",
"tf",
".",
"global_variables_initializer",
"tf",
".",
"compat",
".",
"v1",
".",
"test",
"=",
"tf",
".",
"test",
"tf",
".",
"compat",
".",
"v1",
".",
"test",
".",
"get_temp_dir",
"=",
"tf",
".",
"test",
".",
"get_temp_dir",
"tf",
".",
"nest",
"=",
"tf",
".",
"contrib",
".",
"framework",
".",
"nest"
] | 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.compat.v2.data = types.ModuleType("tf.compat.v2.data")
from tensorflow.python.data.ops import dataset_ops
tf.compat.v2.data.Dataset = dataset_ops.DatasetV2
if not hasattr(tf.compat.v2.data.Dataset, "output_shapes"):
from tensorflow.python.data.ops import dataset_ops
if hasattr(dataset_ops, "get_legacy_output_shapes"):
tf.compat.v2.data.Dataset.output_shapes = property(
dataset_ops.get_legacy_output_shapes)
tf.compat.v2.data.Dataset.output_types = property(
dataset_ops.get_legacy_output_types) | 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.compat.v2.data = types.ModuleType("tf.compat.v2.data")
from tensorflow.python.data.ops import dataset_ops
tf.compat.v2.data.Dataset = dataset_ops.DatasetV2
if not hasattr(tf.compat.v2.data.Dataset, "output_shapes"):
from tensorflow.python.data.ops import dataset_ops
if hasattr(dataset_ops, "get_legacy_output_shapes"):
tf.compat.v2.data.Dataset.output_shapes = property(
dataset_ops.get_legacy_output_shapes)
tf.compat.v2.data.Dataset.output_types = property(
dataset_ops.get_legacy_output_types) | [
"def",
"_patch_for_tf1_13",
"(",
"tf",
")",
":",
"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",
".",
"compat",
".",
"v2",
".",
"data",
"=",
"types",
".",
"ModuleType",
"(",
"\"tf.compat.v2.data\"",
")",
"from",
"tensorflow",
".",
"python",
".",
"data",
".",
"ops",
"import",
"dataset_ops",
"tf",
".",
"compat",
".",
"v2",
".",
"data",
".",
"Dataset",
"=",
"dataset_ops",
".",
"DatasetV2",
"if",
"not",
"hasattr",
"(",
"tf",
".",
"compat",
".",
"v2",
".",
"data",
".",
"Dataset",
",",
"\"output_shapes\"",
")",
":",
"from",
"tensorflow",
".",
"python",
".",
"data",
".",
"ops",
"import",
"dataset_ops",
"if",
"hasattr",
"(",
"dataset_ops",
",",
"\"get_legacy_output_shapes\"",
")",
":",
"tf",
".",
"compat",
".",
"v2",
".",
"data",
".",
"Dataset",
".",
"output_shapes",
"=",
"property",
"(",
"dataset_ops",
".",
"get_legacy_output_shapes",
")",
"tf",
".",
"compat",
".",
"v2",
".",
"data",
".",
"Dataset",
".",
"output_types",
"=",
"property",
"(",
"dataset_ops",
".",
"get_legacy_output_types",
")"
] | 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", None)
if v1_ds is not None:
dataset_types.append(v1_ds)
if v2_ds is not None:
dataset_types.append(v2_ds)
return isinstance(ds, tuple(dataset_types)) | 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", None)
if v1_ds is not None:
dataset_types.append(v1_ds)
if v2_ds is not None:
dataset_types.append(v2_ds)
return isinstance(ds, tuple(dataset_types)) | [
"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",
".",
"rgetattr",
"(",
"tf",
",",
"\"compat.v1.data.Dataset\"",
",",
"None",
")",
"v2_ds",
"=",
"py_utils",
".",
"rgetattr",
"(",
"tf",
",",
"\"compat.v2.data.Dataset\"",
",",
"None",
")",
"if",
"v1_ds",
"is",
"not",
"None",
":",
"dataset_types",
".",
"append",
"(",
"v1_ds",
")",
"if",
"v2_ds",
"is",
"not",
"None",
":",
"dataset_types",
".",
"append",
"(",
"v2_ds",
")",
"return",
"isinstance",
"(",
"ds",
",",
"tuple",
"(",
"dataset_types",
")",
")"
] | 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)
# Extract all label names and associated images
split_label_images = {} # dict[split_name][label_name] = list(img_paths)
for split_name in split_names:
split_dir = os.path.join(dl_manager.manual_dir, split_name)
split_label_images[split_name] = {
label_name: list_imgs(os.path.join(split_dir, label_name))
for label_name in list_folders(split_dir)
}
# Merge all label names from all splits to get the final list of labels
# Sorted list for determinism
labels = [split.keys() for split in split_label_images.values()]
labels = list(sorted(set(itertools.chain(*labels))))
# Could improve the automated encoding format detection
# Extract the list of all image paths
image_paths = [
image_paths
for label_images in split_label_images.values()
for image_paths in label_images.values()
]
if any(f.lower().endswith(".png") for f in itertools.chain(*image_paths)):
encoding_format = "png"
else:
encoding_format = "jpeg"
# Update the info.features. Those info will be automatically resored when
# the dataset is re-created
self.info.features["image"].set_encoding_format(encoding_format)
self.info.features["label"].names = labels
def num_examples(label_images):
return sum(len(imgs) for imgs in label_images.values())
# Define the splits
return [
tfds.core.SplitGenerator(
name=split_name,
# The number of shards is a dynamic function of the total
# number of images (between 0-10)
num_shards=min(10, max(num_examples(label_images) // 1000, 1)),
gen_kwargs=dict(label_images=label_images,),
) for split_name, label_images in split_label_images.items()
] | 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)
# Extract all label names and associated images
split_label_images = {} # dict[split_name][label_name] = list(img_paths)
for split_name in split_names:
split_dir = os.path.join(dl_manager.manual_dir, split_name)
split_label_images[split_name] = {
label_name: list_imgs(os.path.join(split_dir, label_name))
for label_name in list_folders(split_dir)
}
# Merge all label names from all splits to get the final list of labels
# Sorted list for determinism
labels = [split.keys() for split in split_label_images.values()]
labels = list(sorted(set(itertools.chain(*labels))))
# Could improve the automated encoding format detection
# Extract the list of all image paths
image_paths = [
image_paths
for label_images in split_label_images.values()
for image_paths in label_images.values()
]
if any(f.lower().endswith(".png") for f in itertools.chain(*image_paths)):
encoding_format = "png"
else:
encoding_format = "jpeg"
# Update the info.features. Those info will be automatically resored when
# the dataset is re-created
self.info.features["image"].set_encoding_format(encoding_format)
self.info.features["label"].names = labels
def num_examples(label_images):
return sum(len(imgs) for imgs in label_images.values())
# Define the splits
return [
tfds.core.SplitGenerator(
name=split_name,
# The number of shards is a dynamic function of the total
# number of images (between 0-10)
num_shards=min(10, max(num_examples(label_images) // 1000, 1)),
gen_kwargs=dict(label_images=label_images,),
) for split_name, label_images in split_label_images.items()
] | [
"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",
".",
"manual_dir",
")",
"# Extract all label names and associated images",
"split_label_images",
"=",
"{",
"}",
"# dict[split_name][label_name] = list(img_paths)",
"for",
"split_name",
"in",
"split_names",
":",
"split_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dl_manager",
".",
"manual_dir",
",",
"split_name",
")",
"split_label_images",
"[",
"split_name",
"]",
"=",
"{",
"label_name",
":",
"list_imgs",
"(",
"os",
".",
"path",
".",
"join",
"(",
"split_dir",
",",
"label_name",
")",
")",
"for",
"label_name",
"in",
"list_folders",
"(",
"split_dir",
")",
"}",
"# Merge all label names from all splits to get the final list of labels",
"# Sorted list for determinism",
"labels",
"=",
"[",
"split",
".",
"keys",
"(",
")",
"for",
"split",
"in",
"split_label_images",
".",
"values",
"(",
")",
"]",
"labels",
"=",
"list",
"(",
"sorted",
"(",
"set",
"(",
"itertools",
".",
"chain",
"(",
"*",
"labels",
")",
")",
")",
")",
"# Could improve the automated encoding format detection",
"# Extract the list of all image paths",
"image_paths",
"=",
"[",
"image_paths",
"for",
"label_images",
"in",
"split_label_images",
".",
"values",
"(",
")",
"for",
"image_paths",
"in",
"label_images",
".",
"values",
"(",
")",
"]",
"if",
"any",
"(",
"f",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\".png\"",
")",
"for",
"f",
"in",
"itertools",
".",
"chain",
"(",
"*",
"image_paths",
")",
")",
":",
"encoding_format",
"=",
"\"png\"",
"else",
":",
"encoding_format",
"=",
"\"jpeg\"",
"# Update the info.features. Those info will be automatically resored when",
"# the dataset is re-created",
"self",
".",
"info",
".",
"features",
"[",
"\"image\"",
"]",
".",
"set_encoding_format",
"(",
"encoding_format",
")",
"self",
".",
"info",
".",
"features",
"[",
"\"label\"",
"]",
".",
"names",
"=",
"labels",
"def",
"num_examples",
"(",
"label_images",
")",
":",
"return",
"sum",
"(",
"len",
"(",
"imgs",
")",
"for",
"imgs",
"in",
"label_images",
".",
"values",
"(",
")",
")",
"# Define the splits",
"return",
"[",
"tfds",
".",
"core",
".",
"SplitGenerator",
"(",
"name",
"=",
"split_name",
",",
"# The number of shards is a dynamic function of the total",
"# number of images (between 0-10)",
"num_shards",
"=",
"min",
"(",
"10",
",",
"max",
"(",
"num_examples",
"(",
"label_images",
")",
"//",
"1000",
",",
"1",
")",
")",
",",
"gen_kwargs",
"=",
"dict",
"(",
"label_images",
"=",
"label_images",
",",
")",
",",
")",
"for",
"split_name",
",",
"label_images",
"in",
"split_label_images",
".",
"items",
"(",
")",
"]"
] | 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",
",",
"\"label\"",
":",
"label",
",",
"}"
] | 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), 'w') as f:
f.write(context.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), 'w') as f:
f.write(context.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",
"+",
"_CITATION",
"+",
"_DESCRIPTION",
"+",
"_DATASET_DEFAULTS",
")",
"with",
"gfile",
".",
"GFile",
"(",
"file_path",
".",
"format",
"(",
"*",
"*",
"data",
")",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"context",
".",
"format",
"(",
"*",
"*",
"data",
")",
")"
] | 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",
"[",
"validation",
"]"
] | 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.
Yields:
dictionary with the file name, an image file objective, and label of each
imagenet validation data.
"""
# Get the current random seeds.
numpy_st0 = np.random.get_state()
# Set new random seeds.
np.random.seed(135)
logging.warning('Overwriting cv2 RNG seed.')
tfds.core.lazy_imports.cv2.setRNGSeed(357)
for example in super(Imagenet2012Corrupted,
self)._generate_examples_validation(archive, labels):
with tf.Graph().as_default():
tf_img = tf.image.decode_jpeg(example['image'].read(), channels=3)
image_np = tfds.as_numpy(tf_img)
example['image'] = self._get_corrupted_example(image_np)
yield example
# Reset the seeds back to their original values.
np.random.set_state(numpy_st0) | 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.
Yields:
dictionary with the file name, an image file objective, and label of each
imagenet validation data.
"""
# Get the current random seeds.
numpy_st0 = np.random.get_state()
# Set new random seeds.
np.random.seed(135)
logging.warning('Overwriting cv2 RNG seed.')
tfds.core.lazy_imports.cv2.setRNGSeed(357)
for example in super(Imagenet2012Corrupted,
self)._generate_examples_validation(archive, labels):
with tf.Graph().as_default():
tf_img = tf.image.decode_jpeg(example['image'].read(), channels=3)
image_np = tfds.as_numpy(tf_img)
example['image'] = self._get_corrupted_example(image_np)
yield example
# Reset the seeds back to their original values.
np.random.set_state(numpy_st0) | [
"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",
"(",
"135",
")",
"logging",
".",
"warning",
"(",
"'Overwriting cv2 RNG seed.'",
")",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"cv2",
".",
"setRNGSeed",
"(",
"357",
")",
"for",
"example",
"in",
"super",
"(",
"Imagenet2012Corrupted",
",",
"self",
")",
".",
"_generate_examples_validation",
"(",
"archive",
",",
"labels",
")",
":",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
":",
"tf_img",
"=",
"tf",
".",
"image",
".",
"decode_jpeg",
"(",
"example",
"[",
"'image'",
"]",
".",
"read",
"(",
")",
",",
"channels",
"=",
"3",
")",
"image_np",
"=",
"tfds",
".",
"as_numpy",
"(",
"tf_img",
")",
"example",
"[",
"'image'",
"]",
"=",
"self",
".",
"_get_corrupted_example",
"(",
"image_np",
")",
"yield",
"example",
"# Reset the seeds back to their original values.",
"np",
".",
"random",
".",
"set_state",
"(",
"numpy_st0",
")"
] | 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 objective, and label of each
imagenet validation data. | [
"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': corruptions.gaussian_noise,
'shot_noise': corruptions.shot_noise,
'impulse_noise': corruptions.impulse_noise,
'defocus_blur': corruptions.defocus_blur,
'frosted_glass_blur': corruptions.frosted_glass_blur,
'zoom_blur': corruptions.zoom_blur,
'fog': corruptions.fog,
'brightness': corruptions.brightness,
'contrast': corruptions.contrast,
'elastic': corruptions.elastic,
'pixelate': corruptions.pixelate,
'jpeg_compression': corruptions.jpeg_compression,
}[corruption_type](x, severity) | 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': corruptions.gaussian_noise,
'shot_noise': corruptions.shot_noise,
'impulse_noise': corruptions.impulse_noise,
'defocus_blur': corruptions.defocus_blur,
'frosted_glass_blur': corruptions.frosted_glass_blur,
'zoom_blur': corruptions.zoom_blur,
'fog': corruptions.fog,
'brightness': corruptions.brightness,
'contrast': corruptions.contrast,
'elastic': corruptions.elastic,
'pixelate': corruptions.pixelate,
'jpeg_compression': corruptions.jpeg_compression,
}[corruption_type](x, severity) | [
"def",
"_get_corrupted_example",
"(",
"self",
",",
"x",
")",
":",
"corruption_type",
"=",
"self",
".",
"builder_config",
".",
"corruption_type",
"severity",
"=",
"self",
".",
"builder_config",
".",
"severity",
"return",
"{",
"'gaussian_noise'",
":",
"corruptions",
".",
"gaussian_noise",
",",
"'shot_noise'",
":",
"corruptions",
".",
"shot_noise",
",",
"'impulse_noise'",
":",
"corruptions",
".",
"impulse_noise",
",",
"'defocus_blur'",
":",
"corruptions",
".",
"defocus_blur",
",",
"'frosted_glass_blur'",
":",
"corruptions",
".",
"frosted_glass_blur",
",",
"'zoom_blur'",
":",
"corruptions",
".",
"zoom_blur",
",",
"'fog'",
":",
"corruptions",
".",
"fog",
",",
"'brightness'",
":",
"corruptions",
".",
"brightness",
",",
"'contrast'",
":",
"corruptions",
".",
"contrast",
",",
"'elastic'",
":",
"corruptions",
".",
"elastic",
",",
"'pixelate'",
":",
"corruptions",
".",
"pixelate",
",",
"'jpeg_compression'",
":",
"corruptions",
".",
"jpeg_compression",
",",
"}",
"[",
"corruption_type",
"]",
"(",
"x",
",",
"severity",
")"
] | 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(shape2)
if shape1.ndims is None or shape2.ndims is None:
raise ValueError('Shapes must have known rank. Got %s and %s.' %
(shape1.ndims, shape2.ndims))
shape1.assert_same_rank(shape2)
shape1.assert_is_compatible_with(shape2) | 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(shape2)
if shape1.ndims is None or shape2.ndims is None:
raise ValueError('Shapes must have known rank. Got %s and %s.' %
(shape1.ndims, shape2.ndims))
shape1.assert_same_rank(shape2)
shape1.assert_is_compatible_with(shape2) | [
"def",
"assert_shape_match",
"(",
"shape1",
",",
"shape2",
")",
":",
"shape1",
"=",
"tf",
".",
"TensorShape",
"(",
"shape1",
")",
"shape2",
"=",
"tf",
".",
"TensorShape",
"(",
"shape2",
")",
"if",
"shape1",
".",
"ndims",
"is",
"None",
"or",
"shape2",
".",
"ndims",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Shapes must have known rank. Got %s and %s.'",
"%",
"(",
"shape1",
".",
"ndims",
",",
"shape2",
".",
"ndims",
")",
")",
"shape1",
".",
"assert_same_rank",
"(",
"shape2",
")",
"shape1",
".",
"assert_is_compatible_with",
"(",
"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",
"(",
"config",
"=",
"config",
",",
"graph",
"=",
"graph",
")"
] | 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.array(input_)
run_args = RunArgs(fct=fct, input=input_)
signature = self._build_signature(run_args)
if signature not in self._graph_run_cache:
graph_run = self._build_graph_run(run_args)
self._graph_run_cache[signature] = graph_run
else:
graph_run = self._graph_run_cache[signature]
# Then execute the cached graph
return graph_run.session.run(
graph_run.output,
feed_dict={graph_run.placeholder: input_},
) | 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.array(input_)
run_args = RunArgs(fct=fct, input=input_)
signature = self._build_signature(run_args)
if signature not in self._graph_run_cache:
graph_run = self._build_graph_run(run_args)
self._graph_run_cache[signature] = graph_run
else:
graph_run = self._graph_run_cache[signature]
# Then execute the cached graph
return graph_run.session.run(
graph_run.output,
feed_dict={graph_run.placeholder: input_},
) | [
"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 the first time encountered",
"if",
"not",
"isinstance",
"(",
"input_",
",",
"np",
".",
"ndarray",
")",
":",
"input_",
"=",
"np",
".",
"array",
"(",
"input_",
")",
"run_args",
"=",
"RunArgs",
"(",
"fct",
"=",
"fct",
",",
"input",
"=",
"input_",
")",
"signature",
"=",
"self",
".",
"_build_signature",
"(",
"run_args",
")",
"if",
"signature",
"not",
"in",
"self",
".",
"_graph_run_cache",
":",
"graph_run",
"=",
"self",
".",
"_build_graph_run",
"(",
"run_args",
")",
"self",
".",
"_graph_run_cache",
"[",
"signature",
"]",
"=",
"graph_run",
"else",
":",
"graph_run",
"=",
"self",
".",
"_graph_run_cache",
"[",
"signature",
"]",
"# Then execute the cached graph",
"return",
"graph_run",
".",
"session",
".",
"run",
"(",
"graph_run",
".",
"output",
",",
"feed_dict",
"=",
"{",
"graph_run",
".",
"placeholder",
":",
"input_",
"}",
",",
")"
] | 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_ = run_args.input
placeholder = tf.compat.v1.placeholder(
dtype=input_.dtype, shape=input_.shape)
output = run_args.fct(placeholder)
return GraphRun(
session=raw_nogpu_session(g),
graph=g,
placeholder=placeholder,
output=output,
) | 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_ = run_args.input
placeholder = tf.compat.v1.placeholder(
dtype=input_.dtype, shape=input_.shape)
output = run_args.fct(placeholder)
return GraphRun(
session=raw_nogpu_session(g),
graph=g,
placeholder=placeholder,
output=output,
) | [
"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",
"(",
")",
"as",
"g",
":",
"# Create placeholder",
"input_",
"=",
"run_args",
".",
"input",
"placeholder",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"placeholder",
"(",
"dtype",
"=",
"input_",
".",
"dtype",
",",
"shape",
"=",
"input_",
".",
"shape",
")",
"output",
"=",
"run_args",
".",
"fct",
"(",
"placeholder",
")",
"return",
"GraphRun",
"(",
"session",
"=",
"raw_nogpu_session",
"(",
"g",
")",
",",
"graph",
"=",
"g",
",",
"placeholder",
"=",
"placeholder",
",",
"output",
"=",
"output",
",",
")"
] | 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(video_or_path_or_fobj, video_temp_path, overwrite=True)
encoded_video = self._ffmpeg_decode(video_temp_path)
finally:
os.unlink(video_temp_path)
else:
encoded_video = self._ffmpeg_decode(video_or_path_or_fobj)
elif hasattr(video_or_path_or_fobj, 'read'):
encoded_video = self._ffmpeg_decode(video_or_path_or_fobj)
else:
encoded_video = video_or_path_or_fobj
return super(Video, self).encode_example(encoded_video) | 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(video_or_path_or_fobj, video_temp_path, overwrite=True)
encoded_video = self._ffmpeg_decode(video_temp_path)
finally:
os.unlink(video_temp_path)
else:
encoded_video = self._ffmpeg_decode(video_or_path_or_fobj)
elif hasattr(video_or_path_or_fobj, 'read'):
encoded_video = self._ffmpeg_decode(video_or_path_or_fobj)
else:
encoded_video = video_or_path_or_fobj
return super(Video, self).encode_example(encoded_video) | [
"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",
")",
":",
"_",
",",
"video_temp_path",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"try",
":",
"tf",
".",
"gfile",
".",
"Copy",
"(",
"video_or_path_or_fobj",
",",
"video_temp_path",
",",
"overwrite",
"=",
"True",
")",
"encoded_video",
"=",
"self",
".",
"_ffmpeg_decode",
"(",
"video_temp_path",
")",
"finally",
":",
"os",
".",
"unlink",
"(",
"video_temp_path",
")",
"else",
":",
"encoded_video",
"=",
"self",
".",
"_ffmpeg_decode",
"(",
"video_or_path_or_fobj",
")",
"elif",
"hasattr",
"(",
"video_or_path_or_fobj",
",",
"'read'",
")",
":",
"encoded_video",
"=",
"self",
".",
"_ffmpeg_decode",
"(",
"video_or_path_or_fobj",
")",
"else",
":",
"encoded_video",
"=",
"video_or_path_or_fobj",
"return",
"super",
"(",
"Video",
",",
"self",
")",
".",
"encode_example",
"(",
"encoded_video",
")"
] | 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)
if not res: # if anything other than .png; skip
continue
label = res.group(2).lower()
yield {
"image": fobj,
"label": label,
} | 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)
if not res: # if anything other than .png; skip
continue
label = res.group(2).lower()
yield {
"image": fobj,
"label": label,
} | [
"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",
"=",
"res",
".",
"group",
"(",
"2",
")",
".",
"lower",
"(",
")",
"yield",
"{",
"\"image\"",
":",
"fobj",
",",
"\"label\"",
":",
"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_data:
survive_val = row.pop("survived")
yield {
"survived": convert_to_label(survive_val, _SURVIVED_DICT),
"features": {
name: FEATURE_DICT[name][1](value)
for name, value in row.items()
}
} | 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_data:
survive_val = row.pop("survived")
yield {
"survived": convert_to_label(survive_val, _SURVIVED_DICT),
"features": {
name: FEATURE_DICT[name][1](value)
for name, value in row.items()
}
} | [
"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",
":",
"survive_val",
"=",
"row",
".",
"pop",
"(",
"\"survived\"",
")",
"yield",
"{",
"\"survived\"",
":",
"convert_to_label",
"(",
"survive_val",
",",
"_SURVIVED_DICT",
")",
",",
"\"features\"",
":",
"{",
"name",
":",
"FEATURE_DICT",
"[",
"name",
"]",
"[",
"1",
"]",
"(",
"value",
")",
"for",
"name",
",",
"value",
"in",
"row",
".",
"items",
"(",
")",
"}",
"}"
] | 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",
"[",
"idx",
"]",
":",
"idx",
"-=",
"1",
"if",
"idx",
"==",
"-",
"1",
":",
"ids",
"=",
"ids",
"else",
":",
"ids",
"=",
"ids",
"[",
":",
"idx",
"+",
"1",
"]",
"return",
"[",
"i",
"-",
"1",
"for",
"i",
"in",
"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)
reserved_tokens_re = _make_reserved_tokens_re(reserved_tokens)
return reserved_tokens, reserved_tokens_re | 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)
reserved_tokens_re = _make_reserved_tokens_re(reserved_tokens)
return reserved_tokens, reserved_tokens_re | [
"def",
"_prepare_reserved_tokens",
"(",
"reserved_tokens",
")",
":",
"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",
")",
"reserved_tokens_re",
"=",
"_make_reserved_tokens_re",
"(",
"reserved_tokens",
")",
"return",
"reserved_tokens",
",",
"reserved_tokens_re"
] | 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 reserved_tokens_re | 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 reserved_tokens_re | [
"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)\"",
"%",
"\"|\"",
".",
"join",
"(",
"escaped_tokens",
")",
"reserved_tokens_re",
"=",
"_re_compile",
"(",
"pattern",
")",
"return",
"reserved_tokens_re"
] | 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, sort_keys=True))
with tf.io.gfile.GFile(filename, "wb") as f:
for line in [header_line, metadata_line]:
f.write(tf.compat.as_bytes(line))
f.write(tf.compat.as_bytes("\n"))
if lines:
f.write(tf.compat.as_bytes("\n".join(lines)))
f.write(tf.compat.as_bytes("\n")) | 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, sort_keys=True))
with tf.io.gfile.GFile(filename, "wb") as f:
for line in [header_line, metadata_line]:
f.write(tf.compat.as_bytes(line))
f.write(tf.compat.as_bytes("\n"))
if lines:
f.write(tf.compat.as_bytes("\n".join(lines)))
f.write(tf.compat.as_bytes("\n")) | [
"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",
"=",
"\"%s%s\"",
"%",
"(",
"_METADATA_PREFIX",
",",
"json",
".",
"dumps",
"(",
"metadata_dict",
",",
"sort_keys",
"=",
"True",
")",
")",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"filename",
",",
"\"wb\"",
")",
"as",
"f",
":",
"for",
"line",
"in",
"[",
"header_line",
",",
"metadata_line",
"]",
":",
"f",
".",
"write",
"(",
"tf",
".",
"compat",
".",
"as_bytes",
"(",
"line",
")",
")",
"f",
".",
"write",
"(",
"tf",
".",
"compat",
".",
"as_bytes",
"(",
"\"\\n\"",
")",
")",
"if",
"lines",
":",
"f",
".",
"write",
"(",
"tf",
".",
"compat",
".",
"as_bytes",
"(",
"\"\\n\"",
".",
"join",
"(",
"lines",
")",
")",
")",
"f",
".",
"write",
"(",
"tf",
".",
"compat",
".",
"as_bytes",
"(",
"\"\\n\"",
")",
")"
] | 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("File {fname} does not seem to have been created from "
"{name}.save_to_file.".format(
fname=filename, name=cls_name))
metadata_dict = json.loads(lines[1][len(_METADATA_PREFIX):])
return lines[2:], metadata_dict | 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("File {fname} does not seem to have been created from "
"{name}.save_to_file.".format(
fname=filename, name=cls_name))
metadata_dict = json.loads(lines[1][len(_METADATA_PREFIX):])
return lines[2:], metadata_dict | [
"def",
"read_lines_from_file",
"(",
"cls_name",
",",
"filename",
")",
":",
"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",
"(",
"\"File {fname} does not seem to have been created from \"",
"\"{name}.save_to_file.\"",
".",
"format",
"(",
"fname",
"=",
"filename",
",",
"name",
"=",
"cls_name",
")",
")",
"metadata_dict",
"=",
"json",
".",
"loads",
"(",
"lines",
"[",
"1",
"]",
"[",
"len",
"(",
"_METADATA_PREFIX",
")",
":",
"]",
")",
"return",
"lines",
"[",
"2",
":",
"]",
",",
"metadata_dict"
] | 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_tokens:
toks.append(substr)
else:
toks.extend(self._alphanum_re.split(substr))
# Filter out empty strings
toks = [t for t in toks if t]
return toks | 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_tokens:
toks.append(substr)
else:
toks.extend(self._alphanum_re.split(substr))
# Filter out empty strings
toks = [t for t in toks if t]
return toks | [
"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",
".",
"split",
"(",
"s",
")",
"else",
":",
"substrs",
"=",
"[",
"s",
"]",
"toks",
"=",
"[",
"]",
"for",
"substr",
"in",
"substrs",
":",
"if",
"substr",
"in",
"self",
".",
"reserved_tokens",
":",
"toks",
".",
"append",
"(",
"substr",
")",
"else",
":",
"toks",
".",
"extend",
"(",
"self",
".",
"_alphanum_re",
".",
"split",
"(",
"substr",
")",
")",
"# Filter out empty strings",
"toks",
"=",
"[",
"t",
"for",
"t",
"in",
"toks",
"if",
"t",
"]",
"return",
"toks"
] | 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 generation. The mapping shard_id=>num_examples
# should be computed during generation.
# Minimum number of example per shards
num_example_in_shard = total_num_examples // num_shards
shard_id2num_examples = [num_example_in_shard for _ in range(num_shards)]
# If there are remaining examples, we add them to the first shards
for shard_id in range(total_num_examples % num_shards):
shard_id2num_examples[shard_id] += 1
return shard_id2num_examples | 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 generation. The mapping shard_id=>num_examples
# should be computed during generation.
# Minimum number of example per shards
num_example_in_shard = total_num_examples // num_shards
shard_id2num_examples = [num_example_in_shard for _ in range(num_shards)]
# If there are remaining examples, we add them to the first shards
for shard_id in range(total_num_examples % num_shards):
shard_id2num_examples[shard_id] += 1
return shard_id2num_examples | [
"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 shard_id=>num_examples",
"# should be computed during generation.",
"# Minimum number of example per shards",
"num_example_in_shard",
"=",
"total_num_examples",
"//",
"num_shards",
"shard_id2num_examples",
"=",
"[",
"num_example_in_shard",
"for",
"_",
"in",
"range",
"(",
"num_shards",
")",
"]",
"# If there are remaining examples, we add them to the first shards",
"for",
"shard_id",
"in",
"range",
"(",
"total_num_examples",
"%",
"num_shards",
")",
":",
"shard_id2num_examples",
"[",
"shard_id",
"]",
"+=",
"1",
"return",
"shard_id2num_examples"
] | 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_examples)
mask_offsets = []
total_num_examples = 0
for num_examples_in_shard in shard_id2num_examples:
# The offset (nb of examples to skip in the next shard) correspond to the
# number of examples remaining in the current shard
mask_offsets.append(total_num_examples % 100)
total_num_examples += num_examples_in_shard
return mask_offsets | 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_examples)
mask_offsets = []
total_num_examples = 0
for num_examples_in_shard in shard_id2num_examples:
# The offset (nb of examples to skip in the next shard) correspond to the
# number of examples remaining in the current shard
mask_offsets.append(total_num_examples % 100)
total_num_examples += num_examples_in_shard
return mask_offsets | [
"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",
":",
"# The offset (nb of examples to skip in the next shard) correspond to the",
"# number of examples remaining in the current shard",
"mask_offsets",
".",
"append",
"(",
"total_num_examples",
"%",
"100",
")",
"total_num_examples",
"+=",
"num_examples_in_shard",
"return",
"mask_offsets"
] | 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:
return False
return True | 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:
return False
return True | [
"def",
"check_splits_equals",
"(",
"splits1",
",",
"splits2",
")",
":",
"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",
":",
"return",
"False",
"return",
"True"
] | 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 with Named splits correctly.",
"super",
"(",
"SplitDict",
",",
"self",
")",
".",
"__setitem__",
"(",
"split_info",
".",
"name",
",",
"split_info",
")"
] | 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_dict | 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_dict | [
"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_proto",
")",
"split_dict",
".",
"add",
"(",
"split_info",
")",
"return",
"split_dict"
] | 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",
".",
"name",
")"
] | 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 decorator which lock all functions to which it
is applied under a same lock
"""
lock = threading.Lock()
def lock_decorator(fn):
@functools.wraps(fn)
def lock_decorated(*args, **kwargs):
with lock:
return fn(*args, **kwargs)
return lock_decorated
return lock_decorator | 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 decorator which lock all functions to which it
is applied under a same lock
"""
lock = threading.Lock()
def lock_decorator(fn):
@functools.wraps(fn)
def lock_decorated(*args, **kwargs):
with lock:
return fn(*args, **kwargs)
return lock_decorated
return lock_decorator | [
"def",
"build_synchronize_decorator",
"(",
")",
":",
"lock",
"=",
"threading",
".",
"Lock",
"(",
")",
"def",
"lock_decorator",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"lock_decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"lock",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"lock_decorated",
"return",
"lock_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 decorator which lock all functions to which it
is applied under a same lock | [
"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 = [
None,
tfds.features.text.TextEncoderConfig(
name="bytes", encoder=tfds.features.text.ByteTextEncoder()),
tfds.features.text.TextEncoderConfig(
name="subwords8k",
encoder_cls=tfds.features.text.SubwordTextEncoder,
vocab_size=2**13),
tfds.features.text.TextEncoderConfig(
name="subwords32k",
encoder_cls=tfds.features.text.SubwordTextEncoder,
vocab_size=2**15),
]
version = "0.1.0"
configs = []
for text_encoder_config in text_encoder_configs:
for data in _DATA_OPTIONS:
config = LibrispeechConfig(
version=version, text_encoder_config=text_encoder_config, data=data)
configs.append(config)
return 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 = [
None,
tfds.features.text.TextEncoderConfig(
name="bytes", encoder=tfds.features.text.ByteTextEncoder()),
tfds.features.text.TextEncoderConfig(
name="subwords8k",
encoder_cls=tfds.features.text.SubwordTextEncoder,
vocab_size=2**13),
tfds.features.text.TextEncoderConfig(
name="subwords32k",
encoder_cls=tfds.features.text.SubwordTextEncoder,
vocab_size=2**15),
]
version = "0.1.0"
configs = []
for text_encoder_config in text_encoder_configs:
for data in _DATA_OPTIONS:
config = LibrispeechConfig(
version=version, text_encoder_config=text_encoder_config, data=data)
configs.append(config)
return configs | [
"def",
"_make_builder_configs",
"(",
")",
":",
"text_encoder_configs",
"=",
"[",
"None",
",",
"tfds",
".",
"features",
".",
"text",
".",
"TextEncoderConfig",
"(",
"name",
"=",
"\"bytes\"",
",",
"encoder",
"=",
"tfds",
".",
"features",
".",
"text",
".",
"ByteTextEncoder",
"(",
")",
")",
",",
"tfds",
".",
"features",
".",
"text",
".",
"TextEncoderConfig",
"(",
"name",
"=",
"\"subwords8k\"",
",",
"encoder_cls",
"=",
"tfds",
".",
"features",
".",
"text",
".",
"SubwordTextEncoder",
",",
"vocab_size",
"=",
"2",
"**",
"13",
")",
",",
"tfds",
".",
"features",
".",
"text",
".",
"TextEncoderConfig",
"(",
"name",
"=",
"\"subwords32k\"",
",",
"encoder_cls",
"=",
"tfds",
".",
"features",
".",
"text",
".",
"SubwordTextEncoder",
",",
"vocab_size",
"=",
"2",
"**",
"15",
")",
",",
"]",
"version",
"=",
"\"0.1.0\"",
"configs",
"=",
"[",
"]",
"for",
"text_encoder_config",
"in",
"text_encoder_configs",
":",
"for",
"data",
"in",
"_DATA_OPTIONS",
":",
"config",
"=",
"LibrispeechConfig",
"(",
"version",
"=",
"version",
",",
"text_encoder_config",
"=",
"text_encoder_config",
",",
"data",
"=",
"data",
")",
"configs",
".",
"append",
"(",
"config",
")",
"return",
"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>` | [
"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_file:
continue
assert len(transcript_file) == 1
transcript_file, = transcript_file
transcripts = {}
with tf.io.gfile.GFile(os.path.join(path, transcript_file)) as f:
for line in f:
line = line.strip()
key, transcript = line.split(" ", 1)
transcripts[key] = transcript
audio_files = [f for f in files if not f.endswith(".txt")]
for audio_file in audio_files:
assert audio_file.endswith(".flac")
key = audio_file[:-len(".flac")]
transcript = transcripts[key]
speaker_id, chapter_id = [int(el) for el in key.split("-")[:2]]
yield LibrispeechExample(
speaker_id=speaker_id,
chapter_id=chapter_id,
audio_file=os.path.join(path, audio_file),
transcript=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_file:
continue
assert len(transcript_file) == 1
transcript_file, = transcript_file
transcripts = {}
with tf.io.gfile.GFile(os.path.join(path, transcript_file)) as f:
for line in f:
line = line.strip()
key, transcript = line.split(" ", 1)
transcripts[key] = transcript
audio_files = [f for f in files if not f.endswith(".txt")]
for audio_file in audio_files:
assert audio_file.endswith(".flac")
key = audio_file[:-len(".flac")]
transcript = transcripts[key]
speaker_id, chapter_id = [int(el) for el in key.split("-")[:2]]
yield LibrispeechExample(
speaker_id=speaker_id,
chapter_id=chapter_id,
audio_file=os.path.join(path, audio_file),
transcript=transcript) | [
"def",
"_walk_librispeech_dir",
"(",
"directory",
")",
":",
"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_file",
":",
"continue",
"assert",
"len",
"(",
"transcript_file",
")",
"==",
"1",
"transcript_file",
",",
"=",
"transcript_file",
"transcripts",
"=",
"{",
"}",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"transcript_file",
")",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"key",
",",
"transcript",
"=",
"line",
".",
"split",
"(",
"\" \"",
",",
"1",
")",
"transcripts",
"[",
"key",
"]",
"=",
"transcript",
"audio_files",
"=",
"[",
"f",
"for",
"f",
"in",
"files",
"if",
"not",
"f",
".",
"endswith",
"(",
"\".txt\"",
")",
"]",
"for",
"audio_file",
"in",
"audio_files",
":",
"assert",
"audio_file",
".",
"endswith",
"(",
"\".flac\"",
")",
"key",
"=",
"audio_file",
"[",
":",
"-",
"len",
"(",
"\".flac\"",
")",
"]",
"transcript",
"=",
"transcripts",
"[",
"key",
"]",
"speaker_id",
",",
"chapter_id",
"=",
"[",
"int",
"(",
"el",
")",
"for",
"el",
"in",
"key",
".",
"split",
"(",
"\"-\"",
")",
"[",
":",
"2",
"]",
"]",
"yield",
"LibrispeechExample",
"(",
"speaker_id",
"=",
"speaker_id",
",",
"chapter_id",
"=",
"chapter_id",
",",
"audio_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"audio_file",
")",
",",
"transcript",
"=",
"transcript",
")"
] | 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")
if self.data == "all":
urls[tfds.Split.TRAIN].extend(["train_clean360", "train_other500"])
urls[tfds.Split.VALIDATION].append("dev_other")
urls[tfds.Split.TEST].append("test_other")
urls = {
split: [_DL_URLS[name] for name in names
] for split, names in urls.items()
}
return urls | 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")
if self.data == "all":
urls[tfds.Split.TRAIN].extend(["train_clean360", "train_other500"])
urls[tfds.Split.VALIDATION].append("dev_other")
urls[tfds.Split.TEST].append("test_other")
urls = {
split: [_DL_URLS[name] for name in names
] for split, names in urls.items()
}
return urls | [
"def",
"download_urls",
"(",
"self",
")",
":",
"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\"",
")",
"if",
"self",
".",
"data",
"==",
"\"all\"",
":",
"urls",
"[",
"tfds",
".",
"Split",
".",
"TRAIN",
"]",
".",
"extend",
"(",
"[",
"\"train_clean360\"",
",",
"\"train_other500\"",
"]",
")",
"urls",
"[",
"tfds",
".",
"Split",
".",
"VALIDATION",
"]",
".",
"append",
"(",
"\"dev_other\"",
")",
"urls",
"[",
"tfds",
".",
"Split",
".",
"TEST",
"]",
".",
"append",
"(",
"\"test_other\"",
")",
"urls",
"=",
"{",
"split",
":",
"[",
"_DL_URLS",
"[",
"name",
"]",
"for",
"name",
"in",
"names",
"]",
"for",
"split",
",",
"names",
"in",
"urls",
".",
"items",
"(",
")",
"}",
"return",
"urls"
] | 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:
failed_parse = True
if failed_parse or not 0 <= int_value < self._num_classes:
raise ValueError("Invalid string class label %s" % str_value)
return int_value | 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:
failed_parse = True
if failed_parse or not 0 <= int_value < self._num_classes:
raise ValueError("Invalid string class label %s" % str_value)
return int_value | [
"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 to integerize",
"failed_parse",
"=",
"False",
"try",
":",
"int_value",
"=",
"int",
"(",
"str_value",
")",
"except",
"ValueError",
":",
"failed_parse",
"=",
"True",
"if",
"failed_parse",
"or",
"not",
"0",
"<=",
"int_value",
"<",
"self",
".",
"_num_classes",
":",
"raise",
"ValueError",
"(",
"\"Invalid string class label %s\"",
"%",
"str_value",
")",
"return",
"int_value"
] | 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_value]
# No names provided, return str(int)
if not 0 <= int_value < self._num_classes:
raise ValueError("Invalid integer class label %d" % int_value)
return tf.compat.as_text(str(int_value)) | 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_value]
# No names provided, return str(int)
if not 0 <= int_value < self._num_classes:
raise ValueError("Invalid integer class label %d" % int_value)
return tf.compat.as_text(str(int_value)) | [
"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",
"self",
".",
"_int2str",
"[",
"int_value",
"]",
"# No names provided, return str(int)",
"if",
"not",
"0",
"<=",
"int_value",
"<",
"self",
".",
"_num_classes",
":",
"raise",
"ValueError",
"(",
"\"Invalid integer class label %d\"",
"%",
"int_value",
")",
"return",
"tf",
".",
"compat",
".",
"as_text",
"(",
"str",
"(",
"int_value",
")",
")"
] | 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 = collections.defaultdict(int)
for s in generator:
s = tf.compat.as_text(s)
if max_chars and (num_chars + len(s)) >= max_chars:
s = s[:(max_chars - num_chars)]
tokens = tokenizer.tokenize(s)
tokens = _prepare_tokens_for_encode(tokens)
for t in tokens:
token_counts[t] += 1
if max_chars:
num_chars += len(s)
if num_chars > max_chars:
break
return token_counts | 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 = collections.defaultdict(int)
for s in generator:
s = tf.compat.as_text(s)
if max_chars and (num_chars + len(s)) >= max_chars:
s = s[:(max_chars - num_chars)]
tokens = tokenizer.tokenize(s)
tokens = _prepare_tokens_for_encode(tokens)
for t in tokens:
token_counts[t] += 1
if max_chars:
num_chars += len(s)
if num_chars > max_chars:
break
return token_counts | [
"def",
"_token_counts_from_generator",
"(",
"generator",
",",
"max_chars",
",",
"reserved_tokens",
")",
":",
"reserved_tokens",
"=",
"list",
"(",
"reserved_tokens",
")",
"+",
"[",
"_UNDERSCORE_REPLACEMENT",
"]",
"tokenizer",
"=",
"text_encoder",
".",
"Tokenizer",
"(",
"alphanum_only",
"=",
"False",
",",
"reserved_tokens",
"=",
"reserved_tokens",
")",
"num_chars",
"=",
"0",
"token_counts",
"=",
"collections",
".",
"defaultdict",
"(",
"int",
")",
"for",
"s",
"in",
"generator",
":",
"s",
"=",
"tf",
".",
"compat",
".",
"as_text",
"(",
"s",
")",
"if",
"max_chars",
"and",
"(",
"num_chars",
"+",
"len",
"(",
"s",
")",
")",
">=",
"max_chars",
":",
"s",
"=",
"s",
"[",
":",
"(",
"max_chars",
"-",
"num_chars",
")",
"]",
"tokens",
"=",
"tokenizer",
".",
"tokenize",
"(",
"s",
")",
"tokens",
"=",
"_prepare_tokens_for_encode",
"(",
"tokens",
")",
"for",
"t",
"in",
"tokens",
":",
"token_counts",
"[",
"t",
"]",
"+=",
"1",
"if",
"max_chars",
":",
"num_chars",
"+=",
"len",
"(",
"s",
")",
"if",
"num_chars",
">",
"max_chars",
":",
"break",
"return",
"token_counts"
] | 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 "
"building the vocabulary scale quadratically in the length of the "
"longest token.")
for t in reserved_tokens:
if t.endswith("_") or not text_encoder.is_mixed_alphanum(t):
raise ValueError(
"Reserved tokens must not end with _ and they must contain a mix "
"of alphanumeric and non-alphanumeric characters. For example, "
"'<EOS>'.")
# Minimum vocab size = bytes + pad + 1
minimum_vocab_size = text_encoder.NUM_BYTES + 1 + 1
if target_vocab_size < minimum_vocab_size:
raise ValueError("target_vocab_size must be >= %d. Got %d" %
(minimum_vocab_size, target_vocab_size)) | 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 "
"building the vocabulary scale quadratically in the length of the "
"longest token.")
for t in reserved_tokens:
if t.endswith("_") or not text_encoder.is_mixed_alphanum(t):
raise ValueError(
"Reserved tokens must not end with _ and they must contain a mix "
"of alphanumeric and non-alphanumeric characters. For example, "
"'<EOS>'.")
# Minimum vocab size = bytes + pad + 1
minimum_vocab_size = text_encoder.NUM_BYTES + 1 + 1
if target_vocab_size < minimum_vocab_size:
raise ValueError("target_vocab_size must be >= %d. Got %d" %
(minimum_vocab_size, target_vocab_size)) | [
"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 \"",
"\"building the vocabulary scale quadratically in the length of the \"",
"\"longest token.\"",
")",
"for",
"t",
"in",
"reserved_tokens",
":",
"if",
"t",
".",
"endswith",
"(",
"\"_\"",
")",
"or",
"not",
"text_encoder",
".",
"is_mixed_alphanum",
"(",
"t",
")",
":",
"raise",
"ValueError",
"(",
"\"Reserved tokens must not end with _ and they must contain a mix \"",
"\"of alphanumeric and non-alphanumeric characters. For example, \"",
"\"'<EOS>'.\"",
")",
"# Minimum vocab size = bytes + pad + 1",
"minimum_vocab_size",
"=",
"text_encoder",
".",
"NUM_BYTES",
"+",
"1",
"+",
"1",
"if",
"target_vocab_size",
"<",
"minimum_vocab_size",
":",
"raise",
"ValueError",
"(",
"\"target_vocab_size must be >= %d. Got %d\"",
"%",
"(",
"minimum_vocab_size",
",",
"target_vocab_size",
")",
")"
] | 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<str>` prepared tokens.
"""
prepared_tokens = []
def _prepare_token(t, next_t):
skip_next = False
t = _escape(t)
# If next token is a single space, add _ suffix to token and skip the
# empty space.
if next_t == " ":
t += "_"
skip_next = True
return t, skip_next
next_tokens = tokens[1:] + [None]
skip_single_token = False
for token, next_token in zip(tokens, next_tokens):
if skip_single_token:
skip_single_token = False
continue
# If the user-supplied string contains the underscore replacement string,
# break it into 2 tokens and encode those separately.
if token == _UNDERSCORE_REPLACEMENT:
t1, t2 = _UNDERSCORE_REPLACEMENT[:2], _UNDERSCORE_REPLACEMENT[2:]
t1, _ = _prepare_token(t1, None)
t2, _ = _prepare_token(t2, next_token)
prepared_tokens.append(t1)
prepared_tokens.append(t2)
continue
token, skip_single_token = _prepare_token(token, next_token)
prepared_tokens.append(token)
return prepared_tokens | 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<str>` prepared tokens.
"""
prepared_tokens = []
def _prepare_token(t, next_t):
skip_next = False
t = _escape(t)
# If next token is a single space, add _ suffix to token and skip the
# empty space.
if next_t == " ":
t += "_"
skip_next = True
return t, skip_next
next_tokens = tokens[1:] + [None]
skip_single_token = False
for token, next_token in zip(tokens, next_tokens):
if skip_single_token:
skip_single_token = False
continue
# If the user-supplied string contains the underscore replacement string,
# break it into 2 tokens and encode those separately.
if token == _UNDERSCORE_REPLACEMENT:
t1, t2 = _UNDERSCORE_REPLACEMENT[:2], _UNDERSCORE_REPLACEMENT[2:]
t1, _ = _prepare_token(t1, None)
t2, _ = _prepare_token(t2, next_token)
prepared_tokens.append(t1)
prepared_tokens.append(t2)
continue
token, skip_single_token = _prepare_token(token, next_token)
prepared_tokens.append(token)
return prepared_tokens | [
"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 _ suffix to token and skip the",
"# empty space.",
"if",
"next_t",
"==",
"\" \"",
":",
"t",
"+=",
"\"_\"",
"skip_next",
"=",
"True",
"return",
"t",
",",
"skip_next",
"next_tokens",
"=",
"tokens",
"[",
"1",
":",
"]",
"+",
"[",
"None",
"]",
"skip_single_token",
"=",
"False",
"for",
"token",
",",
"next_token",
"in",
"zip",
"(",
"tokens",
",",
"next_tokens",
")",
":",
"if",
"skip_single_token",
":",
"skip_single_token",
"=",
"False",
"continue",
"# If the user-supplied string contains the underscore replacement string,",
"# break it into 2 tokens and encode those separately.",
"if",
"token",
"==",
"_UNDERSCORE_REPLACEMENT",
":",
"t1",
",",
"t2",
"=",
"_UNDERSCORE_REPLACEMENT",
"[",
":",
"2",
"]",
",",
"_UNDERSCORE_REPLACEMENT",
"[",
"2",
":",
"]",
"t1",
",",
"_",
"=",
"_prepare_token",
"(",
"t1",
",",
"None",
")",
"t2",
",",
"_",
"=",
"_prepare_token",
"(",
"t2",
",",
"next_token",
")",
"prepared_tokens",
".",
"append",
"(",
"t1",
")",
"prepared_tokens",
".",
"append",
"(",
"t2",
")",
"continue",
"token",
",",
"skip_single_token",
"=",
"_prepare_token",
"(",
"token",
",",
"next_token",
")",
"prepared_tokens",
".",
"append",
"(",
"token",
")",
"return",
"prepared_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<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",
")",
"ids",
"=",
"[",
"]",
"for",
"token",
"in",
"tokens",
":",
"ids",
".",
"extend",
"(",
"self",
".",
"_token_to_ids",
"(",
"token",
")",
")",
"return",
"text_encoder",
".",
"pad_incr",
"(",
"ids",
")"
] | 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
# all together. Invalid byte sequences are replaced with the unicode
# replacement (i.e. unknown) character U+FFFD.
prev_bytes = []
def consume_prev_bytes():
if prev_bytes:
bytestr = b"".join(prev_bytes)
bytes_text = bytestr.decode("utf-8", "replace")
subwords.append(bytes_text)
return []
for subword_id in subword_ids:
subword = self._id_to_subword(subword_id)
if isinstance(subword, six.binary_type):
# Byte-encoded
prev_bytes.append(subword)
else:
# If there were bytes previously, convert to unicode.
prev_bytes = consume_prev_bytes()
trimmed, add_space = _trim_underscore_and_tell(subword)
subwords.append(trimmed)
if add_space:
subwords.append(" ")
# If there were trailing bytes, convert to unicode.
prev_bytes = consume_prev_bytes()
return tf.compat.as_text("".join(subwords)) | 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
# all together. Invalid byte sequences are replaced with the unicode
# replacement (i.e. unknown) character U+FFFD.
prev_bytes = []
def consume_prev_bytes():
if prev_bytes:
bytestr = b"".join(prev_bytes)
bytes_text = bytestr.decode("utf-8", "replace")
subwords.append(bytes_text)
return []
for subword_id in subword_ids:
subword = self._id_to_subword(subword_id)
if isinstance(subword, six.binary_type):
# Byte-encoded
prev_bytes.append(subword)
else:
# If there were bytes previously, convert to unicode.
prev_bytes = consume_prev_bytes()
trimmed, add_space = _trim_underscore_and_tell(subword)
subwords.append(trimmed)
if add_space:
subwords.append(" ")
# If there were trailing bytes, convert to unicode.
prev_bytes = consume_prev_bytes()
return tf.compat.as_text("".join(subwords)) | [
"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",
"# possibly multiple bytes, we attempt to decode contiguous lists of bytes",
"# all together. Invalid byte sequences are replaced with the unicode",
"# replacement (i.e. unknown) character U+FFFD.",
"prev_bytes",
"=",
"[",
"]",
"def",
"consume_prev_bytes",
"(",
")",
":",
"if",
"prev_bytes",
":",
"bytestr",
"=",
"b\"\"",
".",
"join",
"(",
"prev_bytes",
")",
"bytes_text",
"=",
"bytestr",
".",
"decode",
"(",
"\"utf-8\"",
",",
"\"replace\"",
")",
"subwords",
".",
"append",
"(",
"bytes_text",
")",
"return",
"[",
"]",
"for",
"subword_id",
"in",
"subword_ids",
":",
"subword",
"=",
"self",
".",
"_id_to_subword",
"(",
"subword_id",
")",
"if",
"isinstance",
"(",
"subword",
",",
"six",
".",
"binary_type",
")",
":",
"# Byte-encoded",
"prev_bytes",
".",
"append",
"(",
"subword",
")",
"else",
":",
"# If there were bytes previously, convert to unicode.",
"prev_bytes",
"=",
"consume_prev_bytes",
"(",
")",
"trimmed",
",",
"add_space",
"=",
"_trim_underscore_and_tell",
"(",
"subword",
")",
"subwords",
".",
"append",
"(",
"trimmed",
")",
"if",
"add_space",
":",
"subwords",
".",
"append",
"(",
"\" \"",
")",
"# If there were trailing bytes, convert to unicode.",
"prev_bytes",
"=",
"consume_prev_bytes",
"(",
")",
"return",
"tf",
".",
"compat",
".",
"as_text",
"(",
"\"\"",
".",
"join",
"(",
"subwords",
")",
")"
] | 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_subwords(token)
ids = []
for subword in subwords:
if subword == _UNDERSCORE_REPLACEMENT:
ids.append(len(self._subwords) + ord("_"))
continue
subword_id = self._subword_to_id.get(subword)
if subword_id is None:
# Byte-encode
ids.extend(self._byte_encode(subword))
else:
ids.append(subword_id)
# Update cache
self._token_to_ids_cache[cache_location] = (token, ids)
return ids | 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_subwords(token)
ids = []
for subword in subwords:
if subword == _UNDERSCORE_REPLACEMENT:
ids.append(len(self._subwords) + ord("_"))
continue
subword_id = self._subword_to_id.get(subword)
if subword_id is None:
# Byte-encode
ids.extend(self._byte_encode(subword))
else:
ids.append(subword_id)
# Update cache
self._token_to_ids_cache[cache_location] = (token, ids)
return ids | [
"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",
"]",
"if",
"cache_key",
"==",
"token",
":",
"return",
"cache_value",
"subwords",
"=",
"self",
".",
"_token_to_subwords",
"(",
"token",
")",
"ids",
"=",
"[",
"]",
"for",
"subword",
"in",
"subwords",
":",
"if",
"subword",
"==",
"_UNDERSCORE_REPLACEMENT",
":",
"ids",
".",
"append",
"(",
"len",
"(",
"self",
".",
"_subwords",
")",
"+",
"ord",
"(",
"\"_\"",
")",
")",
"continue",
"subword_id",
"=",
"self",
".",
"_subword_to_id",
".",
"get",
"(",
"subword",
")",
"if",
"subword_id",
"is",
"None",
":",
"# Byte-encode",
"ids",
".",
"extend",
"(",
"self",
".",
"_byte_encode",
"(",
"subword",
")",
")",
"else",
":",
"ids",
".",
"append",
"(",
"subword_id",
")",
"# Update cache",
"self",
".",
"_token_to_ids_cache",
"[",
"cache_location",
"]",
"=",
"(",
"token",
",",
"ids",
")",
"return",
"ids"
] | 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",
")",
"+",
"ord",
"(",
"\" \"",
")",
"]",
"return",
"[",
"i",
"+",
"offset",
"for",
"i",
"in",
"list",
"(",
"bytearray",
"(",
"tf",
".",
"compat",
".",
"as_bytes",
"(",
"token",
")",
")",
")",
"]"
] | 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.