Full Code of taomanwai/tensorboardcolab for AI

master 337dce9890da cached
8 files
17.5 KB
4.2k tokens
30 symbols
1 requests
Download .txt
Repository: taomanwai/tensorboardcolab
Branch: master
Commit: 337dce9890da
Files: 8
Total size: 17.5 KB

Directory structure:
gitextract_h8nil2ab/

├── .gitignore
├── LICENSE
├── MANIFEST
├── README.md
├── setup.py
└── tensorboardcolab/
    ├── __init__.py
    ├── callbacks.py
    └── core.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# dotenv
.env

# virtualenv
.venv
venv/
ENV/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/


================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) 2017 Tommy Tao

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: MANIFEST
================================================
# file GENERATED by distutils, do NOT edit
setup.py
tensorboardcolab/__init__.py
tensorboardcolab/callbacks.py
tensorboardcolab/core.py


================================================
FILE: README.md
================================================
# TensorBoardColab

A library make TensorBoard working in Colab Google

## Install

    pip install tensorboardcolab

In 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

## Requirements

    Tensorflow
    TensorBoard
    npm

## Import

    from tensorboardcolab import *

## Initialization

    tbc=TensorBoardColab()

After initialization, TensorBoard link will be shown in Colab Google Juyter output

PS: If Initialization failed and keep retrying forever, please increase startup_waiting_time larger than 8 seconds as below

    tbc=TensorBoardColab(startup_waiting_time=30)

## Add to Keras callback

    model.fit(x,y,epochs=100000,callbacks=[TensorBoardColabCallback(tbc)])

## Save picture to TensorBoard

    tbc.save_image(title="test_title", image=image)

## Save a value to graph of TensorBoard

    tbc.save_value("graph_name", "line_name", epoch, value)
    .
    .
    .
    tbc.flush_line(line_name)
    tbc.close()

## Thanks

ngrok !


================================================
FILE: setup.py
================================================
from distutils.core import setup

setup(
    name='tensorboardcolab',
    version='0.0.21',
    packages=['tensorboardcolab'],
    url='https://github.com/taomanwai/tensorboardcolab',
    license='MIT',
    author='Tommy Tao',
    author_email='o_otaotao@hotmail.com',
    description=''
)


================================================
FILE: tensorboardcolab/__init__.py
================================================
from tensorboardcolab.core import *
from tensorboardcolab.callbacks import *

================================================
FILE: tensorboardcolab/callbacks.py
================================================
import tensorflow as tf
from keras.callbacks import TensorBoard
import time
import os
import io

from tensorboardcolab.core import TensorBoardColab


