Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions tensorboard/compat/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,29 @@ package(default_visibility = ["//tensorboard:internal"])
licenses(["notice"]) # Apache 2.0

exports_files(["LICENSE"])

py_library(
name = "tensorflow",
# This is a rule that checks whether TensorFlow is installed on
# the system and falls back to tensorflow_stub if needed.
srcs = ["__init__.py"],
srcs_version = "PY2AND3",
visibility = ["//visibility:public"],
deps = [
"//tensorboard/compat/tensorflow_stub",
],
)

py_library(
name = "no_tensorflow",
# This is a rule that forces the use of tensorflow_stub instead of
# a system install of TensorFlow even if it exists.
srcs = [
"notf.py",
],
srcs_version = "PY2AND3",
visibility = ["//visibility:public"],
deps = [
":tensorflow",
],
)
25 changes: 24 additions & 1 deletion tensorboard/compat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,27 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""Compat module.

Provides a compat layer for TensorFlow methods so we can build without
TensorFlow in some cases.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

try:
# Check if non-TensorFlow forcoed by build rules based on this import
from . import notf # noqa
USING_TF = False
except ImportError:
try:
import tensorflow as tf
USING_TF = True
except ImportError:
USING_TF = False

if not USING_TF:
from . import tensorflow_stub as tf # noqa
1 change: 1 addition & 0 deletions tensorboard/compat/notf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# This module is included by build rules to force non-TensorFlow builds
18 changes: 18 additions & 0 deletions tensorboard/compat/tensorflow_stub/BUILD
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Description:
# TensorBoard, a dashboard for investigating TensorFlow

package(default_visibility = ["//tensorboard:internal"])

licenses(["notice"]) # Apache 2.0

exports_files(["LICENSE"])

py_library(
name = "tensorflow_stub",
srcs = glob(["*.py"]),
srcs_version = "PY2AND3",
visibility = ["//visibility:public"],
deps = [
"//tensorboard/compat/proto:protos_all_py_pb2",
],
)
26 changes: 26 additions & 0 deletions tensorboard/compat/tensorflow_stub/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorboard.compat.proto.config_pb2 import * # noqa
from tensorboard.compat.proto.event_pb2 import * # noqa
from tensorboard.compat.proto.graph_pb2 import * # noqa
from tensorboard.compat.proto.meta_graph_pb2 import * # noqa
from tensorboard.compat.proto.summary_pb2 import * # noqa
from .dtypes import as_dtype # noqa
from .dtypes import DType # noqa
from .dtypes import string # noqa
from .tensor_manip import make_ndarray # noqa
from .tensor_manip import make_tensor_proto # noqa
from . import app # noqa
from . import compat # noqa
from . import dtypes # noqa
from . import error_codes # noqa
from . import errors # noqa
from . import flags # noqa
from . import gfile # noqa
from . import logging # noqa
from . import pywrap_tensorflow # noqa
from . import resource_loader # noqa
from . import tensor_manip # noqa
from . import tensor_shape # noqa
129 changes: 129 additions & 0 deletions tensorboard/compat/tensorflow_stub/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""Generic entry point script."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import errno as _errno
import sys as _sys

from . import flags


def _usage(shorthelp):
"""Writes __main__'s docstring to stdout with some help text.

Args:
shorthelp: bool, if True, prints only flags from the main module,
rather than all flags.
"""
doc = _sys.modules['__main__'].__doc__
if not doc:
doc = '\nUSAGE: %s [flags]\n' % _sys.argv[0]
doc = flags.text_wrap(doc, indent=' ', firstline_indent='')
else:
# Replace all '%s' with sys.argv[0], and all '%%' with '%'.
num_specifiers = doc.count('%') - 2 * doc.count('%%')
try:
doc %= (_sys.argv[0],) * num_specifiers
except (OverflowError, TypeError, ValueError):
# Just display the docstring as-is.
pass
if shorthelp:
flag_str = flags.FLAGS.main_module_help()
else:
flag_str = str(flags.FLAGS)
try:
_sys.stdout.write(doc)
if flag_str:
_sys.stdout.write('\nflags:\n')
_sys.stdout.write(flag_str)
_sys.stdout.write('\n')
except IOError as e:
# We avoid printing a huge backtrace if we get EPIPE, because
# "foo.par --help | less" is a frequent use case.
if e.errno != _errno.EPIPE:
raise


class _HelpFlag(flags.BooleanFlag):
"""Special boolean flag that displays usage and raises SystemExit."""
NAME = 'help'
SHORT_NAME = 'h'

def __init__(self):
super(_HelpFlag, self).__init__(
self.NAME, False, 'show this help', short_name=self.SHORT_NAME)

def parse(self, arg):
if arg:
_usage(shorthelp=True)
print()
print('Try --helpfull to get a list of all flags.')
_sys.exit(1)


