Skip to main content

Switch-Hub
switch-hub — это удобная утилита для переключения между разными источниками моделей и датасетов: Hugging Face Hub, Cloud.ru Repo. Она позволяет прозрачно работать с моделями и датасетами в разных экосистемах, не изменяя привычный интерфейс.

Основные возможности

  • Лёгкое переключение между хранилищами: Hugging Face Hub, Cloud.ru Repo.
  • Минимальные изменения в коде — привычный интерфейс transformers, datasets, diffusers ....
  • Гибкость для CI/CD, исследований и продакшена.

Установка

pip install switch-hub

Пример использования

from transformers import AutoModel
from switch_hub import HubSwitcher

switcher = HubSwitcher()

# Переключаемся на Hugging Face Hub
switcher.switch_to_hf()
model = AutoModel.from_pretrained('dmitryradionov/some-model')

# Переключаемся на Repo Cloud.ru и пушим модель туда
switcher.switch_to_rh()
model.push_to_hub('70e5f7a7-f6a7-4fd7-a8ea-e288150b6fb8/some-model')

# Загружаем модель из Cloud.ru Repo 
model_mr = AutoModel.from_pretrained('70e5f7a7-f6a7-4fd7-a8ea-e288150b6fb8/some-model')

# Снова переключаемся на Hugging Face Hub и пушим модель назад
switcher.switch_to_hf()
model_mr.push_to_hub("dmitryradionov/some-model")

Работа с аутентификацией и токенами

Для работы с приватными и большинством публичных репозиториев, потребуется токен доступа:

  • Hugging Face Hub: HF_TOKEN
  • Cloud.ru Repo: RH_TOKEN (обязателен всегда)

Как передавать токены

1. Через переменные окружения или .env файл
Рекомендуется для локальной разработки и CI/CD:
Пример .env:

HF_TOKEN=hf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
RH_TOKEN=rh_yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

2. Явно в конструктор HubSwitcher

from switch_hub import HubSwitcher

switcher = HubSwitcher(
    hf_token="hf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    rh_token="rh_yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
)

Важно:

  • RH_TOKEN обязателен для Cloud.ru Repo всегда
  • HF_TOKEN обязателен только для приватных репозиториев Hugging Face, но рекомендуется указывать всегда, чтобы избежать лимитов и быть готовым к работе с приватным контентом Hugging Face
  • Никогда не публикуйте свои токены в открытых источниках — используйте секреты сборки и переменные окружения

Описание ключевых методов

reset()
Восстанавливает все переменные окружения и внутренние настройки, которые были изменены при переключении между хабами. Используйте этот метод, если нужно вручную откатить все изменения состояния, внесённые switcher'ом, например после завершения операций с приватным registry.

Пример:

switcher.switch_to_rh()
# ... работа с приватным хабом ...
switcher.reset()  # Возвращение к исходным параметрам окружения

context(mode)
Контекстный менеджер для временного переключения хаба.
После выхода из блока with окружение автоматически восстанавливается к исходному.

Пример:

from switch_hub import HubSwitcher

switcher = HubSwitcher()

with switcher.context('rh'):
    # В этом блоке все операции проходят через Cloud.ru Repo
    model = AutoModel.from_pretrained('cloudru_id/some-model')
    # ... другие операции ...

# После выхода из блока — автоматически восстановлен Hugging Face/прежний хаб
# mode: может быть 'hf' (Hugging Face Hub) или 'rh' (Cloud.ru Repo)

Кейсы использования

  • Исследование новых моделей: переключайтесь между публичными репозиториями и приватным registry.
  • Экспорт и импорт моделей между облаком и Hugging Face.
  • Автоматизация CI/CD пайплайнов для MLOps.

P.S. Эти способы аутентификации работают для моделей, датасетов, diffusers и других библиотек, поддерживаемых switch-hub.
Рекомендуется всегда указывать RH_TOKEN и HF_TOKEN через переменные окружения или секреты инфраструктуры для максимальной гибкости и безопасности.

Metadata

Release files for switch-hub 0.0.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for switch-hub 0.0.5
File Size Uploaded Provenance
switch_hub-0.0.5.tar.gz 10.0 kB With provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for switch-hub 0.0.5
File Interpreter ABI Platform
switch_hub-0.0.5-py3-none-any.whl Python 3 none any Details

Total release size: 18.8 kB

Release files / switch_hub-0.0.5.tar.gz

Download URL switch_hub-0.0.5.tar.gz
Size 10.0 kB
Tags Source
SHA-256 checksum
How to use checksums
bcb7cd04e91417983144fd68a375685c31e65bb4d0e6a3c65a17a81418c13271
BLAKE2b-256 checksum
How to use checksums
9d9c5887013637ccdd498aa8679903dff97418fedb263276cf5d47a39cefc8e6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jul 22, 2025.

Transparency log

Release files / switch_hub-0.0.5-py3-none-any.whl

Download URL switch_hub-0.0.5-py3-none-any.whl
Size 8.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3c2d18f098e706131e24ed512c29b7a982c7789af43683769f57488628672521
BLAKE2b-256 checksum
How to use checksums
342733c547560c2e0fbe34519261a9d483727d2d4ff763450407a105bbfb4528
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jul 22, 2025.

Transparency log

Security for switch-hub 0.0.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for switch_hub-0.0.5.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jul 22, 2025.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page