class TensorBoardColab:
    def __init__(self, port=6006, graph_path='./Graph', startup_waiting_time=8):
        self.port = port
        self.graph_path = graph_path
        self.writer = None
        self.deep_writers = {}
        self.eager_execution = None
        get_ipython().system_raw('npm i -s -q --unsafe-perm -g ngrok')  # sudo npm i -s -q --unsafe-perm -g ngrok

        setup_passed = False
        retry_count = 0
        sleep_time = startup_waiting_time / 3.0
        while not setup_passed:
            get_ipython().system_raw('kill -9 $(sudo lsof -t -i:%d)' % port)
            get_ipython().system_raw('rm -Rf ' + graph_path)
            print('Wait for %d seconds...' % startup_waiting_time)
            time.sleep(sleep_time)
            get_ipython().system_raw('tensorboard --logdir %s --host 0.0.0.0 --port %d &' % (graph_path, port))
            time.sleep(sleep_time)
            get_ipython().system_raw('ngrok http %d &' % port)
            time.sleep(sleep_time)
            try:
                tensorboard_link = get_ipython().getoutput(
                    'curl -s http://localhost:4040/api/tunnels | python3 -c "import sys, json; print(json.load(sys.stdin))"')[
                    0]
                tensorboard_link = eval(tensorboard_link)['tunnels'][0]['public_url']
                setup_passed = True
            except:
                setup_passed = False
                retry_count += 1
                print('Initialization failed, retry again (%d)' % retry_count)
                print('\n')

        print("TensorBoard link:")
        print(tensorboard_link)

    def get_graph_path(self):
        return self.graph_path

    def is_eager_execution(self):
        if self.eager_execution is None:
            try:
                tf.summary.FileWriter(self.graph_path)
                self.eager_execution = False
            except Exception as err:
                self.eager_execution = str(
                    err) == 'tf.summary.FileWriter is not compatible with eager execution. Use tf.contrib.summary instead.'
        return self.eager_execution

    def get_writer(self):
        if self.writer is None:
            if self.is_eager_execution():
                self.writer = tf.contrib.summary.create_file_writer(self.graph_path)
            else:
                self.writer = tf.summary.FileWriter(self.graph_path)

        return self.writer

    def get_deep_writers(self, name):
        if not (name in self.deep_writers):
            log_path = os.path.join(self.graph_path, name)
            if self.is_eager_execution():
                self.deep_writers[name] = tf.contrib.summary.create_file_writer(log_path)
            else:
                self.deep_writers[name] = tf.summary.FileWriter(log_path)
        return self.deep_writers[name]

    def save_image(self, title, image):
        image_path = os.path.join(self.graph_path, 'images')
        if self.is_eager_execution():
            print('Warning: save_image() is not supported in eager execution mode')
        #           writer = tf.contrib.summary.create_file_writer(image_path)
        #           writer.set_as_default()
        #           with tf.contrib.summary.always_record_summaries():
        #               tf.contrib.summary.image(
        #                   title,
        #                   image_tensor
        #               )
        else:
            summary_op = tf.summary.image(title, image)
            with tf.Session() as sess:
                summary = sess.run(summary_op)
                writer = tf.summary.FileWriter(image_path)
                writer.add_summary(summary)
                writer.close()

    def save_value(self, graph_name, line_name, epoch, value):
        if self.is_eager_execution():
            self.get_deep_writers(line_name).set_as_default()
            global_step = tf.train.get_or_create_global_step()
            global_step.assign(epoch)
            with tf.contrib.summary.always_record_summaries():
                tf.contrib.summary.scalar(graph_name, value)
        else:
            summary = tf.Summary()
            summary_value = summary.value.add()
            summary_value.simple_value = value
            summary_value.tag = graph_name
            self.get_deep_writers(line_name).add_summary(summary, epoch)

    def flush_line(self, line_name):
        self.get_deep_writers(line_name).flush()

    def close(self):
        if self.writer is not None:
            self.writer.close()
            self.writer = None
        for key in self.deep_writers:
            self.deep_writers[key].close()
        self.deep_writers = {}


class TensorBoardColabCallback(TensorBoard):
    def __init__(self, tbc=None, write_graph=True, **kwargs):
        # Make the original `TensorBoard` log to a subdirectory 'training'

        if tbc is None:
            return

        log_dir = tbc.get_graph_path()

        training_log_dir = os.path.join(log_dir, 'training')
        super(TensorBoardColabCallback, self).__init__(training_log_dir, **kwargs)

        # Log the validation metrics to a separate subdirectory
        self.val_log_dir = os.path.join(log_dir, 'validation')

    def set_model(self, model):
        # Setup writer for validation metrics
        if self.is_eager_execution():
            self.val_writer = tf.contrib.summary.create_file_writer(self.val_log_dir)
        else:
            self.val_writer = tf.summary.FileWriter(self.val_log_dir)

        super(TensorBoardColabCallback, self).set_model(model)

    def on_epoch_end(self, epoch, logs=None):
        # Pop the validation logs and handle them separately with
        # `self.val_writer`. Also rename the keys so that they can
        # be plotted on the same figure with the training metrics
        logs = logs or {}
        val_logs = {k.replace('val_', ''): v for k, v in logs.items() if k.startswith('val_')}

        for name, value in val_logs.items():
            if self.is_eager_execution():
                self.val_writer.set_as_default()
                global_step = tf.train.get_or_create_global_step()
                global_step.assign(epoch)
                with tf.contrib.summary.always_record_summaries():
                    tf.contrib.summary.scalar(name, value.item())
            else:
                summary = tf.Summary()
                summary_value = summary.value.add()
                summary_value.simple_value = value.item()
                summary_value.tag = name
                self.val_writer.add_summary(summary, epoch)

        self.val_writer.flush()

        # Pass the remaining logs to `TensorBoard.on_epoch_end`
        logs = {k: v for k, v in logs.items() if not k.startswith('val_')}
        super(TensorBoardColabCallback, self).on_epoch_end(epoch, logs)

    def on_train_end(self, logs=None):
        super(TensorBoardColabCallback, self).on_train_end(logs)
        self.val_writer.close()


