Desenvolvimento

O documento contém as informações necessárias para configurar o ambiente de desenvolvimento e construção do tensorflow-io pacote de fonte em várias plataformas. Depois que a instalação for concluída, consulte o STYLE_GUIDE para obter orientações sobre a adição de novos ops.

Configuração de IDE

Para obter instruções sobre como configurar o código Visual Studio for desenvolvendo TensorFlow I / O, 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ê só quer executar verificação de fiapos usando linters individuais, então você pode passar seletivamente black , pyupgrade , bazel , ou clang para os comandos acima.

Por exemplo, um black verificação fiapos específica pode ser feito usando:

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

A correção do lint usando o Bazel Buildifier e o Clang Format podem ser feitas usando:

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

Lint verificar usando black e pyupgrade para um arquivo python indivíduo pode ser feito 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 o tensorflow-io com o python 3.8.2 fornecido pelo sistema. Ambos tensorflow e bazel são necessários para fazê-lo.

#!/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 Xcode está instalado, mas $ xcodebuild -version não está exibindo a saída esperada, pode ser necessário para permitir linha de comando Xcode com o comando:

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

Uma reinicialização do terminal pode ser necessária para que as alterações entrem em vigor.

Saída de amostra:

$ 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, podem ser necessárias versões mais recentes do gcc ou python, além das versões padrão instaladas pelo sistema.

Ubuntu 20.04

O Ubuntu 20.04 requer gcc/g++, git e python 3. O seguinte 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 criar bibliotecas compartilhadas para o CentOS 8 são semelhantes ao 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/which (para bazel) e python3.

CentOS 7

No CentOS 7, a versão padrão do python e do gcc é muito antiga para construir as bibliotecas compartilhadas do tensorflow-io (.so). O gcc fornecido pelo Developer Toolset e rh-python36 deve ser usado. Além disso, a libstdc++ deve ser vinculada estaticamente para evitar discrepâncias da libstdc++ instalada no CentOS versus a versão mais recente do gcc pelo devtoolset.

Além disso, uma bandeira especial --//tensorflow_io/core:static_build tem de ser passado para Bazel, a fim de evitar a duplicação de símbolos em bibliotecas estaticamente ligadas para plugins do sistema de arquivos.

O seguinte 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'

Janela de encaixe

Para o desenvolvimento de pitão, uma referência Dockerfile aqui pode ser utilizado para construir o pacote TensorFlow de I / O ( tensorflow-io ) a partir da fonte. Além disso, as imagens devel pré-criadas 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á gerada após uma compilação for bem sucedida.

Rodas Python

É possível construir rodas python após a conclusã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 o Bazel binário diretório bazel-bin tem que ser passado com --data args para que setup.py para localizar os objetos de acções necessárias, como bazel-bin está fora do tensorflow_io diretório do pacote.

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 pela mesma razão.

Nota instalar com -e é diferente do acima. O

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

não será instalado objeto compartilhado automaticamente, mesmo com TFIO_DATAPATH=bazel-bin . Em vez disso, TFIO_DATAPATH=bazel-bin tem que ser passado cada vez que o programa é 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

Teste de Datasets associados com ferramentas como Elasticsearch ou MongoDB exigem janela de encaixe para estar 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, testando algumas características do tensorflow-io não exige que você para girar todas as ferramentas adicionais como os dados foram fornecidos na tests próprio diretório. Por exemplo, para executar testes relacionados com parquet do conjunto de dados, use:

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

R

Nós fornecemos uma referência Dockerfile aqui para você para que você pode usar o pacote de R diretamente para o teste. Você pode construí-lo através de:

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

Dentro do recipiente, você pode começar a sua sessão R, instanciar um SequenceFileDataset partir de um exemplo Hadoop SequenceFile string.seq , e depois usar quaisquer funções de transformação fornecidas pelo pacote tfdatasets no conjunto de dados como o seguinte:

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)
})