Desenvolvimento

O documento contém as informações necessárias para configurar o ambiente de desenvolvimento e construir o pacote tensorflow-io a partir do código-fonte em várias plataformas. Assim que a configuração for concluída, consulte o STYLE_GUIDE para obter orientações sobre como adicionar novas operações.

Configuração do IDE

Para obter instruções sobre como configurar o Visual Studio Code para desenvolver E/S do TensorFlow, consulte este documento .

Fiapos

O código do TensorFlow I/O está em conformidade com Bazel Buildifier, Clang Format, Black e Pyupgrade. Use o seguinte comando para verificar o código-fonte e identificar problemas de lint:

# Install Bazel version specified in .bazelversion
$ curl -OL https://github.com/bazelbuild/bazel/releases/download/$(cat .bazelversion)/bazel-$(cat .bazelversion)-installer-darwin-x86_64.sh
$ sudo bash -x -e bazel-$(cat .bazelversion)-installer-darwin-x86_64.sh
$ bazel run //tools/lint:check

Para Bazel Buildifier e Clang Format, o comando a seguir identificará e corrigirá automaticamente quaisquer erros de lint:

$ bazel run //tools/lint:lint

Alternativamente, se você deseja apenas realizar a verificação de lint usando linters individuais, você pode passar seletivamente black , pyupgrade , bazel ou clang para os comandos acima.

Por exemplo, uma verificação de fiapos específicos black pode ser feita usando:

$ bazel run //tools/lint:check -- black

A correção do Lint usando Bazel Buildifier e Clang Format pode ser feita usando:

$ bazel run //tools/lint:lint -- bazel clang

A verificação do Lint usando black e pyupgrade para um arquivo python individual pode ser feita usando:

$ bazel run //tools/lint:check -- black pyupgrade -- tensorflow_io/python/ops/version_ops.py

Lint corrige um arquivo python individual com black e pyupgrade usando:

$ bazel run //tools/lint:lint -- black pyupgrade --  tensorflow_io/python/ops/version_ops.py

Pitão

Mac OS

No macOS Catalina 10.15.7, é possível construir tensorflow-io com o sistema fornecido python 3.8.2. Tanto tensorflow quanto bazel são necessários para fazer isso.

#!/usr/bin/env bash

# Disable arm64 build by specifying only x86_64 arch.
# Only needed for macOS's system default python 3.8.2 on macOS 10.15.7
export ARCHFLAGS="-arch x86_64"

# Use following command to check if Xcode is correctly installed:
xcodebuild -version

# Show macOS's default python3
python3 --version

# Install Bazel version specified in .bazelversion
curl -OL https://github.com/bazelbuild/bazel/releases/download/$(cat .bazelversion)/bazel-$(cat .bazelversion)-installer-darwin-x86_64.sh
sudo bash -x -e bazel-$(cat .bazelversion)-installer-darwin-x86_64.sh

# Install tensorflow and configure bazel
sudo ./configure.sh

# Add any optimization on bazel command, e.g., --compilation_mode=opt,
#   --copt=-msse4.2, --remote_cache=, etc.
# export BAZEL_OPTIMIZATION=

# Build shared libraries
bazel build -s --verbose_failures $BAZEL_OPTIMIZATION //tensorflow_io/... //tensorflow_io_gcs_filesystem/...

# Once build is complete, shared libraries will be available in
# `bazel-bin/tensorflow_io/core`, `bazel-bin/tensorflow_io/python/ops` and
# it is possible to run tests with `pytest`, e.g.:
sudo python3 -m pip install pytest
TFIO_DATAPATH=bazel-bin python3 -m pytest -s -v tests/test_serialization.py
Solucionar problemas

Se o Xcode estiver instalado, mas $ xcodebuild -version não estiver exibindo a saída esperada, pode ser necessário habilitar a linha de comando do Xcode com o comando:

$ xcode-select -s /Applications/Xcode.app/Contents/Developer .

Pode ser necessário reiniciar o terminal para que as alterações entrem em vigor.

Exemplo de saída:

$ xcodebuild -version
Xcode 12.2
Build version 12B45b

Linux

O desenvolvimento do tensorflow-io no Linux é semelhante ao macOS. Os pacotes necessários são gcc, g++, git, bazel e python 3. No entanto, versões mais recentes do gcc ou python, diferentes das versões padrão instaladas pelo sistema, podem ser necessárias.

Ubuntu 20.04

Ubuntu 20.04 requer gcc/g++, git e python 3. O seguinte irá instalar dependências e construir as bibliotecas compartilhadas no Ubuntu 20.04:

#!/usr/bin/env bash

# Install gcc/g++, git, unzip/curl (for bazel), and python3
sudo apt-get -y -qq update
sudo apt-get -y -qq install gcc g++ git unzip curl python3-pip