================================================
FILE: tensorboardcolab/core.py
================================================
import tensorflow as tf
from keras.callbacks import TensorBoard
import time
import os
import io

class TensorBoardColab:
    def __init__(self, port=6006, graph_path='./Graph', startup_waiting_time=8):
        self.port = port
        self.graph_path = graph_path
        self.writer = None
        self.deep_writers = {}
        self.eager_execution = None
        get_ipython().system_raw('npm i -s -q --unsafe-perm -g ngrok')  # sudo npm i -s -q --unsafe-perm -g ngrok

        setup_passed = False
        retry_count = 0
        sleep_time = startup_waiting_time / 3.0
        while not setup_passed:
            get_ipython().system_raw('kill -9 $(sudo lsof -t -i:%d)' % port)
            get_ipython().system_raw('rm -Rf ' + graph_path)
            print('Wait for %d seconds...' % startup_waiting_time)
            time.sleep(sleep_time)
            get_ipython().system_raw('tensorboard --logdir %s --host 0.0.0.0 --port %d &' % (graph_path, port))
            time.sleep(sleep_time)
            get_ipython().system_raw('ngrok http %d &' % port)
            time.sleep(sleep_time)
            try:
                tensorboard_link = get_ipython().getoutput(
                    'curl -s http://localhost:4040/api/tunnels | python3 -c "import sys, json; print(json.load(sys.stdin))"')[
                    0]
                tensorboard_link = eval(tensorboard_link)['tunnels'][0]['public_url']
                setup_passed = True
            except:
                setup_passed = False
                retry_count += 1
                print('Initialization failed, retry again (%d)' % retry_count)
                print('\n')

        print("TensorBoard link:")
        print(tensorboard_link)

    def get_graph_path(self):
        return self.graph_path

    def is_eager_execution(self):
        if self.eager_execution is None:
            try:
                tf.summary.FileWriter(self.graph_path)
                self.eager_execution = False
            except Exception as err:
                self.eager_execution = str(
                    err) == 'tf.summary.FileWriter is not compatible with eager execution. Use tf.contrib.summary instead.'
        return self.eager_execution

    def get_writer(self):
        if self.writer is None:
            if self.is_eager_execution():
                self.writer = tf.contrib.summary.create_file_writer(self.graph_path)
            else:
                self.writer = tf.summary.FileWriter(self.graph_path)

        return self.writer

    def get_deep_writers(self, name):
        if not (name in self.deep_writers):
            log_path = os.path.join(self.graph_path, name)
            if self.is_eager_execution():
                self.deep_writers[name] = tf.contrib.summary.create_file_writer(log_path)
            else:
                self.deep_writers[name] = tf.summary.FileWriter(log_path)
        return self.deep_writers[name]

    def save_image(self, title, image):
        image_path = os.path.join(self.graph_path, 'images')
        if self.is_eager_execution():
            print('Warning: save_image() is not supported in eager execution mode')
        #           writer = tf.contrib.summary.create_file_writer(image_path)
        #           writer.set_as_default()
        #           with tf.contrib.summary.always_record_summaries():
        #               tf.contrib.summary.image(
        #                   title,
        #                   image_tensor
        #               )
        else:
            summary_op = tf.summary.image(title, image)
            with tf.Session() as sess:
                summary = sess.run(summary_op)
                writer = tf.summary.FileWriter(image_path)
                writer.add_summary(summary)
                writer.close()

    def save_value(self, graph_name, line_name, epoch, value):
        if self.is_eager_execution():
            self.get_deep_writers(line_name).set_as_default()
            global_step = tf.train.get_or_create_global_step()
            global_step.assign(epoch)
            with tf.contrib.summary.always_record_summaries():
                tf.contrib.summary.scalar(graph_name, value)
        else:
            summary = tf.Summary()
            summary_value = summary.value.add()
            summary_value.simple_value = value
            summary_value.tag = graph_name
            self.get_deep_writers(line_name).add_summary(summary, epoch)

    def flush_line(self, line_name):
        self.get_deep_writers(line_name).flush()

    def close(self):
        if self.writer is not None:
            self.writer.close()
            self.writer = None
        for key in self.deep_writers:
            self.deep_writers[key].close()
        self.deep_writers = {}