class _HelpshortFlag(_HelpFlag):
"""--helpshort is an alias for --help."""
NAME = 'helpshort'
SHORT_NAME = None


class _HelpfullFlag(flags.BooleanFlag):
"""Display help for flags in main module and all dependent modules."""

def __init__(self):
super(
_HelpfullFlag,
self).__init__(
'helpfull',
False,
'show full help')

def parse(self, arg):
if arg:
_usage(shorthelp=False)
_sys.exit(1)


_define_help_flags_called = False


def _define_help_flags():
global _define_help_flags_called
if not _define_help_flags_called:
flags.DEFINE_flag(_HelpFlag())
flags.DEFINE_flag(_HelpfullFlag())
flags.DEFINE_flag(_HelpshortFlag())
_define_help_flags_called = True


# @tf_export('app.run')
def run(main=None, argv=None):
"""Runs the program with an optional 'main' function and 'argv' list."""

# Define help flags.
_define_help_flags()

# Parse known flags.
argv = flags.FLAGS(_sys.argv if argv is None else argv, known_only=True)

main = main or _sys.modules['__main__'].main

# Call the main function, passing through any arguments
# to the final program.
_sys.exit(main(argv))
135 changes: 135 additions & 0 deletions tensorboard/compat/tensorflow_stub/compat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Functions for Python 2 vs. 3 compatibility.

## Conversion routines
In addition to the functions below, `as_str` converts an object to a `str`.


## Types
The compatibility module also provides the following types:

* `bytes_or_text_types`
* `complex_types`
* `integral_types`
* `real_types`
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numbers as _numbers
import numpy as _np
import six as _six


def as_bytes(bytes_or_text, encoding="utf-8"):
"""Converts either bytes or unicode to `bytes`, using utf-8 encoding for text.

Args:
bytes_or_text: A `bytes`, `str`, or `unicode` object.
encoding: A string indicating the charset for encoding unicode.

Returns:
A `bytes` object.

Raises:
TypeError: If `bytes_or_text` is not a binary or unicode string.
"""
if isinstance(bytes_or_text, _six.text_type):
return bytes_or_text.encode(encoding)
elif isinstance(bytes_or_text, bytes):
return bytes_or_text
else:
raise TypeError("Expected binary or unicode string, got %r" % (bytes_or_text,))


def as_text(bytes_or_text, encoding="utf-8"):
"""Returns the given argument as a unicode string.

Args:
bytes_or_text: A `bytes`, `str`, or `unicode` object.
encoding: A string indicating the charset for decoding unicode.

Returns:
A `unicode` (Python 2) or `str` (Python 3) object.

Raises:
TypeError: If `bytes_or_text` is not a binary or unicode string.
"""
if isinstance(bytes_or_text, _six.text_type):
return bytes_or_text
elif isinstance(bytes_or_text, bytes):
return bytes_or_text.decode(encoding)
else:
raise TypeError("Expected binary or unicode string, got %r" % bytes_or_text)


# Convert an object to a `str` in both Python 2 and 3.
if _six.PY2:
as_str = as_bytes
# tf_export('compat.as_bytes', 'compat.as_str')(as_bytes)
# tf_export('compat.as_text')(as_text)
else:
as_str = as_text
# tf_export('compat.as_bytes')(as_bytes)
# tf_export('compat.as_text', 'compat.as_str')(as_text)


# @tf_export('compat.as_str_any')
def as_str_any(value):
"""Converts to `str` as `str(value)`, but use `as_str` for `bytes`.

Args:
value: A object that can be converted to `str`.

Returns:
A `str` object.
"""
if isinstance(value, bytes):
return as_str(value)
else:
return str(value)


# @tf_export('compat.path_to_str')
def path_to_str(path):
"""Returns the file system path representation of a `PathLike` object, else as it is.

Args:
path: An object that can be converted to path representation.

Returns:
A `str` object.
"""
if hasattr(path, "__fspath__"):
path = as_str_any(path.__fspath__())
return path


# Numpy 1.8 scalars don't inherit from numbers.Integral in Python 3, so we
# need to check them specifically. The same goes from Real and Complex.
integral_types = (_numbers.Integral, _np.integer)
# tf_export('compat.integral_types').export_constant(__name__, 'integral_types')
real_types = (_numbers.Real, _np.integer, _np.floating)
# tf_export('compat.real_types').export_constant(__name__, 'real_types')
complex_types = (_numbers.Complex, _np.number)
# tf_export('compat.complex_types').export_constant(__name__, 'complex_types')

# Either bytes or text.
bytes_or_text_types = (bytes, _six.text_type)
# tf_export('compat.bytes_or_text_types').export_constant(__name__,
# 'bytes_or_text_types')
Loading