# Install Bazel version specified in .bazelversion
curl -sSOL <a href="https://github.com/bazelbuild/bazel/releases/download/">https://github.com/bazelbuild/bazel/releases/download/</a>\\((cat .bazelversion)/bazel-\\)(cat .bazelversion)-installer-linux-x86_64.sh
sudo bash -x -e bazel-$(cat .bazelversion)-installer-linux-x86_64.sh

# Upgrade pip
sudo python3 -m pip install -U pip

# Install tensorflow and configure bazel
sudo ./configure.sh

# Alias python3 to python, needed by bazel
sudo ln -s /usr/bin/python3 /usr/bin/python

# Add any optimization on bazel command, e.g., --compilation_mode=opt,
#   --copt=-msse4.2, --remote_cache=, etc.
# export BAZEL_OPTIMIZATION=

# Build shared libraries
bazel build -s --verbose_failures $BAZEL_OPTIMIZATION //tensorflow_io/... //tensorflow_io_gcs_filesystem/...

# Once build is complete, shared libraries will be available in
# `bazel-bin/tensorflow_io/core`, `bazel-bin/tensorflow_io/python/ops` and
# it is possible to run tests with `pytest`, e.g.:
sudo python3 -m pip install pytest
TFIO_DATAPATH=bazel-bin python3 -m pytest -s -v tests/test_serialization.py
CentOS 8

As etapas para construir bibliotecas compartilhadas para CentOS 8 são semelhantes às do Ubuntu 20.04 acima, exceto que

sudo yum install -y python3 python3-devel gcc gcc-c++ git unzip which make

deve ser usado para instalar gcc/g++, git, unzip/what (para bazel) e python3.

CentOS 7

No CentOS 7, as versões padrão python e gcc são muito antigas para construir bibliotecas compartilhadas do tensorflow-io (.so). O gcc fornecido pelo Developer Toolset e rh-python36 deve ser usado. Além disso, o libstdc++ deve ser vinculado estaticamente para evitar discrepância entre o libstdc++ instalado no CentOS e a versão mais recente do gcc por devtoolset.

Além disso, um sinalizador especial --//tensorflow_io/core:static_build deve ser passado ao Bazel para evitar a duplicação de símbolos em bibliotecas vinculadas estaticamente para plug-ins de sistema de arquivos.

O seguinte irá instalar bazel, devtoolset-9, rh-python36 e construir as bibliotecas compartilhadas:

#!/usr/bin/env bash

# Install centos-release-scl, then install gcc/g++ (devtoolset), git, and python 3
sudo yum install -y centos-release-scl
sudo yum install -y devtoolset-9 git rh-python36 make

# Install Bazel version specified in .bazelversion
curl -sSOL <a href="https://github.com/bazelbuild/bazel/releases/download/">https://github.com/bazelbuild/bazel/releases/download/</a>\\((cat .bazelversion)/bazel-\\)(cat .bazelversion)-installer-linux-x86_64.sh
sudo bash -x -e bazel-$(cat .bazelversion)-installer-linux-x86_64.sh

# Upgrade pip
scl enable rh-python36 devtoolset-9 \
    'python3 -m pip install -U pip'

# Install tensorflow and configure bazel with rh-python36
scl enable rh-python36 devtoolset-9 \
    './configure.sh'

# Add any optimization on bazel command, e.g., --compilation_mode=opt,
#   --copt=-msse4.2, --remote_cache=, etc.
# export BAZEL_OPTIMIZATION=

# Build shared libraries, notice the passing of --//tensorflow_io/core:static_build
BAZEL_LINKOPTS="-static-libstdc++ -static-libgcc" BAZEL_LINKLIBS="-lm -l%:libstdc++.a" \
  scl enable rh-python36 devtoolset-9 \
    'bazel build -s --verbose_failures $BAZEL_OPTIMIZATION --//tensorflow_io/core:static_build //tensorflow_io/...'

# Once build is complete, shared libraries will be available in
# `bazel-bin/tensorflow_io/core`, `bazel-bin/tensorflow_io/python/ops` and
# it is possible to run tests with `pytest`, e.g.:
scl enable rh-python36 devtoolset-9 \
    'python3 -m pip install pytest'

TFIO_DATAPATH=bazel-bin \
  scl enable rh-python36 devtoolset-9 \
    'python3 -m pytest -s -v tests/test_serialization.py'

Docker

Para desenvolvimento em Python, um Dockerfile de referência aqui pode ser usado para construir o pacote de E/S do TensorFlow ( tensorflow-io ) a partir da fonte. Além disso, as imagens de desenvolvimento pré-construídas também podem ser usadas:

# Pull (if necessary) and start the devel container
\\( docker run -it --rm --name tfio-dev --net=host -v \\){PWD}:/v -w /v tfsigio/tfio:latest-devel bash

