Metadata-Version: 2.4
Name: tdx-tw
Version: 0.1.1
Summary: 臺灣運輸資料流通服務平臺（TDX）的 Python SDK
Keywords: tdx,taiwan,transport,public-transit,odata
Author: Nolan
Author-email: Nolan <300344883+nolantw@users.noreply.github.com>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Dist: anyio>=4.16.0
Requires-Dist: geographiclib>=2.1
Requires-Dist: hishel[httpx2]>=2.0.0
Requires-Dist: httpx2[brotli]>=2.16.2
Requires-Dist: pydantic>=2.14.4
Requires-Dist: tenacity>=9.2.1
Requires-Dist: tzdata>=2026.6
Requires-Dist: tdx-tw[arrow,fast,geo,geohash,gtfs,mqtt,pandas,polars,sqlite,xml] ; extra == 'all'
Requires-Dist: narwhals>=2.29.0 ; extra == 'arrow'
Requires-Dist: pyarrow>=26.0.1 ; extra == 'arrow'
Requires-Dist: pyproj>=3.8.0 ; extra == 'fast'
Requires-Dist: shapely>=2.2.0 ; extra == 'geo'
Requires-Dist: pygeohash>=3.6.0 ; extra == 'geohash'
Requires-Dist: gtfs-realtime-bindings>=3.0.0 ; extra == 'gtfs'
Requires-Dist: paho-mqtt>=2.2.0 ; extra == 'mqtt'
Requires-Dist: narwhals>=2.29.0 ; extra == 'pandas'
Requires-Dist: pandas>=3.1.1 ; extra == 'pandas'
Requires-Dist: pyarrow>=26.0.1 ; extra == 'pandas'
Requires-Dist: narwhals>=2.29.0 ; extra == 'polars'
Requires-Dist: polars>=2.2.0 ; extra == 'polars'
Requires-Dist: anysqlite>=0.0.5 ; extra == 'sqlite'
Requires-Dist: lxml>=6.2.0 ; extra == 'xml'
Requires-Dist: pydantic-xml>=2.22.0 ; extra == 'xml'
Requires-Python: >=3.13
Project-URL: Repository, https://github.com/nolantw/tdx
Project-URL: Issues, https://github.com/nolantw/tdx/issues
Project-URL: Changelog, https://github.com/nolantw/tdx/blob/main/CHANGELOG.md
Project-URL: TDX API, https://tdx.transportdata.tw/api-service/swagger/
Provides-Extra: all
Provides-Extra: arrow
Provides-Extra: fast
Provides-Extra: geo
Provides-Extra: geohash
Provides-Extra: gtfs
Provides-Extra: mqtt
Provides-Extra: pandas
Provides-Extra: polars
Provides-Extra: sqlite
Provides-Extra: xml
Description-Content-Type: text/markdown

<h1 align="center">TDX</h1>

<p align="center">臺灣運輸資料流通服務平臺（TDX）的非官方 Python SDK。</p>

<p align="center">
<a href="https://github.com/nolantw/tdx/actions/workflows/ci.yml"><img src="https://github.com/nolantw/tdx/actions/workflows/ci.yml/badge.svg?branch=dev" alt="CI"></a>
<a href="https://pypi.org/project/tdx-tw/"><img src="https://img.shields.io/pypi/v/tdx-tw.svg" alt="套件版本"></a>
<a href="https://pypi.org/project/tdx-tw/"><img src="https://img.shields.io/pypi/pyversions/tdx-tw.svg" alt="Python 版本"></a>
</p>

<p align="center"><strong>繁體中文</strong> | <a href="https://github.com/nolantw/tdx/blob/main/README.en.md">English</a></p>

臺灣運輸資料流通服務平臺（TDX）匯集全臺公共運輸與道路資料。這個 SDK 負責認證、呼叫 API 與驗證回應，並把公車、軌道、自行車、停車、路況、航空、航運等資料整理成有型別的 Python 物件，同步與非同步皆可使用。

## 安裝

需要 Python 3.13 以上版本。PyPI 套件名稱為 `tdx-tw`，匯入名稱為 `tdx`。