class TensorBoardColabCallback(TensorBoard):
    def __init__(self, tbc=None, write_graph=True, **kwargs):
        # Make the original `TensorBoard` log to a subdirectory 'training'

        if tbc is None:
            return

        self.tbc = tbc

        log_dir = tbc.get_graph_path()

        training_log_dir = os.path.join(log_dir, 'training')
        super(TensorBoardColabCallback, self).__init__(training_log_dir, **kwargs)

        # Log the validation metrics to a separate subdirectory
        self.val_log_dir = os.path.join(log_dir, 'validation')

    def set_model(self, model):
        # Setup writer for validation metrics
        if self.tbc.is_eager_execution():
            self.val_writer = tf.contrib.summary.create_file_writer(self.val_log_dir)
        else:
            self.val_writer = tf.summary.FileWriter(self.val_log_dir)

        super(TensorBoardColabCallback, self).set_model(model)

    def on_epoch_end(self, epoch, logs=None):
        # Pop the validation logs and handle them separately with
        # `self.val_writer`. Also rename the keys so that they can
        # be plotted on the same figure with the training metrics
        logs = logs or {}
        val_logs = {k.replace('val_', ''): v for k, v in logs.items() if k.startswith('val_')}

        for name, value in val_logs.items():
            if self.tbc.is_eager_execution():
                self.val_writer.set_as_default()
                global_step = tf.train.get_or_create_global_step()
                global_step.assign(epoch)
                with tf.contrib.summary.always_record_summaries():
                    tf.contrib.summary.scalar(name, value.item())
            else:
                summary = tf.Summary()
                summary_value = summary.value.add()
                summary_value.simple_value = value.item()
                summary_value.tag = name
                self.val_writer.add_summary(summary, epoch)

        self.val_writer.flush()

        # Pass the remaining logs to `TensorBoard.on_epoch_end`
        logs = {k: v for k, v in logs.items() if not k.startswith('val_')}
        super(TensorBoardColabCallback, self).on_epoch_end(epoch, logs)

    def on_train_end(self, logs=None):
        super(TensorBoardColabCallback, self).on_train_end(logs)
        self.val_writer.close()
Download .txt
gitextract_h8nil2ab/

├── .gitignore
├── LICENSE
├── MANIFEST
├── README.md
├── setup.py
└── tensorboardcolab/
    ├── __init__.py
    ├── callbacks.py
    └── core.py
Download .txt
SYMBOL INDEX (30 symbols across 2 files)

