[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nenv/\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# dotenv\n.env\n\n# virtualenv\n.venv\nvenv/\nENV/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2017 Tommy Tao\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "MANIFEST",
    "content": "# file GENERATED by distutils, do NOT edit\nsetup.py\ntensorboardcolab/__init__.py\ntensorboardcolab/callbacks.py\ntensorboardcolab/core.py\n"
  },
  {
    "path": "README.md",
    "content": "# TensorBoardColab\n\nA library make TensorBoard working in Colab Google\n\n## Install\n\n    pip install tensorboardcolab\n\nIn Colab Google Jupyter, for auto install and ensure using latest version of TensorBoardColab, please add \"!pip install -U tensorboardcolab\" at the first line of Jupyter cell\n\n## Requirements\n\n    Tensorflow\n    TensorBoard\n    npm\n\n## Import\n\n    from tensorboardcolab import *\n\n## Initialization\n\n    tbc=TensorBoardColab()\n\nAfter initialization, TensorBoard link will be shown in Colab Google Juyter output\n\nPS: If Initialization failed and keep retrying forever, please increase startup_waiting_time larger than 8 seconds as below\n\n    tbc=TensorBoardColab(startup_waiting_time=30)\n\n## Add to Keras callback\n\n    model.fit(x,y,epochs=100000,callbacks=[TensorBoardColabCallback(tbc)])\n\n## Save picture to TensorBoard\n\n    tbc.save_image(title=\"test_title\", image=image)\n\n## Save a value to graph of TensorBoard\n\n    tbc.save_value(\"graph_name\", \"line_name\", epoch, value)\n    .\n    .\n    .\n    tbc.flush_line(line_name)\n    tbc.close()\n\n## Thanks\n\nngrok !\n"
  },
  {
    "path": "setup.py",
    "content": "from distutils.core import setup\n\nsetup(\n    name='tensorboardcolab',\n    version='0.0.21',\n    packages=['tensorboardcolab'],\n    url='https://github.com/taomanwai/tensorboardcolab',\n    license='MIT',\n    author='Tommy Tao',\n    author_email='o_otaotao@hotmail.com',\n    description=''\n)\n"
  },
  {
    "path": "tensorboardcolab/__init__.py",
    "content": "from tensorboardcolab.core import *\nfrom tensorboardcolab.callbacks import *"
  },
  {
    "path": "tensorboardcolab/callbacks.py",
    "content": "import tensorflow as tf\nfrom keras.callbacks import TensorBoard\nimport time\nimport os\nimport io\n\nfrom tensorboardcolab.core import TensorBoardColab\n\n\nclass TensorBoardColab:\n    def __init__(self, port=6006, graph_path='./Graph', startup_waiting_time=8):\n        self.port = port\n        self.graph_path = graph_path\n        self.writer = None\n        self.deep_writers = {}\n        self.eager_execution = None\n        get_ipython().system_raw('npm i -s -q --unsafe-perm -g ngrok')  # sudo npm i -s -q --unsafe-perm -g ngrok\n\n        setup_passed = False\n        retry_count = 0\n        sleep_time = startup_waiting_time / 3.0\n        while not setup_passed:\n            get_ipython().system_raw('kill -9 $(sudo lsof -t -i:%d)' % port)\n            get_ipython().system_raw('rm -Rf ' + graph_path)\n            print('Wait for %d seconds...' % startup_waiting_time)\n            time.sleep(sleep_time)\n            get_ipython().system_raw('tensorboard --logdir %s --host 0.0.0.0 --port %d &' % (graph_path, port))\n            time.sleep(sleep_time)\n            get_ipython().system_raw('ngrok http %d &' % port)\n            time.sleep(sleep_time)\n            try:\n                tensorboard_link = get_ipython().getoutput(\n                    'curl -s http://localhost:4040/api/tunnels | python3 -c \"import sys, json; print(json.load(sys.stdin))\"')[\n                    0]\n                tensorboard_link = eval(tensorboard_link)['tunnels'][0]['public_url']\n                setup_passed = True\n            except:\n                setup_passed = False\n                retry_count += 1\n                print('Initialization failed, retry again (%d)' % retry_count)\n                print('\\n')\n\n        print(\"TensorBoard link:\")\n        print(tensorboard_link)\n\n    def get_graph_path(self):\n        return self.graph_path\n\n    def is_eager_execution(self):\n        if self.eager_execution is None:\n            try:\n                tf.summary.FileWriter(self.graph_path)\n                self.eager_execution = False\n            except Exception as err:\n                self.eager_execution = str(\n                    err) == 'tf.summary.FileWriter is not compatible with eager execution. Use tf.contrib.summary instead.'\n        return self.eager_execution\n\n    def get_writer(self):\n        if self.writer is None:\n            if self.is_eager_execution():\n                self.writer = tf.contrib.summary.create_file_writer(self.graph_path)\n            else:\n                self.writer = tf.summary.FileWriter(self.graph_path)\n\n        return self.writer\n\n    def get_deep_writers(self, name):\n        if not (name in self.deep_writers):\n            log_path = os.path.join(self.graph_path, name)\n            if self.is_eager_execution():\n                self.deep_writers[name] = tf.contrib.summary.create_file_writer(log_path)\n            else:\n                self.deep_writers[name] = tf.summary.FileWriter(log_path)\n        return self.deep_writers[name]\n\n    def save_image(self, title, image):\n        image_path = os.path.join(self.graph_path, 'images')\n        if self.is_eager_execution():\n            print('Warning: save_image() is not supported in eager execution mode')\n        #           writer = tf.contrib.summary.create_file_writer(image_path)\n        #           writer.set_as_default()\n        #           with tf.contrib.summary.always_record_summaries():\n        #               tf.contrib.summary.image(\n        #                   title,\n        #                   image_tensor\n        #               )\n        else:\n            summary_op = tf.summary.image(title, image)\n            with tf.Session() as sess:\n                summary = sess.run(summary_op)\n                writer = tf.summary.FileWriter(image_path)\n                writer.add_summary(summary)\n                writer.close()\n\n    def save_value(self, graph_name, line_name, epoch, value):\n        if self.is_eager_execution():\n            self.get_deep_writers(line_name).set_as_default()\n            global_step = tf.train.get_or_create_global_step()\n            global_step.assign(epoch)\n            with tf.contrib.summary.always_record_summaries():\n                tf.contrib.summary.scalar(graph_name, value)\n        else:\n            summary = tf.Summary()\n            summary_value = summary.value.add()\n            summary_value.simple_value = value\n            summary_value.tag = graph_name\n            self.get_deep_writers(line_name).add_summary(summary, epoch)\n\n    def flush_line(self, line_name):\n        self.get_deep_writers(line_name).flush()\n\n    def close(self):\n        if self.writer is not None:\n            self.writer.close()\n            self.writer = None\n        for key in self.deep_writers:\n            self.deep_writers[key].close()\n        self.deep_writers = {}\n\n\nclass TensorBoardColabCallback(TensorBoard):\n    def __init__(self, tbc=None, write_graph=True, **kwargs):\n        # Make the original `TensorBoard` log to a subdirectory 'training'\n\n        if tbc is None:\n            return\n\n        log_dir = tbc.get_graph_path()\n\n        training_log_dir = os.path.join(log_dir, 'training')\n        super(TensorBoardColabCallback, self).__init__(training_log_dir, **kwargs)\n\n        # Log the validation metrics to a separate subdirectory\n        self.val_log_dir = os.path.join(log_dir, 'validation')\n\n    def set_model(self, model):\n        # Setup writer for validation metrics\n        if self.is_eager_execution():\n            self.val_writer = tf.contrib.summary.create_file_writer(self.val_log_dir)\n        else:\n            self.val_writer = tf.summary.FileWriter(self.val_log_dir)\n\n        super(TensorBoardColabCallback, self).set_model(model)\n\n    def on_epoch_end(self, epoch, logs=None):\n        # Pop the validation logs and handle them separately with\n        # `self.val_writer`. Also rename the keys so that they can\n        # be plotted on the same figure with the training metrics\n        logs = logs or {}\n        val_logs = {k.replace('val_', ''): v for k, v in logs.items() if k.startswith('val_')}\n\n        for name, value in val_logs.items():\n            if self.is_eager_execution():\n                self.val_writer.set_as_default()\n                global_step = tf.train.get_or_create_global_step()\n                global_step.assign(epoch)\n                with tf.contrib.summary.always_record_summaries():\n                    tf.contrib.summary.scalar(name, value.item())\n            else:\n                summary = tf.Summary()\n                summary_value = summary.value.add()\n                summary_value.simple_value = value.item()\n                summary_value.tag = name\n                self.val_writer.add_summary(summary, epoch)\n\n        self.val_writer.flush()\n\n        # Pass the remaining logs to `TensorBoard.on_epoch_end`\n        logs = {k: v for k, v in logs.items() if not k.startswith('val_')}\n        super(TensorBoardColabCallback, self).on_epoch_end(epoch, logs)\n\n    def on_train_end(self, logs=None):\n        super(TensorBoardColabCallback, self).on_train_end(logs)\n        self.val_writer.close()\n"
  },
  {
    "path": "tensorboardcolab/core.py",
    "content": "import tensorflow as tf\nfrom keras.callbacks import TensorBoard\nimport time\nimport os\nimport io\n\nclass TensorBoardColab:\n    def __init__(self, port=6006, graph_path='./Graph', startup_waiting_time=8):\n        self.port = port\n        self.graph_path = graph_path\n        self.writer = None\n        self.deep_writers = {}\n        self.eager_execution = None\n        get_ipython().system_raw('npm i -s -q --unsafe-perm -g ngrok')  # sudo npm i -s -q --unsafe-perm -g ngrok\n\n        setup_passed = False\n        retry_count = 0\n        sleep_time = startup_waiting_time / 3.0\n        while not setup_passed:\n            get_ipython().system_raw('kill -9 $(sudo lsof -t -i:%d)' % port)\n            get_ipython().system_raw('rm -Rf ' + graph_path)\n            print('Wait for %d seconds...' % startup_waiting_time)\n            time.sleep(sleep_time)\n            get_ipython().system_raw('tensorboard --logdir %s --host 0.0.0.0 --port %d &' % (graph_path, port))\n            time.sleep(sleep_time)\n            get_ipython().system_raw('ngrok http %d &' % port)\n            time.sleep(sleep_time)\n            try:\n                tensorboard_link = get_ipython().getoutput(\n                    'curl -s http://localhost:4040/api/tunnels | python3 -c \"import sys, json; print(json.load(sys.stdin))\"')[\n                    0]\n                tensorboard_link = eval(tensorboard_link)['tunnels'][0]['public_url']\n                setup_passed = True\n            except:\n                setup_passed = False\n                retry_count += 1\n                print('Initialization failed, retry again (%d)' % retry_count)\n                print('\\n')\n\n        print(\"TensorBoard link:\")\n        print(tensorboard_link)\n\n    def get_graph_path(self):\n        return self.graph_path\n\n    def is_eager_execution(self):\n        if self.eager_execution is None:\n            try:\n                tf.summary.FileWriter(self.graph_path)\n                self.eager_execution = False\n            except Exception as err:\n                self.eager_execution = str(\n                    err) == 'tf.summary.FileWriter is not compatible with eager execution. Use tf.contrib.summary instead.'\n        return self.eager_execution\n\n    def get_writer(self):\n        if self.writer is None:\n            if self.is_eager_execution():\n                self.writer = tf.contrib.summary.create_file_writer(self.graph_path)\n            else:\n                self.writer = tf.summary.FileWriter(self.graph_path)\n\n        return self.writer\n\n    def get_deep_writers(self, name):\n        if not (name in self.deep_writers):\n            log_path = os.path.join(self.graph_path, name)\n            if self.is_eager_execution():\n                self.deep_writers[name] = tf.contrib.summary.create_file_writer(log_path)\n            else:\n                self.deep_writers[name] = tf.summary.FileWriter(log_path)\n        return self.deep_writers[name]\n\n    def save_image(self, title, image):\n        image_path = os.path.join(self.graph_path, 'images')\n        if self.is_eager_execution():\n            print('Warning: save_image() is not supported in eager execution mode')\n        #           writer = tf.contrib.summary.create_file_writer(image_path)\n        #           writer.set_as_default()\n        #           with tf.contrib.summary.always_record_summaries():\n        #               tf.contrib.summary.image(\n        #                   title,\n        #                   image_tensor\n        #               )\n        else:\n            summary_op = tf.summary.image(title, image)\n            with tf.Session() as sess:\n                summary = sess.run(summary_op)\n                writer = tf.summary.FileWriter(image_path)\n                writer.add_summary(summary)\n                writer.close()\n\n    def save_value(self, graph_name, line_name, epoch, value):\n        if self.is_eager_execution():\n            self.get_deep_writers(line_name).set_as_default()\n            global_step = tf.train.get_or_create_global_step()\n            global_step.assign(epoch)\n            with tf.contrib.summary.always_record_summaries():\n                tf.contrib.summary.scalar(graph_name, value)\n        else:\n            summary = tf.Summary()\n            summary_value = summary.value.add()\n            summary_value.simple_value = value\n            summary_value.tag = graph_name\n            self.get_deep_writers(line_name).add_summary(summary, epoch)\n\n    def flush_line(self, line_name):\n        self.get_deep_writers(line_name).flush()\n\n    def close(self):\n        if self.writer is not None:\n            self.writer.close()\n            self.writer = None\n        for key in self.deep_writers:\n            self.deep_writers[key].close()\n        self.deep_writers = {}\n\n\nclass TensorBoardColabCallback(TensorBoard):\n    def __init__(self, tbc=None, write_graph=True, **kwargs):\n        # Make the original `TensorBoard` log to a subdirectory 'training'\n\n        if tbc is None:\n            return\n\n        self.tbc = tbc\n\n        log_dir = tbc.get_graph_path()\n\n        training_log_dir = os.path.join(log_dir, 'training')\n        super(TensorBoardColabCallback, self).__init__(training_log_dir, **kwargs)\n\n        # Log the validation metrics to a separate subdirectory\n        self.val_log_dir = os.path.join(log_dir, 'validation')\n\n    def set_model(self, model):\n        # Setup writer for validation metrics\n        if self.tbc.is_eager_execution():\n            self.val_writer = tf.contrib.summary.create_file_writer(self.val_log_dir)\n        else:\n            self.val_writer = tf.summary.FileWriter(self.val_log_dir)\n\n        super(TensorBoardColabCallback, self).set_model(model)\n\n    def on_epoch_end(self, epoch, logs=None):\n        # Pop the validation logs and handle them separately with\n        # `self.val_writer`. Also rename the keys so that they can\n        # be plotted on the same figure with the training metrics\n        logs = logs or {}\n        val_logs = {k.replace('val_', ''): v for k, v in logs.items() if k.startswith('val_')}\n\n        for name, value in val_logs.items():\n            if self.tbc.is_eager_execution():\n                self.val_writer.set_as_default()\n                global_step = tf.train.get_or_create_global_step()\n                global_step.assign(epoch)\n                with tf.contrib.summary.always_record_summaries():\n                    tf.contrib.summary.scalar(name, value.item())\n            else:\n                summary = tf.Summary()\n                summary_value = summary.value.add()\n                summary_value.simple_value = value.item()\n                summary_value.tag = name\n                self.val_writer.add_summary(summary, epoch)\n\n        self.val_writer.flush()\n\n        # Pass the remaining logs to `TensorBoard.on_epoch_end`\n        logs = {k: v for k, v in logs.items() if not k.startswith('val_')}\n        super(TensorBoardColabCallback, self).on_epoch_end(epoch, logs)\n\n    def on_train_end(self, logs=None):\n        super(TensorBoardColabCallback, self).on_train_end(logs)\n        self.val_writer.close()"
  }
]