# Inside the docker container, ./configure.sh will install TensorFlow or use existing install
(tfio-dev) root@docker-desktop:/v$ ./configure.sh

# Clean up exisiting bazel build's (if any)
(tfio-dev) root@docker-desktop:/v$ rm -rf bazel-*

# Build TensorFlow I/O C++. For compilation optimization flags, the default (-march=native)
# optimizes the generated code for your machine's CPU type.
# Reference: <a href="https://www.tensorflow.orginstall/source#configuration_options">https://www.tensorflow.orginstall/source#configuration_options</a>).

# NOTE: Based on the available resources, please change the number of job workers to:
# -j 4/8/16 to prevent bazel server terminations and resource oriented build errors.

(tfio-dev) root@docker-desktop:/v$ bazel build -j 8 --copt=-msse4.2 --copt=-mavx --compilation_mode=opt --verbose_failures --test_output=errors --crosstool_top=//third_party/toolchains/gcc7_manylinux2010:toolchain //tensorflow_io/... //tensorflow_io_gcs_filesystem/...


# Run tests with PyTest, note: some tests require launching additional containers to run (see below)
(tfio-dev) root@docker-desktop:/v$ pytest -s -v tests/
# Build the TensorFlow I/O package
(tfio-dev) root@docker-desktop:/v$ python setup.py bdist_wheel

Um arquivo de pacote dist/tensorflow_io-*.whl será gerado após uma compilação ser bem-sucedida.

Rodas Python

É possível construir rodas python após a conclusão da construção do bazel com o seguinte comando:

$ python setup.py bdist_wheel --data bazel-bin

O arquivo .whl estará disponível no diretório dist. Observe que o diretório binário bazel bazel-bin deve ser passado com --data args para que setup.py localize os objetos de compartilhamento necessários, pois bazel-bin está fora do diretório do pacote tensorflow_io .

Alternativamente, a instalação do código-fonte pode ser feita com:

$ TFIO_DATAPATH=bazel-bin python -m pip install .

com TFIO_DATAPATH=bazel-bin passado pelo mesmo motivo.

Observe que a instalação com -e é diferente da anterior. O

$ TFIO_DATAPATH=bazel-bin python -m pip install -e .

não instalará o objeto compartilhado automaticamente, mesmo com TFIO_DATAPATH=bazel-bin . Em vez disso, TFIO_DATAPATH=bazel-bin deve ser passado sempre que o programa for executado após a instalação:

$ TFIO_DATAPATH=bazel-bin python

>>> import tensorflow_io as tfio
>>> ...

Teste

Alguns testes exigem o lançamento de um contêiner de teste ou o início de uma instância local da ferramenta associada antes da execução. Por exemplo, para executar testes relacionados ao kafka que iniciarão uma instância local do kafka, zookeeper e registro de esquema, use:

# Start the local instances of kafka, zookeeper and schema-registry
$ bash -x -e tests/test_kafka/kafka_test.sh

# Run the tests
$ TFIO_DATAPATH=bazel-bin pytest -s -vv tests/test_kafka.py

O teste de Datasets associados a ferramentas como Elasticsearch ou MongoDB exige que o docker esteja disponível no sistema. Nesses cenários, use:

# Start elasticsearch within docker container
$ bash tests/test_elasticsearch/elasticsearch_test.sh start

# Run the tests
$ TFIO_DATAPATH=bazel-bin pytest -s -vv tests/test_elasticsearch.py

# Stop and remove the container
$ bash tests/test_elasticsearch/elasticsearch_test.sh stop

Além disso, testar alguns recursos do tensorflow-io não exige que você use nenhuma ferramenta adicional, pois os dados foram fornecidos no próprio diretório tests . Por exemplo, para executar testes relacionados ao conjunto de dados parquet , use:

# Just run the test
$ TFIO_DATAPATH=bazel-bin pytest -s -vv tests/test_parquet.py

R

Fornecemos aqui um Dockerfile de referência para que você possa usar o pacote R diretamente para teste. Você pode construí-lo por meio de:

$ docker build -t tfio-r-dev -f R-package/scripts/Dockerfile .

Dentro do contêiner, você pode iniciar sua sessão R, instanciar um SequenceFileDataset de um exemplo de Hadoop SequenceFile string.seq e, em seguida, usar quaisquer funções de transformação fornecidas pelo pacote tfdatasets no conjunto de dados, como a seguir:

library(tfio)
dataset <- sequence_file_dataset("R-package/tests/testthat/testdata/string.seq") %>%
    dataset_repeat(2)

sess <- tf$Session()
iterator <- make_iterator_one_shot(dataset)
next_batch <- iterator_get_next(iterator)

until_out_of_range({
  batch <- sess$run(next_batch)
  print(batch)
})