```shell
pip install tdx-tw
```

使用 uv 則執行 `uv add tdx-tw`。選用功能以 extra 安裝，例如 `pip install "tdx-tw[polars,geo]"`：

| Extra | 功能 |
| --- | --- |
| `polars` | 匯出為 Polars 表格 |
| `pandas` | 匯出為 pandas 表格 |
| `arrow` | 匯出為 Arrow 表格 |
| `geo` | 座標轉換為 Shapely 幾何物件 |
| `geohash` | 座標轉換為 geohash |
| `fast` | 以 pyproj 加速距離計算 |
| `xml` | 將 XML 解析為 pydantic-xml 模型 |

## 設定 API 金鑰

至 [TDX](https://tdx.transportdata.tw/) 註冊會員，在會員中心取得 API 金鑰的 Client ID 與 Client Secret。範例從環境變數讀取金鑰：

```shell
# macOS、 Linux
export TDX_CLIENT_ID="Client ID"
export TDX_CLIENT_SECRET="Client Secret"
```

```powershell
# Windows PowerShell
$env:TDX_CLIENT_ID = "Client ID"
$env:TDX_CLIENT_SECRET = "Client Secret"
```

## 快速開始

查詢公車路線各站的到站時間：

```python
import os

from tdx import Client

with Client(os.environ["TDX_CLIENT_ID"], os.environ["TDX_CLIENT_SECRET"]) as client:
    for board in client.bus_route("Taipei", "307").board():
        print(board.route_name, board.direction)
        for item in board.stops:
            print(item.stop.name, item.estimate_seconds)
```

在同一個 `with` 區塊中，也可以查詢車站的列車，以及座標附近的自行車站：

```python
from tdx import Position

for train in client.rail_station("TRA", "1000").trains():
    print(train.departure_time, train.destination, train.delay_minutes)

here = Position.at(longitude=121.517, latitude=25.047)
for place in client.nearby(here, city="Taipei", include=("bike",)).bike_stations:
    print(place.item.station.name, place.item.availability, place.distance)
```

非同步用戶端的操作相同，取得資料時加上 `await`：

```python
import asyncio
import os

from tdx import AsyncClient


async def main() -> None:
    async with AsyncClient(
        os.environ["TDX_CLIENT_ID"], os.environ["TDX_CLIENT_SECRET"]
    ) as client:
        for station in await client.bike.stations("Taipei", limit=10):
            print(station.name, station.position)


asyncio.run(main())
```

縣市以 TDX 的英文名稱指定，例如 `Taipei`、`NewTaipei`、`HsinchuCounty`，可用 `client.administration.cities()` 查詢。

## 高階操作

`Client` 與 `AsyncClient` 提供下列操作，自動挑選端點版本並合併靜態與即時資料。非同步版本在取得資料時使用 `await`。

| 操作 | 內容 |
| --- | --- |
| `bus_route(city, name)` | 以完整路線名稱查詢站序、班表、線型、票價、車輛動態；`board()` 合併站序與到站預估 |
| `rail_station(system, station_id)` | 車站資料、出口、設施、列車、到另一站的班次與票價 |
| `bike_station(city, station_uid)` | 租借站點與即時借還數量 |
| `car_park(area, car_park_id)` | 路外停車場與即時空位 |
| `nearby(position, city=...)` | 座標附近的公車站牌、軌道車站、自行車站與停車場，依距離排序 |

`nearby` 每種資料需要一次以上請求，可用 `include` 只選擇需要的種類。

## 基礎服務

| 資料類別 | 查詢入口 | 主要功能 |
| --- | --- | --- |
| 共通資料－行政區 | `administration` | 縣市、鄉鎮市區與村里 |
| 共通資料－公共運輸 | `transport_reference` | 主管機關、資料提供者、營運業者與行事曆 |
| 公車 | `bus` | 路線、站序、班表、票價、車輛動態與到站預估 |
| 軌道 | `rail` | 臺鐵、高鐵、捷運與阿里山林鐵的車站、班表、票價與即時資訊 |
| 自行車 | `bike` | 租借站點、即時借還數量與自行車道 |
| 停車資訊 | `parking` | 路外停車場、路邊路段、車格、即時空位與費率 |
| 共通資料－道路 | `road_reference` | 道路分類、路名、交流道與匝道 |
| 路況資訊 | `traffic` | 車流偵測器、資訊看板、攝影機、eTag 與即時路況 |
| 道路事件 | `road_events` | 公告與即時事件、交通管制及改道資訊 |
| 航空 | `air` | 機場、航班看板、班表、國內票價及 METAR |
| 航運 | `ship` | 港口、航線、船班、票價、即時船位及到離港看板 |
| GIS 圖資 | `gis` | 交通圖層、行政區界線、WKT、GeoJSON 與 XML |
| 路段編碼 | `road_links` | 路段、路口、幾何及版本異動 |
| 充電樁 | `charging` | 站點、設備、費率與接頭即時狀態 |
| 觀光資訊 | `tourism` | 台灣好行路線、班表、票價與即時到站 |
| 有聲號誌 | `audible_signals` | 行人有聲號誌位置、啟動方式與主管機關 |

`Client` 與 `AsyncClient` 共用上述查詢入口。`basic` 可直接呼叫指定版本的端點並傳入端點支援的 OData 參數。提供 `cache_ttl` 的查詢預設關閉快取，傳入秒數即可啟用。

上游端點及授權方式請見 [TDX 線上 API 說明](https://tdx.transportdata.tw/api-service/swagger/)。

## OData 查詢

查詢結果可用條件篩選、排序與分頁。`fields` 涵蓋清單查詢的欄位，包含巢狀欄位與陣列，錯誤的欄位或型別可在執行前由型別檢查器發現。

```python
from tdx import Query, fields
from tdx.bus import BusStop

stop = fields.bus_stop
query = (
    Query[BusStop]()
    .where(stop.name.zh_tw.contains("車站") | stop.name.en.startswith("Main"))
    .near(stop.position, longitude=121.517, latitude=25.047, radius=300)
    .order_by(stop.id.asc())
)
stops = client.bus.stops("Taipei", query=query, limit=20)
```

陣列欄位使用 `any` 與 `all`，條件以 `&`、`|`、`~` 組合。`query` 也接受原始的 OData 參數。

## XML

`tdx.xml.parse_xml` 以 pydantic-xml 模型解析 `get_xml` 取得的內容，不展開外部實體，也不存取網路。此功能需要 `xml` 選用相依套件。

## 回傳資料

清單查詢回傳不可變的 `Records`，`info` 提供更新時間與版本。各類資料共用 `Name`、`Position`、時間與日期型別。

`Records` 可用 `to_polars()`、`to_pandas()`、`to_arrow()` 匯出，巢狀欄位以點號命名，例如 `name.zh_tw`。`Position` 提供 `distance_to()`、`to_shapely()` 與 `to_geohash()`。匯出功能需要對應的選用相依套件。

## 連線

暫時性的連線錯誤、逾時與伺服器錯誤會自動重試，次數由 `retries` 設定。TDX 指定等待時間時會依其等待，權杖失效時會重新取得。所有錯誤皆繼承 `tdx.exceptions.TDXError`。

指定 `cache_dir` 可將回應保存在磁碟。之後的查詢會先向 TDX 確認資料是否更新，未更新時不重新下載，確認請求仍計入用量。快取不保存存取權杖。

## 貢獻

歡迎到 [GitHub Issues](https://github.com/nolantw/tdx/issues) 回報問題或提出 API 需求。

請見[變更紀錄](https://github.com/nolantw/tdx/blob/main/CHANGELOG.md)。資料由[運輸資料流通服務平臺](https://tdx.transportdata.tw/)提供。tdx-tw 為非官方套件，與交通部無關。

---

<p align="center"><i>TDX SDK 以 <a href="https://github.com/nolantw/tdx/blob/main/LICENSE">MIT 授權</a>釋出。</i></p>
