package com.qmth.ops.biz.service; import com.qmth.boot.core.ai.model.ocr.OcrType; import com.qmth.ops.biz.ai.client.OcrApiClient; import com.qmth.ops.biz.ai.client.OcrApiConfig; import com.qmth.ops.biz.ai.exception.OcrClientNotFound; import com.qmth.ops.biz.domain.OcrSupplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class OcrClientService { private static final Logger log = LoggerFactory.getLogger(OcrClientService.class); private OcrApiClient defaultClient; @Resource private OcrSupplierService ocrSupplierService; public synchronized void init() { //取第一个prior的为默认客户端,没有则取第一个 defaultClient = null; List list = ocrSupplierService.list(); if (!list.isEmpty()) { initApiClient(list.stream().filter(OcrSupplier::getPrior).findFirst().orElse(list.get(0))); } } private void initApiClient(OcrSupplier supplier) { try { String className = OcrApiClient.class.getName().replace("OcrApiClient", supplier.getClientClass()); OcrApiConfig config = new OcrApiConfig(supplier); Class clientClass = Class.forName(className); OcrApiClient client = (OcrApiClient) clientClass.getConstructor(OcrApiConfig.class).newInstance(config); if (defaultClient == null) { defaultClient = client; } } catch (Exception e) { log.error("OCR api client init error, supplier={}, class={}", supplier.getName(), supplier.getClientClass()); } } public String forImage(OcrType type, byte[] imageData) throws Exception { if (defaultClient == null) { throw new OcrClientNotFound(type); } return defaultClient.forImage(type, imageData); } }