FILE: tensorboardcolab/callbacks.py
  class TensorBoardColab (line 10) | class TensorBoardColab:
    method __init__ (line 11) | def __init__(self, port=6006, graph_path='./Graph', startup_waiting_ti...
    method get_graph_path (line 46) | def get_graph_path(self):
    method is_eager_execution (line 49) | def is_eager_execution(self):
    method get_writer (line 59) | def get_writer(self):
    method get_deep_writers (line 68) | def get_deep_writers(self, name):
    method save_image (line 77) | def save_image(self, title, image):
    method save_value (line 96) | def save_value(self, graph_name, line_name, epoch, value):
    method flush_line (line 110) | def flush_line(self, line_name):
    method close (line 113) | def close(self):
  class TensorBoardColabCallback (line 122) | class TensorBoardColabCallback(TensorBoard):
    method __init__ (line 123) | def __init__(self, tbc=None, write_graph=True, **kwargs):
    method set_model (line 137) | def set_model(self, model):
    method on_epoch_end (line 146) | def on_epoch_end(self, epoch, logs=None):
    method on_train_end (line 173) | def on_train_end(self, logs=None):

FILE: tensorboardcolab/core.py
  class TensorBoardColab (line 7) | class TensorBoardColab:
    method __init__ (line 8) | def __init__(self, port=6006, graph_path='./Graph', startup_waiting_ti...
    method get_graph_path (line 43) | def get_graph_path(self):
    method is_eager_execution (line 46) | def is_eager_execution(self):
    method get_writer (line 56) | def get_writer(self):
    method get_deep_writers (line 65) | def get_deep_writers(self, name):
    method save_image (line 74) | def save_image(self, title, image):
    method save_value (line 93) | def save_value(self, graph_name, line_name, epoch, value):
    method flush_line (line 107) | def flush_line(self, line_name):
    method close (line 110) | def close(self):
  class TensorBoardColabCallback (line 119) | class TensorBoardColabCallback(TensorBoard):
    method __init__ (line 120) | def __init__(self, tbc=None, write_graph=True, **kwargs):
    method set_model (line 136) | def set_model(self, model):
    method on_epoch_end (line 145) | def on_epoch_end(self, epoch, logs=None):
    method on_train_end (line 172) | def on_train_end(self, logs=None):
Condensed preview — 8 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (19K chars).
[
  {
    "path": ".gitignore",
    "chars": 1157,
    "preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packagi"
  },
  {
    "path": "LICENSE",
    "chars": 1066,
    "preview": "MIT License\n\nCopyright (c) 2017 Tommy Tao\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n"
  },
  {
    "path": "MANIFEST",
    "chars": 136,
    "preview": "# file GENERATED by distutils, do NOT edit\nsetup.py\ntensorboardcolab/__init__.py\ntensorboardcolab/callbacks.py\ntensorboa"
  },
  {
    "path": "README.md",
    "chars": 1077,
    "preview": "# TensorBoardColab\n\nA library make TensorBoard working in Colab Google\n\n## Install\n\n    pip install tensorboardcolab\n\nIn"
  },
  {
    "path": "setup.py",
    "chars": 290,
    "preview": "from distutils.core import setup\n\nsetup(\n    name='tensorboardcolab',\n    version='0.0.21',\n    packages=['tensorboardco"
  },
  {
    "path": "tensorboardcolab/__init__.py",
    "chars": 76,
    "preview": "from tensorboardcolab.core import *\nfrom tensorboardcolab.callbacks import *"
  },
  {
    "path": "tensorboardcolab/callbacks.py",
    "chars": 7077,
    "preview": "import tensorflow as tf\nfrom keras.callbacks import TensorBoard\nimport time\nimport os\nimport io\n\nfrom tensorboardcolab.c"
  },
  {
    "path": "tensorboardcolab/core.py",
    "chars": 7055,
    "preview": "import tensorflow as tf\nfrom keras.callbacks import TensorBoard\nimport time\nimport os\nimport io\n\nclass TensorBoardColab:"
  }
]

About this extraction

This page contains the full source code of the taomanwai/tensorboardcolab GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 8 files (17.5 KB), approximately 4.2k tokens, and a symbol index with 30 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!