Разработка платформы для продажи и дистрибуции AI-моделей
Платформа продажи AI-моделей — это коммерческая инфраструктура для монетизации ML-разработок: secure delivery моделей, защита интеллектуальной собственности, гибкие лицензионные схемы и billing.
Модели монетизации
SaaS (API-as-a-Service): Потребитель не получает веса модели, а вызывает её через API. Наиболее защищённая модель IP. Провайдер полностью контролирует доступ и может мгновенно отозвать лицензию.
On-Premise Deployment: Потребитель разворачивает модель в своей инфраструктуре. Требует hardware-based лицензирования (привязка к hardware fingerprint или cloud account ID). Риск утечки весов выше.
Hybrid: API для разработки и тестирования, on-premise для production — популярная enterprise схема.
Secure Model Delivery
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import base64
class SecureModelPackager:
def package_model(self, model_path: str, license_id: str,
hardware_fingerprint: str) -> bytes:
"""Упаковка модели с привязкой к лицензии и железу"""
# Генерация ключа, привязанного к лицензии + fingerprint
key_material = f"{license_id}:{hardware_fingerprint}".encode()
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=b"model_license_v1",
iterations=100000,
)
key = base64.urlsafe_b64encode(kdf.derive(key_material))
fernet = Fernet(key)
# Чтение и шифрование весов модели
with open(model_path, 'rb') as f:
model_bytes = f.read()
encrypted = fernet.encrypt(model_bytes)
# Создание manifest с лицензионными ограничениями
manifest = {
"license_id": license_id,
"hardware_fingerprint": hardware_fingerprint,
"model_hash": hashlib.sha256(model_bytes).hexdigest(),
"valid_until": (datetime.utcnow() + timedelta(days=365)).isoformat(),
"usage_limit_requests": 1_000_000
}
return package_with_manifest(encrypted, manifest)
class SecureModelLoader:
def load(self, package_path: str, license_key: str) -> torch.nn.Module:
"""Загрузка и расшифровка модели"""
manifest, encrypted_model = unpack(package_path)
# Валидация лицензии
if not self._validate_license(manifest, license_key):
raise LicenseError("Invalid or expired license")
# Расшифровка
fernet = Fernet(self._derive_key(manifest['license_id']))
model_bytes = fernet.decrypt(encrypted_model)
# Проверка целостности
if hashlib.sha256(model_bytes).hexdigest() != manifest['model_hash']:
raise IntegrityError("Model file corrupted")
return torch.load(io.BytesIO(model_bytes))
License Server
class LicenseServer:
async def issue_license(self, purchase_id: str, customer_id: str,
model_id: str, tier: str) -> str:
license_key = secrets.token_hex(32)
await self.db.create_license({
'license_key': license_key,
'customer_id': customer_id,
'model_id': model_id,
'tier': tier,
'requests_limit': self.get_tier_limits(tier)['requests'],
'valid_until': datetime.utcnow() + self.get_tier_duration(tier),
'created_at': datetime.utcnow()
})
return license_key
async def validate_and_track(self, license_key: str) -> dict:
license = await self.db.get_license(license_key)
if not license:
raise LicenseError("License not found")
if license['valid_until'] < datetime.utcnow():
raise LicenseError("License expired")
if license['requests_used'] >= license['requests_limit']:
raise LicenseError("Request limit exceeded")
# Инкремент счётчика использования
await self.db.increment_usage(license_key)
return license
Типичный тип клиентов: AI-стартапы, продающие специализированные модели (медицинская диагностика, юридический анализ, промышленный defect detection) enterprise-компаниям с on-premise требованиями.







