
TabPyをかじってみた
はじめまして。
現在DATA Saber - Bridge 3rdに参加しています、唐内です。
今回、なんか聞いたことあるけど触ったことないなって思ったTabPyを使ってなんかゆるーくやっていこかなと思います。
そもそもTabPyって何?
TabPyのGitHubには以下のように書いてあります。
TabPy framework allows Tableau to remotely execute Python code. It has two components:
1.A process built on Tornado, which allows for the remote execution of Python code through a set of REST APIs. The code can either be immediately executed or persisted in the server process and exposed as a REST endpoint, to be called later.
2.A tools library, based on Python functions which enables the deployment of such endpoints.
ポイントとしては
TabPyは、TableauがリモートでPythonコードを実行できるようにする仕組みである。
TabPyフレームワークは、Tornadoを基盤としたプロセスによりREST APIを通じてPythonコードの即時実行やエンドポイントとしての保存を可能にし、さらにPython関数ベースのツールライブラリでこれらのエンドポイントを簡単にデプロイできるようにする。
なんか便利そうですね。
やってみよう
実行環境
OS : Windows 10
Python ver : 3.11.9
Tableau Desktop :2024.3
仮想環境を作成
TabPyを実行する仮想環境を以下のコードで作成し、アクティベート
# TabPy用の仮想環境を作成
python -m venv tabpy
# 仮想環境をアクティベート
./tabpy/Scripts/activate
サーバ起動
仮想環境にライブラリをインストール
# pipアップデート
python.exe -m pip install --upgrade pip
# TabPyのインストール
pip install --upgrade tabpy
# tabpy-clinetのインストール
pip install --upgrade tabpy_client
TabPyを起動
# TabPyを起動
tabpy
# 以下を聞かれるので,`y`と回答
Do you wish to proceed without authentication? (y/N):
以下が出てきたら起動成功
Web service listening on port 9004
TableauとTabPyサーバの接続
Tableau Desktopを開き'ヘルプ\設定とパフォーマンス\分析拡張機能の接続の管理'を選択

TabPyを選択

ホスト名に`localhost`、ポートに`9004`を入力し、保存を選択

TabPyサーバーに関数を登録
以下のようなスクリプトを仮想環境で実行
3p成功率の関数を登録してみました。
# 3p成功率を定義
def three_point_percentage(made, attempted):
return [m / a if a > 0 else 0 for m, a in zip(made, attempted)]
from tabpy.tabpy_tools.client import Client
# TabPyサーバーに接続
client = Client('http://localhost:9004/')
# スクリプトを登録
client.deploy('three_point_percentage',
three_point_percentage,
'Calculate 3-point shot success rate.')
実際にlocalhostを見に行くと赤枠の部分に登録が!

見に行くのがめんどくさかったら、以下コードを登録スクリプトに上記赤枠の情報がprintされる
print(client.get_endpoints())
Tableauで登録した関数を実際に使う
計算フィールドで以下を入力し、適当な名前を付けて作成
SCRIPT_REAL("
return tabpy.query('three_point_percentage',_arg1, _arg2)['response']
", SUM([3P]), SUM([3PA]))
実際に可視化すると以下のように出てくる!おおぉ!

感想
今回は簡単な関数を登録したが、Pythonに慣れている人からするととても便利なものなのかなと感じた(僕はpythonに慣れていない…)
またメリットとしては以下が思い当たる。
Tableauでの表現の幅が広がる
登録した計算をTabPyサーバで一目で見ることができ、一元管理できるのでマネジメントしやすい
次はKDEとかを登録して高度な表現をしてみたい