diff --git a/src/main/java/com/ai/da/controller/PythonController.java b/src/main/java/com/ai/da/controller/PythonController.java index d1b722f4..966efef4 100644 --- a/src/main/java/com/ai/da/controller/PythonController.java +++ b/src/main/java/com/ai/da/controller/PythonController.java @@ -125,11 +125,11 @@ public class PythonController { @CrossOrigin @Operation(summary = "Seg Anything 转发接口") @PostMapping("/segAnything") - public Response segAnything(@RequestBody Map payload) { + public Response segAnything(@RequestBody Map payload) { // 将前端传来的 Map 转为 fastjson JSONObject 并转发给 python 服务 JSONObject requestJson = (JSONObject) JSON.toJSON(payload); - JSONObject result = pythonService.segAnything(requestJson); - return Response.success(result); + String url = pythonService.segAnything(requestJson); + return Response.success(url); } } diff --git a/src/main/java/com/ai/da/python/PythonService.java b/src/main/java/com/ai/da/python/PythonService.java index 8c742199..3f6a53ac 100644 --- a/src/main/java/com/ai/da/python/PythonService.java +++ b/src/main/java/com/ai/da/python/PythonService.java @@ -1,4607 +1,4632 @@ -package com.ai.da.python; - -import cn.hutool.core.collection.CollectionUtil; -import cn.hutool.core.exceptions.ExceptionUtil; -import com.ai.da.common.config.FileProperties; -import com.ai.da.common.config.exception.BusinessException; -import com.ai.da.common.context.UserContext; -import com.ai.da.common.enums.*; -import com.ai.da.common.utils.*; -import com.ai.da.mapper.primary.CollocationMapper; -import com.ai.da.mapper.primary.DressingMapper; -import com.ai.da.mapper.primary.entity.*; -import com.ai.da.mapper.secondary.AttributeRetrievalMapper; -import com.ai.da.mapper.secondary.entity.AttributeRetrieval; -import com.ai.da.mapper.secondary.entity.AttributeRecognitionJSON; -import com.ai.da.model.dto.*; -import com.ai.da.model.enums.MalePosition; -import com.ai.da.model.enums.Sex; -import com.ai.da.model.vo.*; -import com.ai.da.python.vo.*; -import com.ai.da.service.DesignHistoryService; -import com.ai.da.service.PythonTAllInfoService; -import com.ai.da.service.SysFileService; -import com.alibaba.fastjson.*; -import com.alibaba.fastjson.serializer.SerializerFeature; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import io.netty.util.internal.StringUtil; -import lombok.extern.slf4j.Slf4j; -import okhttp3.*; -import org.apache.commons.lang3.RandomUtils; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.Assert; -import org.springframework.util.CollectionUtils; -import org.springframework.util.StringUtils; -import org.springframework.web.multipart.MultipartFile; - -import jakarta.annotation.Resource; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.*; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -@Slf4j -@Service -public class PythonService { - - @Resource - private FileProperties fileProperties; - @Resource - private SysFileService sysFileService; - @Resource - private DesignHistoryService designHistoryService; - @Value("${access.python.ip:''}") - private String accessPythonIp; - @Value("${access.python.port:''}") - private String accessPythonPort; - @Value("${minio.bucketName.gradient}") - private String gradientBucketName; - @Value("${access.python.generate_sr_port}") - private String srServicePort; - - @Value("${design.callback.url}") - private String callbackUrl; - - @Resource - private PythonTAllInfoService pythonTAllInfoService; - - @Resource - private MinioUtil minioUtil; - - @Resource - private RedisUtil redisUtil; - - /** - * 生成打印的图片 二合一 (废弃于2024/01/02) - * - * @param printPath - * @return - */ - public String generatePrint(List printPath, Long userId) { - //限流校验 -// AccessLimitUtils.validate("generatePrint", 2); - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - Map content = Maps.newHashMap(); - content.put("fusion_content_path", printPath.get(0)); - content.put("fusion_style_path", printPath.get(1)); - content.put("userid", String.valueOf(userId)); -// content.put("fusion_output_path", getPythonOutputPath( -// printPath.get(0), PythonToJavaApiOperationTypeEnum.GENERATE_PRINT)); - RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); - Request request = new Request.Builder() -// .url(accessPythonIp + ":9999/aifda/api/v1.0/fusion_test") - .url(accessPythonIp + ":" + accessPythonPort + "/api/image_fusion") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response; - String responseBody; - try { - log.info("moodboard与printboard图片合成 入参content###{}", JSON.toJSONString(content)); - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService## moodboard与printboard图片合成异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("image.synthesis.failed"); - } - //去除限流 -// AccessLimitUtils.validateOut("generatePrint"); - JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(response)); - if (jsonObject.getBoolean("successful")) { - try { - if (Objects.nonNull(response.body())) { - responseBody = response.body().string(); - JSONObject responseObj = JSON.parseObject(responseBody); - log.info("moodboard与printboard图片合成 python返回###{}", responseObj); - return responseObj.get("data").toString(); - } - } catch (IOException | JSONException e) { - log.error("Python moodboard与printboard图片合成异常 : {}", e.getMessage()); - throw new BusinessException("image.synthesis.failed"); - } - log.error("moodboard与printboard图片合成异常###{}", jsonObject); - throw new BusinessException("image.synthesis.failed"); -// return content.get("fusion_output_path"); - } - log.info("moodboard与printboard图片合成异常###{}", jsonObject); - //生成失败 - throw new BusinessException("image.synthesis.failed"); - } - - /** - * 生成python要保存的文件 - * - * @param picturePath - * @return - */ - private String getPythonOutputPath(String picturePath, PythonToJavaApiOperationTypeEnum pythonOperationType) { - String linuxDomain = fileProperties.getLinuxDomain(); - String day = DateUtil.dateToStr(new Date(), DateUtil.YYYYMM); - //获取图片后缀 - String suffix = picturePath.substring(picturePath.lastIndexOf(".")); - String generateFileName = pythonOperationType.getRealName() - + "-" + UUID.randomUUID().toString() + suffix; - return linuxDomain + day + File.separator + "pythonFile" + File.separator - + pythonOperationType.getRealName() - + File.separator + generateFileName; - } - - /** - * python生成的文件上传到java服务器统一维护 - * - * @param file - * @param operateType - * @return - */ - @Transactional(rollbackFor = Exception.class) - public String upload(MultipartFile file, String operateType) { - //用户信息 - PythonToJavaApiOperationTypeEnum operationType = PythonToJavaApiOperationTypeEnum.uploadOf(operateType); - Assert.notNull(operationType, "unknown operateType " + operateType + "!"); - String path = calculateFileUrl(operationType); - File generateFile = FileUtil.upload2(file, path); - - String linuxDomain = fileProperties.getLinuxDomain(); - if (!StringUtils.isEmpty(linuxDomain)) { - //linux 系统 - String oldPath = fileProperties.getSys().getPath(); - return generateFile.getAbsolutePath().replace(oldPath, linuxDomain); - } - return null; - } - -// @Transactional -// public List upload(MultipartFile[] files, String operateType) { -// List paths = new ArrayList<>(); -// //用户信息 -// PythonToJavaApiOperationTypeEnum operationType = PythonToJavaApiOperationTypeEnum.uploadOf(operateType); -// Assert.notNull(operationType, "unknown operateType " + operateType + "!"); -// String path = calculateFileUrl(operationType); -// for (MultipartFile file : files) { -// File generateFile = FileUtil.upload2(file, path); -// Assert.notNull(generateFile, "An error occurred while processing the file!"); -// -// String linuxDomain = fileProperties.getLinuxDomain(); -// if (!StringUtils.isEmpty(linuxDomain)) { -// //linux 系统 -// String oldPath = fileProperties.getSys().getPath(); -// paths.add(generateFile.getAbsolutePath().replace(oldPath, linuxDomain)); -// } -// } -// return paths; -// } - - - private String calculateFileUrl(PythonToJavaApiOperationTypeEnum operationType) { - String rootPath = fileProperties.getSys().getPath(); - String day = DateUtil.dateToStr(new Date(), DateUtil.YYYYMM); - return rootPath + day + File.separator + "pythonFile" + File.separator - + operationType.getRealName() + File.separator; - } - - - /** - * 组装和计算design参数 - * - * @param systemScale - * @param singleOverall - * @param switchCategory - * @param elementVO - * @param processId - * @return - */ - public DesignPythonObjects covertDesignParam(BigDecimal systemScale, String singleOverall, - String switchCategory, ValidateElementVO elementVO, String processId, Long collectionId) { - DesignPythonObjects designPythonObjects = new DesignPythonObjects(); - List objects = new ArrayList<>(); - designPythonObjects.setObjects(objects); - designPythonObjects.setProcess_id(processId); - designPythonObjects.setCallback_url(callbackUrl); - - long pinPrintNum = calculateDesignPinPrintNum(elementVO.getPrintBoardElements()); - long noPinPrintNum = calculateDesignNoPinPrintNum(elementVO.getPrintBoardElements(), elementVO.getDesignNum()); - long noPrintNum = elementVO.getDesignNum() - pinPrintNum - noPinPrintNum; - elementVO.setNoPinPrintNum(noPinPrintNum); - - int[] sketchNumbers = new int[3]; - - int designNum = elementVO.getDesignNum(); - Set assembledObjects = new HashSet<>(); // 用于存储已组装的 DesignPythonObject - DesignPythonObject lastAssembledObject = null; // 上一次组装的对象 - - for (int i = 0; i < designNum; i++) { - CurrentDesignPictureTypeEnum designPictureType = calculateCurrentDesignPictureTypeNew(elementVO, sketchNumbers, systemScale); - if (designPictureType == null) break; - - CurrentDesignPrintPictureTypeEnum designPrintPictureType = calculateCurrentDesignPintPictureType(pinPrintNum, noPinPrintNum, noPrintNum); - if (designPrintPictureType == null) break; - - updateSketchNumbers(designPictureType, sketchNumbers); - switch (designPrintPictureType) { - case PIN: - pinPrintNum--; - break; - case NO_PIN: - noPinPrintNum--; - break; - case NO: - noPrintNum--; - break; - } - DesignPythonItemPrint designPythonItemPrint = getRandomPrint(elementVO, designPrintPictureType); - elementVO.setDesignPythonItemPrint(designPythonItemPrint); - elementVO.setDesignPrintPictureTypeLayoutList(calculateCurrentDesignPintPictureTypeLayout(elementVO.getModelSex())); - List beforeAssemblyHasUseMd5List = new ArrayList<>(elementVO.getHasUseMd5List()); - DesignPythonObject pythonObject = createDesignPythonObject(elementVO, designPictureType, systemScale, singleOverall, switchCategory, i); - - // 如果当前对象与已组装的对象重复,则跳过当前组装 - DesignPythonObject designPythonObjectCopy = getCopy(pythonObject); - - boolean isDuplicate = assembledObjects.contains(designPythonObjectCopy); - - if (isDuplicate) { - elementVO.setHasUseMd5List(beforeAssemblyHasUseMd5List); - i --; - - switch (designPrintPictureType) { - case PIN: - pinPrintNum++; - break; - case NO_PIN: - noPinPrintNum++; - break; - case NO: - noPrintNum++; - break; - } - continue; - } - - // 将当前对象添加到已组装的集合中,并记录 - assembledObjects.add(designPythonObjectCopy); - - objects.add(pythonObject); - redisUtil.addProcessId(processId, i + 1); - } - return designPythonObjects; - } - - private DesignPythonObject getCopy(DesignPythonObject pythonObject) { - DesignPythonObject designPythonObjectCopy = CopyUtil.copyObject(pythonObject, DesignPythonObject.class); - designPythonObjectCopy.setObjectSign(null); - DesignPythonBasic basic = designPythonObjectCopy.getBasic(); - basic.setSave_name(null); - designPythonObjectCopy.setBasic(basic); - List items = designPythonObjectCopy.getItems(); - List itemsCopy = new ArrayList<>(); - for (DesignPythonItem item : items) { - item.setElementId(null); - item.setIcon(null); - item.setBusinessId(null); - item.setImage_id(null); - item.setImageId(null); - itemsCopy.add(item); - } - designPythonObjectCopy.setItems(itemsCopy); - return designPythonObjectCopy; - } - - private void updateSketchNumbers(CurrentDesignPictureTypeEnum designPictureType, int[] sketchNumbers) { - switch (designPictureType) { - case PIN: - sketchNumbers[0]++; - break; - case NO_PIN: - sketchNumbers[2]--; - break; - case SYS_FILE: - sketchNumbers[1]--; - break; - } - } - - private void updatePrintNumbers(CurrentDesignPrintPictureTypeEnum designPrintPictureType, long pinPrintNum, long noPinPrintNum, long noPrintNum) { - switch (designPrintPictureType) { - case PIN: - pinPrintNum--; - break; - case NO_PIN: - noPinPrintNum--; - break; - case NO: - noPrintNum--; - break; - } - } - - private DesignPythonObject createDesignPythonObject(ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType, BigDecimal systemScale, String singleOverall, String switchCategory, int i) { - DesignPythonObject pythonObject = new DesignPythonObject(); - pythonObject.setItems(coverToDesignPythonItemNew(elementVO, designPictureType, systemScale)); - pythonObject.setBasic(coverToBasic(pythonObject.getItems().get(0), singleOverall, switchCategory, elementVO.getDesignLibraryModelPoint(), elementVO.getDesignLibraryModelPointVO())); - if (CollectionUtil.isNotEmpty(elementVO.getRequestIdList())) { - pythonObject.setObjectSign(elementVO.getRequestIdList().get(i)); - } - return pythonObject; - } - - - private CurrentDesignPictureTypeEnum calculateCurrentDesignPictureTypeNew(ValidateElementVO elementVO, int[] sketchNumbers, BigDecimal systemScale) { - List pinData = getPinData(elementVO); - Integer designNum = elementVO.getDesignNum(); - if (CollectionUtil.isNotEmpty(pinData)) { - return CurrentDesignPictureTypeEnum.PIN; - } else { - if (sketchNumbers[1] == 0 && sketchNumbers[2] == 0) { - sketchNumbers[1] = systemScale.multiply(BigDecimal.valueOf(designNum - sketchNumbers[0])).setScale(0, BigDecimal.ROUND_HALF_UP).intValue(); - sketchNumbers[2] = designNum - sketchNumbers[0] - sketchNumbers[1]; - } - if (sketchNumbers[2] > 0 && sketchNumbers[1] > 0) { - Long l = RandomsUtil.randomSysFile(0l, 2l); - if (l == 0l) { - return CurrentDesignPictureTypeEnum.NO_PIN; - } else { - return CurrentDesignPictureTypeEnum.SYS_FILE; - } - } - if (sketchNumbers[2] > 0) { - return CurrentDesignPictureTypeEnum.NO_PIN; - } - return CurrentDesignPictureTypeEnum.SYS_FILE; - } - } - - private int calculateNoPinSketchNum(int pinSketchNum, int sysSketchNum) { - return 8 - pinSketchNum - sysSketchNum; - } - - private int calculateSysSketchNum(BigDecimal sysRatio, int pinSketchNum) { - // Calculate sysRatio * (8 - pinSketchNum) - BigDecimal result = sysRatio.multiply(BigDecimal.valueOf(8 - pinSketchNum)); - - // Round the result to the nearest integer using half-up rounding - - return result.setScale(0, RoundingMode.HALF_UP).intValue(); - } - -// private int calculatePinSketchNum(List sketchBoardElements, List hasUseMd5List) { -// List pinData = getPinData(sketchBoardElements, hasUseMd5List); -// if (CollectionUtil.isEmpty(pinData)) { -// return 0; -// } -//// long topNum = sketchBoardElements.stream() -//// .filter(skecth -> skecth.getHasPin() == 1 -//// && DesignPythonItem.OUTWEAR_DRESS_BLOUSE.contains(skecth.getLevel2Type())).count(); -//// long bottomNum = sketchBoardElements.stream() -//// .filter(skecth -> skecth.getHasPin() == 1 -//// && DesignPythonItem.SKIRT_TROUSERS.contains(skecth.getLevel2Type())).count(); -//// int num = Arrays.asList(topNum, bottomNum).stream().max(Comparator.comparing(Long::valueOf)).get().intValue(); -// int num = pinData.size(); -// return Math.min(num, 8); -// } - - //计算当前的图片类型 - private CurrentDesignPictureTypeEnum calculateCurrentDesignPictureType(int pinSketchNum, int sysSketchNum, int noPinSketchNum) { - List codes = Lists.newArrayList(); - if (pinSketchNum > 0) { - //pin默认优先选择 不参与计算 后续有调整再说 -// codes.add(pinPictureNum); - return CurrentDesignPictureTypeEnum.PIN; - } - if (sysSketchNum > 0) { - codes.add(CurrentDesignPictureTypeEnum.SYS_FILE.getCode()); - } - - if (noPinSketchNum > 0) { - codes.add(CurrentDesignPictureTypeEnum.NO_PIN.getCode()); - } - List pictureTypeEnums = CurrentDesignPictureTypeEnum.ofList(codes); - if (CollectionUtils.isEmpty(pictureTypeEnums)) { - return null; - } - int max = pictureTypeEnums.size(); - int min = 0; - Long randomIndex = RandomsUtil.randomSysFile((long) min, (long) max); - return pictureTypeEnums.get(randomIndex.intValue()); - } - - //计算系统图片张数 - private static int calculateSysPictureNum(BigDecimal sysRatio, int pinPictureNum) { - if (pinPictureNum > 4) { - int poolSize = 8 - pinPictureNum; - if (poolSize == 0) { - return 0; - } - return BigDecimal.valueOf(poolSize).multiply(sysRatio) - .setScale(0, BigDecimal.ROUND_HALF_UP).intValue(); - } else { - return BigDecimal.valueOf(4).multiply(sysRatio) - .setScale(0, BigDecimal.ROUND_HALF_UP).intValue(); - } - } - - //计算用户库图片张数 - private static int calculateUserLibraryPictureNum(int sysPictureNum, int pinPictureNum) { - if (pinPictureNum > 4) { - return 8 - pinPictureNum - sysPictureNum; - } else { - return 4 - sysPictureNum; - } - } - - //计算Pin图片张数 -// private int calculatePinPictureNum(List sketchBoardElements, List hasUseMd5List) { -// List pinData = getPinData(sketchBoardElements, hasUseMd5List); -// if (CollectionUtil.isEmpty(pinData)) { -// return 0; -// } -// long topNum = sketchBoardElements.stream() -// .filter(skecth -> skecth.getHasPin() == 1 -// && DesignPythonItem.OUTWEAR_DRESS_BLOUSE.contains(skecth.getLevel2Type())).count(); -// long bottomNum = sketchBoardElements.stream() -// .filter(skecth -> skecth.getHasPin() == 1 -// && DesignPythonItem.SKIRT_TROUSERS.contains(skecth.getLevel2Type())).count(); -// int num = Arrays.asList(topNum, bottomNum).stream().max(Comparator.comparing(Long::valueOf)).get().intValue(); -// if (num > 8) { -// return 8; -// } -// return num; -// } - - //计算当前的Print图片类型 - private CurrentDesignPrintPictureTypeEnum calculateCurrentDesignPintPictureType(long pinPrintNum, long noPinPrintNum, long noPrintNum) { - List codes = Lists.newArrayList(); - if (pinPrintNum > 0) { - //pin默认优先选择 不参与计算 后续有调整再说 -// codes.add(pinPictureNum); - return CurrentDesignPrintPictureTypeEnum.PIN; - } - if (noPinPrintNum > 0) { - codes.add(CurrentDesignPrintPictureTypeEnum.NO_PIN.getCode()); - } - if (noPrintNum > 0) { - codes.add(CurrentDesignPrintPictureTypeEnum.NO.getCode()); - } - - List pictureTypeEnums = CurrentDesignPrintPictureTypeEnum.ofList(codes); - if (CollectionUtils.isEmpty(pictureTypeEnums)) { - return null; - } - int max = pictureTypeEnums.size(); - int min = 0; - Long randomIndex = RandomsUtil.randomSysFile((long) min, (long) max); - return pictureTypeEnums.get(randomIndex.intValue()); - } - - //计算当前的Print图片类型具体分布位置 0. 上衣 1.下衣 2.上衣和下衣都print - private List calculateCurrentDesignPintPictureTypeLayout(String modelSex) { - if (modelSex.equals(Sex.FEMALE.getValue())) { - Long randomIndex = RandomsUtil.randomSysFile(0L, 3L); - if (randomIndex == 0) { - return DesignPythonItem.OUTWEAR_DRESS_BLOUSE; - } - if (randomIndex == 1) { - return DesignPythonItem.SKIRT_TROUSERS; - } - if (randomIndex == 2) { - List all = new ArrayList<>(DesignPythonItem.OUTWEAR_DRESS_BLOUSE); - all.addAll(new ArrayList<>(DesignPythonItem.SKIRT_TROUSERS)); - return all; - } - } else if (modelSex.equals(Sex.MALE.getValue())) { - Long randomIndex = RandomsUtil.randomSysFile(0L, 3L); - if (randomIndex == 0) { - return DesignPythonItem.TOPS; - } - if (randomIndex == 1) { - return DesignPythonItem.BOTTOMS; - } - if (randomIndex == 2) { - List all = new ArrayList<>(DesignPythonItem.TOPS); - all.addAll(new ArrayList<>(DesignPythonItem.BOTTOMS)); - return all; - } - } - return null; - } - - //计算print 非Pin图片剩余张数 - private long calculateDesignPinPrintNum(List printBoardElements) { - if (CollectionUtils.isEmpty(printBoardElements)) { - return 0; - } - return printBoardElements.stream().filter(f -> f.getHasPin() == 1).count(); - } - - //计算print 非Pin图片剩余张数 - private long calculateDesignNoPinPrintNum(List printBoardElements, Integer designNum) { - if (CollectionUtils.isEmpty(printBoardElements)) { - return 0; - } - long noPinNum = printBoardElements.stream().filter(f -> f.getHasPin() == 0).count(); - if (noPinNum == 0L) { - return 0; - } else { - long pinNum = printBoardElements.stream().filter(f -> f.getHasPin() == 1).count(); - if (designNum - pinNum < 0){ - return RandomsUtil.randomSysFile(0L, (long) (pinNum/2 + 1)); - } else if (designNum - pinNum < designNum/2) { - return RandomsUtil.randomSysFile(0L, designNum - pinNum + 1); - } else { - return RandomsUtil.randomSysFile(0L, (long) (designNum/2 + 1)); - } - } - } - -// private List coverToDesignPythonItem(ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType) { -// //Pin的数据 -// List pinData = getPinData(elementVO.getSketchBoardElements(), elementVO.getHasUseMd5List()); -// //计算填充PythonItemBlouse -// List items = Lists.newArrayList(); -// if (elementVO.getModelSex().equals("Female")) { -// List blouseList = calculatePythonItemBlouse(pinData, elementVO, designPictureType); -// if (!CollectionUtils.isEmpty(blouseList)) { -// items.addAll(blouseList); -// } -// //计算填充PythonItemSkirt -// DesignPythonItem skirt = calculatePythonItemSkirt(pinData, elementVO, designPictureType); -// if (Objects.nonNull(skirt)) { -// items.add(skirt); -// } -// } else { -// // 男装逻辑 -// DesignPythonItem top = calculatePythonItemTop(pinData, elementVO, designPictureType); -// if (Objects.nonNull(top)) { -// items.add(top); -// } -// DesignPythonItem bottom = calculatePythonItemBottom(pinData, elementVO, designPictureType); -// if (Objects.nonNull(bottom)) { -// items.add(bottom); -// } -// if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall()) && elementVO.getSwitchCategory().equals("Outwear")) { -// DesignPythonItem outwear = calculatePythonItemOutwear(pinData, elementVO, designPictureType); -// if (Objects.nonNull(outwear)) { -// items.add(outwear); -// } -// } -// } -// //计算填充Hairstyle Earring Shoes Body -// items.addAll(calculatePythonItemHairstyleShoes(elementVO, elementVO.getDesignLibraryModelPoint())); -// return items; -// } - - private List coverToDesignPythonItemNew(ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType, BigDecimal systemScale) { - List itemList = new ArrayList<>(); - DesignPythonItem designPythonItem = calculatePythonItem(elementVO, designPictureType); - if (Objects.nonNull(designPythonItem)) { - itemList.add(designPythonItem); - if (elementVO.getSingleOverall().equals(SingleOverallEnum.OVERALL.getRealName())) { - List otherSketchCategoryList = getOtherSketchCategoryList(elementVO.getModelSex(), designPythonItem); - if (!otherSketchCategoryList.isEmpty()) { -// JSONObject attributeRecognition = getAttributeRecognition(designPythonItem.getPath(), designPythonItem.getType(), elementVO.getModelSex()); - for (String styleCategory : otherSketchCategoryList) { -// DesignPythonItem otherSketch = processAttributeRecognition(attributeRecognition, elementVO, designPictureType, styleCategory, systemScale); - DesignPythonItem otherSketch = processAttributeRecognition(null, elementVO, designPictureType, styleCategory, systemScale); - itemList.add(otherSketch); - } - } - itemList.addAll(calculatePythonItemHairstyleShoes(elementVO, elementVO.getDesignLibraryModelPoint())); - } - } - return itemList; - } - - private DesignPythonItem processAttributeRecognition(JSONObject attributeRecognition, ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType, String styleCategory, BigDecimal systemScale) { - switch (designPictureType) { - case PIN: - return processPinAttributeRecognition(attributeRecognition, elementVO, styleCategory, systemScale); - case NO_PIN: - case SYS_FILE: - return processNoPinOrSysFileAttributeRecognition(attributeRecognition, elementVO, styleCategory, systemScale); - default: - throw new BusinessException("unknown.designPictureType"); - } - } - - private DesignPythonItem processPinAttributeRecognition(JSONObject attributeRecognition, ValidateElementVO elementVO, String styleCategory, BigDecimal systemScale) { - List collectPin = getFilteredCollectionElements(elementVO.getSketchBoardElements(), 1, styleCategory); - if (CollectionUtil.isNotEmpty(collectPin)) { - int randomNum = RandomsUtil.randomSysFile(collectPin.size()); - elementVO.getHasUseMd5List().add(collectPin.get(randomNum).getMd5()); - return coverSketchToDesignPythonItem(collectPin.get(randomNum).getId(), collectPin.get(randomNum), elementVO); - } else { - List collectNoPin = getFilteredCollectionElements(elementVO.getSketchBoardElements(), 0, styleCategory); - return processNoPinOrSysFileAttributeRecognitionWithPool(collectNoPin, attributeRecognition, elementVO, styleCategory, systemScale); - } - } - - private DesignPythonItem processNoPinOrSysFileAttributeRecognition(JSONObject attributeRecognition, ValidateElementVO elementVO, String styleCategory, BigDecimal systemScale) { - List collectNoPin = getFilteredCollectionElements(elementVO.getSketchBoardElements(), 0, styleCategory); - return processNoPinOrSysFileAttributeRecognitionWithPool(collectNoPin, attributeRecognition, elementVO, styleCategory, systemScale); - } - - // 生成两位小数随机数(线程安全) - private BigDecimal generateRandomValue() { - // 使用ThreadLocalRandom提高并发性能 - double random = ThreadLocalRandom.current().nextDouble(0.0, 1.0 + 1e-4); - - return new BigDecimal(random) - .setScale(2, RoundingMode.HALF_UP) - .min(BigDecimal.ONE); // 确保不超过1.00 - } - - private DesignPythonItem processNoPinOrSysFileAttributeRecognitionWithPool(List collectionElements, JSONObject attributeRecognition, ValidateElementVO elementVO, String styleCategory, BigDecimal systemScale) { - BigDecimal randomValue = generateRandomValue(); - boolean useSystem = randomValue.compareTo(systemScale) <= 0; - - // 用过存在用户上传,则优先使用用户上传 - if (!useSystem && CollectionUtil.isNotEmpty(collectionElements)) { - int collectionNoPinSize = collectionElements.size(); - int randomNum = RandomsUtil.randomSysFile(collectionNoPinSize); - return coverSketchToDesignPythonItem(collectionElements.get(randomNum).getId(), collectionElements.get(randomNum), elementVO); - } - - // 其他所有情况,都回退到使用系统推荐 - String categoryParam = elementVO.getModelSex().toLowerCase() + "_" + styleCategory.toLowerCase(); - List recommentdUrlList = getSystemSketchByCategory(categoryParam, elementVO.getBrandId(), elementVO.getBrandScale(),elementVO.getStyle()); - - if (CollectionUtils.isEmpty(recommentdUrlList)) { - throw new BusinessException("failed.to.obtain.system.sketch.recommendation"); - } - - String recommendSystemSketch = recommentdUrlList.get(0); - return coverSystemSketchUrlToDesignPythonItem(recommendSystemSketch, styleCategory, elementVO); - -// int poolNum = 20; -// if (CollectionUtil.isNotEmpty(collectionElements)) { -// int collectionNoPinSize = collectionElements.size(); -// if (systemScale.compareTo(BigDecimal.ZERO) == 0) { -// int randomNum = RandomsUtil.randomSysFile(collectionNoPinSize); -// return coverSketchToDesignPythonItem(null, collectionElements.get(randomNum), elementVO); -// } else if (systemScale.compareTo(BigDecimal.ONE) != 0) { -// BigDecimal collectNoPinSize = BigDecimal.valueOf(collectionNoPinSize); -// poolNum = collectNoPinSize.divide(systemScale, 0, RoundingMode.DOWN).intValue(); -// List list = getSystemSketchPool(attributeRecognition, styleCategory, elementVO.getModelSex(), poolNum, elementVO.getStyle()); -// collectionElements.addAll(list); -// int randomNum = RandomsUtil.randomSysFile(collectionElements.size()); -// if (randomNum < collectionNoPinSize) { -// return coverSketchToDesignPythonItem(collectionElements.get(randomNum).getId(), collectionElements.get(randomNum), elementVO); -// } else { -// return coverSketchToDesignPythonItem(null, collectionElements.get(randomNum), elementVO); -// } -// } -// } -// List list = getSystemSketchPool(attributeRecognition, styleCategory, elementVO.getModelSex(), poolNum, elementVO.getStyle()); -// int randomNum = RandomsUtil.randomSysFile(list.size()); -// return coverSketchToDesignPythonItem(null, list.get(randomNum), elementVO); - } - - private List getFilteredCollectionElements(List elements, int hasPin, String styleCategory) { - return CollectionUtil.isNotEmpty(elements) ? elements.stream().filter(o -> o.getHasPin() == hasPin && o.getLevel2Type().equals(styleCategory)).collect(Collectors.toList()) : null; - } - - private DesignPythonItem processAttributeRecognitionBySameCategory(JSONObject attributeRecognition, ValidateElementVO elementVO, String styleCategory) { - List list = getSystemSketchPoolBySameCategory(attributeRecognition, styleCategory, elementVO.getModelSex(), elementVO.getStyle()); - int randomNum = RandomsUtil.randomSysFile(list.size()); - return coverSketchToDesignPythonItem(null, list.get(randomNum), elementVO); - } - - @Resource - private AttributeRetrievalMapper attributeRetrievalMapper; - - private List getSystemSketchPool(JSONObject attributeRecognition, String styleCategory, String modelSex, int poolNum, String style) { - /** - * female trousers->female_pants - * female blouse->female_top - * female skirt->female_skirt - * female outwear->female_outwear - * female dress->female_dress - */ - JSONObject data = attributeRecognition.getJSONObject("data"); - JSONObject attrDict = ((JSONObject) data.getJSONArray("list").get(0)).getJSONObject("attr_dict"); - AttributeRecognitionJSON attrDictJSON = attrDict.toJavaObject(AttributeRecognitionJSON.class); - AttributeRetrieval attributeRetrievalAttrDict = toAttrDict(attrDictJSON); - String tableName; - tableName = getTableName(modelSex, styleCategory); - List attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPool(attributeRetrievalAttrDict, tableName, poolNum, style); - if (CollectionUtil.isEmpty(attributeRetrievalList) || attributeRetrievalList.size() < poolNum) { - attributeRetrievalAttrDict.setDesign(null); - attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPool(attributeRetrievalAttrDict, tableName, poolNum, style); - } - if (CollectionUtil.isEmpty(attributeRetrievalList) || attributeRetrievalList.size() < poolNum) { - attributeRetrievalAttrDict.setSilhouette(null); - attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPool(attributeRetrievalAttrDict, tableName, poolNum, style); - } - if (CollectionUtil.isEmpty(attributeRetrievalList) || attributeRetrievalList.size() < poolNum) { - style = null; - attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPool(attributeRetrievalAttrDict, tableName, poolNum, style); - } - return toColoectionElementList(attributeRetrievalList, styleCategory, modelSex); - } - - private List getSystemSketchPoolBySameCategory(JSONObject attributeRecognition, String styleCategory, String modelSex, String style) { - /** - * female trousers->female_pants - * female blouse->female_top - * female skirt->female_skirt - * female outwear->female_outwear - * female dress->female_dress - */ - JSONObject data = attributeRecognition.getJSONObject("data"); - JSONObject attrDict = ((JSONObject) data.getJSONArray("list").get(0)).getJSONObject("attr_dict"); - AttributeRecognitionJSON attrDictJSON = attrDict.toJavaObject(AttributeRecognitionJSON.class); - AttributeRetrieval attributeRetrievalAttrDict = toAttrDict(attrDictJSON); - String tableName; - tableName = getTableName(modelSex, styleCategory); - - // 存储非空字段的列表 - List nonNullFields = new ArrayList<>(); - if (attributeRetrievalAttrDict.getType() != null) { - nonNullFields.add("type"); - } - if (attributeRetrievalAttrDict.getOpeningType() != null) { - nonNullFields.add("openingType"); - if (tableName.equals("male_outwear") || tableName.equals("male_top") || tableName.equals("male_bottom")) { - nonNullFields.remove("openingType"); - attributeRetrievalAttrDict.setOpeningType(null); - } - } - if (attributeRetrievalAttrDict.getSubtype() != null) { - nonNullFields.add("subtype"); - } - - // 只有当非空字段数量大于等于2时才进行处理 - if (nonNullFields.size() >= 2) { - // 随机数生成器 - Random random = new Random(); - // 随机选择一个字段保留 - String fieldToKeep = nonNullFields.get(random.nextInt(nonNullFields.size())); - - // 设置保留的字段为非null,其他字段为null - for (String field : nonNullFields) { - if (!field.equals(fieldToKeep)) { - switch (field) { - case "type": - attributeRetrievalAttrDict.setType(null); - break; - case "openingType": - attributeRetrievalAttrDict.setOpeningType(null); - break; - case "subtype": - attributeRetrievalAttrDict.setSubtype(null); - break; - } - } - } - } - - List attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPoolBySameCategory(attributeRetrievalAttrDict, tableName, style); - if (CollectionUtil.isEmpty(attributeRetrievalList)) { - System.out.println(attributeRetrievalAttrDict); - System.out.println(tableName); - if (!StringUtils.isEmpty(style)) { - attributeRetrievalAttrDict.setType(null); - attributeRetrievalAttrDict.setOpeningType(null); - attributeRetrievalAttrDict.setSubtype(null); - attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPoolBySameCategory(attributeRetrievalAttrDict, tableName, style); - } - - if (CollectionUtil.isEmpty(attributeRetrievalList)) { - style = null; - attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPoolBySameCategory(attributeRetrievalAttrDict, tableName, style); - - } - } - return toColoectionElementList(attributeRetrievalList, styleCategory, modelSex); - } - - private List toColoectionElementList(List attributeRetrievalList, String styleCategory, String modelSex) { - List systemPool = new ArrayList<>(); - for (AttributeRetrieval attributeRetrieval : attributeRetrievalList) { - CollectionElement system = toCollectionElement(attributeRetrieval, styleCategory, modelSex); - systemPool.add(system); - } - return systemPool; - } - - private CollectionElement toCollectionElement(AttributeRetrieval attributeRetrieval, String styleCategory, String modelSex) { - CollectionElement element = new CollectionElement(); - element.setLevel2Type(styleCategory); - element.setUrl("aida-sys-image/images/" + modelSex.toLowerCase() + "/" + attributeRetrieval.getImgName()); - if (element.getUrl().contains("top")) { - element.setUrl(element.getUrl().replace("top", "tops")); - } - if (element.getUrl().contains("bottom")) { - element.setUrl(element.getUrl().replace("bottom", "bottoms")); - } - if (element.getUrl().contains("outer")) { - element.setUrl(element.getUrl().replace("outer", "outwear")); - } - return element; - } - - private AttributeRetrieval toAttrDict(AttributeRecognitionJSON attrDictJSON) { - AttributeRetrieval attributeRetrieval = new AttributeRetrieval(); -// attributeRetrieval.setImgName(attrDictJSON.getImgName().get(0)); -// attributeRetrieval.setLength(attrDictJSON.getLength().get(0)); -// attributeRetrieval.setSleeveLength(attrDictJSON.getSleeveLength().get(0)); -// attributeRetrieval.setSleeveShape(attrDictJSON.getSleeveShape().get(0)); -// attributeRetrieval.setSleeveShoulder(attrDictJSON.getSleeveShoulder().get(0)); -// attributeRetrieval.setNeckline(attrDictJSON.getNeckline().get(0)); -// attributeRetrieval.setCollar(attrDictJSON.getCollar().get(0)); - if (CollectionUtil.isNotEmpty(attrDictJSON.getDesign()) && attrDictJSON.getDesign().get(0) != null) { - attributeRetrieval.setDesign(attrDictJSON.getDesign().get(0)); - } - if (CollectionUtil.isNotEmpty(attrDictJSON.getSilhouette()) && attrDictJSON.getSilhouette().get(0) != null) { - attributeRetrieval.setSilhouette(attrDictJSON.getSilhouette().get(0)); - } - if (CollectionUtil.isNotEmpty(attrDictJSON.getType()) && attrDictJSON.getType().get(0) != null) { - attributeRetrieval.setType(attrDictJSON.getType().get(0)); - } - if (CollectionUtil.isNotEmpty(attrDictJSON.getSubtype()) && attrDictJSON.getSubtype().get(0) != null) { - attributeRetrieval.setSubtype(attrDictJSON.getSubtype().get(0)); - } - if (CollectionUtil.isNotEmpty(attrDictJSON.getOpeningType()) && attrDictJSON.getOpeningType().get(0) != null) { - attributeRetrieval.setOpeningType(attrDictJSON.getOpeningType().get(0)); - } - return attributeRetrieval; - } - - public JSONObject getAttributeRecognition(String sketchImgUrl, String styleCategory, String modelSex) { - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .readTimeout(60, TimeUnit.SECONDS) - .writeTimeout(60, TimeUnit.SECONDS) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - - JSONObject paramJSONObject = new JSONObject(); - paramJSONObject.put("category", styleCategory); - paramJSONObject.put("colony", modelSex); - paramJSONObject.put("sketch_img_url", sketchImgUrl); - JSONArray paramArray = new JSONArray(); - paramArray.add(paramJSONObject); - String param = JSON.toJSONString(paramArray, SerializerFeature.DisableCircularReferenceDetect); - - log.info("PythonService##design 请求参数:####{}", param); - RequestBody body = RequestBody.create(mediaType, param); - Request request = new Request.Builder() - .url(accessPythonIp + ":" + accessPythonPort + "/api/attribute_recognition") -// .url(fastApiPythonAddress + "/api/attribute_recognition") - .method("POST", body) - .addHeader("Content-Type", "application/json") - .build(); - - try (Response response = client.newCall(request).execute()) { - if (response.isSuccessful()) { - String responseBody = Objects.requireNonNull(response.body()).string(); - JSONObject responseObject = JSON.parseObject(responseBody); - log.info("PythonService##responseObject###{}", responseObject); - return responseObject; - } else { - log.error("PythonService##design 请求异常:{}", response); - throw new BusinessException("attributeRecognition.interface.exception"); - } - } catch (IOException e) { - log.error("PythonService##design 请求异常:{}", e.getMessage()); - throw new BusinessException("attributeRecognition.interface.exception"); - } - } - - public JSONObject getAttributeRecognitionBySameCategory(CollectionElement element, String modelSex) { - // todo 限流校验 -// AccessLimitUtils.validate("design",5); - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - //关闭FastJson的引用检测 防止出现$ref 现象 - JSONObject paramJSONObject = new JSONObject(); - paramJSONObject.put("category", element.getLevel2Type()); - paramJSONObject.put("colony", modelSex); - paramJSONObject.put("sketch_img_url", element.getUrl()); - JSONArray paramArray = new JSONArray(); - paramArray.add(paramJSONObject); - String param = JSON.toJSONString(paramArray, SerializerFeature.DisableCircularReferenceDetect); - log.info("design请求python 参数:####{}", param); - RequestBody body = RequestBody.create(mediaType, param); - Request request = new Request.Builder() - .url(accessPythonIp + ":" + accessPythonPort + "/api/attribute_recognition") -// .url(fastApiPythonAddress + "/api/attribute_recognition") - .method("POST", body) -// .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response; - String responseBody; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - AccessLimitUtils.validateOut("design"); - log.error("PythonService##design异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("design.interface.exception"); - } - //去除限流 -// AccessLimitUtils.validateOut("design"); - if (response.isSuccessful()) { - try { - if (Objects.nonNull(response.body())) { - responseBody = response.body().string(); - JSONObject responseObject = JSON.parseObject(responseBody); - log.info("PythonService##responseObject###{}", responseObject); - return responseObject; - } - throw new BusinessException("design.interface.exception"); - } catch (IOException | JSONException e) { - log.error("PythonService##design异常###{}", e.getMessage()); - throw new BusinessException("design.interface.exception"); - } - } - log.error("PythonService##design异常response###{}", response); - //生成失败 - throw new BusinessException("design.interface.exception"); - } - - @Resource - private CollocationMapper collocationMapper; - @Resource - private DressingMapper dressingMapper; - - private List getOtherSketchCategoryList(String modelSex, DesignPythonItem designPythonItem) { - List collocationList = collocationMapper.getCollocationListBySketch(modelSex, designPythonItem.getType()); - if (CollectionUtil.isNotEmpty(collocationList)) { - Random random = new Random(); - int randomNumber = random.nextInt(collocationList.size()); - List otherSketchCategoryList = dressingMapper.getOtherSketchCategoryNameList(collocationList.get(randomNumber).getId(), designPythonItem.getType().toLowerCase()); - return otherSketchCategoryList; - } - return null; - } - - private DesignPythonItem calculatePythonItem(ValidateElementVO validateElementVO, CurrentDesignPictureTypeEnum currentDesignPictureType) { - switch (currentDesignPictureType) { - case PIN: - return calculatePinPythonItem(validateElementVO); - case NO_PIN: - return calculateNoPinPythonItem(validateElementVO); - case SYS_FILE: - return calculateSysFilePythonItem(validateElementVO); - default: - return null; - } - } - - private DesignPythonItem calculatePinPythonItem(ValidateElementVO validateElementVO) { - List pinCollectionData = getPinData(validateElementVO); - if (CollectionUtil.isEmpty(pinCollectionData)) { - throw new BusinessException("pinData is null"); - } - Random random = new Random(); - int randomNumber = random.nextInt(pinCollectionData.size()); - validateElementVO.getHasUseMd5List().add(pinCollectionData.get(randomNumber).getMd5()); - return coverSketchToDesignPythonItem(pinCollectionData.get(randomNumber).getId(), pinCollectionData.get(randomNumber), validateElementVO); - } - - private DesignPythonItem calculateNoPinPythonItem(ValidateElementVO validateElementVO) { - List noPinCollectionData = getNoPinData(validateElementVO); - if (CollectionUtil.isEmpty(noPinCollectionData)) { - List sketchBoardPins = getPinDataWhole(validateElementVO); - if (CollectionUtil.isNotEmpty(sketchBoardPins) && validateElementVO.getSingleOverall().equals(SingleOverallEnum.SINGLE.getRealName())) { - sketchBoardPins = sketchBoardPins.stream().filter(o -> o.getLevel2Type().equals(validateElementVO.getSwitchCategory())).collect(Collectors.toList()); - } - if (CollectionUtil.isNotEmpty(sketchBoardPins)) { - Integer randomNum = RandomsUtil.randomSysFile(sketchBoardPins.size()); - CollectionElement element = sketchBoardPins.get(randomNum); - // 获取随机pin sketch的category - String category = element.getLevel2Type(); - String categoryParam = validateElementVO.getModelSex().toLowerCase() + "_" + category.toLowerCase(); - List recommentdUrlList = getSystemSketchByCategory(categoryParam, validateElementVO.getBrandId(), validateElementVO.getBrandScale(), validateElementVO.getStyle()); - if (!CollectionUtils.isEmpty(recommentdUrlList)) { - String recommendSystemSketch = recommentdUrlList.get(0); - return coverSystemSketchUrlToDesignPythonItem(recommendSystemSketch, category, validateElementVO); - }else { - throw new BusinessException("failed.to.obtain.system.sketch.recommendation"); - } -// JSONObject attributeRecognition = getAttributeRecognitionBySameCategory(element, validateElementVO.getModelSex()); -// return processAttributeRecognitionBySameCategory(attributeRecognition, validateElementVO, element.getLevel2Type()); - } - QueryWrapper qw = new QueryWrapper<>(); - qw.lambda().eq(Dressing::getApparel, validateElementVO.getModelSex()); - if (validateElementVO.getSingleOverall().equals(SingleOverallEnum.SINGLE.getRealName())) { - qw.lambda().eq(Dressing::getStyleCategory, validateElementVO.getSwitchCategory()); - } - List dressings = dressingMapper.selectList(qw); - if (CollectionUtil.isEmpty(dressings)) { - throw new BusinessException("dressings is null"); - } - Integer randomNum = RandomsUtil.randomSysFile(dressings.size()); - String category = dressings.get(randomNum).getStyleCategory(); - - String categoryParam = validateElementVO.getModelSex().toLowerCase() + "_" + category.toLowerCase(); - List recommentdUrlList = getSystemSketchByCategory(categoryParam, validateElementVO.getBrandId(), validateElementVO.getBrandScale(), validateElementVO.getStyle()); - if (!CollectionUtils.isEmpty(recommentdUrlList)) { - String recommendSystemSketch = recommentdUrlList.get(0); - return coverSystemSketchUrlToDesignPythonItem(recommendSystemSketch, category, validateElementVO); - }else { - throw new BusinessException("failed.to.obtain.system.sketch.recommendation"); - } - -// String tableName = getTableName(validateElementVO.getModelSex(), category); -// AttributeRetrieval attributeRetrieval = attributeRetrievalMapper.getSystemRandom(tableName, validateElementVO.getStyle()); -// CollectionElement collectionElement = toCollectionElement(attributeRetrieval, category, validateElementVO.getModelSex()); -// return coverSketchToDesignPythonItem(null, collectionElement, validateElementVO); - } - Random random = new Random(); - int randomNumber = random.nextInt(noPinCollectionData.size()); - return coverSketchToDesignPythonItem(noPinCollectionData.get(randomNumber).getId(), noPinCollectionData.get(randomNumber), validateElementVO); - } - - private DesignPythonItem calculateSysFilePythonItem(ValidateElementVO validateElementVO) { - List sketchBoardCollectionElements = validateElementVO.getSketchBoardElements(); - if (!CollectionUtils.isEmpty(sketchBoardCollectionElements)) { - if (validateElementVO.getModelSex().equals(Sex.MALE.getValue())) { - sketchBoardCollectionElements = sketchBoardCollectionElements.stream().filter(o -> MALE_CATEGORY.contains(o.getLevel2Type())).collect(Collectors.toList()); - } - if (validateElementVO.getModelSex().equals(Sex.FEMALE.getValue())) { - sketchBoardCollectionElements = sketchBoardCollectionElements.stream().filter(o -> FEMALE_CATEGORY.contains(o.getLevel2Type())).collect(Collectors.toList()); - } - if (CollectionUtil.isNotEmpty(sketchBoardCollectionElements) && validateElementVO.getSingleOverall().equals(SingleOverallEnum.SINGLE.getRealName())) { - sketchBoardCollectionElements = sketchBoardCollectionElements.stream().filter(o -> o.getLevel2Type().equals(validateElementVO.getSwitchCategory())).collect(Collectors.toList()); - } - if (CollectionUtil.isNotEmpty(sketchBoardCollectionElements)) { - Integer randomNum = RandomsUtil.randomSysFile(sketchBoardCollectionElements.size()); - CollectionElement element = sketchBoardCollectionElements.get(randomNum); - String category = element.getLevel2Type(); - - String categoryParam = validateElementVO.getModelSex().toLowerCase() + "_" + category.toLowerCase(); - List recommentdUrlList = getSystemSketchByCategory(categoryParam, validateElementVO.getBrandId(), validateElementVO.getBrandScale(), validateElementVO.getStyle()); - if (!CollectionUtils.isEmpty(recommentdUrlList)) { - String recommendSystemSketch = recommentdUrlList.get(0); - return coverSystemSketchUrlToDesignPythonItem(recommendSystemSketch, category, validateElementVO); - }else { - throw new BusinessException("failed.to.obtain.system.sketch.recommendation"); - } -// JSONObject attributeRecognition = getAttributeRecognitionBySameCategory(element, validateElementVO.getModelSex()); -// return processAttributeRecognitionBySameCategory(attributeRecognition, validateElementVO, element.getLevel2Type()); - } - } - QueryWrapper qw = new QueryWrapper<>(); - qw.lambda().eq(Dressing::getApparel, validateElementVO.getModelSex()); - if (validateElementVO.getSingleOverall().equals(SingleOverallEnum.SINGLE.getRealName())) { - qw.lambda().eq(Dressing::getStyleCategory, validateElementVO.getSwitchCategory()); - } - List dressings = dressingMapper.selectList(qw); - if (CollectionUtil.isEmpty(dressings)) { - throw new BusinessException("dressings is null"); - } - Integer randomNum = RandomsUtil.randomSysFile(dressings.size()); - String category = dressings.get(randomNum).getStyleCategory(); - - String categoryParam = validateElementVO.getModelSex().toLowerCase() + "_" + category.toLowerCase(); - List recommentdUrlList = getSystemSketchByCategory(categoryParam, validateElementVO.getBrandId(), validateElementVO.getBrandScale(), validateElementVO.getStyle()); - if (!CollectionUtils.isEmpty(recommentdUrlList)) { - String recommendSystemSketch = recommentdUrlList.get(0); - return coverSystemSketchUrlToDesignPythonItem(recommendSystemSketch, category, validateElementVO); - }else { - throw new BusinessException("failed.to.obtain.system.sketch.recommendation"); - } -// String tableName = getTableName(validateElementVO.getModelSex(), category); -// -// AttributeRetrieval attributeRetrieval = attributeRetrievalMapper.getSystemRandom(tableName, validateElementVO.getStyle()); -// CollectionElement collectionElement = toCollectionElement(attributeRetrieval, category, validateElementVO.getModelSex()); -// return coverSketchToDesignPythonItem(null, collectionElement, validateElementVO); - } - - private String getTableName(String modelSex, String category) { - switch (modelSex) { - case "Female": { - switch (category) { - case "Blouse": { - return "female_top"; - } - case "Trousers": { - return "female_pants"; - } - case "Skirt": { - return "female_skirt"; - } - case "Outwear": { - return "female_outwear"; - } - case "Dress": { - return "female_dress"; - } - default: { - throw new BusinessException("unknown attributeRetrieval dressing"); - } - } - } - case "Male": { - switch (category) { - case "Tops": { - return "male_top"; - } - case "Bottoms": { - return "male_bottom"; - } - case "Outwear": { - return "male_outwear"; - } - default: { - throw new BusinessException("unknown male dressing"); - } - } - } - default: { - throw new BusinessException("unknown modelSex"); - } - } - } - - private DesignPythonItem calculatePythonItemOutwear(List pinData, ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType) { - DesignPythonItem outwear = null; - //剩余的的PinData - List existPinDataIds = elementVO.getExistPinDataIds(); - List residuePinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); - if (CollectionUtil.isNotEmpty(residuePinData)) { - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.OUTWEAR.contains(elementVO.getSwitchCategory())) { - //是否包含的Pin - Boolean isPin = residuePinData.stream().filter(residue -> - elementVO.getSwitchCategory().equals(residue.getLevel2Type())).findFirst().isPresent(); - //如果包含Pin只传一个 - if (isPin) { - //Pin的数据 - pinData = getPinDataByLevel2Type(pinData, elementVO.getSwitchCategory()); - //剩余的的PinData - List residueInnerPinDataByType = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); - CollectionElement elementNew = CollectionUtils.isEmpty(residueInnerPinDataByType) ? null : residueInnerPinDataByType.get(0); - if (Objects.nonNull(elementNew)) { - outwear = coverToDesignPythonItem(elementNew.getId(), elementVO.getSwitchCategory(), elementNew.getUrl(), elementVO); - //去重用 - existPinDataIds.add(elementNew.getId()); - //添加已使用的md5 - elementVO.getHasUseMd5List().add(elementNew.getMd5()); - } - } - } - } else { - //是否包含skirt的Pin - Boolean isPin = residuePinData.stream().filter(residue -> - DesignPythonItem.OUTWEAR.contains(residue.getLevel2Type())).findFirst().isPresent(); - //如果包含Pin只传一个 - if (isPin) { - for (String type : DesignPythonItem.OUTWEAR) { - //剩余的的PinData - List residueInnerPinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); - CollectionElement elementNew = residueInnerPinData.stream() - .filter(element -> element.getLevel2Type().equals(type)).findFirst().orElse(null); - if (Objects.nonNull(elementNew)) { - outwear = coverToDesignPythonItem(elementNew.getId(), type, elementNew.getUrl(), elementVO); - //去重用 - existPinDataIds.add(elementNew.getId()); - //添加已使用的md5 - elementVO.getHasUseMd5List().add(elementNew.getMd5()); - break; - } - } - } - } - - } - if (Objects.nonNull(outwear)) { - return outwear; - } - switch (designPictureType) { - case PIN: - if (Objects.isNull(outwear)) { - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.OUTWEAR.contains(elementVO.getSwitchCategory())) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); - outwear = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - outwear.setBusinessId(sysFileVO.getId()); - return outwear; - } - } else { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileMaleBottoms(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); - outwear = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - outwear.setBusinessId(sysFileVO.getId()); - //添加已使用的md5 - return outwear; - } - } - break; -// case USER_LIBRARY: -// //single模式 -// if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { -// if (DesignPythonItem.OUTWEAR.contains(elementVO.getSwitchCategory())) { -// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), -// Arrays.asList(elementVO.getSwitchCategory()), elementVO.getHasUseMd5List()); -// if (StringUtils.isEmpty(libraryVo)) { -// //系统获取 -// SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); -// outwear = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); -// outwear.setBusinessId(sysFileVO.getId()); -// return outwear; -// } -// outwear = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); -// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); -// outwear.setBusinessId(libraryVo.getId()); -// } -// } else { -// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), -// DesignPythonItem.OUTWEAR, elementVO.getHasUseMd5List()); -// if (StringUtils.isEmpty(libraryVo)) { -// //系统获取 -// SysFileVO sysFileVO = getRandomSysFileMaleBottoms(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); -// outwear = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); -// outwear.setBusinessId(sysFileVO.getId()); -// //添加已使用的md5 -// return outwear; -// } -// outwear = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); -// outwear.setBusinessId(libraryVo.getId()); -// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); -// } -// break; - case SYS_FILE: - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.OUTWEAR.contains(elementVO.getSwitchCategory())) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); - outwear = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - outwear.setBusinessId(sysFileVO.getId()); - return outwear; - } - } else { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileMaleBottoms(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); - outwear = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - outwear.setBusinessId(sysFileVO.getId()); - //添加已使用的md5 - return outwear; - } - break; - case NO_PIN: - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.OUTWEAR.contains(elementVO.getSwitchCategory())) { - //非Pin的数据 - List noPinDataByType = - getNoPinData(elementVO.getSketchBoardElements(), Collections.singletonList(elementVO.getSwitchCategory())); - CollectionElement collectionElement = getRandomSketchLibrary(noPinDataByType, elementVO.getHasUseMd5List()); - if (Objects.isNull(collectionElement)) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); - outwear = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - outwear.setBusinessId(sysFileVO.getId()); - } else { - elementVO.getHasUseMd5List().add(collectionElement.getMd5()); - outwear = coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO); - } - } - } else { - //非Pin的数据 - List noPinData = getNoPinData(elementVO.getSketchBoardElements(), DesignPythonItem.OUTWEAR); - CollectionElement collectionElement = getRandomSketchLibrary(noPinData, elementVO.getHasUseMd5List()); - if (Objects.isNull(collectionElement)) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileMaleBottoms(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); - outwear = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - outwear.setBusinessId(sysFileVO.getId()); - } else { - elementVO.getHasUseMd5List().add(collectionElement.getMd5()); - outwear = coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO); - } - } - break; - default: - } - return outwear; - } - - private DesignPythonItem calculatePythonItemBottom(List pinData, ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType) { - DesignPythonItem bottom = null; - //剩余的的PinData - List existPinDataIds = elementVO.getExistPinDataIds(); - List residuePinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); - if (CollectionUtil.isNotEmpty(residuePinData)) { - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.BOTTOMS.contains(elementVO.getSwitchCategory())) { - //是否包含的Pin - Boolean isPin = residuePinData.stream().filter(residue -> - elementVO.getSwitchCategory().equals(residue.getLevel2Type())).findFirst().isPresent(); - //如果包含Pin只传一个 - if (isPin) { - //Pin的数据 - pinData = getPinDataByLevel2Type(pinData, elementVO.getSwitchCategory()); - //剩余的的PinData - List residueInnerPinDataByType = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); - CollectionElement elementNew = CollectionUtils.isEmpty(residueInnerPinDataByType) ? null : residueInnerPinDataByType.get(0); - if (Objects.nonNull(elementNew)) { - bottom = coverToDesignPythonItem(elementNew.getId(), elementVO.getSwitchCategory(), elementNew.getUrl(), elementVO); - //去重用 - existPinDataIds.add(elementNew.getId()); - //添加已使用的md5 - elementVO.getHasUseMd5List().add(elementNew.getMd5()); - } - } - } - } else { - //是否包含skirt的Pin - Boolean isPin = residuePinData.stream().filter(residue -> - DesignPythonItem.BOTTOMS.contains(residue.getLevel2Type())).findFirst().isPresent(); - //如果包含Pin只传一个 - if (isPin) { - for (String type : DesignPythonItem.BOTTOMS) { - //剩余的的PinData - List residueInnerPinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); - CollectionElement elementNew = residueInnerPinData.stream() - .filter(element -> element.getLevel2Type().equals(type)).findFirst().orElse(null); - if (Objects.nonNull(elementNew)) { - bottom = coverToDesignPythonItem(elementNew.getId(), type, elementNew.getUrl(), elementVO); - //去重用 - existPinDataIds.add(elementNew.getId()); - //添加已使用的md5 - elementVO.getHasUseMd5List().add(elementNew.getMd5()); - break; - } - } - } - } - - } - if (Objects.nonNull(bottom)) { - return bottom; - } - switch (designPictureType) { - case PIN: - if (Objects.isNull(bottom)) { - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.BOTTOMS.contains(elementVO.getSwitchCategory())) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); - bottom = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - bottom.setBusinessId(sysFileVO.getId()); - return bottom; - } - } else { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileMaleBottoms(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); - bottom = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - bottom.setBusinessId(sysFileVO.getId()); - //添加已使用的md5 - return bottom; - } - } - break; -// case USER_LIBRARY: -// //single模式 -// if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { -// if (DesignPythonItem.BOTTOMS.contains(elementVO.getSwitchCategory())) { -// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), -// Arrays.asList(elementVO.getSwitchCategory()), elementVO.getHasUseMd5List()); -// if (StringUtils.isEmpty(libraryVo)) { -// //系统获取 -// SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); -// bottom = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); -// bottom.setBusinessId(sysFileVO.getId()); -// return bottom; -// } -// bottom = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); -// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); -// bottom.setBusinessId(libraryVo.getId()); -// } -// } else { -// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), -// DesignPythonItem.BOTTOMS, elementVO.getHasUseMd5List()); -// if (StringUtils.isEmpty(libraryVo)) { -// //系统获取 -// SysFileVO sysFileVO = getRandomSysFileMaleBottoms(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); -// bottom = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); -// bottom.setBusinessId(sysFileVO.getId()); -// //添加已使用的md5 -// return bottom; -// } -// bottom = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); -// bottom.setBusinessId(libraryVo.getId()); -// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); -// } -// break; - case SYS_FILE: - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.BOTTOMS.contains(elementVO.getSwitchCategory())) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); - bottom = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - bottom.setBusinessId(sysFileVO.getId()); - return bottom; - } - } else { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileMaleBottoms(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); - bottom = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - bottom.setBusinessId(sysFileVO.getId()); - //添加已使用的md5 - return bottom; - } - break; - case NO_PIN: - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.BOTTOMS.contains(elementVO.getSwitchCategory())) { - //非Pin的数据 - List noPinDataByType = - getNoPinData(elementVO.getSketchBoardElements(), Collections.singletonList(elementVO.getSwitchCategory())); - CollectionElement collectionElement = getRandomSketchLibrary(noPinDataByType, elementVO.getHasUseMd5List()); - if (Objects.isNull(collectionElement)) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); - bottom = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - bottom.setBusinessId(sysFileVO.getId()); - } else { - elementVO.getHasUseMd5List().add(collectionElement.getMd5()); - bottom = coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO); - } - } - } else { - //非Pin的数据 - List noPinData = getNoPinData(elementVO.getSketchBoardElements(), DesignPythonItem.BOTTOMS); - CollectionElement collectionElement = getRandomSketchLibrary(noPinData, elementVO.getHasUseMd5List()); - if (Objects.isNull(collectionElement)) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileMaleBottoms(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); - bottom = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - bottom.setBusinessId(sysFileVO.getId()); - } else { - elementVO.getHasUseMd5List().add(collectionElement.getMd5()); - bottom = coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO); - } - } - break; - default: - } - return bottom; - } - - private DesignPythonItem calculatePythonItemTop(List pinData, ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType) { - DesignPythonItem top = null; - //剩余的的PinData - List existPinDataIds = elementVO.getExistPinDataIds(); - List residuePinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); - if (CollectionUtil.isNotEmpty(residuePinData)) { - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.TOPS.contains(elementVO.getSwitchCategory())) { - //是否包含的Pin - Boolean isPin = residuePinData.stream().filter(residue -> - elementVO.getSwitchCategory().equals(residue.getLevel2Type())).findFirst().isPresent(); - //如果包含Pin只传一个 - if (isPin) { - //Pin的数据 - pinData = getPinDataByLevel2Type(pinData, elementVO.getSwitchCategory()); - //剩余的的PinData - List residueInnerPinDataByType = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); - CollectionElement elementNew = CollectionUtils.isEmpty(residueInnerPinDataByType) ? null : residueInnerPinDataByType.get(0); - if (Objects.nonNull(elementNew)) { - top = coverToDesignPythonItem(elementNew.getId(), elementVO.getSwitchCategory(), elementNew.getUrl(), elementVO); - //去重用 - existPinDataIds.add(elementNew.getId()); - //添加已使用的md5 - elementVO.getHasUseMd5List().add(elementNew.getMd5()); - } - } - } - } else { - //是否包含skirt的Pin - Boolean isPin = residuePinData.stream().filter(residue -> - DesignPythonItem.TOPS.contains(residue.getLevel2Type())).findFirst().isPresent(); - //如果包含Pin只传一个 - if (isPin) { - for (String type : DesignPythonItem.TOPS) { - //剩余的的PinData - List residueInnerPinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); - CollectionElement elementNew = residueInnerPinData.stream() - .filter(element -> element.getLevel2Type().equals(type)).findFirst().orElse(null); - if (Objects.nonNull(elementNew)) { - top = coverToDesignPythonItem(elementNew.getId(), type, elementNew.getUrl(), elementVO); - //去重用 - existPinDataIds.add(elementNew.getId()); - //添加已使用的md5 - elementVO.getHasUseMd5List().add(elementNew.getMd5()); - break; - } - } - } - } - - } - if (Objects.nonNull(top)) { - return top; - } - switch (designPictureType) { - case PIN: - if (Objects.isNull(top)) { - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.TOPS.contains(elementVO.getSwitchCategory())) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); - top = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - top.setBusinessId(sysFileVO.getId()); - return top; - } - } else { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileMaleTops(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); - top = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - top.setBusinessId(sysFileVO.getId()); - //添加已使用的md5 - return top; - } - } - break; -// case USER_LIBRARY: -// //single模式 -// if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { -// if (DesignPythonItem.TOPS.contains(elementVO.getSwitchCategory())) { -// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), -// Arrays.asList(elementVO.getSwitchCategory()), elementVO.getHasUseMd5List()); -// if (StringUtils.isEmpty(libraryVo)) { -// //系统获取 -// SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); -// top = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); -// top.setBusinessId(sysFileVO.getId()); -// return top; -// } -// top = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); -// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); -// top.setBusinessId(libraryVo.getId()); -// } -// } else { -// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), -// DesignPythonItem.TOPS, elementVO.getHasUseMd5List()); -// if (StringUtils.isEmpty(libraryVo)) { -// //系统获取 -// SysFileVO sysFileVO = getRandomSysFileMaleTops(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); -// top = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); -// top.setBusinessId(sysFileVO.getId()); -// //添加已使用的md5 -// return top; -// } -// top = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); -// top.setBusinessId(libraryVo.getId()); -// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); -// } -// break; - case SYS_FILE: - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.TOPS.contains(elementVO.getSwitchCategory())) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); - top = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - top.setBusinessId(sysFileVO.getId()); - return top; - } - } else { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileMaleTops(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); - top = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - top.setBusinessId(sysFileVO.getId()); - //添加已使用的md5 - return top; - } - break; - case NO_PIN: - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.TOPS.contains(elementVO.getSwitchCategory())) { - //非Pin的数据 - List noPinDataByType = - getNoPinData(elementVO.getSketchBoardElements(), Collections.singletonList(elementVO.getSwitchCategory())); - CollectionElement collectionElement = getRandomSketchLibrary(noPinDataByType, elementVO.getHasUseMd5List()); - if (Objects.isNull(collectionElement)) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); - top = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - top.setBusinessId(sysFileVO.getId()); - } else { - elementVO.getHasUseMd5List().add(collectionElement.getMd5()); - top = coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO); - } - } - } else { - //非Pin的数据 - List noPinData = getNoPinData(elementVO.getSketchBoardElements(), DesignPythonItem.TOPS); - CollectionElement collectionElement = getRandomSketchLibrary(noPinData, elementVO.getHasUseMd5List()); - if (Objects.isNull(collectionElement)) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileMaleTops(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); - top = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - top.setBusinessId(sysFileVO.getId()); - } else { - elementVO.getHasUseMd5List().add(collectionElement.getMd5()); - top = coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO); - } - } - break; - default: - } - return top; - } - - private List calculatePythonItemHairstyleShoes(ValidateElementVO elementVO, DesignLibraryModelPointVO designLibraryModelPoint) { - List items = Lists.newArrayList(); - for (String type : DesignPythonItem.SYS_HAIRSTYLE_SHOES_BODY) { - if (!type.equals("Body")) { - continue; - } - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall()) || Objects.nonNull(designLibraryModelPoint)) { - //single和models模特时候不传耳环 首饰,鞋子等 - if (!SysFileLevel2TypeEnum.BODY.getRealName().equals(type)) { - continue; - } - } - DesignPythonItem pythonItem = new DesignPythonItem(); - items.add(pythonItem); - //类型 - pythonItem.setType(type); - if (SysFileLevel2TypeEnum.BODY.getRealName().equals(type)) { - if (!CollectionUtils.isEmpty(elementVO.getMannequins())) { - DesignLibraryModelPointVO vo = getRandomDesignLibraryModelPoint(elementVO.getMannequins()); - pythonItem.setBody_path(vo.getTemplateUrl()); - elementVO.setDesignLibraryModelPointVO(vo); - } else { -// pythonItem.setBody_path("/workspace/python_code/Multi-layer-Virtual-Try-on/dataset_for_test/Img_model.png"); - pythonItem.setBody_path("aida-sys-image/models/female/dd6b48ce-1bab-4861-bb87-a30b82377a8f.png"); - } -// if (Objects.nonNull(designLibraryModelPoint)) { -// pythonItem.setBody_path(designLibraryModelPoint.getTemplateUrl()); -// } else { -//// pythonItem.setBody_path("/workspace/python_code/Multi-layer-Virtual-Try-on/dataset_for_test/Img_model.png"); -// pythonItem.setBody_path("aida-mannequins/model_1693218345.2714432.png"); -// } - } else { - SysFileVO sysFileVO = getRandomSysFileByLevel2Type(type, Lists.newArrayList(), elementVO.getModelSex()); - pythonItem.setPath(sysFileVO.getUrl()); - pythonItem.setBusinessId(sysFileVO.getId()); - if (SysFileLevel2TypeEnum.SHOES.getRealName().equals(type)) { - CollectionColorDTO randomColor = getRandomColor(elementVO.getColorBoards()); - if (Objects.nonNull(randomColor)) { - pythonItem.setColor(randomColor.getRgbValue()); - pythonItem.setGradient(randomColor.getGradientMinioUrl()); - pythonItem.setGradientString(randomColor.getGradientString()); - } - } - } - } - return items; - } - - private DesignPythonItem calculatePythonItemSkirt(List pinData, ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType) { - // skirt, trousers 只选择一个 - DesignPythonItem skirt = null; - //剩余的的PinData - List existPinDataIds = elementVO.getExistPinDataIds(); - List residuePinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); - if (CollectionUtil.isNotEmpty(residuePinData)) { - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.SKIRT_TROUSERS.contains(elementVO.getSwitchCategory())) { - //是否包含的Pin - Boolean isPin = residuePinData.stream().filter(residue -> - elementVO.getSwitchCategory().equals(residue.getLevel2Type())).findFirst().isPresent(); - //如果包含Pin只传一个 - if (isPin) { - //Pin的数据 - pinData = getPinDataByLevel2Type(pinData, elementVO.getSwitchCategory()); - //剩余的的PinData - List residueInnerPinDataByType = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); - CollectionElement elementNew = CollectionUtils.isEmpty(residueInnerPinDataByType) ? null : residueInnerPinDataByType.get(0); - if (Objects.nonNull(elementNew)) { - skirt = coverToDesignPythonItem(elementNew.getId(), elementVO.getSwitchCategory(), elementNew.getUrl(), elementVO); - //去重用 - existPinDataIds.add(elementNew.getId()); - //添加已使用的md5 - elementVO.getHasUseMd5List().add(elementNew.getMd5()); - } - } - } - } else { - //是否包含skirt的Pin - Boolean isPin = residuePinData.stream().filter(residue -> - DesignPythonItem.SKIRT_TROUSERS.contains(residue.getLevel2Type())).findFirst().isPresent(); - //如果包含Pin只传一个 - if (isPin) { - for (String type : DesignPythonItem.SKIRT_TROUSERS) { - //剩余的的PinData - List residueInnerPinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); - CollectionElement elementNew = residueInnerPinData.stream() - .filter(element -> element.getLevel2Type().equals(type)).findFirst().orElse(null); - if (Objects.nonNull(elementNew)) { - skirt = coverToDesignPythonItem(elementNew.getId(), type, elementNew.getUrl(), elementVO); - //去重用 - existPinDataIds.add(elementNew.getId()); - //添加已使用的md5 - elementVO.getHasUseMd5List().add(elementNew.getMd5()); - break; - } - } - } - } - - } - if (Objects.nonNull(skirt)) { - return skirt; - } - switch (designPictureType) { - case PIN: - if (Objects.isNull(skirt)) { - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.SKIRT_TROUSERS.contains(elementVO.getSwitchCategory())) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); - skirt = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - skirt.setBusinessId(sysFileVO.getId()); - return skirt; - } - } else { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileSkirt(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); - skirt = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - skirt.setBusinessId(sysFileVO.getId()); - //添加已使用的md5 - return skirt; - } - } - break; -// case USER_LIBRARY: -// //single模式 -// if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { -// if (DesignPythonItem.SKIRT_TROUSERS.contains(elementVO.getSwitchCategory())) { -// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), -// Arrays.asList(elementVO.getSwitchCategory()), elementVO.getHasUseMd5List()); -// if (StringUtils.isEmpty(libraryVo)) { -// //系统获取 -// SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); -// skirt = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); -// skirt.setBusinessId(sysFileVO.getId()); -// return skirt; -// } -// skirt = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); -// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); -// skirt.setBusinessId(libraryVo.getId()); -// } -// } else { -// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), -// DesignPythonItem.SKIRT_TROUSERS, elementVO.getHasUseMd5List()); -// if (StringUtils.isEmpty(libraryVo)) { -// //系统获取 -// SysFileVO sysFileVO = getRandomSysFileSkirt(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); -// skirt = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); -// skirt.setBusinessId(sysFileVO.getId()); -// //添加已使用的md5 -// return skirt; -// } -// skirt = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); -// skirt.setBusinessId(libraryVo.getId()); -// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); -// } -// break; - case SYS_FILE: - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.SKIRT_TROUSERS.contains(elementVO.getSwitchCategory())) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); - skirt = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - skirt.setBusinessId(sysFileVO.getId()); - return skirt; - } - } else { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileSkirt(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); - skirt = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - skirt.setBusinessId(sysFileVO.getId()); - //添加已使用的md5 - return skirt; - } - break; - case NO_PIN: - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.SKIRT_TROUSERS.contains(elementVO.getSwitchCategory())) { - //非Pin的数据 - List noPinDataByType = - getNoPinData(elementVO.getSketchBoardElements(), Collections.singletonList(elementVO.getSwitchCategory())); - CollectionElement collectionElement = getRandomSketchLibrary(noPinDataByType, elementVO.getHasUseMd5List()); - if (Objects.isNull(collectionElement)) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); - skirt = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - skirt.setBusinessId(sysFileVO.getId()); - } else { - elementVO.getHasUseMd5List().add(collectionElement.getMd5()); - skirt = coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO); - } - } - } else { - //非Pin的数据 - List noPinData = getNoPinData(elementVO.getSketchBoardElements(), DesignPythonItem.SKIRT_TROUSERS); - CollectionElement collectionElement = getRandomSketchLibrary(noPinData, elementVO.getHasUseMd5List()); - if (Objects.isNull(collectionElement)) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileSkirt(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); - skirt = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - skirt.setBusinessId(sysFileVO.getId()); - } else { - elementVO.getHasUseMd5List().add(collectionElement.getMd5()); - skirt = coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO); - } - } - break; - default: - } - return skirt; - } - - private List calculatePythonItemBlouse(List pinData, ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType) { - List items = Lists.newArrayList(); - //剩余的的PinData - List existPinDataIds = elementVO.getExistPinDataIds(); - List residuePinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); - if (CollectionUtil.isNotEmpty(residuePinData)) { - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.OUTWEAR_DRESS_BLOUSE.contains(elementVO.getSwitchCategory())) { - //是否包含的Pin - Boolean isPin = residuePinData.stream().filter(residue -> - elementVO.getSwitchCategory().equals(residue.getLevel2Type())).findFirst().isPresent(); - //如果包含Pin只传一个 - if (isPin) { - //Pin的数据 - pinData = getPinDataByLevel2Type(pinData, elementVO.getSwitchCategory()); - //剩余的的PinData - List residueInnerPinDataByType = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); - CollectionElement elementNew = CollectionUtils.isEmpty(residueInnerPinDataByType) ? null : residueInnerPinDataByType.get(0); - if (Objects.nonNull(elementNew)) { - items.add(coverToDesignPythonItem(elementNew.getId(), elementVO.getSwitchCategory(), elementNew.getUrl(), elementVO)); - //去重用 - existPinDataIds.add(elementNew.getId()); - //添加MD5 - elementVO.getHasUseMd5List().add(elementNew.getMd5()); - } - } - } - } else { - //是否包含blouse的Pin - Boolean isPin = residuePinData.stream().filter(residue -> - DesignPythonItem.OUTWEAR_DRESS_BLOUSE.contains(residue.getLevel2Type())).findFirst().isPresent(); - //如果包含Pin只传一个 - if (isPin) { - List finalPinData = pinData; - for (String type : DesignPythonItem.OUTWEAR_DRESS_BLOUSE) { - // 剩余的的 PinData - List residueInnerPinData = residuePinData(finalPinData, existPinDataIds, elementVO.getHasUseMd5List()); - CollectionElement elementNew = residueInnerPinData.stream() - .filter(element -> element.getLevel2Type().equals(type)).findFirst().orElse(null); - if (Objects.nonNull(elementNew)) { - items.add(coverToDesignPythonItem(elementNew.getId(), type, elementNew.getUrl(), elementVO)); - // 去重用 - existPinDataIds.add(elementNew.getId()); - // 添加md5 - elementVO.getHasUseMd5List().add(elementNew.getMd5()); - - // 提前结束循环 - break; - } - } - } - } - - } - if (CollectionUtil.isNotEmpty(items)) { - return items; - } - switch (designPictureType) { - case PIN: - if (CollectionUtil.isEmpty(items)) { - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.OUTWEAR_DRESS_BLOUSE.contains(elementVO.getSwitchCategory())) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); - DesignPythonItem item = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - item.setBusinessId(sysFileVO.getId()); - items.add(item); - return items; - } - } else { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileOutwear(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); - DesignPythonItem item = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - item.setBusinessId(sysFileVO.getId()); - items.add(item); - return items; - } - } - break; -// case USER_LIBRARY: -// //single模式 -// if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { -// if (DesignPythonItem.OUTWEAR_DRESS_BLOUSE.contains(elementVO.getSwitchCategory())) { -// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), -// Arrays.asList(elementVO.getSwitchCategory()), elementVO.getHasUseMd5List()); -// if (StringUtils.isEmpty(libraryVo)) { -// //系统获取 -// SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); -// DesignPythonItem item = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); -// item.setBusinessId(sysFileVO.getId()); -// items.add(item); -// return items; -// } -// DesignPythonItem item = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); -// item.setBusinessId(libraryVo.getId()); -// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); -// items.add(item); -// } -// } else { -// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), -// DesignPythonItem.OUTWEAR_DRESS_BLOUSE, elementVO.getHasUseMd5List()); -// if (StringUtils.isEmpty(libraryVo)) { -// //系统获取 -// SysFileVO sysFileVO = getRandomSysFileOutwear(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); -// DesignPythonItem item = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); -// item.setBusinessId(sysFileVO.getId()); -// items.add(item); -// return items; -// } -// DesignPythonItem item = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); -// item.setBusinessId(libraryVo.getId()); -// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); -// items.add(item); -// } -// break; - case SYS_FILE: - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.OUTWEAR_DRESS_BLOUSE.contains(elementVO.getSwitchCategory())) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); - DesignPythonItem item = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - item.setBusinessId(sysFileVO.getId()); - items.add(item); - return items; - } - } else { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileOutwear(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); - DesignPythonItem item = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - item.setBusinessId(sysFileVO.getId()); - items.add(item); - return items; - } - break; - case NO_PIN: - //single模式 - if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { - if (DesignPythonItem.OUTWEAR_DRESS_BLOUSE.contains(elementVO.getSwitchCategory())) { - //非Pin的数据 - List noPinDataByType = getNoPinData( - elementVO.getSketchBoardElements(), Collections.singletonList(elementVO.getSwitchCategory())); - CollectionElement collectionElement = getRandomSketchLibrary(noPinDataByType, elementVO.getHasUseMd5List()); - if (Objects.isNull(collectionElement)) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); - DesignPythonItem item = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - item.setBusinessId(sysFileVO.getId()); - items.add(item); - } else { - elementVO.getHasUseMd5List().add(collectionElement.getMd5()); - items.add(coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO)); - } - } - } else { - //非Pin的数据 - List noPinData = getNoPinData(elementVO.getSketchBoardElements(), DesignPythonItem.OUTWEAR_DRESS_BLOUSE); - CollectionElement collectionElement = getRandomSketchLibrary(noPinData, elementVO.getHasUseMd5List()); - if (Objects.isNull(collectionElement)) { - //系统获取 - SysFileVO sysFileVO = getRandomSysFileOutwear(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); - DesignPythonItem item = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); - item.setBusinessId(sysFileVO.getId()); - items.add(item); - } else { - elementVO.getHasUseMd5List().add(collectionElement.getMd5()); - items.add(coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO)); - } - } - break; - default: - } - return items; - } - - private DesignPythonItem coverToDesignPythonItem(Long elementId, String type, String path, - ValidateElementVO elementVO) { - DesignPythonItem designPythonItemBlouse = new DesignPythonItem(); - if (Objects.nonNull(elementId)) { - designPythonItemBlouse.setElementId(elementId); - designPythonItemBlouse.setBusinessId(elementId); - } - designPythonItemBlouse.setType(type); - designPythonItemBlouse.setPath(path); - //所有的icon都是none - designPythonItemBlouse.setIcon("none"); - CollectionColorDTO randomColor = getRandomColor(elementVO.getColorBoards()); - if (Objects.nonNull(randomColor)) { - designPythonItemBlouse.setColor(randomColor.getRgbValue()); - designPythonItemBlouse.setGradient(randomColor.getGradientMinioUrl()); - designPythonItemBlouse.setGradientString(randomColor.getGradientString()); - } - if (!elementVO.getDesignPythonItemPrint().getPath().equals("none") - && elementVO.getDesignPrintPictureTypeLayoutList().contains(type)) { - DesignPythonItemPrint designPythonItemPrint = CopyUtil.copyObject(elementVO.getDesignPythonItemPrint(), DesignPythonItemPrint.class); -// designPythonItemPrint.setIfSingle(false); - designPythonItemPrint.setPrint_path_list(Collections.singletonList(designPythonItemPrint.getPath())); - designPythonItemBlouse.setPrint(new PrintToPython(designPythonItemPrint)); - } else { - DesignPythonItemPrint designPythonItemPrint = new DesignPythonItemPrint(); -// designPythonItemPrint.setIfSingle(false); - designPythonItemPrint.setPrint_path_list(new ArrayList<>()); - designPythonItemBlouse.setPrint(new PrintToPython(designPythonItemPrint)); - } - return designPythonItemBlouse; - } - - private DesignPythonItem coverSketchToDesignPythonItem(Long elementId, CollectionElement collectionElement, ValidateElementVO elementVO) { - DesignPythonItem designPythonItemBlouse = new DesignPythonItem(); - if (Objects.nonNull(elementId)) { - designPythonItemBlouse.setElementId(elementId); - designPythonItemBlouse.setBusinessId(elementId); - } - designPythonItemBlouse.setType(collectionElement.getLevel2Type()); - designPythonItemBlouse.setPath(collectionElement.getUrl()); - //所有的icon都是none - designPythonItemBlouse.setIcon("none"); - CollectionColorDTO randomColor = getRandomColor(elementVO.getColorBoards()); - if (Objects.nonNull(randomColor)) { - designPythonItemBlouse.setColor(randomColor.getRgbValue()); - designPythonItemBlouse.setGradient(randomColor.getGradientMinioUrl()); - designPythonItemBlouse.setGradientString(randomColor.getGradientString()); - } - if (!elementVO.getDesignPythonItemPrint().getPath().equals("none") - && elementVO.getDesignPrintPictureTypeLayoutList().contains(collectionElement.getLevel2Type())) { - DesignPythonItemPrint designPythonItemPrint = CopyUtil.copyObject(elementVO.getDesignPythonItemPrint(), DesignPythonItemPrint.class); -// designPythonItemPrint.setIfSingle(false); - designPythonItemPrint.setPrint_path_list(Collections.singletonList(designPythonItemPrint.getPath())); - designPythonItemBlouse.setPrint(new PrintToPython(designPythonItemPrint)); - } else { - DesignPythonItemPrint designPythonItemPrint = new DesignPythonItemPrint(); -// designPythonItemPrint.setIfSingle(false); - designPythonItemPrint.setPrint_path_list(new ArrayList<>()); - designPythonItemBlouse.setPrint(new PrintToPython(designPythonItemPrint)); - } - return designPythonItemBlouse; - } - - private DesignPythonItem coverSystemSketchUrlToDesignPythonItem(String url, String category, ValidateElementVO elementVO) { - DesignPythonItem designPythonItemBlouse = new DesignPythonItem(); -// if (Objects.nonNull(elementId)) { -// designPythonItemBlouse.setElementId(null); -// designPythonItemBlouse.setBusinessId(null); -// } - designPythonItemBlouse.setType(category); - designPythonItemBlouse.setPath(url); - //所有的icon都是none - designPythonItemBlouse.setIcon("none"); - CollectionColorDTO randomColor = getRandomColor(elementVO.getColorBoards()); - if (Objects.nonNull(randomColor)) { - designPythonItemBlouse.setColor(randomColor.getRgbValue()); - designPythonItemBlouse.setGradient(randomColor.getGradientMinioUrl()); - designPythonItemBlouse.setGradientString(randomColor.getGradientString()); - } - if (!elementVO.getDesignPythonItemPrint().getPath().equals("none") - && elementVO.getDesignPrintPictureTypeLayoutList().contains(category)) { - DesignPythonItemPrint designPythonItemPrint = CopyUtil.copyObject(elementVO.getDesignPythonItemPrint(), DesignPythonItemPrint.class); -// designPythonItemPrint.setIfSingle(false); - designPythonItemPrint.setPrint_path_list(Collections.singletonList(designPythonItemPrint.getPath())); - designPythonItemBlouse.setPrint(new PrintToPython(designPythonItemPrint)); - } else { - DesignPythonItemPrint designPythonItemPrint = new DesignPythonItemPrint(); -// designPythonItemPrint.setIfSingle(false); - designPythonItemPrint.setPrint_path_list(new ArrayList<>()); - designPythonItemBlouse.setPrint(new PrintToPython(designPythonItemPrint)); - } - return designPythonItemBlouse; - } - - private List residuePinData(List pinData, List existPinDataIds, List hasUseMd5List) { - if (CollectionUtils.isEmpty(pinData)) { - return null; - } - return pinData.stream().filter(v -> (!existPinDataIds.contains(v.getId())) - && (!hasUseMd5List.contains(v.getMd5()))).collect(Collectors.toList()); - } - - private DesignPythonBasic coverToBasic(DesignPythonItem designPythonItem, String singleOverall, - String switchCategory, DesignLibraryModelPointVO designLibraryModelPoint, DesignLibraryModelPointVO designLibraryModelPointVO) { - DesignPythonBasic basic = new DesignPythonBasic(); - basic.setSingle_overall(singleOverall); - basic.setSwitch_category(switchCategory); -// basic.setSave_name(getPythonOutputPath( -// StringUtils.isEmpty(designPythonItem.getPath()) ? designPythonItem.getBody_path() : designPythonItem.getPath(), -// PythonToJavaApiOperationTypeEnum.DESIGN_COLLECTION)); - basic.setScale_bag(0.7); - basic.setSelf_template(Boolean.FALSE); - if (Objects.nonNull(designLibraryModelPoint)) { - basic.setSelf_template(Boolean.TRUE); - } - basic.setScale_earrings(0.16); - if (Objects.nonNull(designLibraryModelPointVO)) { - basic.setBody_point_test(getMap(designLibraryModelPointVO)); - }else { - basic.setBody_point_test(getMap(designLibraryModelPoint)); - } - return basic; - } - - private DesignLibraryModelPointVO getRandomDesignLibraryModelPoint(List mannequins) { - DesignLibraryModelPointVO vo = new DesignLibraryModelPointVO(); - Random random = new Random(); - int randomNumber = random.nextInt(mannequins.size()); - return mannequins.get(randomNumber); - - } - - private Map getMap(DesignLibraryModelPointVO designLibraryModelPointOld) { - Map body_point = Maps.newHashMap(); - if (Objects.nonNull(designLibraryModelPointOld)) { - DesignLibraryModelPointVO designLibraryModelPoint = - CopyUtil.copyObject(designLibraryModelPointOld, DesignLibraryModelPointVO.class); - //自己的template是6个点 - body_point.put("shoulder_left", resolve(designLibraryModelPoint.getShoulderLeft())); - body_point.put("shoulder_right", resolve(designLibraryModelPoint.getShoulderRight())); - body_point.put("waistband_left", resolve(designLibraryModelPoint.getWaistbandLeft())); - body_point.put("waistband_right", resolve(designLibraryModelPoint.getWaistbandRight())); - body_point.put("hand_point_left", resolve(designLibraryModelPoint.getHandLeft())); - body_point.put("hand_point_right", resolve(designLibraryModelPoint.getHandRight())); - body_point.put("relation_id", designLibraryModelPoint.getRelationId()); - body_point.put("relation_type", designLibraryModelPoint.getRelationType()); - } else { - //默认是13个点 - body_point.put("shoulder_left", Arrays.asList(755, 519)); - body_point.put("shoulder_right", Arrays.asList(912, 519)); - body_point.put("waistband_left", Arrays.asList(777, 725)); - body_point.put("waistband_right", Arrays.asList(891, 725)); - body_point.put("hand_point_left", Arrays.asList(754, 886)); - body_point.put("hand_point_right", Arrays.asList(915, 886)); - body_point.put("head_point_up", Arrays.asList(834, 390)); - body_point.put("head_point_left", Arrays.asList(804, 424)); - body_point.put("head_point_right", Arrays.asList(864, 424)); - body_point.put("toe_left", Arrays.asList(817, 1355)); - body_point.put("toe_right", Arrays.asList(850, 1355)); - body_point.put("ear_point_left", Arrays.asList(802, 439)); - body_point.put("ear_point_right", Arrays.asList(865, 438)); - body_point.put("foot_length", Arrays.asList(784, 1336, 825, 1336)); - } - return body_point; - } - - private List resolve(List list) { - List integerList = Lists.newArrayList(); - list.forEach(l -> { - integerList.add(l.intValue()); - }); - return integerList; - } - - private List getPinData(ValidateElementVO elementVO) { - List pinData = getPinData(elementVO.getSketchBoardElements(), elementVO.getHasUseMd5List(), elementVO.getModelSex()); - if (elementVO.getSingleOverall().equals(SingleOverallEnum.SINGLE.getRealName())) { - if (!CollectionUtils.isEmpty(pinData)) { - return pinData.stream().filter(o -> o.getLevel2Type().equals(elementVO.getSwitchCategory())).collect(Collectors.toList()); - } else { - return pinData; - } - } else { - return pinData; - } - } - - private List getPinDataWhole(ValidateElementVO elementVO) { - List pinData = getPinDataWhole(elementVO.getSketchBoardElements(), elementVO.getHasUseMd5List(), elementVO.getModelSex()); - if (elementVO.getSingleOverall().equals(SingleOverallEnum.SINGLE.getRealName())) { - if (!CollectionUtils.isEmpty(pinData)) { - return pinData.stream().filter(o -> o.getLevel2Type().equals(elementVO.getSwitchCategory())).collect(Collectors.toList()); - } else { - return pinData; - } - } else { - return pinData; - } - } - - private List getPinDataWhole(List sketchBoardElements, List hasUseMd5List, String modelSex) { - if (CollectionUtils.isEmpty(sketchBoardElements)) { - return null; - } - List sketchBoardPins = sketchBoardElements - .stream().filter(v -> v.getHasPin() == 1).collect(Collectors.toList()); - if (modelSex.equals(Sex.MALE.getValue())) { - sketchBoardPins = sketchBoardPins.stream().filter(o -> MALE_CATEGORY.contains(o.getLevel2Type())).collect(Collectors.toList()); - } - if (modelSex.equals(Sex.FEMALE.getValue())) { - sketchBoardPins = sketchBoardPins.stream().filter(o -> FEMALE_CATEGORY.contains(o.getLevel2Type())).collect(Collectors.toList()); - } - if (CollectionUtils.isEmpty(sketchBoardPins)) { - return null; - } - return sketchBoardPins; - } - - public final static List FEMALE_CATEGORY = Arrays.asList("Dress", "Blouse", "Skirt", "Trousers", "Outwear"); - public final static List MALE_CATEGORY = Arrays.asList("Tops", "Bottoms", "Outwear"); - - private List getPinData(List sketchBoardElements, List hasUseMd5List, String modelSex) { - if (CollectionUtils.isEmpty(sketchBoardElements)) { - return null; - } - List sketchBoardPins = sketchBoardElements - .stream().filter(v -> v.getHasPin() == 1 && (!hasUseMd5List.contains(v.getMd5()))).collect(Collectors.toList()); - if (modelSex.equals(Sex.MALE.getValue())) { - sketchBoardPins = sketchBoardPins.stream().filter(o -> MALE_CATEGORY.contains(o.getLevel2Type())).collect(Collectors.toList()); - } - if (modelSex.equals(Sex.FEMALE.getValue())) { - sketchBoardPins = sketchBoardPins.stream().filter(o -> FEMALE_CATEGORY.contains(o.getLevel2Type())).collect(Collectors.toList()); - } - if (CollectionUtils.isEmpty(sketchBoardPins)) { - return null; - } - return sketchBoardPins; - } - - private List getNoPinData(ValidateElementVO elementVO) { - if (elementVO.getSingleOverall().equals(SingleOverallEnum.SINGLE.getRealName())) { - List noPinData = getNoPinData(elementVO.getSketchBoardElements(), elementVO.getModelSex()); - if (CollectionUtils.isEmpty(noPinData)) { - return null; - } - return noPinData.stream().filter(o -> o.getLevel2Type().equals(elementVO.getSwitchCategory())).collect(Collectors.toList()); - } else { - return getNoPinData(elementVO.getSketchBoardElements(), elementVO.getModelSex()); - } - } - - private List getNoPinData(List sketchBoardElements, String modelSex) { - if (CollectionUtils.isEmpty(sketchBoardElements)) { - return null; - } - List sketchBoardPins = sketchBoardElements - .stream().filter(v -> v.getHasPin() == 0).collect(Collectors.toList()); - if (modelSex.equals(Sex.MALE.getValue())) { - sketchBoardPins = sketchBoardPins.stream().filter(o -> MALE_CATEGORY.contains(o.getLevel2Type())).collect(Collectors.toList()); - } - if (modelSex.equals(Sex.FEMALE.getValue())) { - sketchBoardPins = sketchBoardPins.stream().filter(o -> FEMALE_CATEGORY.contains(o.getLevel2Type())).collect(Collectors.toList()); - } - if (CollectionUtils.isEmpty(sketchBoardPins)) { - return null; - } - return sketchBoardPins; - } - - private List resolveElementFilterHistoryMd5(List elemet) { - //查询历史design数据 - List md5List = elemet.stream().map(CollectionElement::getMd5).collect(Collectors.toList()); - List designHistories = designHistoryService.getByMD5List(md5List); - if (CollectionUtils.isEmpty(designHistories)) { - return elemet; - } - List existMd5List = designHistories.stream().map(DesignHistory::getMd5).collect(Collectors.toList()); - return elemet.stream().filter(f -> !existMd5List.contains(f.getMd5())).collect(Collectors.toList()); - } - - private List getPinDataByLevel2Type(List sketchBoardElements, String level2Type) { - if (CollectionUtils.isEmpty(sketchBoardElements)) { - return null; - } - List sketchBoardPins = sketchBoardElements - .stream().filter(v -> v.getHasPin() == 1 && v.getLevel2Type().equals(level2Type)).collect(Collectors.toList()); - if (CollectionUtils.isEmpty(sketchBoardPins)) { - return null; - } - return CopyUtil.copyList(sketchBoardPins, CollectionElement.class); - } - - private List getNoPinData(List sketchBoardElements, List Level2TypeList) { - if (CollectionUtils.isEmpty(sketchBoardElements)) { - return null; - } - List sketchBoardPins = sketchBoardElements - .stream().filter(v -> v.getHasPin() == 0 && Level2TypeList.contains(v.getLevel2Type())).collect(Collectors.toList()); - if (CollectionUtils.isEmpty(sketchBoardPins)) { - return null; - } - return CopyUtil.copyList(sketchBoardPins, CollectionElement.class); - } - - private SysFileVO getRandomSysFileOutwear(List sysFileVo, List sysFileIds, String modelSex) { - Long randomIndex = RandomsUtil.randomSysFile(0L, 3L); - if (CollectionUtils.isEmpty(sysFileVo)) { - return getRandomSysFileByLevel2Type(DesignPythonItem.OUTWEAR_DRESS_BLOUSE.get(randomIndex.intValue()), sysFileIds, modelSex); - } else { - //attribute_retrieval 算法,满足blouse + outwear+dress>8,以及 skirt+trousers>8 - return getRandomSysFileByAttributeRetrieval(DesignPythonItem.OUTWEAR_DRESS_BLOUSE, sysFileVo, sysFileIds); - } - } - - private SysFileVO getRandomSysFileMaleTops(List sysFileVo, List sysFileIds, String modelSex) { - Long randomIndex = RandomsUtil.randomSysFile(0L, 1L); - if (CollectionUtils.isEmpty(sysFileVo)) { - return getRandomSysFileByLevel2Type(DesignPythonItem.TOPS.get(randomIndex.intValue()), sysFileIds, modelSex); - } else { - //attribute_retrieval 算法,满足blouse + outwear+dress>8,以及 skirt+trousers>8 - return getRandomSysFileByAttributeRetrieval(DesignPythonItem.TOPS, sysFileVo, sysFileIds); - } - } - - private SysFileVO getRandomSysFileMaleBottoms(List sysFileVo, List sysFileIds, String modelSex) { - Long randomIndex = RandomsUtil.randomSysFile(0L, 1L); - if (CollectionUtils.isEmpty(sysFileVo)) { - return getRandomSysFileByLevel2Type(DesignPythonItem.BOTTOMS.get(randomIndex.intValue()), sysFileIds, modelSex); - } else { - //attribute_retrieval 算法,满足blouse + outwear+dress>8,以及 skirt+trousers>8 - return getRandomSysFileByAttributeRetrieval(DesignPythonItem.BOTTOMS, sysFileVo, sysFileIds); - } - } - - private SysFileVO getRandomSysFileSkirt(List sysFileVo, List sysFileIds, String modelSex) { - Long randomIndex = RandomsUtil.randomSysFile(0L, 2L); - if (CollectionUtils.isEmpty(sysFileVo)) { - return getRandomSysFileByLevel2Type(DesignPythonItem.SKIRT_TROUSERS.get(randomIndex.intValue()), sysFileIds, modelSex); - } else { - //attribute_retrieval 算法,满足blouse + outwear+dress>8,以及 skirt+trousers>8 - return getRandomSysFileByAttributeRetrieval(DesignPythonItem.SKIRT_TROUSERS, sysFileVo, sysFileIds); - } - } - - private SysFileVO getRandomSysFileByLevel2Type(String level2Type, List sysFileIds, String modelSex) { - Long maxId = sysFileService.getMaxIdByLevel2Type(level2Type, modelSex); - Long minId = sysFileService.getMinIdByLevel2Type(level2Type, modelSex); - Long sysFileId = null; - do { - sysFileId = RandomsUtil.randomSysFile(minId, maxId + 1); - } while (sysFileIds.contains(sysFileId)); - sysFileIds.add(sysFileId); - return sysFileService.getById(sysFileId); - } - - private SysFileVO getRandomSysFileByAttributeRetrieval(List level2TypeList, List sysFileVo, List sysFileIds) { - sysFileVo = sysFileVo.stream().filter( - f -> level2TypeList.contains(f.getLevel2Type()) && (!sysFileIds.contains(f.getId()))) - .collect(Collectors.toList()); - Long maxId = (long) sysFileVo.size(); - Long minId = 0L; - Long key = null; - Long sysFileId = null; - do { - key = RandomsUtil.randomSysFile(minId, maxId); - sysFileId = sysFileVo.get(key.intValue()).getId(); - } while (sysFileIds.contains(sysFileId)); - sysFileIds.add(sysFileId); - return sysFileVo.get(key.intValue()); - } - - private CollectionColorDTO getRandomColor(List colorBoards) { - if (CollectionUtils.isEmpty(colorBoards)) { - return null; - } - if (colorBoards.size() == 1) { - return colorBoards.get(0); - } - long maxColor = colorBoards.size(); - long minColor = 0; - Long randomIndex = RandomsUtil.randomSysFile(minColor, maxColor); - return colorBoards.get(randomIndex.intValue()); - } - - private CollectionElement getRandomSketchLibrary(List sketchBoardElementOlds, List hasUseMd5List) { - if (CollectionUtil.isEmpty(sketchBoardElementOlds)) { - return null; - } - List sketchBoardElements = sketchBoardElementOlds.stream().filter(f -> !hasUseMd5List.contains(f.getMd5())).collect(Collectors.toList()); - if (CollectionUtils.isEmpty(sketchBoardElements)) { - return null; - } - if (sketchBoardElements.size() == 1) { - return sketchBoardElements.get(0); - } - long maxSketch = sketchBoardElements.size(); - long minSketch = 0; - Long randomIndex = RandomsUtil.randomSysFile(minSketch, maxSketch); - return sketchBoardElements.get(randomIndex.intValue()); - } - - private DesignPythonItemPrint getRandomPrint(ValidateElementVO elementVO, CurrentDesignPrintPictureTypeEnum designPrintPictureType) { - //print 不取library的 只取element的 - DesignPythonItemPrint print = new DesignPythonItemPrint(); - if (CollectionUtil.isEmpty(elementVO.getPrintBoardElements())) { - print.setPath("none"); - return print; - } - List printBoardElements; - if (designPrintPictureType.equals(CurrentDesignPrintPictureTypeEnum.PIN)) { - printBoardElements = elementVO.getPrintBoardElements() - .stream() - .filter(f -> !elementVO.getHasUseMd5List().contains(f.getMd5())).collect(Collectors.toList()); - } else { - printBoardElements = elementVO.getPrintBoardElements(); - } - if (CollectionUtil.isEmpty(printBoardElements)) { - print.setPath("none"); - return print; - } - switch (designPrintPictureType) { - case NO: - //print 已用完 - print.setPath("none"); - return print; - case NO_PIN: - printBoardElements = printBoardElements.stream().filter(f -> f.getHasPin() == 0).collect(Collectors.toList()); - break; - case PIN: - printBoardElements = printBoardElements.stream().filter(f -> f.getHasPin() == 1).collect(Collectors.toList()); - break; - default: - } - - if (printBoardElements.size() == 1) { - print.setPath(printBoardElements.get(0).getUrl()); - elementVO.getHasUseMd5List().add(printBoardElements.get(0).getMd5()); - return print; - } - long maxPrint = printBoardElements.size(); - long minPrint = 0; - Long randomIndex = RandomsUtil.randomSysFile(minPrint, maxPrint); - print.setPath(printBoardElements.get(randomIndex.intValue()).getUrl()); - elementVO.getHasUseMd5List().add(printBoardElements.get(randomIndex.intValue()).getMd5()); - return print; - } - - private LibraryVo getRandomLibrary(List libraryOldVos, List containLevel2Type, List hasUseMd5List) { - if (CollectionUtils.isEmpty(libraryOldVos)) { - return null; - } - List libraryVos = libraryOldVos.stream().filter(f -> (!hasUseMd5List.contains(f.getMd5())) && - CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName().equals(f.getLevel1Type())).collect(Collectors.toList()); - if (CollectionUtils.isEmpty(libraryVos)) { - return null; - } - if (StringUtils.isEmpty(containLevel2Type)) { - if (libraryVos.size() == 1) { - return libraryVos.get(0); - } - long maxLibrary = libraryVos.size(); - long minLibrary = 0; - Long randomIndex = RandomsUtil.randomSysFile(minLibrary, maxLibrary); - return libraryVos.get(randomIndex.intValue()); - } else { - List filter = libraryVos.stream().filter(f -> containLevel2Type.contains(f.getLevel2Type())).collect(Collectors.toList()); - if (CollectionUtils.isEmpty(filter)) { - return null; - } - if (filter.size() == 1) { - return filter.get(0); - } - long maxLibrary = filter.size(); - long minLibrary = 0; - Long randomIndex = RandomsUtil.randomSysFile(minLibrary, maxLibrary); - return filter.get(randomIndex.intValue()); - } - - } - - /** - * 生成design服装 - * - * @param designPythonObjects - * @return - */ - public Boolean design(DesignPythonObjects designPythonObjects) { - //限流校验 - AccessLimitUtils.validate("design", 5); - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - //关闭FastJson的引用检测 防止出现$ref 现象 - String param = JSON.toJSONString(designPythonObjects, SerializerFeature.DisableCircularReferenceDetect); - log.info("design请求python 参数:####{}", param); - RequestBody body = RequestBody.create(mediaType, param); - Request request = new Request.Builder() - .url(accessPythonIp + ":" + accessPythonPort + "/api/design") -// .url(fastApiPythonAddress + "/api/design") -// .url(accessPythonIp + ":10200/aifda/api/v1.0/generate") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response = null; - try { - response = client.newCall(request).execute(); - log.info("PythonService##response###{}", response); - log.info("PythonService##responseBodyStr###{}", response.body().string()); - log.info("PythonService##responseBodyJson###{}", JSON.toJSONString(response.body())); - } catch (IOException ioException) { - log.error("PythonService##design异常###{}", ExceptionUtil.getThrowableList(ioException)); - } - //去除限流 - AccessLimitUtils.validateOut("design"); - if (Objects.isNull(response)) { - log.error("PythonService##design异常###{}", "response or body is empty!"); - throw new BusinessException("system error!"); - } - JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(response)); - log.info("PythonService##jsonObject###{}", jsonObject); - Boolean result = jsonObject.getBoolean("successful"); - if (result) { - return Boolean.TRUE; - } - log.info("PythonService##design异常jsonObject###{}", jsonObject); - //生成失败 - throw new BusinessException("generate design exception!"); - } - - /** - * 生成高级图片(废弃) - * - * @param designPath - * @return - */ - public String generateHighDesign(String designPath) { - //限流校验 - AccessLimitUtils.validate("generateHighDesign", 2); - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - Map content = Maps.newHashMap(); - content.put("img_path", designPath); - content.put("img_path_out_put", getPythonOutputPath( - designPath, PythonToJavaApiOperationTypeEnum.GENERATE_ADVANCED_DESIGN)); - MediaType mediaType = MediaType.parse("application/json"); - RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); - Request request = new Request.Builder() - .url(accessPythonIp + ":11111/aifda/api/v1.0/sketch_to_real") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response = null; - try { - log.info("生成高级design请求入参content###{}", JSON.toJSONString(content)); - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##generateHighDesign异常###{}", ExceptionUtil.getThrowableList(ioException)); - } - //去除限流 - AccessLimitUtils.validateOut("generateHighDesign"); - if (Objects.isNull(response)) { - log.error("PythonService##generateHighDesign异常###{}", "response or body is empty!"); - throw new BusinessException("system error!"); - } - JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(response)); - Boolean result = jsonObject.getBoolean("successful"); - if (result) { - return content.get("img_path_out_put"); - } - log.info("生成高级design失败###{}", jsonObject); - //生成失败 - throw new BusinessException("system error!"); - } - - /** - * 生成 attribute_retrieval - * - * @param sketchUrlList - * @param modelSex - * @return - */ - public DesignAttributeRetrievalDTO generateAttributeRetrieval(List sketchUrlList, Long userId, String modelSex) { - //限流校验 - AccessLimitUtils.validate("generateAttributeRetrieval", 4); - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - Map content = Maps.newHashMap(); - content.put("sketch_upload_img_path", sketchUrlList); - content.put("userid", userId); - content.put("colony", modelSex); - MediaType mediaType = MediaType.parse("application/json"); - System.out.println(JSON.toJSONString(content)); - RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); - Request request = new Request.Builder() - .url(accessPythonIp + ":" + accessPythonPort + "/api/attribute_retrieve") -// .url(fastApiPythonAddress + "/api/attribute_retrieve") -// .url(accessPythonIp+":9991/aifda/api/v1.0/attribute_retrieval") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response; - String bodyStr; - try { - log.info("generateAttributeRetrieval请求入参content###{}", JSON.toJSONString(content)); - response = client.newCall(request).execute(); - } catch (IOException ioException) { - AccessLimitUtils.validateOut("generateAttributeRetrieval"); - log.error("generateAttributeRetrieval异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("attributeRetrieval.interface.exception"); - } - //去除限流 - AccessLimitUtils.validateOut("generateAttributeRetrieval"); - if (response.isSuccessful()) { - try { - if (Objects.nonNull(response.body())) { - bodyStr = response.body().string(); - return resolveDesignAttributeRetrievalDTO(bodyStr); - } - //生成失败 - throw new BusinessException("attributeRetrieval.interface.exception"); - } catch (JSONException | IOException e) { - log.error("generateAttributeRetrieval异常###{}", e.getMessage()); - throw new BusinessException("attributeRetrieval.interface.exception"); - } - } - log.error("generateAttributeRetrieval异常###{}", response); - //生成失败 - throw new BusinessException("attributeRetrieval.interface.exception"); - } - - private static DesignAttributeRetrievalDTO resolveDesignAttributeRetrievalDTO(String bodyStr) { - DesignAttributeRetrievalDTO response = new DesignAttributeRetrievalDTO(); - JSONObject jsonObject = JSON.parseObject(bodyStr); - JSONObject data = jsonObject.getJSONObject("data"); - if (data != null) { - JSONObject jsonObjectSys = data.getJSONObject("sys_lib_dict"); - if (null == jsonObjectSys || jsonObjectSys.isEmpty()) { - log.error("generateAttributeRetrieval异常###{}", "jsonObjectSys is empty!"); - throw new BusinessException("attributeRetrieval.interface.exception"); - } - setUrls(jsonObjectSys, response.getSysFileUrlS()); - JSONObject jsonObjectLibrary = data.getJSONObject("user_lib_dict"); - if (null == jsonObjectLibrary || jsonObjectLibrary.isEmpty()) { - log.error("generateAttributeRetrieval异常###{}", "jsonObjectLibrary is empty!"); - throw new BusinessException("attributeRetrieval.interface.exception"); - } - setUrls(jsonObjectLibrary, response.getLibraryUrls()); - return response; - } - throw new BusinessException("attributeRetrieval.interface.exception"); - } - - private static void setUrls(JSONObject jsonObjectSys, List urls) { - List finalUrls = urls; - SysFileLevel2TypeEnum.ofPythonPath().forEach(path -> { - JSONArray array = jsonObjectSys.getJSONArray(path); - List urlList = JSONObject.parseArray(JSON.toJSONString(array), String.class); - if (CollectionUtil.isNotEmpty(urlList)) { - finalUrls.addAll(urlList); - } - }); - } - - /** - * 组装和计算designSingle参数 - * - * @param designSingleDTO - * @return - */ - public DesignPythonObjects covertDesignSingleParam(DesignSingleDTO designSingleDTO, String singleOverall, - String switchCategory, DesignLibraryModelPointVO designLibraryModelPoint) { - DesignPythonObjects designPythonObjects = new DesignPythonObjects(); - List objects = Lists.newArrayList(); - designPythonObjects.setObjects(objects); - - DesignPythonObject pythonObject = new DesignPythonObject(); - pythonObject.setItems(coverToDesignSinglePythonItem(designSingleDTO, designLibraryModelPoint)); - pythonObject.setBasic(coverToSingleBasic(pythonObject.getItems().get(0), - singleOverall, switchCategory, designSingleDTO.getPriority(), designLibraryModelPoint)); - objects.add(pythonObject); - return designPythonObjects; - } - - /** - * 组装和计算设计包括图层的单品的参数,不需要priority - * - * @param designSingleDTO - * @param singleOverall - * @param switchCategory - * @param designLibraryModelPoint - * @return - */ - public DesignPythonObjects covertDesignSingleParam(DesignSingleIncludeLayersDTO designSingleDTO, String singleOverall, - String switchCategory, DesignLibraryModelPointVO designLibraryModelPoint, - String previewOrSubmit) { - DesignPythonObjects designPythonObjects = new DesignPythonObjects(); - List objects = Lists.newArrayList(); - designPythonObjects.setObjects(objects); - - DesignPythonObject pythonObject = new DesignPythonObject(); - designPythonObjects.setProcess_id(designSingleDTO.getProcessId()); - pythonObject.setItems(coverToDesignSinglePythonItem(designSingleDTO, designLibraryModelPoint, singleOverall)); - pythonObject.setBasic(coverToSingleBasic(singleOverall, switchCategory, designLibraryModelPoint, previewOrSubmit)); - objects.add(pythonObject); - return designPythonObjects; - } - - private List coverToDesignSinglePythonItem(DesignSingleDTO designSingleDTO, DesignLibraryModelPointVO designLibraryModelPoint) { - List designPythonItemDto = designSingleDTO.getClothes(); - if (!CollectionUtils.isEmpty(designSingleDTO.getOthers())) { - designPythonItemDto.addAll(designSingleDTO.getOthers()); - } - List response = CopyUtil.copyList(designPythonItemDto, DesignPythonItem.class, (o, d) -> { - d.setBusinessId(o.getId()); - d.setIcon("none"); -// d.setPrint(resolveDesignSinglePrint(o.getPrintObject(), o.getPath())); - }); - DesignPythonItem body = new DesignPythonItem(); - body.setType(SysFileLevel2TypeEnum.BODY.getRealName()); - if (Objects.nonNull(designLibraryModelPoint)) { - body.setBody_path(designLibraryModelPoint.getTemplateUrl()); - } else { -// body.setBody_path("/home/pangkaicheng/python_code/Multi-layer-Virtual-Try-on/dataset_for_test/Img_model.png"); - body.setBody_path("/workspace/python_code/Multi-layer-Virtual-Try-on/dataset_for_test/Img_model.png"); - } - response.add(body); - return response; - } - - /** - * 设计包括图层的单品,每次只针对一个单品 - * - * @param designSingleIncludeLayersDTO - * @param designLibraryModelPoint - * @return - */ - private List coverToDesignSinglePythonItem(DesignSingleIncludeLayersDTO designSingleIncludeLayersDTO, - DesignLibraryModelPointVO designLibraryModelPoint, - String singleOverall) { - List designSingleItemList = designSingleIncludeLayersDTO.getDesignSingleItemDTOList(); - List response = new ArrayList<>(); - - designSingleItemList.forEach(designSingleItem -> { - Long businessId; - if (!designSingleIncludeLayersDTO.getIsPreview() && designSingleItem.getChanged()) { - String s = String.valueOf(designSingleItem.getId()); - businessId = Long.parseLong(s.substring(0, s.length() - 3)); - } else { - businessId = designSingleItem.getId(); - } - - // 判断是否是渐变色 - String minioPath = null; - String gradientString = null; - if (!Objects.isNull(designSingleItem.getGradient())) { - String colorImg = designSingleItem.getGradient().getColorImg(); - if (StringUtil.isNullOrEmpty(colorImg)) { - throw new BusinessException("base64.data.empty"); - } - minioPath = minioUtil.base64UploadToPath(colorImg, gradientBucketName, null); - designSingleItem.getGradient().setColorImg(null); - gradientString = JSONObject.toJSONString(designSingleItem.getGradient()); - } - - PrintToPython printToPython = resolveDesignSinglePrint(designSingleItem.getPrintObject().getPrints(), - designSingleItem.getPartialDesign().getPartialDesignMinioPath()); - resolveDesignElement(designSingleItem.getTrims(), printToPython); - log.info("组装参数【服装:{}的maskUrl: {}】",designSingleItem.getType(), designSingleItem.getMaskUrl()); - response.add(new DesignPythonItem( - designSingleItem.getType(), - designSingleItem.getPath(), - designSingleItem.getColor(), - printToPython, - // businessId designItemDetailId (python端确认没有作用,但是数据库需要存,作用:未知) -// designSingleItem.getId(), - businessId, - pythonTAllInfoService.getImageIdByPath(designSingleItem.getPath()), - designSingleItem.getOffset(), - designSingleItem.getScale(), - designSingleItem.getPriority(), - minioPath, - gradientString, - designSingleItem.getMaskUrl(), - designSingleItem.getTranspose(), - designSingleItem.getRotate() - )); - - }); - - if (singleOverall.equals("overall")){ - String bodyPath; - if (Objects.nonNull(designLibraryModelPoint)) { - bodyPath = designLibraryModelPoint.getTemplateUrl(); - } else { -// bodyPath = "/workspace/python_code/Multi-layer-Virtual-Try-on/dataset_for_test/Img_model.png"; - bodyPath = "aida-mannequins/model_1693218345.2714432.png"; - } - response.add(new DesignPythonItem(SysFileLevel2TypeEnum.BODY.getRealName(), bodyPath, pythonTAllInfoService.getImageIdByPath(bodyPath))); - } - return response; - } - - - private PrintToPython resolveDesignSinglePrint(List printObject, String partialDesign) { - PrintToPython printToPython = new PrintToPython(); - DesignPythonItemPrint printSingle = new DesignPythonItemPrint(); - DesignPythonItemPrint printOverall = new DesignPythonItemPrint(); - printToPython.setSingle(printSingle); - printToPython.setOverall(printOverall); - printToPython.setPartial(StringUtil.isNullOrEmpty(partialDesign) ? null : partialDesign); - if (Objects.isNull(printObject) || printObject.isEmpty()){ - return printToPython; - } - - // 没有印花时的参数设置 -// if (printObject.getIfSingle().equals(Boolean.FALSE) && CollectionUtil.isEmpty(printObject.getPrints())) { -// return new DesignPythonItemPrint(new ArrayList<>(), false); -// } -// DesignPythonItemPrint print = CopyUtil.copyObject(printObject, DesignPythonItemPrint.class); - - int size = printObject.size(); - // 占位符填充数组 - List> locationS = new ArrayList<>(Collections.nCopies(size, null)); - List> scaleS = new ArrayList<>(Collections.nCopies(size, null)); - List angleS = new ArrayList<>(Collections.nCopies(size, null)); - ArrayList pathsS = new ArrayList<>(Collections.nCopies(size, null)); - - List> locationO = new ArrayList<>(Collections.nCopies(size, null)); - List> scaleO = new ArrayList<>(Collections.nCopies(size, null)); - List angleO = new ArrayList<>(Collections.nCopies(size, null)); - ArrayList pathsO = new ArrayList<>(Collections.nCopies(size, null)); - - // 设置印花的位置、大小、旋转角度 - // 优先级越大,越靠近顶层,在传输给python的数组中,越靠前 -// List prints = printObject.getPrints(); - printObject.forEach(p -> { - p.getLocation().set(0, p.getLocation().get(0)); - p.getLocation().set(1, p.getLocation().get(1)); - Integer priority = p.getPriority(); - setUriToMinioPath(p); - // todo 下标越界问题 - if (p.getIfSingle()){ - locationS.set(priority - 1, p.getLocation()); - scaleS.set(priority - 1, p.getScale()); - angleS.set( priority - 1, p.getAngle()); - pathsS.set(priority - 1, p.getMinIOPath()); - }else { - locationO.set(priority - 1, p.getLocation()); - scaleO.set(priority - 1, p.getScale()); - angleO.set(priority - 1, p.getAngle()); - pathsO.set(priority - 1, p.getMinIOPath()); - } -// log.info("本次print打点locations###{}###fileVO{}", p.getLocation(), JSON.toJSONString(fileVO)); - }); - locationS.removeAll(Collections.singleton(null)); - scaleS.removeAll(Collections.singleton(null)); - angleS.removeAll(Collections.singleton(null)); - pathsS.removeAll(Collections.singleton(null)); - printSingle.setLocation(locationS); - printSingle.setPrint_scale_list(scaleS); - printSingle.setPrint_angle_list(angleS); - printSingle.setPrint_path_list(pathsS); - - locationO.removeAll(Collections.singleton(null)); - scaleO.removeAll(Collections.singleton(null)); - angleO.removeAll(Collections.singleton(null)); - pathsO.removeAll(Collections.singleton(null)); - printOverall.setLocation(locationO); - printOverall.setPrint_scale_list(scaleO); - printOverall.setPrint_angle_list(angleO); - printOverall.setPrint_path_list(pathsO); - - return printToPython; - } - - // 对印花类型为Generate的图片路径进行特殊处理 - private void setUriToMinioPath(DesignSinglePrint print){ - if (!StringUtil.isNullOrEmpty(print.getDesignType()) && print.getDesignType().equals("Generate")){ - if (!StringUtil.isNullOrEmpty(print.getPath())){ - try { - URI uri = new URI(print.getPath()); - String path = uri.getPath(); // 获取路径部分: /aida-users/87/print/9ac32f65-6043-424d-a146-92c9c6d204ee-4-87.png - String substring = path.substring(1); - print.setMinIOPath(substring); - } catch (URISyntaxException e) { - throw new BusinessException(e.getMessage()); - } - } else { - log.error("designType为Generate的印花path传值为空 :{}", print.getPath()); - throw new BusinessException("path.cannot.be.empty"); - } - } - } - - private void resolveDesignElement(DesignSinglePrintDTO trims, PrintToPython printToPython) { - // 没有design element 时的参数设置 - DesignPythonItemElement element = new DesignPythonItemElement(); - if (CollectionUtil.isEmpty(trims.getPrints())) { - printToPython.setElement(element); - return; - } - - - int size = trims.getPrints().size(); - // 占位符填充数组 - List> location = new ArrayList<>(Collections.nCopies(size, null)); - List> scale = new ArrayList<>(Collections.nCopies(size, null)); - List angle = new ArrayList<>(Collections.nCopies(size, null)); - ArrayList paths = new ArrayList<>(Collections.nCopies(size, null)); - - // 设置印花的位置、大小、旋转角度 - // 优先级越大,越靠近顶层,在传输给python的数组中,越靠前 - List prints = trims.getPrints(); - prints.forEach(p -> { - p.getLocation().set(0, p.getLocation().get(0)); - p.getLocation().set(1, p.getLocation().get(1)); - p.getScale().set(0, p.getScale().get(0)); - p.getScale().set(1, p.getScale().get(1)); - Integer priority = p.getPriority(); - location.set(priority - 1, p.getLocation()); - scale.set(priority - 1, p.getScale()); - angle.set(priority - 1, p.getAngle()); - paths.set(priority - 1, p.getMinIOPath()); -// log.info("本次print打点locations###{}###fileVO{}", p.getLocation(), JSON.toJSONString(fileVO)); - }); - element.setLocation(location); - element.setElement_scale_list(scale); - element.setElement_angle_list(angle); - element.setElement_path_list(paths); - printToPython.setElement(element); - } - - private DesignPythonBasic coverToSingleBasic(DesignPythonItem designPythonItem, String singleOverall, - String switchCategory, List priority, - DesignLibraryModelPointVO designLibraryModelPoint) { - DesignPythonBasic basic = new DesignPythonBasic(); - basic.setSingle_overall(singleOverall); - basic.setSwitch_category(switchCategory); - basic.setSave_name(getPythonOutputPath( - StringUtils.isEmpty(designPythonItem.getPath()) ? designPythonItem.getBody_path() : designPythonItem.getPath(), - PythonToJavaApiOperationTypeEnum.DESIGN_COLLECTION)); - basic.setPriority(priority); - basic.setSelf_template(Boolean.FALSE); - if (Objects.nonNull(designLibraryModelPoint)) { - basic.setSelf_template(Boolean.TRUE); - } - basic.setScale_bag(0.7); - basic.setScale_earrings(0.16); - basic.setBody_point_test(getMap(designLibraryModelPoint)); - return basic; - } - - /** - * 设计包括图层的单品,不用指定save_name和priority - * - * @param singleOverall - * @param switchCategory - * @param designLibraryModelPoint - * @return - */ - private DesignPythonBasic coverToSingleBasic(String singleOverall, String switchCategory, - DesignLibraryModelPointVO designLibraryModelPoint, - String previewOrSubmit) { - DesignPythonBasic basic = new DesignPythonBasic(); - basic.setSingle_overall(singleOverall); - basic.setSwitch_category(switchCategory); - basic.setSelf_template(Boolean.FALSE); - if (Objects.nonNull(designLibraryModelPoint)) { - basic.setSelf_template(Boolean.TRUE); - } - basic.setScale_bag(0.7); - basic.setScale_earrings(0.16); - basic.setBody_point_test(getMap(designLibraryModelPoint)); - basic.setLayer_order(Boolean.TRUE); - basic.setPreview_submit(previewOrSubmit); - return basic; - } - - /** - * 组装和计算designSingle参数 - * - * @param modelsDotDTO - * @return - */ - public DesignPythonObjects covertModelsDotParam(ModelsDotDTO modelsDotDTO, String singleOverall, String switchCategory) { - DesignPythonObjects designPythonObjects = new DesignPythonObjects(); - List objects = Lists.newArrayList(); - designPythonObjects.setObjects(objects); - designPythonObjects.setProcess_id(UUID.randomUUID().toString()); - DesignPythonObject pythonObject = new DesignPythonObject(); - pythonObject.setItems(coverToModelsDotPythonItem(modelsDotDTO)); - pythonObject.setBasic(coverToModelsDotBasic(pythonObject.getItems().get(0), modelsDotDTO)); - objects.add(pythonObject); - return designPythonObjects; - } - - private List coverToModelsDotPythonItem(ModelsDotDTO modelsDotDTO) { - List response = Lists.newArrayList(); - if (modelsDotDTO.getSex().contains("Female")) { - DesignPythonItem dress = new DesignPythonItem(); - dress.setType(SysFileLevel2TypeEnum.BLOUSE.getRealName()); - dress.setColor("none"); - dress.setIcon("none"); - DesignPythonItemPrint designPythonItemPrint = new DesignPythonItemPrint(); -// designPythonItemPrint.setIfSingle(false); - designPythonItemPrint.setPrint_path_list(new ArrayList<>()); - dress.setPrint(new PrintToPython(designPythonItemPrint)); - dress.setPath("aida-sys-image/images/female/blouse/0628001551.jpg"); - dress.setColor("255 255 255"); - response.add(dress); - - DesignPythonItem skirt = new DesignPythonItem(); - skirt.setType(SysFileLevel2TypeEnum.SKIRT.getRealName()); - skirt.setColor("none"); - skirt.setIcon("none"); - DesignPythonItemPrint designPythonItemPrint1 = new DesignPythonItemPrint(); -// designPythonItemPrint1.setIfSingle(false); - designPythonItemPrint1.setPrint_path_list(new ArrayList<>()); - skirt.setPrint(new PrintToPython(designPythonItemPrint1)); - skirt.setPath("aida-sys-image/images/female/skirt/0628000022.jpg"); - skirt.setColor("255 255 255"); -// skirt.setPath("aida-sys-image/images/female/dress/0628000000.jpg"); - response.add(skirt); - } else { - DesignPythonItem top = new DesignPythonItem(); - top.setType(MalePosition.TOPS.getValue()); - top.setColor("none"); - top.setIcon("none"); - DesignPythonItemPrint designPythonItemPrint = new DesignPythonItemPrint(); -// designPythonItemPrint.setIfSingle(false); - designPythonItemPrint.setPrint_path_list(new ArrayList<>()); - top.setPrint(new PrintToPython(designPythonItemPrint)); - top.setPath("aida-sys-image/images/male/tops/mens_test_10.png"); - top.setColor("255 255 255"); - response.add(top); - - DesignPythonItem bottom = new DesignPythonItem(); - bottom.setType(MalePosition.BOTTOMS.getValue()); - bottom.setColor("none"); - bottom.setIcon("none"); - DesignPythonItemPrint designPythonItemPrint1 = new DesignPythonItemPrint(); -// designPythonItemPrint1.setIfSingle(false); - designPythonItemPrint1.setPrint_path_list(new ArrayList<>()); - bottom.setPrint(new PrintToPython(designPythonItemPrint1)); - bottom.setPath("aida-sys-image/images/male/bottoms/mens_test_6252.png"); - bottom.setColor("255 255 255"); - response.add(bottom); - } - - DesignPythonItem body = new DesignPythonItem(); - body.setType(SysFileLevel2TypeEnum.BODY.getRealName()); - body.setBody_path(modelsDotDTO.getTemplateUrl()); - response.add(body); - return response; - } - - private DesignPythonBasic coverToModelsDotBasic(DesignPythonItem designPythonItem, ModelsDotDTO modelsDotDTO) { - DesignPythonBasic basic = new DesignPythonBasic(); - basic.setSingle_overall(SingleOverallEnum.OVERALL.getRealName()); - basic.setSwitch_category(""); - basic.setSave_name(getPythonOutputPath( - StringUtils.isEmpty(designPythonItem.getPath()) ? designPythonItem.getBody_path() : designPythonItem.getPath(), - PythonToJavaApiOperationTypeEnum.DESIGN_COLLECTION)); - basic.setSelf_template(Boolean.TRUE); - basic.setScale_bag(0.7); - basic.setScale_earrings(0.16); - - basic.setBody_point_test(getMap(calculateTemplatePoint(modelsDotDTO, modelsDotDTO.getHigh(), modelsDotDTO.getWidth()))); - return basic; - } - - public DesignLibraryModelPointVO calculateTemplatePoint(ModelsDotDTO modelsDotDTO, Integer high, Integer width) { - DesignLibraryModelPointVO libraryModelPoint = new DesignLibraryModelPointVO(); - libraryModelPoint.setHandLeft(calculateTemplatePointOne(modelsDotDTO.getHandLeft(), high, width)); - libraryModelPoint.setHandRight(calculateTemplatePointOne(modelsDotDTO.getHandRight(), high, width)); - libraryModelPoint.setShoulderLeft(calculateTemplatePointOne(modelsDotDTO.getShoulderLeft(), high, width)); - libraryModelPoint.setShoulderRight(calculateTemplatePointOne(modelsDotDTO.getShoulderRight(), high, width)); - libraryModelPoint.setWaistbandLeft(calculateTemplatePointOne(modelsDotDTO.getWaistbandLeft(), high, width)); - libraryModelPoint.setWaistbandRight(calculateTemplatePointOne(modelsDotDTO.getWaistbandRight(), high, width)); - return libraryModelPoint; - } - - private List calculateTemplatePointOne(List originRatioList, Integer high, Integer width) { - originRatioList.set(0, originRatioList.get(0).multiply(BigDecimal.valueOf(width))); - originRatioList.set(1, originRatioList.get(1).multiply(BigDecimal.valueOf(high))); - return originRatioList; - } - - public JSONObject designNew(DesignPythonObjects designPythonObjects) { - // todo 限流校验 -// AccessLimitUtils.validate("design",5); - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - //关闭FastJson的引用检测 防止出现$ref 现象 - String param = JSON.toJSONString(designPythonObjects, SerializerFeature.DisableCircularReferenceDetect); - log.info("design请求python 参数:####{}", param); - RequestBody body = RequestBody.create(mediaType, param); - Request request = new Request.Builder() - .url(accessPythonIp + ":" + accessPythonPort + "/api/design") -// .url(fastApiPythonAddress + "/api/design") -// .url(accessPythonIp + ":10200/aifda/api/v1.0/generate") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response; - String responseBody; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - AccessLimitUtils.validateOut("design"); - log.error("PythonService##design异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("design.interface.exception"); - } - //去除限流 -// AccessLimitUtils.validateOut("design"); - if (response.isSuccessful()) { - try { - if (Objects.nonNull(response.body())) { - responseBody = response.body().string(); - JSONObject responseObject = JSON.parseObject(responseBody); - log.info("PythonService##responseObject###{}", responseObject); - return responseObject; - } - throw new BusinessException("design.interface.exception"); - } catch (IOException | JSONException e) { - log.error("PythonService##design异常###{}", e.getMessage()); - throw new BusinessException("design.interface.exception"); - } - } - log.error("PythonService##design异常response###{}", response); - //生成失败 - throw new BusinessException("design.interface.exception"); - } - - public JSONObject designStream(DesignPythonObjects designPythonObjects) { - // todo 限流校验 -// AccessLimitUtils.validate("design",5); - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - //关闭FastJson的引用检测 防止出现$ref 现象 - String param = JSON.toJSONString(designPythonObjects, SerializerFeature.DisableCircularReferenceDetect); - log.info("design请求python 参数:####{}", param); - RequestBody body = RequestBody.create(mediaType, param); - Request request = new Request.Builder() - .url(accessPythonIp + ":" + accessPythonPort + "/api/design_v2") -// .url(fastApiPythonAddress + "/api/design") -// .url(accessPythonIp + ":10200/aifda/api/v1.0/generate") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response; - String responseBody; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - AccessLimitUtils.validateOut("design"); - log.error("PythonService##design异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("design.interface.exception"); - } - //去除限流 -// AccessLimitUtils.validateOut("design"); - if (response.isSuccessful()) { - try { - if (Objects.nonNull(response.body())) { - responseBody = response.body().string(); - JSONObject responseObject = JSON.parseObject(responseBody); - log.info("PythonService##responseObject###{}", responseObject); - return responseObject; - } - throw new BusinessException("design.interface.exception"); - } catch (IOException | JSONException e) { - log.error("PythonService##design异常###{}", e.getMessage()); - throw new BusinessException("design.interface.exception"); - } - } - log.error("PythonService##design异常response###{}", response); - //生成失败 - throw new BusinessException("design.interface.exception"); - } - - /** - * 暂时未用 - */ - public String generateSketchCaption(String url) { - //限流校验 - AccessLimitUtils.validate("generateSketchCaption", 5); - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - RequestBody body = RequestBody.create(mediaType, url); - Request request = new Request.Builder() - .url(accessPythonIp + ":" + accessPythonPort + "/aida/interrogator") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response = null; - String bodyStr = null; - try { - log.info("generateSketchCaption请求入参content###{}", url); - response = client.newCall(request).execute(); - bodyStr = response.body().string(); - } catch (IOException ioException) { - log.error("generateSketchCaption异常###{}", ExceptionUtil.getThrowableList(ioException)); - } - //去除限流 - AccessLimitUtils.validateOut("generateSketchCaption"); - if (Objects.isNull(response)) { - log.error("generateSketchCaption异常###{}", "response or body is empty!"); - throw new BusinessException("system error!"); - } - JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(response)); - Boolean result = jsonObject.getBoolean("successful"); - if (result) { - return bodyStr; - } - log.info("attribute_retrieval失败###{}", bodyStr); - //生成失败 - throw new BusinessException("system error!"); - } - - public Boolean generateSketchOrPrint(String params, String port, String servicePath) { - //限流校验 -// AccessLimitUtils.validate("generateSketchOrPrint", 5); - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); -// RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(generateToPythonDTO, SerializerFeature.WriteMapNullValue)); - RequestBody body = RequestBody.create(mediaType, params); - - log.info("generate 请求地址: {}", accessPythonIp + ":" + port + servicePath); - Request request = new Request.Builder() -// .url("http://18.167.251.121:9992") -// .url("http://127.0.0.1:5000/api/diffusion") -// .url(accessPythonIp + ":" + accessPythonPort + "/api/diffusion") -// .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_image") - .url(accessPythonIp + ":" + port + servicePath) - .method("POST", body) -// .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response = null; - String bodyString; - try { -// log.info("generateSketchOrPrint请求入参content###{}", JSON.toJSONString(generateToPythonDTO, SerializerFeature.WriteMapNullValue)); - log.info("generateSketchOrPrint请求入参content###{}", params); - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##generateSketchOrPrint异常###{}", ExceptionUtil.getThrowableList(ioException)); -// throw new BusinessException("generate.interface.error"); - throw new BusinessException(ioException.getMessage()); - } - //去除限流 -// AccessLimitUtils.validateOut("generateSketchOrPrint"); - - // 判断是否生成失败 - if (Objects.isNull(response.body())) { - log.error("PythonService##generateSketchOrPrint异常###{}", "response or body is empty!"); -// throw new BusinessException("generate.interface.error"); - throw new BusinessException("PythonService##generateSketchOrPrint异常###: response or body is empty!"); - } else if (response.code() != HttpURLConnection.HTTP_OK) { - log.error("PythonService##generateSketchOrPrint异常###{}", "Response error!Response code ## " + response.code() + " ##"); -// throw new BusinessException("generate.interface.error"); - throw new BusinessException("PythonService##generateSketchOrPrint异常### Response error!Response code ## " + response.code() + " ##"); - } else { - try { - bodyString = response.body().string(); - } catch (IOException e) { - log.error(e.getMessage()); -// throw new BusinessException("generate.interface.error"); - throw new BusinessException(e.getMessage()); - } - } - JSONObject jsonObject = JSON.parseObject(bodyString); - Boolean result = JSON.parseObject(JSON.toJSONString(response)).getBoolean("successful"); - - if (result && jsonObject.get("code").equals(200)) { - log.info("Generate##responseObject###{}", jsonObject); -// return setGenerateImageList(jsonObject.getJSONObject("data")); - return Boolean.TRUE; - } else { - log.info("generateSketchOrPrintPrint失败###{}", jsonObject); - log.info("Generate Exception! Code : " + jsonObject.get("code")); - return Boolean.FALSE; - } - } - - public Response sendPostToModel(String content, String portAndRoute, String functionName) { - - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - RequestBody body = RequestBody.create(mediaType, content); - Request request = new Request.Builder() - .url(accessPythonIp + ":" + accessPythonPort + portAndRoute) -// .url(fastApiPythonAddress + portAndRoute) - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response = null; -// String bodyString = null; - try { - log.info(functionName + "请求入参content###{}", content); - response = client.newCall(request).execute(); -// bodyString = response.body().string(); - } catch (IOException ioException) { - log.error("PythonService##" + functionName + "异常###{}", ExceptionUtil.getThrowableList(ioException)); - } - return response; - } - -/* private List setGenerateImageList(JSONObject jsonObject) { - List imageUrlList = JSONObject.parseArray(jsonObject.get("list").toString(), String.class); - if (imageUrlList.isEmpty()) { - log.error("PythonService##generateSketchOrPrint异常###{}", "diffusion response list is null"); - // 如果这里返回为空,是判断出错还是返回给前端空 - throw new BusinessException("The data returned on the python side is empty"); - } - - return imageUrlList; - }*/ - /** 废弃状态 */ - public String composeLayers(List layersDetail) { - HashMap> layers = new HashMap<>(); - HashMap>> content = new HashMap<>(); - layers.put("layers", layersDetail); - content.put("0", layers); - String jsonString = JSON.toJSONString(content, SerializerFeature.WriteNullStringAsEmpty); - - // todo 添加限流 - Response response = this.sendPostToModel(jsonString, "/api/preview_control", "composeLayers"); - // todo 结束限流 - - String bodyString; - // 生成失败 - if (Objects.isNull(response) || Objects.isNull(response.body())) { - log.error("PythonService##composeLayers异常###{}", "response or body is empty!"); - throw new BusinessException("compose-layer.interface.exception"); - } else if (response.code() != HttpURLConnection.HTTP_OK) { - log.error("PythonService##composeLayers异常###{}", "Response error!Response code ## " + response.code() + " ##"); - throw new BusinessException("compose-layer.interface.exception"); - } else { - try { - bodyString = response.body().string(); - } catch (IOException e) { - throw new BusinessException("compose-layer.interface.exception"); - } - } - JSONObject jsonObject = JSON.parseObject(bodyString); - Boolean result = JSON.parseObject(JSON.toJSONString(response)).getBoolean("successful"); - if (result && jsonObject.get("msg").equals("OK!")) { - return getCompositeImage(jsonObject.getJSONObject("code")); - } - log.info("composeLayers 失败###{}", jsonObject); - //生成失败 - throw new BusinessException("compose-layer.interface.exception"); - } - - private String getCompositeImage(JSONObject jsonObject) { - JSONObject item0 = jsonObject.getJSONObject("0"); - return item0.getString("synthesis_url"); - } - - public String getClothCategory(String path, String gender) { - HashMap content = new HashMap<>(); - content.put("sketch_img_url", path); - content.put("colony", gender); - List> contents = Collections.singletonList(content); - String jsonString = JSON.toJSONString(contents, SerializerFeature.WriteNullStringAsEmpty); - - // todo 添加限流 - Response response = this.sendPostToModel(jsonString, "/api/category_recognition", "getClothCategory"); - // todo 结束限流 - - String bodyString; - // 生成失败 - if (Objects.isNull(response) || Objects.isNull(response.body())) { - log.error("PythonService##GetClothCategory###{}", "response or body is empty!"); - throw new BusinessException("cloth-classification.interface.exception"); - } else if (response.code() != HttpURLConnection.HTTP_OK) { - log.error("PythonService##GetClothCategory###{}", "Response error!Response code ## " + response.code() + " ##"); - throw new BusinessException("cloth-classification.interface.exception"); - } else { - try { - bodyString = response.body().string(); - } catch (IOException e) { - throw new BusinessException("cloth-classification.interface.exception"); - } - } - JSONObject jsonObject = JSON.parseObject(bodyString); - try { - Boolean result = JSON.parseObject(JSON.toJSONString(response)).getBoolean("successful"); - if (result && jsonObject.get("msg").equals("OK!")) { -// JSONObject data = jsonObject.getJSONObject("data"); -// JSONArray list = JSONArray.parseArray(data.get("list").toString()); - JSONArray list = jsonObject.getJSONArray("data"); - JSONObject map = (JSONObject) list.get(0); - return map.get("category").toString(); - } - } catch (NullPointerException e) { - log.info("getClothCategory 失败###{},未返回category", jsonObject); - throw new BusinessException("cloth-classification.interface.exception"); - } - log.info("getClothCategory 失败###{}", jsonObject); - //生成失败 - throw new BusinessException("cloth-classification.interface.exception"); - } - - public Boolean cancelGenerateTask(String taskId, String path) { - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - String url = accessPythonIp + ":" + accessPythonPort + path + taskId; -// String url = fastApiPythonAddress + "/api/generate_cancel/" + taskId; - Request request = new Request.Builder() - .url(url) -// .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") -// .addHeader("Content-Type", "application/json") - .build(); - Response response = null; - try { - log.info("cancelGenerateTask请求入参content###{}", taskId); - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##cancelGenerateTask异常###{}", response); - return null; - } - int responseCode = response.code(); - response.close(); - - if (responseCode != HttpURLConnection.HTTP_OK) { - log.info("generate-python 取消请求失败. {}", response); - return Boolean.FALSE; - } - log.info("generate-python 取消请求成功"); - return Boolean.TRUE; - } - - public Boolean superResolution(SuperResolutionDTO superResolutionDTO) throws BusinessException { - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - - HashMap content = new HashMap<>(); - content.put("sr_image_url", superResolutionDTO.getImages()); - content.put("sr_xn", superResolutionDTO.getScale().toString()); - content.put("sr_tasks_id", superResolutionDTO.getUniqueId()); - - String jsonString = JSON.toJSONString(content, SerializerFeature.WriteNullStringAsEmpty); - RequestBody body = RequestBody.create(mediaType, jsonString); - Request request = new Request.Builder() - .url(accessPythonIp + ":" + srServicePort + "/api/super_resolution") - .method("POST", body) - .addHeader("Content-Type", "application/json") - .build(); - Response response = null; - try { - log.info("superResolution请求入参content###{}", jsonString); - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##superResolution异常###{}", ExceptionUtil.getThrowableList(ioException)); - return null; - } - int responseCode = response.code(); - response.close(); - - if (responseCode != HttpURLConnection.HTTP_OK) { - // 基本不会有除200以外的code - log.info("superResolution 请求超分操作失败。 Response code " + response.code()); - throw new BusinessException("superResolution 请求超分操作失败。 Response code " + response.code()); - } - log.info("superResolution 请求超分操作成功"); - return Boolean.TRUE; - } - - public String promptTranslate(String text) throws BusinessException { - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - - HashMap content = new HashMap<>(); - content.put("text", text); - - String jsonString = JSON.toJSONString(content, SerializerFeature.WriteNullStringAsEmpty); - RequestBody body = RequestBody.create(mediaType, jsonString); - String path = accessPythonIp + ":" + accessPythonPort + "/api/translateToEN"; - log.info("translateToEN 请求地址: {}", path); - Request request = new Request.Builder() - .url(path) -// .url(fastApiPythonAddress + "/api/translateToEN") - .method("POST", body) - .addHeader("Content-Type", "application/json") - .build(); - Response response = null; - try { - log.info("promptTranslation请求入参content###{}", jsonString); - response = client.newCall(request).execute(); - } catch (IOException ioException) { - response.close(); - log.error("PythonService##promptTranslation异常###{}", ExceptionUtil.getThrowableList(ioException)); - return text; - } - int responseCode = response.code(); - String bodyString; - try { - bodyString = response.body().string(); - if (responseCode != HttpURLConnection.HTTP_OK) { - // 基本不会有除200以外的code - log.info("promptTranslation 用户输入翻译失败。 Response code " + responseCode); - throw new BusinessException("promptTranslation 用户输入翻译失败。 Response code " + responseCode); - } - JSONObject jsonObject = JSON.parseObject(bodyString); - Boolean result = JSON.parseObject(JSON.toJSONString(response)).getBoolean("successful"); - if (result && jsonObject.get("msg").equals("OK!")) { - String translated = jsonObject.get("data").toString(); - log.info("翻译或处理后的文本 : {}", translated); - return translated; - } - } catch (IOException e) { - log.error("promptTranslation 用户输入翻译失败; error message => " + e.getMessage()); - response.close(); - throw new RuntimeException(e); - - } finally { - response.close(); - } - - log.info("promptTranslation 用户输入翻译失败,返回用户输入"); - return text; - } - - public Boolean toProductImage(String url, String taskId, String prompt, BigDecimal imageStrength, String productType) { - // todo 限流校验 -// AccessLimitUtils.validate("design",5); - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - //关闭FastJson的引用检测 防止出现$ref 现象 - Map map = new HashMap<>(); - map.put("tasks_id", taskId); - map.put("image_url", url); - map.put("prompt", prompt); - map.put("image_strength", imageStrength); - map.put("product_type", productType); - log.info("toProductImage请求python 参数:####{}", map); - String param = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty); - System.out.println(param); - RequestBody body = RequestBody.create(mediaType, param); - Request request = new Request.Builder() -// .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_product_image") -// .url(accessPythonIp + ":9996/api/generate_product_image") - .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_product_image") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response; - String responseBody; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##toProductImage异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("toProductImage.interface.exception"); - } - if (response.isSuccessful()) { - return Boolean.TRUE; - } - log.error("PythonService##toProductImage异常response###{}", response); - //生成失败 - throw new BusinessException("toProductImage.interface.exception"); - } - - public Boolean relight(String url, String taskId, String prompt, String direction, String relightType) { - // todo 限流校验 -// AccessLimitUtils.validate("design",5); - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - //关闭FastJson的引用检测 防止出现$ref 现象 - Map map = new HashMap<>(); - map.put("tasks_id", taskId); - map.put("image_url", url); - map.put("prompt", prompt); - map.put("direction", direction); - map.put("product_type", relightType); - log.info("relightImage请求python 参数:####{}", map); - String param = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty); - log.info(param); - RequestBody body = RequestBody.create(mediaType, param); - Request request = new Request.Builder() -// .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_product_image") -// .url(accessPythonIp + ":9996/api/generate_product_image") - .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_relight_image") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response; - String responseBody; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##relightImage异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("relightImage.interface.exception"); - } - if (response.isSuccessful()) { - return Boolean.TRUE; - } - log.error("PythonService##relightImage异常response###{}", response); - //生成失败 - throw new BusinessException("relightImage.interface.exception"); - } - - public String imageToSketch(String imagePath, String bucket, String objectName, String styleCode, String styleImageUrl){ - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType paramMap = MediaType.parse("application/json"); - //关闭FastJson的引用检测 防止出现$ref 现象 - Map map = new HashMap<>(); - map.put("image_url", imagePath); - map.put("style_image_url", styleImageUrl); - map.put("default_style", styleCode); - map.put("sketch_bucket", bucket); - map.put("sketch_name", objectName); - - String param = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty); - log.info("ImageToSketch请求python 参数:####{}", param); - RequestBody body = RequestBody.create(paramMap, param); - Request request = new Request.Builder() - .url(accessPythonIp + ":" + accessPythonPort + "/api/image2sketch") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response; - - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##ImageToSketch异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("generate.interface.error"); - } - int responseCode = response.code(); - String bodyString; - try { - bodyString = response.body().string(); - if (responseCode != HttpURLConnection.HTTP_OK) { - // 基本不会有除200以外的code - log.info("ImageToSketch 失败。 Response code {}", responseCode); - throw new BusinessException("ImageToSketch 失败。 Response code " + responseCode); - } - JSONObject jsonObject = JSON.parseObject(bodyString); - if (response.isSuccessful() && jsonObject.get("msg").equals("OK!")) { - String sketchResult = jsonObject.get("data").toString(); - log.info("ImageToSketch 结果 : {}", sketchResult); - return sketchResult; - }else { - log.info("ImageToSketch 失败。 Response code {}", responseCode); - throw new BusinessException("ImageToSketch 失败。 Response code " + responseCode); - } - } catch (IOException e) { - log.error("ImageToSketch 失败; error message => {}", e.getMessage()); - response.close(); - throw new BusinessException("generate.interface.error"); - } finally { - response.close(); - } - } - - public void bright(String url, Double brightenValue) { - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - //关闭FastJson的引用检测 防止出现$ref 现象 - Map map = new HashMap<>(); - map.put("image_url", url); - map.put("brighten_value", brightenValue); - log.info("bright请求python 参数:####{}", map); - String param = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty); - log.info(param); - RequestBody body = RequestBody.create(mediaType, param); - Request request = new Request.Builder() -// .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_product_image") -// .url(accessPythonIp + ":9996/api/generate_product_image") - .url(accessPythonIp + ":" + accessPythonPort + "/api/brighten") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response; - String responseBody; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##bright异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("bright.interface.exception"); - } - if (response.isSuccessful()) { - return; - } - log.error("PythonService##bright异常response###{}", response); - //生成失败 - throw new BusinessException("bright.interface.exception"); - } - - public JSONObject attributeRecognition(List pictureUrls,List ids, List category) { - //限流校验 - AccessLimitUtils.validate("attributeRecognition", 20); - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(300, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(300, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - Map> content = Maps.newHashMap(); - //识别图片路径数组 - content.put("upload_img_path", pictureUrls); - //识别图片id数组 - content.put("upload_img_id", ids); - content.put("upload_img_category", category); - RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); - Request request = new Request.Builder() - .url(accessPythonIp + ":9993/api/attribute") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response = null; - String bodyStr = null; - try { - log.info("识别python对应的属性标签值请求入参content###{}", JSON.toJSONString(content)); - response = client.newCall(request).execute(); - bodyStr = response.body().string(); - } catch (IOException ioException) { - log.error("PythonService###attributeRecognition异常##{}", ExceptionUtil.getThrowableList(ioException)); - } - log.info("识别python对应的属性标签值结果###{}",bodyStr.trim()); - //去除限流 - AccessLimitUtils.validateOut("attributeRecognition"); - if (Objects.isNull(response)) { - log.error("PythonService##attributeRecognition异常###{}", "response or body is empty!"); - throw new BusinessException("attribute recognition exception!"); - } - JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(response)); - Boolean result = jsonObject.getBoolean("successful"); - if (result) { - JSONObject attributeJSONObject = JSON.parseObject(bodyStr.trim()); - return attributeJSONObject; - } - log.info("识别python对应的属性标签值异常###{}", jsonObject); - //生成失败 - throw new BusinessException("Atribute recognition exception!"); - } - - public String designBatch(DesignPythonObjects designPythonObjects, Long accountId, int designNum, String taskId) { - // todo 限流校验 - // AccessLimitUtils.validate("design",5); - - // 将 designPythonObjects 写入文件 - File file = new File("design_batch_test.txt"); - try (FileWriter writer = new FileWriter(file)) { - String param = JSON.toJSONString(designPythonObjects, SerializerFeature.DisableCircularReferenceDetect); - writer.write(param); - log.info("设计请求参数已写入文件:####{}", file.getAbsolutePath()); - } catch (IOException e) { - log.error("写入文件异常:{}", e.getMessage()); - throw new BusinessException("file.write.exception"); - } - - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS) - .readTimeout(60, TimeUnit.SECONDS) - .writeTimeout(60, TimeUnit.SECONDS) - .build(); - - // 构建 multipart 表单 - RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM) - .addFormDataPart("file", "design_batch_test.txt", - RequestBody.create(MediaType.parse("text/plain"), file)) - .addFormDataPart("tasks_id", taskId) - .addFormDataPart("user_id", String.valueOf(accountId)) - .addFormDataPart("file_name", "design_batch_test" + taskId + ".json") - .addFormDataPart("total", String.valueOf(designNum)) - .build(); - - Request request = new Request.Builder() - .url("http://18.167.251.121:9994/api/design_batch_generate") - .method("POST", body) - .addHeader("Content-Type", "multipart/form-data") - .build(); - - Response response; - String responseBody; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - AccessLimitUtils.validateOut("design"); - log.error("PythonService##design异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("design.interface.exception"); - } - - if (response.isSuccessful()) { - try { - if (Objects.nonNull(response.body())) { - responseBody = response.body().string(); - JSONObject responseObject = JSON.parseObject(responseBody); - log.info("PythonService##responseObject###{}", responseObject); - return taskId; - } - throw new BusinessException("design.interface.exception"); - } catch (IOException | JSONException e) { - log.error("PythonService##design异常###{}", e.getMessage()); - throw new BusinessException("design.interface.exception"); - } - } - log.error("PythonService##design异常response###{}", response); - throw new BusinessException("design.interface.exception"); - } - - public List getSystemSketchByCategory(String category, Long brandId, Double brandScale,String style) { - //******3.1.2版本临时使用java推荐方案去解决style未使用的问题********** -// try { -// //使用新库attribute_retrieval_style,表命名修改为elementVO.getModelSex().toLowerCase() + "_" + styleCategory.toLowerCase()比如female_skirt,与传入的category保持一致 -// Integer countByStyle = attributeRetrievalMapper.getCountByStyle(category, style); -// //根据数量随机获取一个系统sketch -// if (countByStyle > 0) { -// //获取一个不大于countByStyle的随机整数 -// Integer randomNum = RandomUtils.nextInt(0, countByStyle); -// //返回格式为 dress/0902000649.jpg -// String oneSystemSketchRadom = attributeRetrievalMapper.getOneSystemSketchRadom(category, style,randomNum); -// String imgName = oneSystemSketchRadom.split("/")[1]; -// //补齐正确格式aida-sys-image/images/male/tops/mens_test_5689.png -// //裁切category前半部分 -// String sex = category.split("_")[0]; -// String realCategory = category.split("_")[1]; -// String path = "aida-sys-image/images/" + sex + "/" +realCategory +"/" +imgName; -// return Arrays.asList(path); -// } -// } catch (Exception e) { -// log.info("推荐失败:{}",e.getMessage()); -// throw new BusinessException("system.error"); -// } - //**********************end*********************************** - AuthPrincipalVo userHolder = UserContext.getUserHolder(); - - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .readTimeout(60, TimeUnit.SECONDS) - .writeTimeout(60, TimeUnit.SECONDS) - .build(); - - // 构建动态路径参数(保留两位小数) -// String url = String.format("%s:%s/recommend/%d/%s/1", -// accessPythonIp, -// accessPythonPort, -// userHolder.getId(), -// category); - String brandIdParam = (brandId != null) ? "" + brandId : "-1"; - String brandScaleParam = (brandScale != null) ? String.format("%.2f", brandScale) : "0.00"; - - String baseUrl = String.format("%s:%s/api/recommend/%d/%s", - "http://18.167.251.121", - accessPythonPort, - userHolder.getId(), - category); - -// 如果style不为空,则添加到查询参数中 - String url; - if (style != null && !style.isEmpty()) { - url = baseUrl + "?style=" + style; - } else { - url = baseUrl; - } - - log.info("Recommendation request URL: {}", url); - - Request request = new Request.Builder() - .url(url) - .get() - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .build(); - - try (Response response = client.newCall(request).execute()) { - log.info("Response status: {}", response.code()); - - if (!response.isSuccessful()) { - String errorBody = response.body() != null ? - response.body().string() : "empty response"; - log.error("Request failed with code: {}, body: {}", - response.code(), errorBody); - throw new BusinessException("Recommendation service unavailable"); - } - - // 解析图片路径数组 - String responseBody = response.body().string(); - List imagePaths = JSON.parseArray(responseBody, String.class); - - if (imagePaths == null || imagePaths.isEmpty()) { - log.warn("Empty recommendation result for {}", category); - return Collections.emptyList(); - } - - log.info("Received {} recommended images", imagePaths.size()); - return imagePaths; - - } catch (IOException e) { - log.error("Network error: {}", ExceptionUtil.getRootCauseMessage(e)); - throw new BusinessException("Failed to get recommendations: " + e.getMessage()); - } catch (JSONException e) { - log.error("Response parsing error: {}", ExceptionUtil.getMessage(e)); - throw new BusinessException("Invalid service response format"); - } - } - - public JSONObject segProduct(String url) { - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - //关闭FastJson的引用检测 防止出现$ref 现象 - Map map = new HashMap<>(); - map.put("image_url", url); - map.put("is_brand_dna", Boolean.TRUE); - log.info("bright请求python 参数:####{}", map); - String param = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty); - log.info(param); - RequestBody body = RequestBody.create(mediaType, param); - Request request = new Request.Builder() -// .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_product_image") -// .url(accessPythonIp + ":9996/api/generate_product_image") - .url(accessPythonIp + ":" + accessPythonPort + "/api/seg_product") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response; - String responseBody; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##bright异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("segProduct.interface.exception"); - } - if (response.isSuccessful()) { - try { - if (Objects.nonNull(response.body())) { - responseBody = response.body().string(); - JSONObject responseObject = JSON.parseObject(responseBody); - log.info("PythonService##responseObject###{}", responseObject); - return responseObject; - } - throw new BusinessException("segProduct.interface.exception"); - } catch (IOException | JSONException e) { - log.error("PythonService##segProduct异常###{}", e.getMessage()); - throw new BusinessException("segProduct.interface.exception"); - } - } - log.error("PythonService##segProduct异常response###{}", response); - //生成失败 - throw new BusinessException("segProduct.interface.exception"); - } - /** - * 转发 seg_anything 请求到 python 服务 - * 请求 body 由调用方组装(包含 user_id, image_path, type, points, labels, box 等) - */ - public JSONObject segAnything(JSONObject content) { - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS) - .readTimeout(60, TimeUnit.SECONDS) - .writeTimeout(60, TimeUnit.SECONDS) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); - - String url = accessPythonIp + ":" + accessPythonPort + "/api/seg_anything"; - log.info("segAnything 请求地址: {}, 参数:{}", url, JSON.toJSONString(content)); - - Request request = new Request.Builder() - .url(url) - .method("POST", body) - .addHeader("Content-Type", "application/json") - .build(); - - Response response; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##segAnything异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("segAnything.interface.exception"); - } - - if (response.isSuccessful()) { - try { - if (Objects.nonNull(response.body())) { - String responseBody = response.body().string(); - JSONObject responseObject = JSON.parseObject(responseBody); - log.info("PythonService##segAnything response###{}", responseObject); - return responseObject; - } - throw new BusinessException("segAnything.interface.exception"); - } catch (IOException | JSONException e) { - log.error("PythonService##segAnything异常###{}", e.getMessage()); - throw new BusinessException("segAnything.interface.exception"); - } - } - log.error("PythonService##segAnything异常response###{}", response); - throw new BusinessException("segAnything.interface.exception"); - } - public Boolean poseTransformation(JSONObject content, String apiUri) { - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); - - log.info("poseTransformation 请求地址: {}", accessPythonIp + ":" + accessPythonPort + apiUri); - Request request = new Request.Builder() - .url(accessPythonIp + ":" + accessPythonPort + apiUri) - .method("POST", body) - .addHeader("Content-Type", "application/json") - .build(); - Response response = null; - String bodyString; - try { - log.info("poseTransformation请求入参content###{}", JSON.toJSONString(content)); - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##poseTransformation异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException(ioException.getMessage()); - } - - // 判断是否生成失败 - if (Objects.isNull(response.body())) { - log.error("PythonService##poseTransformation异常###{}", "response or body is empty!"); - throw new BusinessException("PythonService##poseTransformation异常###: response or body is empty!"); - } else if (response.code() != HttpURLConnection.HTTP_OK) { - log.error("PythonService##poseTransformation异常###{}", "Response error!Response code ## " + response.code() + " ##"); - throw new BusinessException("PythonService##poseTransformation异常### Response error!Response code ## " + response.code() + " ##"); - } else { - try { - bodyString = response.body().string(); - } catch (IOException e) { - log.error(e.getMessage()); - throw new BusinessException(e.getMessage()); - } - } - JSONObject jsonObject = JSON.parseObject(bodyString); - Boolean result = JSON.parseObject(JSON.toJSONString(response)).getBoolean("successful"); - - if (result && jsonObject.get("code").equals(200)) { - log.info("poseTransformation##responseObject###{}", jsonObject); - return Boolean.TRUE; - } else { - log.info("poseTransformation失败###{}", jsonObject); - log.info("poseTransformation Exception! Code : {}", jsonObject.get("code")); - return Boolean.FALSE; - } - } - - public String modifyModelProportion(String mannequinPath, Float stretch, String name, int top, int bottom) { - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - - MediaType mediaType = MediaType.parse("application/json"); - Map content = Maps.newHashMap(); - // 模特的minio地址 - content.put("mannequins", mannequinPath); - // 缩放比 - content.put("resize_pixel", stretch.toString()); - // 结果存放桶名 - content.put("bucket_name", "aida-users"); - // 模特名uuid - content.put("mannequin_name", name); - content.put("top", String.valueOf(top)); - content.put("bottom", String.valueOf(bottom)); - RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); - - log.info("modifyModelProportion 请求地址: {},\n 参数:{}", accessPythonIp + ":" + accessPythonPort + "/api/mannequins_edit", JSON.toJSONString(content)); - Request request = new Request.Builder() - .url(accessPythonIp + ":" + accessPythonPort + "/api/mannequins_edit") - .method("POST", body) - .addHeader("Content-Type", "application/json") - .build(); - Response response = null; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##modifyModelProportion异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("generate.interface.error"); - } - int responseCode = response.code(); - String bodyString; - try { - bodyString = response.body().string(); - if (responseCode != HttpURLConnection.HTTP_OK) { - // 基本不会有除200以外的code - log.info("modifyModelProportion 失败。 Response code {}", responseCode); - throw new BusinessException("modifyModelProportion 失败。 Response code " + responseCode); - } - JSONObject jsonObject = JSON.parseObject(bodyString); - if (response.isSuccessful() && jsonObject.get("msg").equals("OK!")) { - String modifiedModel = jsonObject.get("data").toString(); - log.info("modifyModelProportion 结果 : {}", modifiedModel); - return modifiedModel; - }else { - log.info("modifyModelProportion 失败。 Response code {}", responseCode); - throw new BusinessException("modifyModelProportion 失败。 Response code " + responseCode); - } - } catch (IOException e) { - log.error("modifyModelProportion 失败; error message => {}", e.getMessage()); - response.close(); - throw new BusinessException("generate.interface.error"); - } finally { - response.close(); - } - } - - public JSONObject brandDNAGenerate(String prompt) { - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - //关闭FastJson的引用检测 防止出现$ref 现象 - Map map = new HashMap<>(); - map.put("prompt", prompt); - AuthPrincipalVo userHolder = UserContext.getUserHolder(); - map.put("user_id", userHolder.getId()); - log.info("brandDNAGenerate请求python 参数:####{}", map); - String param = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty); - log.info(param); - RequestBody body = RequestBody.create(mediaType, param); - Request request = new Request.Builder() -// .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_product_image") -// .url(accessPythonIp + ":9996/api/generate_product_image") - .url(accessPythonIp + ":" + accessPythonPort + "/api/GenerateBrand") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response; - String responseBody; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##brandDNAGenerate异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("brandDNAGenerate.interface.exception"); - } - if (response.isSuccessful()) { - try { - if (Objects.nonNull(response.body())) { - responseBody = response.body().string(); - JSONObject responseObject = JSON.parseObject(responseBody); - log.info("PythonService##responseObject###{}", responseObject); - return responseObject; - } - throw new BusinessException("brandDNAGenerate.interface.exception"); - } catch (IOException | JSONException e) { - log.error("PythonService##brandDNAGenerate异常###{}", e.getMessage()); - throw new BusinessException("brandDNAGenerate.interface.exception"); - } - } - log.error("PythonService##brandDNAGenerate异常response###{}", response); - //生成失败 - throw new BusinessException("brandDNAGenerate.interface.exception"); - } - - public List imageSegmentation(ImageSegmentation imageSegmentation) { - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - - MediaType mediaType = MediaType.parse("application/json"); - RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(imageSegmentation)); - - log.info("modifyModelProportion 请求地址: {},\n 参数:{}", accessPythonIp + ":" + accessPythonPort + "/api/clothing_seg", JSON.toJSONString(imageSegmentation)); - Request request = new Request.Builder() - .url(accessPythonIp + ":" + accessPythonPort + "/api/clothing_seg") - .method("POST", body) - .addHeader("Content-Type", "application/json") - .build(); - Response response = null; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##imageSegmentation异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("generate.interface.error"); - } - int responseCode = response.code(); - String bodyString; - try { - bodyString = response.body().string(); - if (responseCode != HttpURLConnection.HTTP_OK) { - // 基本不会有除200以外的code - log.info("imageSegmentation 失败。 Response code {}", responseCode); - throw new BusinessException("imageSegmentation 失败。 Response code " + responseCode); - } - JSONObject jsonObject = JSON.parseObject(bodyString); - if (response.isSuccessful() && jsonObject.get("msg").equals("OK!")) { - log.info("imageSegmentation 结果 : {}", jsonObject.get("data").toString()); - List seg = JSONObject.parseObject( - jsonObject.get("data").toString(), - new TypeReference>() {} - ); - return seg; - }else { - log.info("imageSegmentation 失败。 Response code {}", responseCode); - throw new BusinessException("imageSegmentation 失败。 Response code " + responseCode); - } - } catch (IOException e) { - log.error("imageSegmentation 失败; error message => {}", e.getMessage()); - response.close(); - throw new BusinessException("generate.interface.error"); - } finally { - response.close(); - } - } - - public Boolean toProductImageBatch(String taskIdBatch, List paramList, String userId) { - // todo 限流校验 -// AccessLimitUtils.validate("design",5); - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - //关闭FastJson的引用检测 防止出现$ref 现象 - Map map = new HashMap<>(); - map.put("user_id", userId); - map.put("batch_data_list", paramList); - map.put("batch_tasks_id", taskIdBatch); - log.info("toProductImage请求python 参数:####{}", map); - String param = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty); - System.out.println(JSONObject.toJSONString(param)); - RequestBody body = RequestBody.create(mediaType, param); - Request request = new Request.Builder() -// .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_product_image") -// .url(accessPythonIp + ":9996/api/generate_product_image") - .url(accessPythonIp + ":" + accessPythonPort + "/api/batch_generate_product_image") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response; - String responseBody; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##toProductImage异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("toProductImage.interface.exception"); - } - if (response.isSuccessful()) { - return Boolean.TRUE; - } - log.error("PythonService##toProductImage异常response###{}", response); - //生成失败 - throw new BusinessException("toProductImage.interface.exception"); - } - - public Boolean relightBatch(String taskIdBatch, List paramList, String userId) { - // todo 限流校验 -// AccessLimitUtils.validate("design",5); - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - //关闭FastJson的引用检测 防止出现$ref 现象 - Map map = new HashMap<>(); - map.put("batch_tasks_id", taskIdBatch); - map.put("user_id", userId); - map.put("batch_data_list", paramList); - log.info("relightImage请求python 参数:####{}", map); - String param = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty); - log.info(param); - RequestBody body = RequestBody.create(mediaType, param); - Request request = new Request.Builder() -// .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_product_image") -// .url(accessPythonIp + ":9996/api/generate_product_image") - .url(accessPythonIp + ":" + accessPythonPort + "/api/batch_generate_relight_image") - .method("POST", body) - .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") - .addHeader("Content-Type", "application/json") - .build(); - Response response; - String responseBody; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##relightImage异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("relightImage.interface.exception"); - } - if (response.isSuccessful()) { - return Boolean.TRUE; - } - log.error("PythonService##relightImage异常response###{}", response); - //生成失败 - throw new BusinessException("relightImage.interface.exception"); - } - - public Boolean poseTransformationBatch(String productImage, Integer poseId, String taskId) { - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - Map content = Maps.newHashMap(); - content.put("image_url", productImage); - content.put("tasks_id", taskId); - content.put("pose_id", String.valueOf(poseId)); - content.put("batch_size", 1); - RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); - - log.info("poseTransformation 请求地址: {}", accessPythonIp + ":" + accessPythonPort + "/api/batch_generate_pose_transform_image"); - Request request = new Request.Builder() - .url(accessPythonIp + ":" + accessPythonPort + "/api/batch_generate_pose_transform_image") - .method("POST", body) - .addHeader("Content-Type", "application/json") - .build(); - Response response = null; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##poseTransferBatch异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("poseTransferBatch.interface.exception"); - } - - if (response.isSuccessful() && response.body() != null) { - String responseBody = response.body().toString(); - log.info("PythonService##poseTransferBatch返回内容###{}", responseBody); - - return Boolean.TRUE; - } - - log.error("PythonService##poseTransferBatch接口调用失败###{}", response); - throw new BusinessException("poseTransferBatch.interface.exception"); - } - - public JSONObject getProjectParam(String prompt, String fileUrl, List imageUrlList, String process) { - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - Map content = Maps.newHashMap(); - content.put("prompt", prompt); - content.put("process", process); - content.put("image_list", !CollectionUtils.isEmpty(imageUrlList) ? imageUrlList : new ArrayList<>()); - content.put("file_list", !StringUtils.isEmpty(fileUrl) ? Collections.singletonList(fileUrl) : new ArrayList<>()); - RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); - -// log.info("getProjectParam 请求地址: {}", accessPythonIp + ":" + accessPythonPort + "/api/extraction_project_info"); - log.info("getProjectParam 请求地址: {}", "http://18.167.251.121:2011/api/extraction_project_info"); - Request request = new Request.Builder() -// .url(accessPythonIp + ":" + accessPythonPort + "/api/extraction_project_info") - .url("http://18.167.251.121:2011/api/extraction_project_info") - .method("POST", body) - .addHeader("Content-Type", "application/json") - .build(); - Response response = null; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##getProjectParam异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("getProjectParam.interface.exception"); - } - String responseBody; - if (response.isSuccessful() && response.body() != null) { - try { - responseBody = response.body().string(); - JSONObject responseObject = JSON.parseObject(responseBody); - log.info("PythonService##responseObject###{}", responseObject); - return responseObject; - } catch (IOException | JSONException e) { - log.error("PythonService##getProjectParam异常###{}", e.getMessage()); - throw new BusinessException("getProjectParam.interface.exception"); - } - } - - log.error("PythonService##getProjectParam接口调用失败###{}", response); - throw new BusinessException("getProjectParam.interface.exception"); - } - - public List getPrompt(String string, int num) { - OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) - .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) - .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) - .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) - .build(); - MediaType mediaType = MediaType.parse("application/json"); - Map content = Maps.newHashMap(); - content.put("text", string); - content.put("num", num); - content.put("language", "english"); - RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); - - log.info("batch_prompt_optimizer 请求地址: {}", accessPythonIp + ":" + accessPythonPort + "/api/batch_prompt_optimizer"); - Request request = new Request.Builder() - .url(accessPythonIp + ":" + "2011" + "/api/batch_prompt_optimizer") - .method("POST", body) - .addHeader("Content-Type", "application/json") - .build(); - Response response = null; - try { - response = client.newCall(request).execute(); - } catch (IOException ioException) { - log.error("PythonService##batch_prompt_optimizer异常###{}", ExceptionUtil.getThrowableList(ioException)); - throw new BusinessException("batch_prompt_optimizer.interface.exception"); - } - String responseBody; - if (response.isSuccessful() && response.body() != null) { - try { - responseBody = response.body().string(); - JSONObject responseObject = JSON.parseObject(responseBody); - JSONObject dataObject = responseObject.getJSONObject("data"); - if (dataObject != null) { - // 获取prompt_list数组 - JSONArray promptArray = dataObject.getJSONArray("prompt_list"); - if (promptArray != null) { - // 转换为List - List promptList = new ArrayList<>(); - for (int i = 0; i < promptArray.size(); i++) { - promptList.add(promptArray.getString(i)); - } - return promptList; - } - } - log.info("PythonService##responseObject###{}", responseObject); - return null; - } catch (IOException | JSONException e) { - log.error("PythonService##batch_prompt_optimizer异常###{}", e.getMessage()); - throw new BusinessException("batch_prompt_optimizer.interface.exception"); - } - } - - log.error("PythonService##batch_prompt_optimizer接口调用失败###{}", response); - throw new BusinessException("batch_prompt_optimizer.interface.exception"); - } -} +package com.ai.da.python; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.exceptions.ExceptionUtil; +import com.ai.da.common.config.FileProperties; +import com.ai.da.common.config.exception.BusinessException; +import com.ai.da.common.context.UserContext; +import com.ai.da.common.enums.*; +import com.ai.da.common.utils.*; +import com.ai.da.mapper.primary.CollocationMapper; +import com.ai.da.mapper.primary.DressingMapper; +import com.ai.da.mapper.primary.entity.*; +import com.ai.da.mapper.secondary.AttributeRetrievalMapper; +import com.ai.da.mapper.secondary.entity.AttributeRetrieval; +import com.ai.da.mapper.secondary.entity.AttributeRecognitionJSON; +import com.ai.da.model.dto.*; +import com.ai.da.model.enums.MalePosition; +import com.ai.da.model.enums.Sex; +import com.ai.da.model.vo.*; +import com.ai.da.python.vo.*; +import com.ai.da.service.DesignHistoryService; +import com.ai.da.service.PythonTAllInfoService; +import com.ai.da.service.SysFileService; +import com.alibaba.fastjson.*; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import io.netty.util.internal.StringUtil; +import lombok.extern.slf4j.Slf4j; +import okhttp3.*; +import org.apache.commons.lang3.RandomUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.Assert; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; +import org.springframework.web.multipart.MultipartFile; + +import jakarta.annotation.Resource; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +@Slf4j +@Service +public class PythonService { + + @Resource + private FileProperties fileProperties; + @Resource + private SysFileService sysFileService; + @Resource + private DesignHistoryService designHistoryService; + @Value("${access.python.ip:''}") + private String accessPythonIp; + @Value("${access.python.port:''}") + private String accessPythonPort; + @Value("${minio.bucketName.gradient}") + private String gradientBucketName; + @Value("${access.python.generate_sr_port}") + private String srServicePort; + + @Value("${design.callback.url}") + private String callbackUrl; + + @Resource + private PythonTAllInfoService pythonTAllInfoService; + + @Resource + private MinioUtil minioUtil; + + @Resource + private RedisUtil redisUtil; + + /** + * 生成打印的图片 二合一 (废弃于2024/01/02) + * + * @param printPath + * @return + */ + public String generatePrint(List printPath, Long userId) { + //限流校验 +// AccessLimitUtils.validate("generatePrint", 2); + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + Map content = Maps.newHashMap(); + content.put("fusion_content_path", printPath.get(0)); + content.put("fusion_style_path", printPath.get(1)); + content.put("userid", String.valueOf(userId)); +// content.put("fusion_output_path", getPythonOutputPath( +// printPath.get(0), PythonToJavaApiOperationTypeEnum.GENERATE_PRINT)); + RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); + Request request = new Request.Builder() +// .url(accessPythonIp + ":9999/aifda/api/v1.0/fusion_test") + .url(accessPythonIp + ":" + accessPythonPort + "/api/image_fusion") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response; + String responseBody; + try { + log.info("moodboard与printboard图片合成 入参content###{}", JSON.toJSONString(content)); + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService## moodboard与printboard图片合成异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("image.synthesis.failed"); + } + //去除限流 +// AccessLimitUtils.validateOut("generatePrint"); + JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(response)); + if (jsonObject.getBoolean("successful")) { + try { + if (Objects.nonNull(response.body())) { + responseBody = response.body().string(); + JSONObject responseObj = JSON.parseObject(responseBody); + log.info("moodboard与printboard图片合成 python返回###{}", responseObj); + return responseObj.get("data").toString(); + } + } catch (IOException | JSONException e) { + log.error("Python moodboard与printboard图片合成异常 : {}", e.getMessage()); + throw new BusinessException("image.synthesis.failed"); + } + log.error("moodboard与printboard图片合成异常###{}", jsonObject); + throw new BusinessException("image.synthesis.failed"); +// return content.get("fusion_output_path"); + } + log.info("moodboard与printboard图片合成异常###{}", jsonObject); + //生成失败 + throw new BusinessException("image.synthesis.failed"); + } + + /** + * 生成python要保存的文件 + * + * @param picturePath + * @return + */ + private String getPythonOutputPath(String picturePath, PythonToJavaApiOperationTypeEnum pythonOperationType) { + String linuxDomain = fileProperties.getLinuxDomain(); + String day = DateUtil.dateToStr(new Date(), DateUtil.YYYYMM); + //获取图片后缀 + String suffix = picturePath.substring(picturePath.lastIndexOf(".")); + String generateFileName = pythonOperationType.getRealName() + + "-" + UUID.randomUUID().toString() + suffix; + return linuxDomain + day + File.separator + "pythonFile" + File.separator + + pythonOperationType.getRealName() + + File.separator + generateFileName; + } + + /** + * python生成的文件上传到java服务器统一维护 + * + * @param file + * @param operateType + * @return + */ + @Transactional(rollbackFor = Exception.class) + public String upload(MultipartFile file, String operateType) { + //用户信息 + PythonToJavaApiOperationTypeEnum operationType = PythonToJavaApiOperationTypeEnum.uploadOf(operateType); + Assert.notNull(operationType, "unknown operateType " + operateType + "!"); + String path = calculateFileUrl(operationType); + File generateFile = FileUtil.upload2(file, path); + + String linuxDomain = fileProperties.getLinuxDomain(); + if (!StringUtils.isEmpty(linuxDomain)) { + //linux 系统 + String oldPath = fileProperties.getSys().getPath(); + return generateFile.getAbsolutePath().replace(oldPath, linuxDomain); + } + return null; + } + +// @Transactional +// public List upload(MultipartFile[] files, String operateType) { +// List paths = new ArrayList<>(); +// //用户信息 +// PythonToJavaApiOperationTypeEnum operationType = PythonToJavaApiOperationTypeEnum.uploadOf(operateType); +// Assert.notNull(operationType, "unknown operateType " + operateType + "!"); +// String path = calculateFileUrl(operationType); +// for (MultipartFile file : files) { +// File generateFile = FileUtil.upload2(file, path); +// Assert.notNull(generateFile, "An error occurred while processing the file!"); +// +// String linuxDomain = fileProperties.getLinuxDomain(); +// if (!StringUtils.isEmpty(linuxDomain)) { +// //linux 系统 +// String oldPath = fileProperties.getSys().getPath(); +// paths.add(generateFile.getAbsolutePath().replace(oldPath, linuxDomain)); +// } +// } +// return paths; +// } + + + private String calculateFileUrl(PythonToJavaApiOperationTypeEnum operationType) { + String rootPath = fileProperties.getSys().getPath(); + String day = DateUtil.dateToStr(new Date(), DateUtil.YYYYMM); + return rootPath + day + File.separator + "pythonFile" + File.separator + + operationType.getRealName() + File.separator; + } + + + /** + * 组装和计算design参数 + * + * @param systemScale + * @param singleOverall + * @param switchCategory + * @param elementVO + * @param processId + * @return + */ + public DesignPythonObjects covertDesignParam(BigDecimal systemScale, String singleOverall, + String switchCategory, ValidateElementVO elementVO, String processId, Long collectionId) { + DesignPythonObjects designPythonObjects = new DesignPythonObjects(); + List objects = new ArrayList<>(); + designPythonObjects.setObjects(objects); + designPythonObjects.setProcess_id(processId); + designPythonObjects.setCallback_url(callbackUrl); + + long pinPrintNum = calculateDesignPinPrintNum(elementVO.getPrintBoardElements()); + long noPinPrintNum = calculateDesignNoPinPrintNum(elementVO.getPrintBoardElements(), elementVO.getDesignNum()); + long noPrintNum = elementVO.getDesignNum() - pinPrintNum - noPinPrintNum; + elementVO.setNoPinPrintNum(noPinPrintNum); + + int[] sketchNumbers = new int[3]; + + int designNum = elementVO.getDesignNum(); + Set assembledObjects = new HashSet<>(); // 用于存储已组装的 DesignPythonObject + DesignPythonObject lastAssembledObject = null; // 上一次组装的对象 + + for (int i = 0; i < designNum; i++) { + CurrentDesignPictureTypeEnum designPictureType = calculateCurrentDesignPictureTypeNew(elementVO, sketchNumbers, systemScale); + if (designPictureType == null) break; + + CurrentDesignPrintPictureTypeEnum designPrintPictureType = calculateCurrentDesignPintPictureType(pinPrintNum, noPinPrintNum, noPrintNum); + if (designPrintPictureType == null) break; + + updateSketchNumbers(designPictureType, sketchNumbers); + switch (designPrintPictureType) { + case PIN: + pinPrintNum--; + break; + case NO_PIN: + noPinPrintNum--; + break; + case NO: + noPrintNum--; + break; + } + DesignPythonItemPrint designPythonItemPrint = getRandomPrint(elementVO, designPrintPictureType); + elementVO.setDesignPythonItemPrint(designPythonItemPrint); + elementVO.setDesignPrintPictureTypeLayoutList(calculateCurrentDesignPintPictureTypeLayout(elementVO.getModelSex())); + List beforeAssemblyHasUseMd5List = new ArrayList<>(elementVO.getHasUseMd5List()); + DesignPythonObject pythonObject = createDesignPythonObject(elementVO, designPictureType, systemScale, singleOverall, switchCategory, i); + + // 如果当前对象与已组装的对象重复,则跳过当前组装 + DesignPythonObject designPythonObjectCopy = getCopy(pythonObject); + + boolean isDuplicate = assembledObjects.contains(designPythonObjectCopy); + + if (isDuplicate) { + elementVO.setHasUseMd5List(beforeAssemblyHasUseMd5List); + i --; + + switch (designPrintPictureType) { + case PIN: + pinPrintNum++; + break; + case NO_PIN: + noPinPrintNum++; + break; + case NO: + noPrintNum++; + break; + } + continue; + } + + // 将当前对象添加到已组装的集合中,并记录 + assembledObjects.add(designPythonObjectCopy); + + objects.add(pythonObject); + redisUtil.addProcessId(processId, i + 1); + } + return designPythonObjects; + } + + private DesignPythonObject getCopy(DesignPythonObject pythonObject) { + DesignPythonObject designPythonObjectCopy = CopyUtil.copyObject(pythonObject, DesignPythonObject.class); + designPythonObjectCopy.setObjectSign(null); + DesignPythonBasic basic = designPythonObjectCopy.getBasic(); + basic.setSave_name(null); + designPythonObjectCopy.setBasic(basic); + List items = designPythonObjectCopy.getItems(); + List itemsCopy = new ArrayList<>(); + for (DesignPythonItem item : items) { + item.setElementId(null); + item.setIcon(null); + item.setBusinessId(null); + item.setImage_id(null); + item.setImageId(null); + itemsCopy.add(item); + } + designPythonObjectCopy.setItems(itemsCopy); + return designPythonObjectCopy; + } + + private void updateSketchNumbers(CurrentDesignPictureTypeEnum designPictureType, int[] sketchNumbers) { + switch (designPictureType) { + case PIN: + sketchNumbers[0]++; + break; + case NO_PIN: + sketchNumbers[2]--; + break; + case SYS_FILE: + sketchNumbers[1]--; + break; + } + } + + private void updatePrintNumbers(CurrentDesignPrintPictureTypeEnum designPrintPictureType, long pinPrintNum, long noPinPrintNum, long noPrintNum) { + switch (designPrintPictureType) { + case PIN: + pinPrintNum--; + break; + case NO_PIN: + noPinPrintNum--; + break; + case NO: + noPrintNum--; + break; + } + } + + private DesignPythonObject createDesignPythonObject(ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType, BigDecimal systemScale, String singleOverall, String switchCategory, int i) { + DesignPythonObject pythonObject = new DesignPythonObject(); + pythonObject.setItems(coverToDesignPythonItemNew(elementVO, designPictureType, systemScale)); + pythonObject.setBasic(coverToBasic(pythonObject.getItems().get(0), singleOverall, switchCategory, elementVO.getDesignLibraryModelPoint(), elementVO.getDesignLibraryModelPointVO())); + if (CollectionUtil.isNotEmpty(elementVO.getRequestIdList())) { + pythonObject.setObjectSign(elementVO.getRequestIdList().get(i)); + } + return pythonObject; + } + + + private CurrentDesignPictureTypeEnum calculateCurrentDesignPictureTypeNew(ValidateElementVO elementVO, int[] sketchNumbers, BigDecimal systemScale) { + List pinData = getPinData(elementVO); + Integer designNum = elementVO.getDesignNum(); + if (CollectionUtil.isNotEmpty(pinData)) { + return CurrentDesignPictureTypeEnum.PIN; + } else { + if (sketchNumbers[1] == 0 && sketchNumbers[2] == 0) { + sketchNumbers[1] = systemScale.multiply(BigDecimal.valueOf(designNum - sketchNumbers[0])).setScale(0, BigDecimal.ROUND_HALF_UP).intValue(); + sketchNumbers[2] = designNum - sketchNumbers[0] - sketchNumbers[1]; + } + if (sketchNumbers[2] > 0 && sketchNumbers[1] > 0) { + Long l = RandomsUtil.randomSysFile(0l, 2l); + if (l == 0l) { + return CurrentDesignPictureTypeEnum.NO_PIN; + } else { + return CurrentDesignPictureTypeEnum.SYS_FILE; + } + } + if (sketchNumbers[2] > 0) { + return CurrentDesignPictureTypeEnum.NO_PIN; + } + return CurrentDesignPictureTypeEnum.SYS_FILE; + } + } + + private int calculateNoPinSketchNum(int pinSketchNum, int sysSketchNum) { + return 8 - pinSketchNum - sysSketchNum; + } + + private int calculateSysSketchNum(BigDecimal sysRatio, int pinSketchNum) { + // Calculate sysRatio * (8 - pinSketchNum) + BigDecimal result = sysRatio.multiply(BigDecimal.valueOf(8 - pinSketchNum)); + + // Round the result to the nearest integer using half-up rounding + + return result.setScale(0, RoundingMode.HALF_UP).intValue(); + } + +// private int calculatePinSketchNum(List sketchBoardElements, List hasUseMd5List) { +// List pinData = getPinData(sketchBoardElements, hasUseMd5List); +// if (CollectionUtil.isEmpty(pinData)) { +// return 0; +// } +//// long topNum = sketchBoardElements.stream() +//// .filter(skecth -> skecth.getHasPin() == 1 +//// && DesignPythonItem.OUTWEAR_DRESS_BLOUSE.contains(skecth.getLevel2Type())).count(); +//// long bottomNum = sketchBoardElements.stream() +//// .filter(skecth -> skecth.getHasPin() == 1 +//// && DesignPythonItem.SKIRT_TROUSERS.contains(skecth.getLevel2Type())).count(); +//// int num = Arrays.asList(topNum, bottomNum).stream().max(Comparator.comparing(Long::valueOf)).get().intValue(); +// int num = pinData.size(); +// return Math.min(num, 8); +// } + + //计算当前的图片类型 + private CurrentDesignPictureTypeEnum calculateCurrentDesignPictureType(int pinSketchNum, int sysSketchNum, int noPinSketchNum) { + List codes = Lists.newArrayList(); + if (pinSketchNum > 0) { + //pin默认优先选择 不参与计算 后续有调整再说 +// codes.add(pinPictureNum); + return CurrentDesignPictureTypeEnum.PIN; + } + if (sysSketchNum > 0) { + codes.add(CurrentDesignPictureTypeEnum.SYS_FILE.getCode()); + } + + if (noPinSketchNum > 0) { + codes.add(CurrentDesignPictureTypeEnum.NO_PIN.getCode()); + } + List pictureTypeEnums = CurrentDesignPictureTypeEnum.ofList(codes); + if (CollectionUtils.isEmpty(pictureTypeEnums)) { + return null; + } + int max = pictureTypeEnums.size(); + int min = 0; + Long randomIndex = RandomsUtil.randomSysFile((long) min, (long) max); + return pictureTypeEnums.get(randomIndex.intValue()); + } + + //计算系统图片张数 + private static int calculateSysPictureNum(BigDecimal sysRatio, int pinPictureNum) { + if (pinPictureNum > 4) { + int poolSize = 8 - pinPictureNum; + if (poolSize == 0) { + return 0; + } + return BigDecimal.valueOf(poolSize).multiply(sysRatio) + .setScale(0, BigDecimal.ROUND_HALF_UP).intValue(); + } else { + return BigDecimal.valueOf(4).multiply(sysRatio) + .setScale(0, BigDecimal.ROUND_HALF_UP).intValue(); + } + } + + //计算用户库图片张数 + private static int calculateUserLibraryPictureNum(int sysPictureNum, int pinPictureNum) { + if (pinPictureNum > 4) { + return 8 - pinPictureNum - sysPictureNum; + } else { + return 4 - sysPictureNum; + } + } + + //计算Pin图片张数 +// private int calculatePinPictureNum(List sketchBoardElements, List hasUseMd5List) { +// List pinData = getPinData(sketchBoardElements, hasUseMd5List); +// if (CollectionUtil.isEmpty(pinData)) { +// return 0; +// } +// long topNum = sketchBoardElements.stream() +// .filter(skecth -> skecth.getHasPin() == 1 +// && DesignPythonItem.OUTWEAR_DRESS_BLOUSE.contains(skecth.getLevel2Type())).count(); +// long bottomNum = sketchBoardElements.stream() +// .filter(skecth -> skecth.getHasPin() == 1 +// && DesignPythonItem.SKIRT_TROUSERS.contains(skecth.getLevel2Type())).count(); +// int num = Arrays.asList(topNum, bottomNum).stream().max(Comparator.comparing(Long::valueOf)).get().intValue(); +// if (num > 8) { +// return 8; +// } +// return num; +// } + + //计算当前的Print图片类型 + private CurrentDesignPrintPictureTypeEnum calculateCurrentDesignPintPictureType(long pinPrintNum, long noPinPrintNum, long noPrintNum) { + List codes = Lists.newArrayList(); + if (pinPrintNum > 0) { + //pin默认优先选择 不参与计算 后续有调整再说 +// codes.add(pinPictureNum); + return CurrentDesignPrintPictureTypeEnum.PIN; + } + if (noPinPrintNum > 0) { + codes.add(CurrentDesignPrintPictureTypeEnum.NO_PIN.getCode()); + } + if (noPrintNum > 0) { + codes.add(CurrentDesignPrintPictureTypeEnum.NO.getCode()); + } + + List pictureTypeEnums = CurrentDesignPrintPictureTypeEnum.ofList(codes); + if (CollectionUtils.isEmpty(pictureTypeEnums)) { + return null; + } + int max = pictureTypeEnums.size(); + int min = 0; + Long randomIndex = RandomsUtil.randomSysFile((long) min, (long) max); + return pictureTypeEnums.get(randomIndex.intValue()); + } + + //计算当前的Print图片类型具体分布位置 0. 上衣 1.下衣 2.上衣和下衣都print + private List calculateCurrentDesignPintPictureTypeLayout(String modelSex) { + if (modelSex.equals(Sex.FEMALE.getValue())) { + Long randomIndex = RandomsUtil.randomSysFile(0L, 3L); + if (randomIndex == 0) { + return DesignPythonItem.OUTWEAR_DRESS_BLOUSE; + } + if (randomIndex == 1) { + return DesignPythonItem.SKIRT_TROUSERS; + } + if (randomIndex == 2) { + List all = new ArrayList<>(DesignPythonItem.OUTWEAR_DRESS_BLOUSE); + all.addAll(new ArrayList<>(DesignPythonItem.SKIRT_TROUSERS)); + return all; + } + } else if (modelSex.equals(Sex.MALE.getValue())) { + Long randomIndex = RandomsUtil.randomSysFile(0L, 3L); + if (randomIndex == 0) { + return DesignPythonItem.TOPS; + } + if (randomIndex == 1) { + return DesignPythonItem.BOTTOMS; + } + if (randomIndex == 2) { + List all = new ArrayList<>(DesignPythonItem.TOPS); + all.addAll(new ArrayList<>(DesignPythonItem.BOTTOMS)); + return all; + } + } + return null; + } + + //计算print 非Pin图片剩余张数 + private long calculateDesignPinPrintNum(List printBoardElements) { + if (CollectionUtils.isEmpty(printBoardElements)) { + return 0; + } + return printBoardElements.stream().filter(f -> f.getHasPin() == 1).count(); + } + + //计算print 非Pin图片剩余张数 + private long calculateDesignNoPinPrintNum(List printBoardElements, Integer designNum) { + if (CollectionUtils.isEmpty(printBoardElements)) { + return 0; + } + long noPinNum = printBoardElements.stream().filter(f -> f.getHasPin() == 0).count(); + if (noPinNum == 0L) { + return 0; + } else { + long pinNum = printBoardElements.stream().filter(f -> f.getHasPin() == 1).count(); + if (designNum - pinNum < 0){ + return RandomsUtil.randomSysFile(0L, (long) (pinNum/2 + 1)); + } else if (designNum - pinNum < designNum/2) { + return RandomsUtil.randomSysFile(0L, designNum - pinNum + 1); + } else { + return RandomsUtil.randomSysFile(0L, (long) (designNum/2 + 1)); + } + } + } + +// private List coverToDesignPythonItem(ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType) { +// //Pin的数据 +// List pinData = getPinData(elementVO.getSketchBoardElements(), elementVO.getHasUseMd5List()); +// //计算填充PythonItemBlouse +// List items = Lists.newArrayList(); +// if (elementVO.getModelSex().equals("Female")) { +// List blouseList = calculatePythonItemBlouse(pinData, elementVO, designPictureType); +// if (!CollectionUtils.isEmpty(blouseList)) { +// items.addAll(blouseList); +// } +// //计算填充PythonItemSkirt +// DesignPythonItem skirt = calculatePythonItemSkirt(pinData, elementVO, designPictureType); +// if (Objects.nonNull(skirt)) { +// items.add(skirt); +// } +// } else { +// // 男装逻辑 +// DesignPythonItem top = calculatePythonItemTop(pinData, elementVO, designPictureType); +// if (Objects.nonNull(top)) { +// items.add(top); +// } +// DesignPythonItem bottom = calculatePythonItemBottom(pinData, elementVO, designPictureType); +// if (Objects.nonNull(bottom)) { +// items.add(bottom); +// } +// if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall()) && elementVO.getSwitchCategory().equals("Outwear")) { +// DesignPythonItem outwear = calculatePythonItemOutwear(pinData, elementVO, designPictureType); +// if (Objects.nonNull(outwear)) { +// items.add(outwear); +// } +// } +// } +// //计算填充Hairstyle Earring Shoes Body +// items.addAll(calculatePythonItemHairstyleShoes(elementVO, elementVO.getDesignLibraryModelPoint())); +// return items; +// } + + private List coverToDesignPythonItemNew(ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType, BigDecimal systemScale) { + List itemList = new ArrayList<>(); + DesignPythonItem designPythonItem = calculatePythonItem(elementVO, designPictureType); + if (Objects.nonNull(designPythonItem)) { + itemList.add(designPythonItem); + if (elementVO.getSingleOverall().equals(SingleOverallEnum.OVERALL.getRealName())) { + List otherSketchCategoryList = getOtherSketchCategoryList(elementVO.getModelSex(), designPythonItem); + if (!otherSketchCategoryList.isEmpty()) { +// JSONObject attributeRecognition = getAttributeRecognition(designPythonItem.getPath(), designPythonItem.getType(), elementVO.getModelSex()); + for (String styleCategory : otherSketchCategoryList) { +// DesignPythonItem otherSketch = processAttributeRecognition(attributeRecognition, elementVO, designPictureType, styleCategory, systemScale); + DesignPythonItem otherSketch = processAttributeRecognition(null, elementVO, designPictureType, styleCategory, systemScale); + itemList.add(otherSketch); + } + } + itemList.addAll(calculatePythonItemHairstyleShoes(elementVO, elementVO.getDesignLibraryModelPoint())); + } + } + return itemList; + } + + private DesignPythonItem processAttributeRecognition(JSONObject attributeRecognition, ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType, String styleCategory, BigDecimal systemScale) { + switch (designPictureType) { + case PIN: + return processPinAttributeRecognition(attributeRecognition, elementVO, styleCategory, systemScale); + case NO_PIN: + case SYS_FILE: + return processNoPinOrSysFileAttributeRecognition(attributeRecognition, elementVO, styleCategory, systemScale); + default: + throw new BusinessException("unknown.designPictureType"); + } + } + + private DesignPythonItem processPinAttributeRecognition(JSONObject attributeRecognition, ValidateElementVO elementVO, String styleCategory, BigDecimal systemScale) { + List collectPin = getFilteredCollectionElements(elementVO.getSketchBoardElements(), 1, styleCategory); + if (CollectionUtil.isNotEmpty(collectPin)) { + int randomNum = RandomsUtil.randomSysFile(collectPin.size()); + elementVO.getHasUseMd5List().add(collectPin.get(randomNum).getMd5()); + return coverSketchToDesignPythonItem(collectPin.get(randomNum).getId(), collectPin.get(randomNum), elementVO); + } else { + List collectNoPin = getFilteredCollectionElements(elementVO.getSketchBoardElements(), 0, styleCategory); + return processNoPinOrSysFileAttributeRecognitionWithPool(collectNoPin, attributeRecognition, elementVO, styleCategory, systemScale); + } + } + + private DesignPythonItem processNoPinOrSysFileAttributeRecognition(JSONObject attributeRecognition, ValidateElementVO elementVO, String styleCategory, BigDecimal systemScale) { + List collectNoPin = getFilteredCollectionElements(elementVO.getSketchBoardElements(), 0, styleCategory); + return processNoPinOrSysFileAttributeRecognitionWithPool(collectNoPin, attributeRecognition, elementVO, styleCategory, systemScale); + } + + // 生成两位小数随机数(线程安全) + private BigDecimal generateRandomValue() { + // 使用ThreadLocalRandom提高并发性能 + double random = ThreadLocalRandom.current().nextDouble(0.0, 1.0 + 1e-4); + + return new BigDecimal(random) + .setScale(2, RoundingMode.HALF_UP) + .min(BigDecimal.ONE); // 确保不超过1.00 + } + + private DesignPythonItem processNoPinOrSysFileAttributeRecognitionWithPool(List collectionElements, JSONObject attributeRecognition, ValidateElementVO elementVO, String styleCategory, BigDecimal systemScale) { + BigDecimal randomValue = generateRandomValue(); + boolean useSystem = randomValue.compareTo(systemScale) <= 0; + + // 用过存在用户上传,则优先使用用户上传 + if (!useSystem && CollectionUtil.isNotEmpty(collectionElements)) { + int collectionNoPinSize = collectionElements.size(); + int randomNum = RandomsUtil.randomSysFile(collectionNoPinSize); + return coverSketchToDesignPythonItem(collectionElements.get(randomNum).getId(), collectionElements.get(randomNum), elementVO); + } + + // 其他所有情况,都回退到使用系统推荐 + String categoryParam = elementVO.getModelSex().toLowerCase() + "_" + styleCategory.toLowerCase(); + List recommentdUrlList = getSystemSketchByCategory(categoryParam, elementVO.getBrandId(), elementVO.getBrandScale(),elementVO.getStyle()); + + if (CollectionUtils.isEmpty(recommentdUrlList)) { + throw new BusinessException("failed.to.obtain.system.sketch.recommendation"); + } + + String recommendSystemSketch = recommentdUrlList.get(0); + return coverSystemSketchUrlToDesignPythonItem(recommendSystemSketch, styleCategory, elementVO); + +// int poolNum = 20; +// if (CollectionUtil.isNotEmpty(collectionElements)) { +// int collectionNoPinSize = collectionElements.size(); +// if (systemScale.compareTo(BigDecimal.ZERO) == 0) { +// int randomNum = RandomsUtil.randomSysFile(collectionNoPinSize); +// return coverSketchToDesignPythonItem(null, collectionElements.get(randomNum), elementVO); +// } else if (systemScale.compareTo(BigDecimal.ONE) != 0) { +// BigDecimal collectNoPinSize = BigDecimal.valueOf(collectionNoPinSize); +// poolNum = collectNoPinSize.divide(systemScale, 0, RoundingMode.DOWN).intValue(); +// List list = getSystemSketchPool(attributeRecognition, styleCategory, elementVO.getModelSex(), poolNum, elementVO.getStyle()); +// collectionElements.addAll(list); +// int randomNum = RandomsUtil.randomSysFile(collectionElements.size()); +// if (randomNum < collectionNoPinSize) { +// return coverSketchToDesignPythonItem(collectionElements.get(randomNum).getId(), collectionElements.get(randomNum), elementVO); +// } else { +// return coverSketchToDesignPythonItem(null, collectionElements.get(randomNum), elementVO); +// } +// } +// } +// List list = getSystemSketchPool(attributeRecognition, styleCategory, elementVO.getModelSex(), poolNum, elementVO.getStyle()); +// int randomNum = RandomsUtil.randomSysFile(list.size()); +// return coverSketchToDesignPythonItem(null, list.get(randomNum), elementVO); + } + + private List getFilteredCollectionElements(List elements, int hasPin, String styleCategory) { + return CollectionUtil.isNotEmpty(elements) ? elements.stream().filter(o -> o.getHasPin() == hasPin && o.getLevel2Type().equals(styleCategory)).collect(Collectors.toList()) : null; + } + + private DesignPythonItem processAttributeRecognitionBySameCategory(JSONObject attributeRecognition, ValidateElementVO elementVO, String styleCategory) { + List list = getSystemSketchPoolBySameCategory(attributeRecognition, styleCategory, elementVO.getModelSex(), elementVO.getStyle()); + int randomNum = RandomsUtil.randomSysFile(list.size()); + return coverSketchToDesignPythonItem(null, list.get(randomNum), elementVO); + } + + @Resource + private AttributeRetrievalMapper attributeRetrievalMapper; + + private List getSystemSketchPool(JSONObject attributeRecognition, String styleCategory, String modelSex, int poolNum, String style) { + /** + * female trousers->female_pants + * female blouse->female_top + * female skirt->female_skirt + * female outwear->female_outwear + * female dress->female_dress + */ + JSONObject data = attributeRecognition.getJSONObject("data"); + JSONObject attrDict = ((JSONObject) data.getJSONArray("list").get(0)).getJSONObject("attr_dict"); + AttributeRecognitionJSON attrDictJSON = attrDict.toJavaObject(AttributeRecognitionJSON.class); + AttributeRetrieval attributeRetrievalAttrDict = toAttrDict(attrDictJSON); + String tableName; + tableName = getTableName(modelSex, styleCategory); + List attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPool(attributeRetrievalAttrDict, tableName, poolNum, style); + if (CollectionUtil.isEmpty(attributeRetrievalList) || attributeRetrievalList.size() < poolNum) { + attributeRetrievalAttrDict.setDesign(null); + attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPool(attributeRetrievalAttrDict, tableName, poolNum, style); + } + if (CollectionUtil.isEmpty(attributeRetrievalList) || attributeRetrievalList.size() < poolNum) { + attributeRetrievalAttrDict.setSilhouette(null); + attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPool(attributeRetrievalAttrDict, tableName, poolNum, style); + } + if (CollectionUtil.isEmpty(attributeRetrievalList) || attributeRetrievalList.size() < poolNum) { + style = null; + attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPool(attributeRetrievalAttrDict, tableName, poolNum, style); + } + return toColoectionElementList(attributeRetrievalList, styleCategory, modelSex); + } + + private List getSystemSketchPoolBySameCategory(JSONObject attributeRecognition, String styleCategory, String modelSex, String style) { + /** + * female trousers->female_pants + * female blouse->female_top + * female skirt->female_skirt + * female outwear->female_outwear + * female dress->female_dress + */ + JSONObject data = attributeRecognition.getJSONObject("data"); + JSONObject attrDict = ((JSONObject) data.getJSONArray("list").get(0)).getJSONObject("attr_dict"); + AttributeRecognitionJSON attrDictJSON = attrDict.toJavaObject(AttributeRecognitionJSON.class); + AttributeRetrieval attributeRetrievalAttrDict = toAttrDict(attrDictJSON); + String tableName; + tableName = getTableName(modelSex, styleCategory); + + // 存储非空字段的列表 + List nonNullFields = new ArrayList<>(); + if (attributeRetrievalAttrDict.getType() != null) { + nonNullFields.add("type"); + } + if (attributeRetrievalAttrDict.getOpeningType() != null) { + nonNullFields.add("openingType"); + if (tableName.equals("male_outwear") || tableName.equals("male_top") || tableName.equals("male_bottom")) { + nonNullFields.remove("openingType"); + attributeRetrievalAttrDict.setOpeningType(null); + } + } + if (attributeRetrievalAttrDict.getSubtype() != null) { + nonNullFields.add("subtype"); + } + + // 只有当非空字段数量大于等于2时才进行处理 + if (nonNullFields.size() >= 2) { + // 随机数生成器 + Random random = new Random(); + // 随机选择一个字段保留 + String fieldToKeep = nonNullFields.get(random.nextInt(nonNullFields.size())); + + // 设置保留的字段为非null,其他字段为null + for (String field : nonNullFields) { + if (!field.equals(fieldToKeep)) { + switch (field) { + case "type": + attributeRetrievalAttrDict.setType(null); + break; + case "openingType": + attributeRetrievalAttrDict.setOpeningType(null); + break; + case "subtype": + attributeRetrievalAttrDict.setSubtype(null); + break; + } + } + } + } + + List attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPoolBySameCategory(attributeRetrievalAttrDict, tableName, style); + if (CollectionUtil.isEmpty(attributeRetrievalList)) { + System.out.println(attributeRetrievalAttrDict); + System.out.println(tableName); + if (!StringUtils.isEmpty(style)) { + attributeRetrievalAttrDict.setType(null); + attributeRetrievalAttrDict.setOpeningType(null); + attributeRetrievalAttrDict.setSubtype(null); + attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPoolBySameCategory(attributeRetrievalAttrDict, tableName, style); + } + + if (CollectionUtil.isEmpty(attributeRetrievalList)) { + style = null; + attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPoolBySameCategory(attributeRetrievalAttrDict, tableName, style); + + } + } + return toColoectionElementList(attributeRetrievalList, styleCategory, modelSex); + } + + private List toColoectionElementList(List attributeRetrievalList, String styleCategory, String modelSex) { + List systemPool = new ArrayList<>(); + for (AttributeRetrieval attributeRetrieval : attributeRetrievalList) { + CollectionElement system = toCollectionElement(attributeRetrieval, styleCategory, modelSex); + systemPool.add(system); + } + return systemPool; + } + + private CollectionElement toCollectionElement(AttributeRetrieval attributeRetrieval, String styleCategory, String modelSex) { + CollectionElement element = new CollectionElement(); + element.setLevel2Type(styleCategory); + element.setUrl("aida-sys-image/images/" + modelSex.toLowerCase() + "/" + attributeRetrieval.getImgName()); + if (element.getUrl().contains("top")) { + element.setUrl(element.getUrl().replace("top", "tops")); + } + if (element.getUrl().contains("bottom")) { + element.setUrl(element.getUrl().replace("bottom", "bottoms")); + } + if (element.getUrl().contains("outer")) { + element.setUrl(element.getUrl().replace("outer", "outwear")); + } + return element; + } + + private AttributeRetrieval toAttrDict(AttributeRecognitionJSON attrDictJSON) { + AttributeRetrieval attributeRetrieval = new AttributeRetrieval(); +// attributeRetrieval.setImgName(attrDictJSON.getImgName().get(0)); +// attributeRetrieval.setLength(attrDictJSON.getLength().get(0)); +// attributeRetrieval.setSleeveLength(attrDictJSON.getSleeveLength().get(0)); +// attributeRetrieval.setSleeveShape(attrDictJSON.getSleeveShape().get(0)); +// attributeRetrieval.setSleeveShoulder(attrDictJSON.getSleeveShoulder().get(0)); +// attributeRetrieval.setNeckline(attrDictJSON.getNeckline().get(0)); +// attributeRetrieval.setCollar(attrDictJSON.getCollar().get(0)); + if (CollectionUtil.isNotEmpty(attrDictJSON.getDesign()) && attrDictJSON.getDesign().get(0) != null) { + attributeRetrieval.setDesign(attrDictJSON.getDesign().get(0)); + } + if (CollectionUtil.isNotEmpty(attrDictJSON.getSilhouette()) && attrDictJSON.getSilhouette().get(0) != null) { + attributeRetrieval.setSilhouette(attrDictJSON.getSilhouette().get(0)); + } + if (CollectionUtil.isNotEmpty(attrDictJSON.getType()) && attrDictJSON.getType().get(0) != null) { + attributeRetrieval.setType(attrDictJSON.getType().get(0)); + } + if (CollectionUtil.isNotEmpty(attrDictJSON.getSubtype()) && attrDictJSON.getSubtype().get(0) != null) { + attributeRetrieval.setSubtype(attrDictJSON.getSubtype().get(0)); + } + if (CollectionUtil.isNotEmpty(attrDictJSON.getOpeningType()) && attrDictJSON.getOpeningType().get(0) != null) { + attributeRetrieval.setOpeningType(attrDictJSON.getOpeningType().get(0)); + } + return attributeRetrieval; + } + + public JSONObject getAttributeRecognition(String sketchImgUrl, String styleCategory, String modelSex) { + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .readTimeout(60, TimeUnit.SECONDS) + .writeTimeout(60, TimeUnit.SECONDS) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + + JSONObject paramJSONObject = new JSONObject(); + paramJSONObject.put("category", styleCategory); + paramJSONObject.put("colony", modelSex); + paramJSONObject.put("sketch_img_url", sketchImgUrl); + JSONArray paramArray = new JSONArray(); + paramArray.add(paramJSONObject); + String param = JSON.toJSONString(paramArray, SerializerFeature.DisableCircularReferenceDetect); + + log.info("PythonService##design 请求参数:####{}", param); + RequestBody body = RequestBody.create(mediaType, param); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + accessPythonPort + "/api/attribute_recognition") +// .url(fastApiPythonAddress + "/api/attribute_recognition") + .method("POST", body) + .addHeader("Content-Type", "application/json") + .build(); + + try (Response response = client.newCall(request).execute()) { + if (response.isSuccessful()) { + String responseBody = Objects.requireNonNull(response.body()).string(); + JSONObject responseObject = JSON.parseObject(responseBody); + log.info("PythonService##responseObject###{}", responseObject); + return responseObject; + } else { + log.error("PythonService##design 请求异常:{}", response); + throw new BusinessException("attributeRecognition.interface.exception"); + } + } catch (IOException e) { + log.error("PythonService##design 请求异常:{}", e.getMessage()); + throw new BusinessException("attributeRecognition.interface.exception"); + } + } + + public JSONObject getAttributeRecognitionBySameCategory(CollectionElement element, String modelSex) { + // todo 限流校验 +// AccessLimitUtils.validate("design",5); + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + //关闭FastJson的引用检测 防止出现$ref 现象 + JSONObject paramJSONObject = new JSONObject(); + paramJSONObject.put("category", element.getLevel2Type()); + paramJSONObject.put("colony", modelSex); + paramJSONObject.put("sketch_img_url", element.getUrl()); + JSONArray paramArray = new JSONArray(); + paramArray.add(paramJSONObject); + String param = JSON.toJSONString(paramArray, SerializerFeature.DisableCircularReferenceDetect); + log.info("design请求python 参数:####{}", param); + RequestBody body = RequestBody.create(mediaType, param); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + accessPythonPort + "/api/attribute_recognition") +// .url(fastApiPythonAddress + "/api/attribute_recognition") + .method("POST", body) +// .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response; + String responseBody; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + AccessLimitUtils.validateOut("design"); + log.error("PythonService##design异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("design.interface.exception"); + } + //去除限流 +// AccessLimitUtils.validateOut("design"); + if (response.isSuccessful()) { + try { + if (Objects.nonNull(response.body())) { + responseBody = response.body().string(); + JSONObject responseObject = JSON.parseObject(responseBody); + log.info("PythonService##responseObject###{}", responseObject); + return responseObject; + } + throw new BusinessException("design.interface.exception"); + } catch (IOException | JSONException e) { + log.error("PythonService##design异常###{}", e.getMessage()); + throw new BusinessException("design.interface.exception"); + } + } + log.error("PythonService##design异常response###{}", response); + //生成失败 + throw new BusinessException("design.interface.exception"); + } + + @Resource + private CollocationMapper collocationMapper; + @Resource + private DressingMapper dressingMapper; + + private List getOtherSketchCategoryList(String modelSex, DesignPythonItem designPythonItem) { + List collocationList = collocationMapper.getCollocationListBySketch(modelSex, designPythonItem.getType()); + if (CollectionUtil.isNotEmpty(collocationList)) { + Random random = new Random(); + int randomNumber = random.nextInt(collocationList.size()); + List otherSketchCategoryList = dressingMapper.getOtherSketchCategoryNameList(collocationList.get(randomNumber).getId(), designPythonItem.getType().toLowerCase()); + return otherSketchCategoryList; + } + return null; + } + + private DesignPythonItem calculatePythonItem(ValidateElementVO validateElementVO, CurrentDesignPictureTypeEnum currentDesignPictureType) { + switch (currentDesignPictureType) { + case PIN: + return calculatePinPythonItem(validateElementVO); + case NO_PIN: + return calculateNoPinPythonItem(validateElementVO); + case SYS_FILE: + return calculateSysFilePythonItem(validateElementVO); + default: + return null; + } + } + + private DesignPythonItem calculatePinPythonItem(ValidateElementVO validateElementVO) { + List pinCollectionData = getPinData(validateElementVO); + if (CollectionUtil.isEmpty(pinCollectionData)) { + throw new BusinessException("pinData is null"); + } + Random random = new Random(); + int randomNumber = random.nextInt(pinCollectionData.size()); + validateElementVO.getHasUseMd5List().add(pinCollectionData.get(randomNumber).getMd5()); + return coverSketchToDesignPythonItem(pinCollectionData.get(randomNumber).getId(), pinCollectionData.get(randomNumber), validateElementVO); + } + + private DesignPythonItem calculateNoPinPythonItem(ValidateElementVO validateElementVO) { + List noPinCollectionData = getNoPinData(validateElementVO); + if (CollectionUtil.isEmpty(noPinCollectionData)) { + List sketchBoardPins = getPinDataWhole(validateElementVO); + if (CollectionUtil.isNotEmpty(sketchBoardPins) && validateElementVO.getSingleOverall().equals(SingleOverallEnum.SINGLE.getRealName())) { + sketchBoardPins = sketchBoardPins.stream().filter(o -> o.getLevel2Type().equals(validateElementVO.getSwitchCategory())).collect(Collectors.toList()); + } + if (CollectionUtil.isNotEmpty(sketchBoardPins)) { + Integer randomNum = RandomsUtil.randomSysFile(sketchBoardPins.size()); + CollectionElement element = sketchBoardPins.get(randomNum); + // 获取随机pin sketch的category + String category = element.getLevel2Type(); + String categoryParam = validateElementVO.getModelSex().toLowerCase() + "_" + category.toLowerCase(); + List recommentdUrlList = getSystemSketchByCategory(categoryParam, validateElementVO.getBrandId(), validateElementVO.getBrandScale(), validateElementVO.getStyle()); + if (!CollectionUtils.isEmpty(recommentdUrlList)) { + String recommendSystemSketch = recommentdUrlList.get(0); + return coverSystemSketchUrlToDesignPythonItem(recommendSystemSketch, category, validateElementVO); + }else { + throw new BusinessException("failed.to.obtain.system.sketch.recommendation"); + } +// JSONObject attributeRecognition = getAttributeRecognitionBySameCategory(element, validateElementVO.getModelSex()); +// return processAttributeRecognitionBySameCategory(attributeRecognition, validateElementVO, element.getLevel2Type()); + } + QueryWrapper qw = new QueryWrapper<>(); + qw.lambda().eq(Dressing::getApparel, validateElementVO.getModelSex()); + if (validateElementVO.getSingleOverall().equals(SingleOverallEnum.SINGLE.getRealName())) { + qw.lambda().eq(Dressing::getStyleCategory, validateElementVO.getSwitchCategory()); + } + List dressings = dressingMapper.selectList(qw); + if (CollectionUtil.isEmpty(dressings)) { + throw new BusinessException("dressings is null"); + } + Integer randomNum = RandomsUtil.randomSysFile(dressings.size()); + String category = dressings.get(randomNum).getStyleCategory(); + + String categoryParam = validateElementVO.getModelSex().toLowerCase() + "_" + category.toLowerCase(); + List recommentdUrlList = getSystemSketchByCategory(categoryParam, validateElementVO.getBrandId(), validateElementVO.getBrandScale(), validateElementVO.getStyle()); + if (!CollectionUtils.isEmpty(recommentdUrlList)) { + String recommendSystemSketch = recommentdUrlList.get(0); + return coverSystemSketchUrlToDesignPythonItem(recommendSystemSketch, category, validateElementVO); + }else { + throw new BusinessException("failed.to.obtain.system.sketch.recommendation"); + } + +// String tableName = getTableName(validateElementVO.getModelSex(), category); +// AttributeRetrieval attributeRetrieval = attributeRetrievalMapper.getSystemRandom(tableName, validateElementVO.getStyle()); +// CollectionElement collectionElement = toCollectionElement(attributeRetrieval, category, validateElementVO.getModelSex()); +// return coverSketchToDesignPythonItem(null, collectionElement, validateElementVO); + } + Random random = new Random(); + int randomNumber = random.nextInt(noPinCollectionData.size()); + return coverSketchToDesignPythonItem(noPinCollectionData.get(randomNumber).getId(), noPinCollectionData.get(randomNumber), validateElementVO); + } + + private DesignPythonItem calculateSysFilePythonItem(ValidateElementVO validateElementVO) { + List sketchBoardCollectionElements = validateElementVO.getSketchBoardElements(); + if (!CollectionUtils.isEmpty(sketchBoardCollectionElements)) { + if (validateElementVO.getModelSex().equals(Sex.MALE.getValue())) { + sketchBoardCollectionElements = sketchBoardCollectionElements.stream().filter(o -> MALE_CATEGORY.contains(o.getLevel2Type())).collect(Collectors.toList()); + } + if (validateElementVO.getModelSex().equals(Sex.FEMALE.getValue())) { + sketchBoardCollectionElements = sketchBoardCollectionElements.stream().filter(o -> FEMALE_CATEGORY.contains(o.getLevel2Type())).collect(Collectors.toList()); + } + if (CollectionUtil.isNotEmpty(sketchBoardCollectionElements) && validateElementVO.getSingleOverall().equals(SingleOverallEnum.SINGLE.getRealName())) { + sketchBoardCollectionElements = sketchBoardCollectionElements.stream().filter(o -> o.getLevel2Type().equals(validateElementVO.getSwitchCategory())).collect(Collectors.toList()); + } + if (CollectionUtil.isNotEmpty(sketchBoardCollectionElements)) { + Integer randomNum = RandomsUtil.randomSysFile(sketchBoardCollectionElements.size()); + CollectionElement element = sketchBoardCollectionElements.get(randomNum); + String category = element.getLevel2Type(); + + String categoryParam = validateElementVO.getModelSex().toLowerCase() + "_" + category.toLowerCase(); + List recommentdUrlList = getSystemSketchByCategory(categoryParam, validateElementVO.getBrandId(), validateElementVO.getBrandScale(), validateElementVO.getStyle()); + if (!CollectionUtils.isEmpty(recommentdUrlList)) { + String recommendSystemSketch = recommentdUrlList.get(0); + return coverSystemSketchUrlToDesignPythonItem(recommendSystemSketch, category, validateElementVO); + }else { + throw new BusinessException("failed.to.obtain.system.sketch.recommendation"); + } +// JSONObject attributeRecognition = getAttributeRecognitionBySameCategory(element, validateElementVO.getModelSex()); +// return processAttributeRecognitionBySameCategory(attributeRecognition, validateElementVO, element.getLevel2Type()); + } + } + QueryWrapper qw = new QueryWrapper<>(); + qw.lambda().eq(Dressing::getApparel, validateElementVO.getModelSex()); + if (validateElementVO.getSingleOverall().equals(SingleOverallEnum.SINGLE.getRealName())) { + qw.lambda().eq(Dressing::getStyleCategory, validateElementVO.getSwitchCategory()); + } + List dressings = dressingMapper.selectList(qw); + if (CollectionUtil.isEmpty(dressings)) { + throw new BusinessException("dressings is null"); + } + Integer randomNum = RandomsUtil.randomSysFile(dressings.size()); + String category = dressings.get(randomNum).getStyleCategory(); + + String categoryParam = validateElementVO.getModelSex().toLowerCase() + "_" + category.toLowerCase(); + List recommentdUrlList = getSystemSketchByCategory(categoryParam, validateElementVO.getBrandId(), validateElementVO.getBrandScale(), validateElementVO.getStyle()); + if (!CollectionUtils.isEmpty(recommentdUrlList)) { + String recommendSystemSketch = recommentdUrlList.get(0); + return coverSystemSketchUrlToDesignPythonItem(recommendSystemSketch, category, validateElementVO); + }else { + throw new BusinessException("failed.to.obtain.system.sketch.recommendation"); + } +// String tableName = getTableName(validateElementVO.getModelSex(), category); +// +// AttributeRetrieval attributeRetrieval = attributeRetrievalMapper.getSystemRandom(tableName, validateElementVO.getStyle()); +// CollectionElement collectionElement = toCollectionElement(attributeRetrieval, category, validateElementVO.getModelSex()); +// return coverSketchToDesignPythonItem(null, collectionElement, validateElementVO); + } + + private String getTableName(String modelSex, String category) { + switch (modelSex) { + case "Female": { + switch (category) { + case "Blouse": { + return "female_top"; + } + case "Trousers": { + return "female_pants"; + } + case "Skirt": { + return "female_skirt"; + } + case "Outwear": { + return "female_outwear"; + } + case "Dress": { + return "female_dress"; + } + default: { + throw new BusinessException("unknown attributeRetrieval dressing"); + } + } + } + case "Male": { + switch (category) { + case "Tops": { + return "male_top"; + } + case "Bottoms": { + return "male_bottom"; + } + case "Outwear": { + return "male_outwear"; + } + default: { + throw new BusinessException("unknown male dressing"); + } + } + } + default: { + throw new BusinessException("unknown modelSex"); + } + } + } + + private DesignPythonItem calculatePythonItemOutwear(List pinData, ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType) { + DesignPythonItem outwear = null; + //剩余的的PinData + List existPinDataIds = elementVO.getExistPinDataIds(); + List residuePinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); + if (CollectionUtil.isNotEmpty(residuePinData)) { + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.OUTWEAR.contains(elementVO.getSwitchCategory())) { + //是否包含的Pin + Boolean isPin = residuePinData.stream().filter(residue -> + elementVO.getSwitchCategory().equals(residue.getLevel2Type())).findFirst().isPresent(); + //如果包含Pin只传一个 + if (isPin) { + //Pin的数据 + pinData = getPinDataByLevel2Type(pinData, elementVO.getSwitchCategory()); + //剩余的的PinData + List residueInnerPinDataByType = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); + CollectionElement elementNew = CollectionUtils.isEmpty(residueInnerPinDataByType) ? null : residueInnerPinDataByType.get(0); + if (Objects.nonNull(elementNew)) { + outwear = coverToDesignPythonItem(elementNew.getId(), elementVO.getSwitchCategory(), elementNew.getUrl(), elementVO); + //去重用 + existPinDataIds.add(elementNew.getId()); + //添加已使用的md5 + elementVO.getHasUseMd5List().add(elementNew.getMd5()); + } + } + } + } else { + //是否包含skirt的Pin + Boolean isPin = residuePinData.stream().filter(residue -> + DesignPythonItem.OUTWEAR.contains(residue.getLevel2Type())).findFirst().isPresent(); + //如果包含Pin只传一个 + if (isPin) { + for (String type : DesignPythonItem.OUTWEAR) { + //剩余的的PinData + List residueInnerPinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); + CollectionElement elementNew = residueInnerPinData.stream() + .filter(element -> element.getLevel2Type().equals(type)).findFirst().orElse(null); + if (Objects.nonNull(elementNew)) { + outwear = coverToDesignPythonItem(elementNew.getId(), type, elementNew.getUrl(), elementVO); + //去重用 + existPinDataIds.add(elementNew.getId()); + //添加已使用的md5 + elementVO.getHasUseMd5List().add(elementNew.getMd5()); + break; + } + } + } + } + + } + if (Objects.nonNull(outwear)) { + return outwear; + } + switch (designPictureType) { + case PIN: + if (Objects.isNull(outwear)) { + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.OUTWEAR.contains(elementVO.getSwitchCategory())) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); + outwear = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + outwear.setBusinessId(sysFileVO.getId()); + return outwear; + } + } else { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileMaleBottoms(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); + outwear = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + outwear.setBusinessId(sysFileVO.getId()); + //添加已使用的md5 + return outwear; + } + } + break; +// case USER_LIBRARY: +// //single模式 +// if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { +// if (DesignPythonItem.OUTWEAR.contains(elementVO.getSwitchCategory())) { +// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), +// Arrays.asList(elementVO.getSwitchCategory()), elementVO.getHasUseMd5List()); +// if (StringUtils.isEmpty(libraryVo)) { +// //系统获取 +// SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); +// outwear = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); +// outwear.setBusinessId(sysFileVO.getId()); +// return outwear; +// } +// outwear = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); +// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); +// outwear.setBusinessId(libraryVo.getId()); +// } +// } else { +// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), +// DesignPythonItem.OUTWEAR, elementVO.getHasUseMd5List()); +// if (StringUtils.isEmpty(libraryVo)) { +// //系统获取 +// SysFileVO sysFileVO = getRandomSysFileMaleBottoms(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); +// outwear = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); +// outwear.setBusinessId(sysFileVO.getId()); +// //添加已使用的md5 +// return outwear; +// } +// outwear = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); +// outwear.setBusinessId(libraryVo.getId()); +// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); +// } +// break; + case SYS_FILE: + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.OUTWEAR.contains(elementVO.getSwitchCategory())) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); + outwear = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + outwear.setBusinessId(sysFileVO.getId()); + return outwear; + } + } else { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileMaleBottoms(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); + outwear = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + outwear.setBusinessId(sysFileVO.getId()); + //添加已使用的md5 + return outwear; + } + break; + case NO_PIN: + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.OUTWEAR.contains(elementVO.getSwitchCategory())) { + //非Pin的数据 + List noPinDataByType = + getNoPinData(elementVO.getSketchBoardElements(), Collections.singletonList(elementVO.getSwitchCategory())); + CollectionElement collectionElement = getRandomSketchLibrary(noPinDataByType, elementVO.getHasUseMd5List()); + if (Objects.isNull(collectionElement)) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); + outwear = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + outwear.setBusinessId(sysFileVO.getId()); + } else { + elementVO.getHasUseMd5List().add(collectionElement.getMd5()); + outwear = coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO); + } + } + } else { + //非Pin的数据 + List noPinData = getNoPinData(elementVO.getSketchBoardElements(), DesignPythonItem.OUTWEAR); + CollectionElement collectionElement = getRandomSketchLibrary(noPinData, elementVO.getHasUseMd5List()); + if (Objects.isNull(collectionElement)) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileMaleBottoms(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); + outwear = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + outwear.setBusinessId(sysFileVO.getId()); + } else { + elementVO.getHasUseMd5List().add(collectionElement.getMd5()); + outwear = coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO); + } + } + break; + default: + } + return outwear; + } + + private DesignPythonItem calculatePythonItemBottom(List pinData, ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType) { + DesignPythonItem bottom = null; + //剩余的的PinData + List existPinDataIds = elementVO.getExistPinDataIds(); + List residuePinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); + if (CollectionUtil.isNotEmpty(residuePinData)) { + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.BOTTOMS.contains(elementVO.getSwitchCategory())) { + //是否包含的Pin + Boolean isPin = residuePinData.stream().filter(residue -> + elementVO.getSwitchCategory().equals(residue.getLevel2Type())).findFirst().isPresent(); + //如果包含Pin只传一个 + if (isPin) { + //Pin的数据 + pinData = getPinDataByLevel2Type(pinData, elementVO.getSwitchCategory()); + //剩余的的PinData + List residueInnerPinDataByType = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); + CollectionElement elementNew = CollectionUtils.isEmpty(residueInnerPinDataByType) ? null : residueInnerPinDataByType.get(0); + if (Objects.nonNull(elementNew)) { + bottom = coverToDesignPythonItem(elementNew.getId(), elementVO.getSwitchCategory(), elementNew.getUrl(), elementVO); + //去重用 + existPinDataIds.add(elementNew.getId()); + //添加已使用的md5 + elementVO.getHasUseMd5List().add(elementNew.getMd5()); + } + } + } + } else { + //是否包含skirt的Pin + Boolean isPin = residuePinData.stream().filter(residue -> + DesignPythonItem.BOTTOMS.contains(residue.getLevel2Type())).findFirst().isPresent(); + //如果包含Pin只传一个 + if (isPin) { + for (String type : DesignPythonItem.BOTTOMS) { + //剩余的的PinData + List residueInnerPinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); + CollectionElement elementNew = residueInnerPinData.stream() + .filter(element -> element.getLevel2Type().equals(type)).findFirst().orElse(null); + if (Objects.nonNull(elementNew)) { + bottom = coverToDesignPythonItem(elementNew.getId(), type, elementNew.getUrl(), elementVO); + //去重用 + existPinDataIds.add(elementNew.getId()); + //添加已使用的md5 + elementVO.getHasUseMd5List().add(elementNew.getMd5()); + break; + } + } + } + } + + } + if (Objects.nonNull(bottom)) { + return bottom; + } + switch (designPictureType) { + case PIN: + if (Objects.isNull(bottom)) { + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.BOTTOMS.contains(elementVO.getSwitchCategory())) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); + bottom = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + bottom.setBusinessId(sysFileVO.getId()); + return bottom; + } + } else { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileMaleBottoms(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); + bottom = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + bottom.setBusinessId(sysFileVO.getId()); + //添加已使用的md5 + return bottom; + } + } + break; +// case USER_LIBRARY: +// //single模式 +// if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { +// if (DesignPythonItem.BOTTOMS.contains(elementVO.getSwitchCategory())) { +// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), +// Arrays.asList(elementVO.getSwitchCategory()), elementVO.getHasUseMd5List()); +// if (StringUtils.isEmpty(libraryVo)) { +// //系统获取 +// SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); +// bottom = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); +// bottom.setBusinessId(sysFileVO.getId()); +// return bottom; +// } +// bottom = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); +// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); +// bottom.setBusinessId(libraryVo.getId()); +// } +// } else { +// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), +// DesignPythonItem.BOTTOMS, elementVO.getHasUseMd5List()); +// if (StringUtils.isEmpty(libraryVo)) { +// //系统获取 +// SysFileVO sysFileVO = getRandomSysFileMaleBottoms(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); +// bottom = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); +// bottom.setBusinessId(sysFileVO.getId()); +// //添加已使用的md5 +// return bottom; +// } +// bottom = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); +// bottom.setBusinessId(libraryVo.getId()); +// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); +// } +// break; + case SYS_FILE: + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.BOTTOMS.contains(elementVO.getSwitchCategory())) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); + bottom = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + bottom.setBusinessId(sysFileVO.getId()); + return bottom; + } + } else { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileMaleBottoms(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); + bottom = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + bottom.setBusinessId(sysFileVO.getId()); + //添加已使用的md5 + return bottom; + } + break; + case NO_PIN: + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.BOTTOMS.contains(elementVO.getSwitchCategory())) { + //非Pin的数据 + List noPinDataByType = + getNoPinData(elementVO.getSketchBoardElements(), Collections.singletonList(elementVO.getSwitchCategory())); + CollectionElement collectionElement = getRandomSketchLibrary(noPinDataByType, elementVO.getHasUseMd5List()); + if (Objects.isNull(collectionElement)) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); + bottom = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + bottom.setBusinessId(sysFileVO.getId()); + } else { + elementVO.getHasUseMd5List().add(collectionElement.getMd5()); + bottom = coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO); + } + } + } else { + //非Pin的数据 + List noPinData = getNoPinData(elementVO.getSketchBoardElements(), DesignPythonItem.BOTTOMS); + CollectionElement collectionElement = getRandomSketchLibrary(noPinData, elementVO.getHasUseMd5List()); + if (Objects.isNull(collectionElement)) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileMaleBottoms(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); + bottom = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + bottom.setBusinessId(sysFileVO.getId()); + } else { + elementVO.getHasUseMd5List().add(collectionElement.getMd5()); + bottom = coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO); + } + } + break; + default: + } + return bottom; + } + + private DesignPythonItem calculatePythonItemTop(List pinData, ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType) { + DesignPythonItem top = null; + //剩余的的PinData + List existPinDataIds = elementVO.getExistPinDataIds(); + List residuePinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); + if (CollectionUtil.isNotEmpty(residuePinData)) { + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.TOPS.contains(elementVO.getSwitchCategory())) { + //是否包含的Pin + Boolean isPin = residuePinData.stream().filter(residue -> + elementVO.getSwitchCategory().equals(residue.getLevel2Type())).findFirst().isPresent(); + //如果包含Pin只传一个 + if (isPin) { + //Pin的数据 + pinData = getPinDataByLevel2Type(pinData, elementVO.getSwitchCategory()); + //剩余的的PinData + List residueInnerPinDataByType = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); + CollectionElement elementNew = CollectionUtils.isEmpty(residueInnerPinDataByType) ? null : residueInnerPinDataByType.get(0); + if (Objects.nonNull(elementNew)) { + top = coverToDesignPythonItem(elementNew.getId(), elementVO.getSwitchCategory(), elementNew.getUrl(), elementVO); + //去重用 + existPinDataIds.add(elementNew.getId()); + //添加已使用的md5 + elementVO.getHasUseMd5List().add(elementNew.getMd5()); + } + } + } + } else { + //是否包含skirt的Pin + Boolean isPin = residuePinData.stream().filter(residue -> + DesignPythonItem.TOPS.contains(residue.getLevel2Type())).findFirst().isPresent(); + //如果包含Pin只传一个 + if (isPin) { + for (String type : DesignPythonItem.TOPS) { + //剩余的的PinData + List residueInnerPinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); + CollectionElement elementNew = residueInnerPinData.stream() + .filter(element -> element.getLevel2Type().equals(type)).findFirst().orElse(null); + if (Objects.nonNull(elementNew)) { + top = coverToDesignPythonItem(elementNew.getId(), type, elementNew.getUrl(), elementVO); + //去重用 + existPinDataIds.add(elementNew.getId()); + //添加已使用的md5 + elementVO.getHasUseMd5List().add(elementNew.getMd5()); + break; + } + } + } + } + + } + if (Objects.nonNull(top)) { + return top; + } + switch (designPictureType) { + case PIN: + if (Objects.isNull(top)) { + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.TOPS.contains(elementVO.getSwitchCategory())) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); + top = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + top.setBusinessId(sysFileVO.getId()); + return top; + } + } else { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileMaleTops(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); + top = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + top.setBusinessId(sysFileVO.getId()); + //添加已使用的md5 + return top; + } + } + break; +// case USER_LIBRARY: +// //single模式 +// if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { +// if (DesignPythonItem.TOPS.contains(elementVO.getSwitchCategory())) { +// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), +// Arrays.asList(elementVO.getSwitchCategory()), elementVO.getHasUseMd5List()); +// if (StringUtils.isEmpty(libraryVo)) { +// //系统获取 +// SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); +// top = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); +// top.setBusinessId(sysFileVO.getId()); +// return top; +// } +// top = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); +// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); +// top.setBusinessId(libraryVo.getId()); +// } +// } else { +// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), +// DesignPythonItem.TOPS, elementVO.getHasUseMd5List()); +// if (StringUtils.isEmpty(libraryVo)) { +// //系统获取 +// SysFileVO sysFileVO = getRandomSysFileMaleTops(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); +// top = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); +// top.setBusinessId(sysFileVO.getId()); +// //添加已使用的md5 +// return top; +// } +// top = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); +// top.setBusinessId(libraryVo.getId()); +// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); +// } +// break; + case SYS_FILE: + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.TOPS.contains(elementVO.getSwitchCategory())) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); + top = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + top.setBusinessId(sysFileVO.getId()); + return top; + } + } else { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileMaleTops(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); + top = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + top.setBusinessId(sysFileVO.getId()); + //添加已使用的md5 + return top; + } + break; + case NO_PIN: + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.TOPS.contains(elementVO.getSwitchCategory())) { + //非Pin的数据 + List noPinDataByType = + getNoPinData(elementVO.getSketchBoardElements(), Collections.singletonList(elementVO.getSwitchCategory())); + CollectionElement collectionElement = getRandomSketchLibrary(noPinDataByType, elementVO.getHasUseMd5List()); + if (Objects.isNull(collectionElement)) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); + top = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + top.setBusinessId(sysFileVO.getId()); + } else { + elementVO.getHasUseMd5List().add(collectionElement.getMd5()); + top = coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO); + } + } + } else { + //非Pin的数据 + List noPinData = getNoPinData(elementVO.getSketchBoardElements(), DesignPythonItem.TOPS); + CollectionElement collectionElement = getRandomSketchLibrary(noPinData, elementVO.getHasUseMd5List()); + if (Objects.isNull(collectionElement)) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileMaleTops(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); + top = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + top.setBusinessId(sysFileVO.getId()); + } else { + elementVO.getHasUseMd5List().add(collectionElement.getMd5()); + top = coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO); + } + } + break; + default: + } + return top; + } + + private List calculatePythonItemHairstyleShoes(ValidateElementVO elementVO, DesignLibraryModelPointVO designLibraryModelPoint) { + List items = Lists.newArrayList(); + for (String type : DesignPythonItem.SYS_HAIRSTYLE_SHOES_BODY) { + if (!type.equals("Body")) { + continue; + } + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall()) || Objects.nonNull(designLibraryModelPoint)) { + //single和models模特时候不传耳环 首饰,鞋子等 + if (!SysFileLevel2TypeEnum.BODY.getRealName().equals(type)) { + continue; + } + } + DesignPythonItem pythonItem = new DesignPythonItem(); + items.add(pythonItem); + //类型 + pythonItem.setType(type); + if (SysFileLevel2TypeEnum.BODY.getRealName().equals(type)) { + if (!CollectionUtils.isEmpty(elementVO.getMannequins())) { + DesignLibraryModelPointVO vo = getRandomDesignLibraryModelPoint(elementVO.getMannequins()); + pythonItem.setBody_path(vo.getTemplateUrl()); + elementVO.setDesignLibraryModelPointVO(vo); + } else { +// pythonItem.setBody_path("/workspace/python_code/Multi-layer-Virtual-Try-on/dataset_for_test/Img_model.png"); + pythonItem.setBody_path("aida-sys-image/models/female/dd6b48ce-1bab-4861-bb87-a30b82377a8f.png"); + } +// if (Objects.nonNull(designLibraryModelPoint)) { +// pythonItem.setBody_path(designLibraryModelPoint.getTemplateUrl()); +// } else { +//// pythonItem.setBody_path("/workspace/python_code/Multi-layer-Virtual-Try-on/dataset_for_test/Img_model.png"); +// pythonItem.setBody_path("aida-mannequins/model_1693218345.2714432.png"); +// } + } else { + SysFileVO sysFileVO = getRandomSysFileByLevel2Type(type, Lists.newArrayList(), elementVO.getModelSex()); + pythonItem.setPath(sysFileVO.getUrl()); + pythonItem.setBusinessId(sysFileVO.getId()); + if (SysFileLevel2TypeEnum.SHOES.getRealName().equals(type)) { + CollectionColorDTO randomColor = getRandomColor(elementVO.getColorBoards()); + if (Objects.nonNull(randomColor)) { + pythonItem.setColor(randomColor.getRgbValue()); + pythonItem.setGradient(randomColor.getGradientMinioUrl()); + pythonItem.setGradientString(randomColor.getGradientString()); + } + } + } + } + return items; + } + + private DesignPythonItem calculatePythonItemSkirt(List pinData, ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType) { + // skirt, trousers 只选择一个 + DesignPythonItem skirt = null; + //剩余的的PinData + List existPinDataIds = elementVO.getExistPinDataIds(); + List residuePinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); + if (CollectionUtil.isNotEmpty(residuePinData)) { + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.SKIRT_TROUSERS.contains(elementVO.getSwitchCategory())) { + //是否包含的Pin + Boolean isPin = residuePinData.stream().filter(residue -> + elementVO.getSwitchCategory().equals(residue.getLevel2Type())).findFirst().isPresent(); + //如果包含Pin只传一个 + if (isPin) { + //Pin的数据 + pinData = getPinDataByLevel2Type(pinData, elementVO.getSwitchCategory()); + //剩余的的PinData + List residueInnerPinDataByType = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); + CollectionElement elementNew = CollectionUtils.isEmpty(residueInnerPinDataByType) ? null : residueInnerPinDataByType.get(0); + if (Objects.nonNull(elementNew)) { + skirt = coverToDesignPythonItem(elementNew.getId(), elementVO.getSwitchCategory(), elementNew.getUrl(), elementVO); + //去重用 + existPinDataIds.add(elementNew.getId()); + //添加已使用的md5 + elementVO.getHasUseMd5List().add(elementNew.getMd5()); + } + } + } + } else { + //是否包含skirt的Pin + Boolean isPin = residuePinData.stream().filter(residue -> + DesignPythonItem.SKIRT_TROUSERS.contains(residue.getLevel2Type())).findFirst().isPresent(); + //如果包含Pin只传一个 + if (isPin) { + for (String type : DesignPythonItem.SKIRT_TROUSERS) { + //剩余的的PinData + List residueInnerPinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); + CollectionElement elementNew = residueInnerPinData.stream() + .filter(element -> element.getLevel2Type().equals(type)).findFirst().orElse(null); + if (Objects.nonNull(elementNew)) { + skirt = coverToDesignPythonItem(elementNew.getId(), type, elementNew.getUrl(), elementVO); + //去重用 + existPinDataIds.add(elementNew.getId()); + //添加已使用的md5 + elementVO.getHasUseMd5List().add(elementNew.getMd5()); + break; + } + } + } + } + + } + if (Objects.nonNull(skirt)) { + return skirt; + } + switch (designPictureType) { + case PIN: + if (Objects.isNull(skirt)) { + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.SKIRT_TROUSERS.contains(elementVO.getSwitchCategory())) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); + skirt = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + skirt.setBusinessId(sysFileVO.getId()); + return skirt; + } + } else { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileSkirt(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); + skirt = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + skirt.setBusinessId(sysFileVO.getId()); + //添加已使用的md5 + return skirt; + } + } + break; +// case USER_LIBRARY: +// //single模式 +// if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { +// if (DesignPythonItem.SKIRT_TROUSERS.contains(elementVO.getSwitchCategory())) { +// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), +// Arrays.asList(elementVO.getSwitchCategory()), elementVO.getHasUseMd5List()); +// if (StringUtils.isEmpty(libraryVo)) { +// //系统获取 +// SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); +// skirt = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); +// skirt.setBusinessId(sysFileVO.getId()); +// return skirt; +// } +// skirt = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); +// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); +// skirt.setBusinessId(libraryVo.getId()); +// } +// } else { +// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), +// DesignPythonItem.SKIRT_TROUSERS, elementVO.getHasUseMd5List()); +// if (StringUtils.isEmpty(libraryVo)) { +// //系统获取 +// SysFileVO sysFileVO = getRandomSysFileSkirt(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); +// skirt = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); +// skirt.setBusinessId(sysFileVO.getId()); +// //添加已使用的md5 +// return skirt; +// } +// skirt = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); +// skirt.setBusinessId(libraryVo.getId()); +// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); +// } +// break; + case SYS_FILE: + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.SKIRT_TROUSERS.contains(elementVO.getSwitchCategory())) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); + skirt = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + skirt.setBusinessId(sysFileVO.getId()); + return skirt; + } + } else { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileSkirt(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); + skirt = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + skirt.setBusinessId(sysFileVO.getId()); + //添加已使用的md5 + return skirt; + } + break; + case NO_PIN: + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.SKIRT_TROUSERS.contains(elementVO.getSwitchCategory())) { + //非Pin的数据 + List noPinDataByType = + getNoPinData(elementVO.getSketchBoardElements(), Collections.singletonList(elementVO.getSwitchCategory())); + CollectionElement collectionElement = getRandomSketchLibrary(noPinDataByType, elementVO.getHasUseMd5List()); + if (Objects.isNull(collectionElement)) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); + skirt = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + skirt.setBusinessId(sysFileVO.getId()); + } else { + elementVO.getHasUseMd5List().add(collectionElement.getMd5()); + skirt = coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO); + } + } + } else { + //非Pin的数据 + List noPinData = getNoPinData(elementVO.getSketchBoardElements(), DesignPythonItem.SKIRT_TROUSERS); + CollectionElement collectionElement = getRandomSketchLibrary(noPinData, elementVO.getHasUseMd5List()); + if (Objects.isNull(collectionElement)) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileSkirt(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); + skirt = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + skirt.setBusinessId(sysFileVO.getId()); + } else { + elementVO.getHasUseMd5List().add(collectionElement.getMd5()); + skirt = coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO); + } + } + break; + default: + } + return skirt; + } + + private List calculatePythonItemBlouse(List pinData, ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType) { + List items = Lists.newArrayList(); + //剩余的的PinData + List existPinDataIds = elementVO.getExistPinDataIds(); + List residuePinData = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); + if (CollectionUtil.isNotEmpty(residuePinData)) { + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.OUTWEAR_DRESS_BLOUSE.contains(elementVO.getSwitchCategory())) { + //是否包含的Pin + Boolean isPin = residuePinData.stream().filter(residue -> + elementVO.getSwitchCategory().equals(residue.getLevel2Type())).findFirst().isPresent(); + //如果包含Pin只传一个 + if (isPin) { + //Pin的数据 + pinData = getPinDataByLevel2Type(pinData, elementVO.getSwitchCategory()); + //剩余的的PinData + List residueInnerPinDataByType = residuePinData(pinData, existPinDataIds, elementVO.getHasUseMd5List()); + CollectionElement elementNew = CollectionUtils.isEmpty(residueInnerPinDataByType) ? null : residueInnerPinDataByType.get(0); + if (Objects.nonNull(elementNew)) { + items.add(coverToDesignPythonItem(elementNew.getId(), elementVO.getSwitchCategory(), elementNew.getUrl(), elementVO)); + //去重用 + existPinDataIds.add(elementNew.getId()); + //添加MD5 + elementVO.getHasUseMd5List().add(elementNew.getMd5()); + } + } + } + } else { + //是否包含blouse的Pin + Boolean isPin = residuePinData.stream().filter(residue -> + DesignPythonItem.OUTWEAR_DRESS_BLOUSE.contains(residue.getLevel2Type())).findFirst().isPresent(); + //如果包含Pin只传一个 + if (isPin) { + List finalPinData = pinData; + for (String type : DesignPythonItem.OUTWEAR_DRESS_BLOUSE) { + // 剩余的的 PinData + List residueInnerPinData = residuePinData(finalPinData, existPinDataIds, elementVO.getHasUseMd5List()); + CollectionElement elementNew = residueInnerPinData.stream() + .filter(element -> element.getLevel2Type().equals(type)).findFirst().orElse(null); + if (Objects.nonNull(elementNew)) { + items.add(coverToDesignPythonItem(elementNew.getId(), type, elementNew.getUrl(), elementVO)); + // 去重用 + existPinDataIds.add(elementNew.getId()); + // 添加md5 + elementVO.getHasUseMd5List().add(elementNew.getMd5()); + + // 提前结束循环 + break; + } + } + } + } + + } + if (CollectionUtil.isNotEmpty(items)) { + return items; + } + switch (designPictureType) { + case PIN: + if (CollectionUtil.isEmpty(items)) { + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.OUTWEAR_DRESS_BLOUSE.contains(elementVO.getSwitchCategory())) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); + DesignPythonItem item = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + item.setBusinessId(sysFileVO.getId()); + items.add(item); + return items; + } + } else { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileOutwear(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); + DesignPythonItem item = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + item.setBusinessId(sysFileVO.getId()); + items.add(item); + return items; + } + } + break; +// case USER_LIBRARY: +// //single模式 +// if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { +// if (DesignPythonItem.OUTWEAR_DRESS_BLOUSE.contains(elementVO.getSwitchCategory())) { +// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), +// Arrays.asList(elementVO.getSwitchCategory()), elementVO.getHasUseMd5List()); +// if (StringUtils.isEmpty(libraryVo)) { +// //系统获取 +// SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); +// DesignPythonItem item = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); +// item.setBusinessId(sysFileVO.getId()); +// items.add(item); +// return items; +// } +// DesignPythonItem item = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); +// item.setBusinessId(libraryVo.getId()); +// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); +// items.add(item); +// } +// } else { +// LibraryVo libraryVo = getRandomLibrary(elementVO.getLibraryVos(), +// DesignPythonItem.OUTWEAR_DRESS_BLOUSE, elementVO.getHasUseMd5List()); +// if (StringUtils.isEmpty(libraryVo)) { +// //系统获取 +// SysFileVO sysFileVO = getRandomSysFileOutwear(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); +// DesignPythonItem item = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); +// item.setBusinessId(sysFileVO.getId()); +// items.add(item); +// return items; +// } +// DesignPythonItem item = coverToDesignPythonItem(null, libraryVo.getLevel2Type(), libraryVo.getUrl(), elementVO); +// item.setBusinessId(libraryVo.getId()); +// elementVO.getHasUseMd5List().add(libraryVo.getMd5()); +// items.add(item); +// } +// break; + case SYS_FILE: + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.OUTWEAR_DRESS_BLOUSE.contains(elementVO.getSwitchCategory())) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); + DesignPythonItem item = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + item.setBusinessId(sysFileVO.getId()); + items.add(item); + return items; + } + } else { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileOutwear(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); + DesignPythonItem item = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + item.setBusinessId(sysFileVO.getId()); + items.add(item); + return items; + } + break; + case NO_PIN: + //single模式 + if (SingleOverallEnum.SINGLE.getRealName().equals(elementVO.getSingleOverall())) { + if (DesignPythonItem.OUTWEAR_DRESS_BLOUSE.contains(elementVO.getSwitchCategory())) { + //非Pin的数据 + List noPinDataByType = getNoPinData( + elementVO.getSketchBoardElements(), Collections.singletonList(elementVO.getSwitchCategory())); + CollectionElement collectionElement = getRandomSketchLibrary(noPinDataByType, elementVO.getHasUseMd5List()); + if (Objects.isNull(collectionElement)) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileByLevel2Type(elementVO.getSwitchCategory(), elementVO.getSysFileIds(), elementVO.getModelSex()); + DesignPythonItem item = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + item.setBusinessId(sysFileVO.getId()); + items.add(item); + } else { + elementVO.getHasUseMd5List().add(collectionElement.getMd5()); + items.add(coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO)); + } + } + } else { + //非Pin的数据 + List noPinData = getNoPinData(elementVO.getSketchBoardElements(), DesignPythonItem.OUTWEAR_DRESS_BLOUSE); + CollectionElement collectionElement = getRandomSketchLibrary(noPinData, elementVO.getHasUseMd5List()); + if (Objects.isNull(collectionElement)) { + //系统获取 + SysFileVO sysFileVO = getRandomSysFileOutwear(elementVO.getSysFileVo(), elementVO.getSysFileIds(), elementVO.getModelSex()); + DesignPythonItem item = coverToDesignPythonItem(null, sysFileVO.getLevel2Type(), sysFileVO.getUrl(), elementVO); + item.setBusinessId(sysFileVO.getId()); + items.add(item); + } else { + elementVO.getHasUseMd5List().add(collectionElement.getMd5()); + items.add(coverToDesignPythonItem(collectionElement.getId(), collectionElement.getLevel2Type(), collectionElement.getUrl(), elementVO)); + } + } + break; + default: + } + return items; + } + + private DesignPythonItem coverToDesignPythonItem(Long elementId, String type, String path, + ValidateElementVO elementVO) { + DesignPythonItem designPythonItemBlouse = new DesignPythonItem(); + if (Objects.nonNull(elementId)) { + designPythonItemBlouse.setElementId(elementId); + designPythonItemBlouse.setBusinessId(elementId); + } + designPythonItemBlouse.setType(type); + designPythonItemBlouse.setPath(path); + //所有的icon都是none + designPythonItemBlouse.setIcon("none"); + CollectionColorDTO randomColor = getRandomColor(elementVO.getColorBoards()); + if (Objects.nonNull(randomColor)) { + designPythonItemBlouse.setColor(randomColor.getRgbValue()); + designPythonItemBlouse.setGradient(randomColor.getGradientMinioUrl()); + designPythonItemBlouse.setGradientString(randomColor.getGradientString()); + } + if (!elementVO.getDesignPythonItemPrint().getPath().equals("none") + && elementVO.getDesignPrintPictureTypeLayoutList().contains(type)) { + DesignPythonItemPrint designPythonItemPrint = CopyUtil.copyObject(elementVO.getDesignPythonItemPrint(), DesignPythonItemPrint.class); +// designPythonItemPrint.setIfSingle(false); + designPythonItemPrint.setPrint_path_list(Collections.singletonList(designPythonItemPrint.getPath())); + designPythonItemBlouse.setPrint(new PrintToPython(designPythonItemPrint)); + } else { + DesignPythonItemPrint designPythonItemPrint = new DesignPythonItemPrint(); +// designPythonItemPrint.setIfSingle(false); + designPythonItemPrint.setPrint_path_list(new ArrayList<>()); + designPythonItemBlouse.setPrint(new PrintToPython(designPythonItemPrint)); + } + return designPythonItemBlouse; + } + + private DesignPythonItem coverSketchToDesignPythonItem(Long elementId, CollectionElement collectionElement, ValidateElementVO elementVO) { + DesignPythonItem designPythonItemBlouse = new DesignPythonItem(); + if (Objects.nonNull(elementId)) { + designPythonItemBlouse.setElementId(elementId); + designPythonItemBlouse.setBusinessId(elementId); + } + designPythonItemBlouse.setType(collectionElement.getLevel2Type()); + designPythonItemBlouse.setPath(collectionElement.getUrl()); + //所有的icon都是none + designPythonItemBlouse.setIcon("none"); + CollectionColorDTO randomColor = getRandomColor(elementVO.getColorBoards()); + if (Objects.nonNull(randomColor)) { + designPythonItemBlouse.setColor(randomColor.getRgbValue()); + designPythonItemBlouse.setGradient(randomColor.getGradientMinioUrl()); + designPythonItemBlouse.setGradientString(randomColor.getGradientString()); + } + if (!elementVO.getDesignPythonItemPrint().getPath().equals("none") + && elementVO.getDesignPrintPictureTypeLayoutList().contains(collectionElement.getLevel2Type())) { + DesignPythonItemPrint designPythonItemPrint = CopyUtil.copyObject(elementVO.getDesignPythonItemPrint(), DesignPythonItemPrint.class); +// designPythonItemPrint.setIfSingle(false); + designPythonItemPrint.setPrint_path_list(Collections.singletonList(designPythonItemPrint.getPath())); + designPythonItemBlouse.setPrint(new PrintToPython(designPythonItemPrint)); + } else { + DesignPythonItemPrint designPythonItemPrint = new DesignPythonItemPrint(); +// designPythonItemPrint.setIfSingle(false); + designPythonItemPrint.setPrint_path_list(new ArrayList<>()); + designPythonItemBlouse.setPrint(new PrintToPython(designPythonItemPrint)); + } + return designPythonItemBlouse; + } + + private DesignPythonItem coverSystemSketchUrlToDesignPythonItem(String url, String category, ValidateElementVO elementVO) { + DesignPythonItem designPythonItemBlouse = new DesignPythonItem(); +// if (Objects.nonNull(elementId)) { +// designPythonItemBlouse.setElementId(null); +// designPythonItemBlouse.setBusinessId(null); +// } + designPythonItemBlouse.setType(category); + designPythonItemBlouse.setPath(url); + //所有的icon都是none + designPythonItemBlouse.setIcon("none"); + CollectionColorDTO randomColor = getRandomColor(elementVO.getColorBoards()); + if (Objects.nonNull(randomColor)) { + designPythonItemBlouse.setColor(randomColor.getRgbValue()); + designPythonItemBlouse.setGradient(randomColor.getGradientMinioUrl()); + designPythonItemBlouse.setGradientString(randomColor.getGradientString()); + } + if (!elementVO.getDesignPythonItemPrint().getPath().equals("none") + && elementVO.getDesignPrintPictureTypeLayoutList().contains(category)) { + DesignPythonItemPrint designPythonItemPrint = CopyUtil.copyObject(elementVO.getDesignPythonItemPrint(), DesignPythonItemPrint.class); +// designPythonItemPrint.setIfSingle(false); + designPythonItemPrint.setPrint_path_list(Collections.singletonList(designPythonItemPrint.getPath())); + designPythonItemBlouse.setPrint(new PrintToPython(designPythonItemPrint)); + } else { + DesignPythonItemPrint designPythonItemPrint = new DesignPythonItemPrint(); +// designPythonItemPrint.setIfSingle(false); + designPythonItemPrint.setPrint_path_list(new ArrayList<>()); + designPythonItemBlouse.setPrint(new PrintToPython(designPythonItemPrint)); + } + return designPythonItemBlouse; + } + + private List residuePinData(List pinData, List existPinDataIds, List hasUseMd5List) { + if (CollectionUtils.isEmpty(pinData)) { + return null; + } + return pinData.stream().filter(v -> (!existPinDataIds.contains(v.getId())) + && (!hasUseMd5List.contains(v.getMd5()))).collect(Collectors.toList()); + } + + private DesignPythonBasic coverToBasic(DesignPythonItem designPythonItem, String singleOverall, + String switchCategory, DesignLibraryModelPointVO designLibraryModelPoint, DesignLibraryModelPointVO designLibraryModelPointVO) { + DesignPythonBasic basic = new DesignPythonBasic(); + basic.setSingle_overall(singleOverall); + basic.setSwitch_category(switchCategory); +// basic.setSave_name(getPythonOutputPath( +// StringUtils.isEmpty(designPythonItem.getPath()) ? designPythonItem.getBody_path() : designPythonItem.getPath(), +// PythonToJavaApiOperationTypeEnum.DESIGN_COLLECTION)); + basic.setScale_bag(0.7); + basic.setSelf_template(Boolean.FALSE); + if (Objects.nonNull(designLibraryModelPoint)) { + basic.setSelf_template(Boolean.TRUE); + } + basic.setScale_earrings(0.16); + if (Objects.nonNull(designLibraryModelPointVO)) { + basic.setBody_point_test(getMap(designLibraryModelPointVO)); + }else { + basic.setBody_point_test(getMap(designLibraryModelPoint)); + } + return basic; + } + + private DesignLibraryModelPointVO getRandomDesignLibraryModelPoint(List mannequins) { + DesignLibraryModelPointVO vo = new DesignLibraryModelPointVO(); + Random random = new Random(); + int randomNumber = random.nextInt(mannequins.size()); + return mannequins.get(randomNumber); + + } + + private Map getMap(DesignLibraryModelPointVO designLibraryModelPointOld) { + Map body_point = Maps.newHashMap(); + if (Objects.nonNull(designLibraryModelPointOld)) { + DesignLibraryModelPointVO designLibraryModelPoint = + CopyUtil.copyObject(designLibraryModelPointOld, DesignLibraryModelPointVO.class); + //自己的template是6个点 + body_point.put("shoulder_left", resolve(designLibraryModelPoint.getShoulderLeft())); + body_point.put("shoulder_right", resolve(designLibraryModelPoint.getShoulderRight())); + body_point.put("waistband_left", resolve(designLibraryModelPoint.getWaistbandLeft())); + body_point.put("waistband_right", resolve(designLibraryModelPoint.getWaistbandRight())); + body_point.put("hand_point_left", resolve(designLibraryModelPoint.getHandLeft())); + body_point.put("hand_point_right", resolve(designLibraryModelPoint.getHandRight())); + body_point.put("relation_id", designLibraryModelPoint.getRelationId()); + body_point.put("relation_type", designLibraryModelPoint.getRelationType()); + } else { + //默认是13个点 + body_point.put("shoulder_left", Arrays.asList(755, 519)); + body_point.put("shoulder_right", Arrays.asList(912, 519)); + body_point.put("waistband_left", Arrays.asList(777, 725)); + body_point.put("waistband_right", Arrays.asList(891, 725)); + body_point.put("hand_point_left", Arrays.asList(754, 886)); + body_point.put("hand_point_right", Arrays.asList(915, 886)); + body_point.put("head_point_up", Arrays.asList(834, 390)); + body_point.put("head_point_left", Arrays.asList(804, 424)); + body_point.put("head_point_right", Arrays.asList(864, 424)); + body_point.put("toe_left", Arrays.asList(817, 1355)); + body_point.put("toe_right", Arrays.asList(850, 1355)); + body_point.put("ear_point_left", Arrays.asList(802, 439)); + body_point.put("ear_point_right", Arrays.asList(865, 438)); + body_point.put("foot_length", Arrays.asList(784, 1336, 825, 1336)); + } + return body_point; + } + + private List resolve(List list) { + List integerList = Lists.newArrayList(); + list.forEach(l -> { + integerList.add(l.intValue()); + }); + return integerList; + } + + private List getPinData(ValidateElementVO elementVO) { + List pinData = getPinData(elementVO.getSketchBoardElements(), elementVO.getHasUseMd5List(), elementVO.getModelSex()); + if (elementVO.getSingleOverall().equals(SingleOverallEnum.SINGLE.getRealName())) { + if (!CollectionUtils.isEmpty(pinData)) { + return pinData.stream().filter(o -> o.getLevel2Type().equals(elementVO.getSwitchCategory())).collect(Collectors.toList()); + } else { + return pinData; + } + } else { + return pinData; + } + } + + private List getPinDataWhole(ValidateElementVO elementVO) { + List pinData = getPinDataWhole(elementVO.getSketchBoardElements(), elementVO.getHasUseMd5List(), elementVO.getModelSex()); + if (elementVO.getSingleOverall().equals(SingleOverallEnum.SINGLE.getRealName())) { + if (!CollectionUtils.isEmpty(pinData)) { + return pinData.stream().filter(o -> o.getLevel2Type().equals(elementVO.getSwitchCategory())).collect(Collectors.toList()); + } else { + return pinData; + } + } else { + return pinData; + } + } + + private List getPinDataWhole(List sketchBoardElements, List hasUseMd5List, String modelSex) { + if (CollectionUtils.isEmpty(sketchBoardElements)) { + return null; + } + List sketchBoardPins = sketchBoardElements + .stream().filter(v -> v.getHasPin() == 1).collect(Collectors.toList()); + if (modelSex.equals(Sex.MALE.getValue())) { + sketchBoardPins = sketchBoardPins.stream().filter(o -> MALE_CATEGORY.contains(o.getLevel2Type())).collect(Collectors.toList()); + } + if (modelSex.equals(Sex.FEMALE.getValue())) { + sketchBoardPins = sketchBoardPins.stream().filter(o -> FEMALE_CATEGORY.contains(o.getLevel2Type())).collect(Collectors.toList()); + } + if (CollectionUtils.isEmpty(sketchBoardPins)) { + return null; + } + return sketchBoardPins; + } + + public final static List FEMALE_CATEGORY = Arrays.asList("Dress", "Blouse", "Skirt", "Trousers", "Outwear"); + public final static List MALE_CATEGORY = Arrays.asList("Tops", "Bottoms", "Outwear"); + + private List getPinData(List sketchBoardElements, List hasUseMd5List, String modelSex) { + if (CollectionUtils.isEmpty(sketchBoardElements)) { + return null; + } + List sketchBoardPins = sketchBoardElements + .stream().filter(v -> v.getHasPin() == 1 && (!hasUseMd5List.contains(v.getMd5()))).collect(Collectors.toList()); + if (modelSex.equals(Sex.MALE.getValue())) { + sketchBoardPins = sketchBoardPins.stream().filter(o -> MALE_CATEGORY.contains(o.getLevel2Type())).collect(Collectors.toList()); + } + if (modelSex.equals(Sex.FEMALE.getValue())) { + sketchBoardPins = sketchBoardPins.stream().filter(o -> FEMALE_CATEGORY.contains(o.getLevel2Type())).collect(Collectors.toList()); + } + if (CollectionUtils.isEmpty(sketchBoardPins)) { + return null; + } + return sketchBoardPins; + } + + private List getNoPinData(ValidateElementVO elementVO) { + if (elementVO.getSingleOverall().equals(SingleOverallEnum.SINGLE.getRealName())) { + List noPinData = getNoPinData(elementVO.getSketchBoardElements(), elementVO.getModelSex()); + if (CollectionUtils.isEmpty(noPinData)) { + return null; + } + return noPinData.stream().filter(o -> o.getLevel2Type().equals(elementVO.getSwitchCategory())).collect(Collectors.toList()); + } else { + return getNoPinData(elementVO.getSketchBoardElements(), elementVO.getModelSex()); + } + } + + private List getNoPinData(List sketchBoardElements, String modelSex) { + if (CollectionUtils.isEmpty(sketchBoardElements)) { + return null; + } + List sketchBoardPins = sketchBoardElements + .stream().filter(v -> v.getHasPin() == 0).collect(Collectors.toList()); + if (modelSex.equals(Sex.MALE.getValue())) { + sketchBoardPins = sketchBoardPins.stream().filter(o -> MALE_CATEGORY.contains(o.getLevel2Type())).collect(Collectors.toList()); + } + if (modelSex.equals(Sex.FEMALE.getValue())) { + sketchBoardPins = sketchBoardPins.stream().filter(o -> FEMALE_CATEGORY.contains(o.getLevel2Type())).collect(Collectors.toList()); + } + if (CollectionUtils.isEmpty(sketchBoardPins)) { + return null; + } + return sketchBoardPins; + } + + private List resolveElementFilterHistoryMd5(List elemet) { + //查询历史design数据 + List md5List = elemet.stream().map(CollectionElement::getMd5).collect(Collectors.toList()); + List designHistories = designHistoryService.getByMD5List(md5List); + if (CollectionUtils.isEmpty(designHistories)) { + return elemet; + } + List existMd5List = designHistories.stream().map(DesignHistory::getMd5).collect(Collectors.toList()); + return elemet.stream().filter(f -> !existMd5List.contains(f.getMd5())).collect(Collectors.toList()); + } + + private List getPinDataByLevel2Type(List sketchBoardElements, String level2Type) { + if (CollectionUtils.isEmpty(sketchBoardElements)) { + return null; + } + List sketchBoardPins = sketchBoardElements + .stream().filter(v -> v.getHasPin() == 1 && v.getLevel2Type().equals(level2Type)).collect(Collectors.toList()); + if (CollectionUtils.isEmpty(sketchBoardPins)) { + return null; + } + return CopyUtil.copyList(sketchBoardPins, CollectionElement.class); + } + + private List getNoPinData(List sketchBoardElements, List Level2TypeList) { + if (CollectionUtils.isEmpty(sketchBoardElements)) { + return null; + } + List sketchBoardPins = sketchBoardElements + .stream().filter(v -> v.getHasPin() == 0 && Level2TypeList.contains(v.getLevel2Type())).collect(Collectors.toList()); + if (CollectionUtils.isEmpty(sketchBoardPins)) { + return null; + } + return CopyUtil.copyList(sketchBoardPins, CollectionElement.class); + } + + private SysFileVO getRandomSysFileOutwear(List sysFileVo, List sysFileIds, String modelSex) { + Long randomIndex = RandomsUtil.randomSysFile(0L, 3L); + if (CollectionUtils.isEmpty(sysFileVo)) { + return getRandomSysFileByLevel2Type(DesignPythonItem.OUTWEAR_DRESS_BLOUSE.get(randomIndex.intValue()), sysFileIds, modelSex); + } else { + //attribute_retrieval 算法,满足blouse + outwear+dress>8,以及 skirt+trousers>8 + return getRandomSysFileByAttributeRetrieval(DesignPythonItem.OUTWEAR_DRESS_BLOUSE, sysFileVo, sysFileIds); + } + } + + private SysFileVO getRandomSysFileMaleTops(List sysFileVo, List sysFileIds, String modelSex) { + Long randomIndex = RandomsUtil.randomSysFile(0L, 1L); + if (CollectionUtils.isEmpty(sysFileVo)) { + return getRandomSysFileByLevel2Type(DesignPythonItem.TOPS.get(randomIndex.intValue()), sysFileIds, modelSex); + } else { + //attribute_retrieval 算法,满足blouse + outwear+dress>8,以及 skirt+trousers>8 + return getRandomSysFileByAttributeRetrieval(DesignPythonItem.TOPS, sysFileVo, sysFileIds); + } + } + + private SysFileVO getRandomSysFileMaleBottoms(List sysFileVo, List sysFileIds, String modelSex) { + Long randomIndex = RandomsUtil.randomSysFile(0L, 1L); + if (CollectionUtils.isEmpty(sysFileVo)) { + return getRandomSysFileByLevel2Type(DesignPythonItem.BOTTOMS.get(randomIndex.intValue()), sysFileIds, modelSex); + } else { + //attribute_retrieval 算法,满足blouse + outwear+dress>8,以及 skirt+trousers>8 + return getRandomSysFileByAttributeRetrieval(DesignPythonItem.BOTTOMS, sysFileVo, sysFileIds); + } + } + + private SysFileVO getRandomSysFileSkirt(List sysFileVo, List sysFileIds, String modelSex) { + Long randomIndex = RandomsUtil.randomSysFile(0L, 2L); + if (CollectionUtils.isEmpty(sysFileVo)) { + return getRandomSysFileByLevel2Type(DesignPythonItem.SKIRT_TROUSERS.get(randomIndex.intValue()), sysFileIds, modelSex); + } else { + //attribute_retrieval 算法,满足blouse + outwear+dress>8,以及 skirt+trousers>8 + return getRandomSysFileByAttributeRetrieval(DesignPythonItem.SKIRT_TROUSERS, sysFileVo, sysFileIds); + } + } + + private SysFileVO getRandomSysFileByLevel2Type(String level2Type, List sysFileIds, String modelSex) { + Long maxId = sysFileService.getMaxIdByLevel2Type(level2Type, modelSex); + Long minId = sysFileService.getMinIdByLevel2Type(level2Type, modelSex); + Long sysFileId = null; + do { + sysFileId = RandomsUtil.randomSysFile(minId, maxId + 1); + } while (sysFileIds.contains(sysFileId)); + sysFileIds.add(sysFileId); + return sysFileService.getById(sysFileId); + } + + private SysFileVO getRandomSysFileByAttributeRetrieval(List level2TypeList, List sysFileVo, List sysFileIds) { + sysFileVo = sysFileVo.stream().filter( + f -> level2TypeList.contains(f.getLevel2Type()) && (!sysFileIds.contains(f.getId()))) + .collect(Collectors.toList()); + Long maxId = (long) sysFileVo.size(); + Long minId = 0L; + Long key = null; + Long sysFileId = null; + do { + key = RandomsUtil.randomSysFile(minId, maxId); + sysFileId = sysFileVo.get(key.intValue()).getId(); + } while (sysFileIds.contains(sysFileId)); + sysFileIds.add(sysFileId); + return sysFileVo.get(key.intValue()); + } + + private CollectionColorDTO getRandomColor(List colorBoards) { + if (CollectionUtils.isEmpty(colorBoards)) { + return null; + } + if (colorBoards.size() == 1) { + return colorBoards.get(0); + } + long maxColor = colorBoards.size(); + long minColor = 0; + Long randomIndex = RandomsUtil.randomSysFile(minColor, maxColor); + return colorBoards.get(randomIndex.intValue()); + } + + private CollectionElement getRandomSketchLibrary(List sketchBoardElementOlds, List hasUseMd5List) { + if (CollectionUtil.isEmpty(sketchBoardElementOlds)) { + return null; + } + List sketchBoardElements = sketchBoardElementOlds.stream().filter(f -> !hasUseMd5List.contains(f.getMd5())).collect(Collectors.toList()); + if (CollectionUtils.isEmpty(sketchBoardElements)) { + return null; + } + if (sketchBoardElements.size() == 1) { + return sketchBoardElements.get(0); + } + long maxSketch = sketchBoardElements.size(); + long minSketch = 0; + Long randomIndex = RandomsUtil.randomSysFile(minSketch, maxSketch); + return sketchBoardElements.get(randomIndex.intValue()); + } + + private DesignPythonItemPrint getRandomPrint(ValidateElementVO elementVO, CurrentDesignPrintPictureTypeEnum designPrintPictureType) { + //print 不取library的 只取element的 + DesignPythonItemPrint print = new DesignPythonItemPrint(); + if (CollectionUtil.isEmpty(elementVO.getPrintBoardElements())) { + print.setPath("none"); + return print; + } + List printBoardElements; + if (designPrintPictureType.equals(CurrentDesignPrintPictureTypeEnum.PIN)) { + printBoardElements = elementVO.getPrintBoardElements() + .stream() + .filter(f -> !elementVO.getHasUseMd5List().contains(f.getMd5())).collect(Collectors.toList()); + } else { + printBoardElements = elementVO.getPrintBoardElements(); + } + if (CollectionUtil.isEmpty(printBoardElements)) { + print.setPath("none"); + return print; + } + switch (designPrintPictureType) { + case NO: + //print 已用完 + print.setPath("none"); + return print; + case NO_PIN: + printBoardElements = printBoardElements.stream().filter(f -> f.getHasPin() == 0).collect(Collectors.toList()); + break; + case PIN: + printBoardElements = printBoardElements.stream().filter(f -> f.getHasPin() == 1).collect(Collectors.toList()); + break; + default: + } + + if (printBoardElements.size() == 1) { + print.setPath(printBoardElements.get(0).getUrl()); + elementVO.getHasUseMd5List().add(printBoardElements.get(0).getMd5()); + return print; + } + long maxPrint = printBoardElements.size(); + long minPrint = 0; + Long randomIndex = RandomsUtil.randomSysFile(minPrint, maxPrint); + print.setPath(printBoardElements.get(randomIndex.intValue()).getUrl()); + elementVO.getHasUseMd5List().add(printBoardElements.get(randomIndex.intValue()).getMd5()); + return print; + } + + private LibraryVo getRandomLibrary(List libraryOldVos, List containLevel2Type, List hasUseMd5List) { + if (CollectionUtils.isEmpty(libraryOldVos)) { + return null; + } + List libraryVos = libraryOldVos.stream().filter(f -> (!hasUseMd5List.contains(f.getMd5())) && + CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName().equals(f.getLevel1Type())).collect(Collectors.toList()); + if (CollectionUtils.isEmpty(libraryVos)) { + return null; + } + if (StringUtils.isEmpty(containLevel2Type)) { + if (libraryVos.size() == 1) { + return libraryVos.get(0); + } + long maxLibrary = libraryVos.size(); + long minLibrary = 0; + Long randomIndex = RandomsUtil.randomSysFile(minLibrary, maxLibrary); + return libraryVos.get(randomIndex.intValue()); + } else { + List filter = libraryVos.stream().filter(f -> containLevel2Type.contains(f.getLevel2Type())).collect(Collectors.toList()); + if (CollectionUtils.isEmpty(filter)) { + return null; + } + if (filter.size() == 1) { + return filter.get(0); + } + long maxLibrary = filter.size(); + long minLibrary = 0; + Long randomIndex = RandomsUtil.randomSysFile(minLibrary, maxLibrary); + return filter.get(randomIndex.intValue()); + } + + } + + /** + * 生成design服装 + * + * @param designPythonObjects + * @return + */ + public Boolean design(DesignPythonObjects designPythonObjects) { + //限流校验 + AccessLimitUtils.validate("design", 5); + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + //关闭FastJson的引用检测 防止出现$ref 现象 + String param = JSON.toJSONString(designPythonObjects, SerializerFeature.DisableCircularReferenceDetect); + log.info("design请求python 参数:####{}", param); + RequestBody body = RequestBody.create(mediaType, param); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + accessPythonPort + "/api/design") +// .url(fastApiPythonAddress + "/api/design") +// .url(accessPythonIp + ":10200/aifda/api/v1.0/generate") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response = null; + try { + response = client.newCall(request).execute(); + log.info("PythonService##response###{}", response); + log.info("PythonService##responseBodyStr###{}", response.body().string()); + log.info("PythonService##responseBodyJson###{}", JSON.toJSONString(response.body())); + } catch (IOException ioException) { + log.error("PythonService##design异常###{}", ExceptionUtil.getThrowableList(ioException)); + } + //去除限流 + AccessLimitUtils.validateOut("design"); + if (Objects.isNull(response)) { + log.error("PythonService##design异常###{}", "response or body is empty!"); + throw new BusinessException("system error!"); + } + JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(response)); + log.info("PythonService##jsonObject###{}", jsonObject); + Boolean result = jsonObject.getBoolean("successful"); + if (result) { + return Boolean.TRUE; + } + log.info("PythonService##design异常jsonObject###{}", jsonObject); + //生成失败 + throw new BusinessException("generate design exception!"); + } + + /** + * 生成高级图片(废弃) + * + * @param designPath + * @return + */ + public String generateHighDesign(String designPath) { + //限流校验 + AccessLimitUtils.validate("generateHighDesign", 2); + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + Map content = Maps.newHashMap(); + content.put("img_path", designPath); + content.put("img_path_out_put", getPythonOutputPath( + designPath, PythonToJavaApiOperationTypeEnum.GENERATE_ADVANCED_DESIGN)); + MediaType mediaType = MediaType.parse("application/json"); + RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); + Request request = new Request.Builder() + .url(accessPythonIp + ":11111/aifda/api/v1.0/sketch_to_real") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response = null; + try { + log.info("生成高级design请求入参content###{}", JSON.toJSONString(content)); + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##generateHighDesign异常###{}", ExceptionUtil.getThrowableList(ioException)); + } + //去除限流 + AccessLimitUtils.validateOut("generateHighDesign"); + if (Objects.isNull(response)) { + log.error("PythonService##generateHighDesign异常###{}", "response or body is empty!"); + throw new BusinessException("system error!"); + } + JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(response)); + Boolean result = jsonObject.getBoolean("successful"); + if (result) { + return content.get("img_path_out_put"); + } + log.info("生成高级design失败###{}", jsonObject); + //生成失败 + throw new BusinessException("system error!"); + } + + /** + * 生成 attribute_retrieval + * + * @param sketchUrlList + * @param modelSex + * @return + */ + public DesignAttributeRetrievalDTO generateAttributeRetrieval(List sketchUrlList, Long userId, String modelSex) { + //限流校验 + AccessLimitUtils.validate("generateAttributeRetrieval", 4); + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + Map content = Maps.newHashMap(); + content.put("sketch_upload_img_path", sketchUrlList); + content.put("userid", userId); + content.put("colony", modelSex); + MediaType mediaType = MediaType.parse("application/json"); + System.out.println(JSON.toJSONString(content)); + RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + accessPythonPort + "/api/attribute_retrieve") +// .url(fastApiPythonAddress + "/api/attribute_retrieve") +// .url(accessPythonIp+":9991/aifda/api/v1.0/attribute_retrieval") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response; + String bodyStr; + try { + log.info("generateAttributeRetrieval请求入参content###{}", JSON.toJSONString(content)); + response = client.newCall(request).execute(); + } catch (IOException ioException) { + AccessLimitUtils.validateOut("generateAttributeRetrieval"); + log.error("generateAttributeRetrieval异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("attributeRetrieval.interface.exception"); + } + //去除限流 + AccessLimitUtils.validateOut("generateAttributeRetrieval"); + if (response.isSuccessful()) { + try { + if (Objects.nonNull(response.body())) { + bodyStr = response.body().string(); + return resolveDesignAttributeRetrievalDTO(bodyStr); + } + //生成失败 + throw new BusinessException("attributeRetrieval.interface.exception"); + } catch (JSONException | IOException e) { + log.error("generateAttributeRetrieval异常###{}", e.getMessage()); + throw new BusinessException("attributeRetrieval.interface.exception"); + } + } + log.error("generateAttributeRetrieval异常###{}", response); + //生成失败 + throw new BusinessException("attributeRetrieval.interface.exception"); + } + + private static DesignAttributeRetrievalDTO resolveDesignAttributeRetrievalDTO(String bodyStr) { + DesignAttributeRetrievalDTO response = new DesignAttributeRetrievalDTO(); + JSONObject jsonObject = JSON.parseObject(bodyStr); + JSONObject data = jsonObject.getJSONObject("data"); + if (data != null) { + JSONObject jsonObjectSys = data.getJSONObject("sys_lib_dict"); + if (null == jsonObjectSys || jsonObjectSys.isEmpty()) { + log.error("generateAttributeRetrieval异常###{}", "jsonObjectSys is empty!"); + throw new BusinessException("attributeRetrieval.interface.exception"); + } + setUrls(jsonObjectSys, response.getSysFileUrlS()); + JSONObject jsonObjectLibrary = data.getJSONObject("user_lib_dict"); + if (null == jsonObjectLibrary || jsonObjectLibrary.isEmpty()) { + log.error("generateAttributeRetrieval异常###{}", "jsonObjectLibrary is empty!"); + throw new BusinessException("attributeRetrieval.interface.exception"); + } + setUrls(jsonObjectLibrary, response.getLibraryUrls()); + return response; + } + throw new BusinessException("attributeRetrieval.interface.exception"); + } + + private static void setUrls(JSONObject jsonObjectSys, List urls) { + List finalUrls = urls; + SysFileLevel2TypeEnum.ofPythonPath().forEach(path -> { + JSONArray array = jsonObjectSys.getJSONArray(path); + List urlList = JSONObject.parseArray(JSON.toJSONString(array), String.class); + if (CollectionUtil.isNotEmpty(urlList)) { + finalUrls.addAll(urlList); + } + }); + } + + /** + * 组装和计算designSingle参数 + * + * @param designSingleDTO + * @return + */ + public DesignPythonObjects covertDesignSingleParam(DesignSingleDTO designSingleDTO, String singleOverall, + String switchCategory, DesignLibraryModelPointVO designLibraryModelPoint) { + DesignPythonObjects designPythonObjects = new DesignPythonObjects(); + List objects = Lists.newArrayList(); + designPythonObjects.setObjects(objects); + + DesignPythonObject pythonObject = new DesignPythonObject(); + pythonObject.setItems(coverToDesignSinglePythonItem(designSingleDTO, designLibraryModelPoint)); + pythonObject.setBasic(coverToSingleBasic(pythonObject.getItems().get(0), + singleOverall, switchCategory, designSingleDTO.getPriority(), designLibraryModelPoint)); + objects.add(pythonObject); + return designPythonObjects; + } + + /** + * 组装和计算设计包括图层的单品的参数,不需要priority + * + * @param designSingleDTO + * @param singleOverall + * @param switchCategory + * @param designLibraryModelPoint + * @return + */ + public DesignPythonObjects covertDesignSingleParam(DesignSingleIncludeLayersDTO designSingleDTO, String singleOverall, + String switchCategory, DesignLibraryModelPointVO designLibraryModelPoint, + String previewOrSubmit) { + DesignPythonObjects designPythonObjects = new DesignPythonObjects(); + List objects = Lists.newArrayList(); + designPythonObjects.setObjects(objects); + + DesignPythonObject pythonObject = new DesignPythonObject(); + designPythonObjects.setProcess_id(designSingleDTO.getProcessId()); + pythonObject.setItems(coverToDesignSinglePythonItem(designSingleDTO, designLibraryModelPoint, singleOverall)); + pythonObject.setBasic(coverToSingleBasic(singleOverall, switchCategory, designLibraryModelPoint, previewOrSubmit)); + objects.add(pythonObject); + return designPythonObjects; + } + + private List coverToDesignSinglePythonItem(DesignSingleDTO designSingleDTO, DesignLibraryModelPointVO designLibraryModelPoint) { + List designPythonItemDto = designSingleDTO.getClothes(); + if (!CollectionUtils.isEmpty(designSingleDTO.getOthers())) { + designPythonItemDto.addAll(designSingleDTO.getOthers()); + } + List response = CopyUtil.copyList(designPythonItemDto, DesignPythonItem.class, (o, d) -> { + d.setBusinessId(o.getId()); + d.setIcon("none"); +// d.setPrint(resolveDesignSinglePrint(o.getPrintObject(), o.getPath())); + }); + DesignPythonItem body = new DesignPythonItem(); + body.setType(SysFileLevel2TypeEnum.BODY.getRealName()); + if (Objects.nonNull(designLibraryModelPoint)) { + body.setBody_path(designLibraryModelPoint.getTemplateUrl()); + } else { +// body.setBody_path("/home/pangkaicheng/python_code/Multi-layer-Virtual-Try-on/dataset_for_test/Img_model.png"); + body.setBody_path("/workspace/python_code/Multi-layer-Virtual-Try-on/dataset_for_test/Img_model.png"); + } + response.add(body); + return response; + } + + /** + * 设计包括图层的单品,每次只针对一个单品 + * + * @param designSingleIncludeLayersDTO + * @param designLibraryModelPoint + * @return + */ + private List coverToDesignSinglePythonItem(DesignSingleIncludeLayersDTO designSingleIncludeLayersDTO, + DesignLibraryModelPointVO designLibraryModelPoint, + String singleOverall) { + List designSingleItemList = designSingleIncludeLayersDTO.getDesignSingleItemDTOList(); + List response = new ArrayList<>(); + + designSingleItemList.forEach(designSingleItem -> { + Long businessId; + if (!designSingleIncludeLayersDTO.getIsPreview() && designSingleItem.getChanged()) { + String s = String.valueOf(designSingleItem.getId()); + businessId = Long.parseLong(s.substring(0, s.length() - 3)); + } else { + businessId = designSingleItem.getId(); + } + + // 判断是否是渐变色 + String minioPath = null; + String gradientString = null; + if (!Objects.isNull(designSingleItem.getGradient())) { + String colorImg = designSingleItem.getGradient().getColorImg(); + if (StringUtil.isNullOrEmpty(colorImg)) { + throw new BusinessException("base64.data.empty"); + } + minioPath = minioUtil.base64UploadToPath(colorImg, gradientBucketName, null); + designSingleItem.getGradient().setColorImg(null); + gradientString = JSONObject.toJSONString(designSingleItem.getGradient()); + } + + PrintToPython printToPython = resolveDesignSinglePrint(designSingleItem.getPrintObject().getPrints(), + designSingleItem.getPartialDesign().getPartialDesignMinioPath()); + resolveDesignElement(designSingleItem.getTrims(), printToPython); + log.info("组装参数【服装:{}的maskUrl: {}】",designSingleItem.getType(), designSingleItem.getMaskUrl()); + response.add(new DesignPythonItem( + designSingleItem.getType(), + designSingleItem.getPath(), + designSingleItem.getColor(), + printToPython, + // businessId designItemDetailId (python端确认没有作用,但是数据库需要存,作用:未知) +// designSingleItem.getId(), + businessId, + pythonTAllInfoService.getImageIdByPath(designSingleItem.getPath()), + designSingleItem.getOffset(), + designSingleItem.getScale(), + designSingleItem.getPriority(), + minioPath, + gradientString, + designSingleItem.getMaskUrl(), + designSingleItem.getTranspose(), + designSingleItem.getRotate() + )); + + }); + + if (singleOverall.equals("overall")){ + String bodyPath; + if (Objects.nonNull(designLibraryModelPoint)) { + bodyPath = designLibraryModelPoint.getTemplateUrl(); + } else { +// bodyPath = "/workspace/python_code/Multi-layer-Virtual-Try-on/dataset_for_test/Img_model.png"; + bodyPath = "aida-mannequins/model_1693218345.2714432.png"; + } + response.add(new DesignPythonItem(SysFileLevel2TypeEnum.BODY.getRealName(), bodyPath, pythonTAllInfoService.getImageIdByPath(bodyPath))); + } + return response; + } + + + private PrintToPython resolveDesignSinglePrint(List printObject, String partialDesign) { + PrintToPython printToPython = new PrintToPython(); + DesignPythonItemPrint printSingle = new DesignPythonItemPrint(); + DesignPythonItemPrint printOverall = new DesignPythonItemPrint(); + printToPython.setSingle(printSingle); + printToPython.setOverall(printOverall); + printToPython.setPartial(StringUtil.isNullOrEmpty(partialDesign) ? null : partialDesign); + if (Objects.isNull(printObject) || printObject.isEmpty()){ + return printToPython; + } + + // 没有印花时的参数设置 +// if (printObject.getIfSingle().equals(Boolean.FALSE) && CollectionUtil.isEmpty(printObject.getPrints())) { +// return new DesignPythonItemPrint(new ArrayList<>(), false); +// } +// DesignPythonItemPrint print = CopyUtil.copyObject(printObject, DesignPythonItemPrint.class); + + int size = printObject.size(); + // 占位符填充数组 + List> locationS = new ArrayList<>(Collections.nCopies(size, null)); + List> scaleS = new ArrayList<>(Collections.nCopies(size, null)); + List angleS = new ArrayList<>(Collections.nCopies(size, null)); + ArrayList pathsS = new ArrayList<>(Collections.nCopies(size, null)); + + List> locationO = new ArrayList<>(Collections.nCopies(size, null)); + List> scaleO = new ArrayList<>(Collections.nCopies(size, null)); + List angleO = new ArrayList<>(Collections.nCopies(size, null)); + ArrayList pathsO = new ArrayList<>(Collections.nCopies(size, null)); + + // 设置印花的位置、大小、旋转角度 + // 优先级越大,越靠近顶层,在传输给python的数组中,越靠前 +// List prints = printObject.getPrints(); + printObject.forEach(p -> { + p.getLocation().set(0, p.getLocation().get(0)); + p.getLocation().set(1, p.getLocation().get(1)); + Integer priority = p.getPriority(); + setUriToMinioPath(p); + // todo 下标越界问题 + if (p.getIfSingle()){ + locationS.set(priority - 1, p.getLocation()); + scaleS.set(priority - 1, p.getScale()); + angleS.set( priority - 1, p.getAngle()); + pathsS.set(priority - 1, p.getMinIOPath()); + }else { + locationO.set(priority - 1, p.getLocation()); + scaleO.set(priority - 1, p.getScale()); + angleO.set(priority - 1, p.getAngle()); + pathsO.set(priority - 1, p.getMinIOPath()); + } +// log.info("本次print打点locations###{}###fileVO{}", p.getLocation(), JSON.toJSONString(fileVO)); + }); + locationS.removeAll(Collections.singleton(null)); + scaleS.removeAll(Collections.singleton(null)); + angleS.removeAll(Collections.singleton(null)); + pathsS.removeAll(Collections.singleton(null)); + printSingle.setLocation(locationS); + printSingle.setPrint_scale_list(scaleS); + printSingle.setPrint_angle_list(angleS); + printSingle.setPrint_path_list(pathsS); + + locationO.removeAll(Collections.singleton(null)); + scaleO.removeAll(Collections.singleton(null)); + angleO.removeAll(Collections.singleton(null)); + pathsO.removeAll(Collections.singleton(null)); + printOverall.setLocation(locationO); + printOverall.setPrint_scale_list(scaleO); + printOverall.setPrint_angle_list(angleO); + printOverall.setPrint_path_list(pathsO); + + return printToPython; + } + + // 对印花类型为Generate的图片路径进行特殊处理 + private void setUriToMinioPath(DesignSinglePrint print){ + if (!StringUtil.isNullOrEmpty(print.getDesignType()) && print.getDesignType().equals("Generate")){ + if (!StringUtil.isNullOrEmpty(print.getPath())){ + try { + URI uri = new URI(print.getPath()); + String path = uri.getPath(); // 获取路径部分: /aida-users/87/print/9ac32f65-6043-424d-a146-92c9c6d204ee-4-87.png + String substring = path.substring(1); + print.setMinIOPath(substring); + } catch (URISyntaxException e) { + throw new BusinessException(e.getMessage()); + } + } else { + log.error("designType为Generate的印花path传值为空 :{}", print.getPath()); + throw new BusinessException("path.cannot.be.empty"); + } + } + } + + private void resolveDesignElement(DesignSinglePrintDTO trims, PrintToPython printToPython) { + // 没有design element 时的参数设置 + DesignPythonItemElement element = new DesignPythonItemElement(); + if (CollectionUtil.isEmpty(trims.getPrints())) { + printToPython.setElement(element); + return; + } + + + int size = trims.getPrints().size(); + // 占位符填充数组 + List> location = new ArrayList<>(Collections.nCopies(size, null)); + List> scale = new ArrayList<>(Collections.nCopies(size, null)); + List angle = new ArrayList<>(Collections.nCopies(size, null)); + ArrayList paths = new ArrayList<>(Collections.nCopies(size, null)); + + // 设置印花的位置、大小、旋转角度 + // 优先级越大,越靠近顶层,在传输给python的数组中,越靠前 + List prints = trims.getPrints(); + prints.forEach(p -> { + p.getLocation().set(0, p.getLocation().get(0)); + p.getLocation().set(1, p.getLocation().get(1)); + p.getScale().set(0, p.getScale().get(0)); + p.getScale().set(1, p.getScale().get(1)); + Integer priority = p.getPriority(); + location.set(priority - 1, p.getLocation()); + scale.set(priority - 1, p.getScale()); + angle.set(priority - 1, p.getAngle()); + paths.set(priority - 1, p.getMinIOPath()); +// log.info("本次print打点locations###{}###fileVO{}", p.getLocation(), JSON.toJSONString(fileVO)); + }); + element.setLocation(location); + element.setElement_scale_list(scale); + element.setElement_angle_list(angle); + element.setElement_path_list(paths); + printToPython.setElement(element); + } + + private DesignPythonBasic coverToSingleBasic(DesignPythonItem designPythonItem, String singleOverall, + String switchCategory, List priority, + DesignLibraryModelPointVO designLibraryModelPoint) { + DesignPythonBasic basic = new DesignPythonBasic(); + basic.setSingle_overall(singleOverall); + basic.setSwitch_category(switchCategory); + basic.setSave_name(getPythonOutputPath( + StringUtils.isEmpty(designPythonItem.getPath()) ? designPythonItem.getBody_path() : designPythonItem.getPath(), + PythonToJavaApiOperationTypeEnum.DESIGN_COLLECTION)); + basic.setPriority(priority); + basic.setSelf_template(Boolean.FALSE); + if (Objects.nonNull(designLibraryModelPoint)) { + basic.setSelf_template(Boolean.TRUE); + } + basic.setScale_bag(0.7); + basic.setScale_earrings(0.16); + basic.setBody_point_test(getMap(designLibraryModelPoint)); + return basic; + } + + /** + * 设计包括图层的单品,不用指定save_name和priority + * + * @param singleOverall + * @param switchCategory + * @param designLibraryModelPoint + * @return + */ + private DesignPythonBasic coverToSingleBasic(String singleOverall, String switchCategory, + DesignLibraryModelPointVO designLibraryModelPoint, + String previewOrSubmit) { + DesignPythonBasic basic = new DesignPythonBasic(); + basic.setSingle_overall(singleOverall); + basic.setSwitch_category(switchCategory); + basic.setSelf_template(Boolean.FALSE); + if (Objects.nonNull(designLibraryModelPoint)) { + basic.setSelf_template(Boolean.TRUE); + } + basic.setScale_bag(0.7); + basic.setScale_earrings(0.16); + basic.setBody_point_test(getMap(designLibraryModelPoint)); + basic.setLayer_order(Boolean.TRUE); + basic.setPreview_submit(previewOrSubmit); + return basic; + } + + /** + * 组装和计算designSingle参数 + * + * @param modelsDotDTO + * @return + */ + public DesignPythonObjects covertModelsDotParam(ModelsDotDTO modelsDotDTO, String singleOverall, String switchCategory) { + DesignPythonObjects designPythonObjects = new DesignPythonObjects(); + List objects = Lists.newArrayList(); + designPythonObjects.setObjects(objects); + designPythonObjects.setProcess_id(UUID.randomUUID().toString()); + DesignPythonObject pythonObject = new DesignPythonObject(); + pythonObject.setItems(coverToModelsDotPythonItem(modelsDotDTO)); + pythonObject.setBasic(coverToModelsDotBasic(pythonObject.getItems().get(0), modelsDotDTO)); + objects.add(pythonObject); + return designPythonObjects; + } + + private List coverToModelsDotPythonItem(ModelsDotDTO modelsDotDTO) { + List response = Lists.newArrayList(); + if (modelsDotDTO.getSex().contains("Female")) { + DesignPythonItem dress = new DesignPythonItem(); + dress.setType(SysFileLevel2TypeEnum.BLOUSE.getRealName()); + dress.setColor("none"); + dress.setIcon("none"); + DesignPythonItemPrint designPythonItemPrint = new DesignPythonItemPrint(); +// designPythonItemPrint.setIfSingle(false); + designPythonItemPrint.setPrint_path_list(new ArrayList<>()); + dress.setPrint(new PrintToPython(designPythonItemPrint)); + dress.setPath("aida-sys-image/images/female/blouse/0628001551.jpg"); + dress.setColor("255 255 255"); + response.add(dress); + + DesignPythonItem skirt = new DesignPythonItem(); + skirt.setType(SysFileLevel2TypeEnum.SKIRT.getRealName()); + skirt.setColor("none"); + skirt.setIcon("none"); + DesignPythonItemPrint designPythonItemPrint1 = new DesignPythonItemPrint(); +// designPythonItemPrint1.setIfSingle(false); + designPythonItemPrint1.setPrint_path_list(new ArrayList<>()); + skirt.setPrint(new PrintToPython(designPythonItemPrint1)); + skirt.setPath("aida-sys-image/images/female/skirt/0628000022.jpg"); + skirt.setColor("255 255 255"); +// skirt.setPath("aida-sys-image/images/female/dress/0628000000.jpg"); + response.add(skirt); + } else { + DesignPythonItem top = new DesignPythonItem(); + top.setType(MalePosition.TOPS.getValue()); + top.setColor("none"); + top.setIcon("none"); + DesignPythonItemPrint designPythonItemPrint = new DesignPythonItemPrint(); +// designPythonItemPrint.setIfSingle(false); + designPythonItemPrint.setPrint_path_list(new ArrayList<>()); + top.setPrint(new PrintToPython(designPythonItemPrint)); + top.setPath("aida-sys-image/images/male/tops/mens_test_10.png"); + top.setColor("255 255 255"); + response.add(top); + + DesignPythonItem bottom = new DesignPythonItem(); + bottom.setType(MalePosition.BOTTOMS.getValue()); + bottom.setColor("none"); + bottom.setIcon("none"); + DesignPythonItemPrint designPythonItemPrint1 = new DesignPythonItemPrint(); +// designPythonItemPrint1.setIfSingle(false); + designPythonItemPrint1.setPrint_path_list(new ArrayList<>()); + bottom.setPrint(new PrintToPython(designPythonItemPrint1)); + bottom.setPath("aida-sys-image/images/male/bottoms/mens_test_6252.png"); + bottom.setColor("255 255 255"); + response.add(bottom); + } + + DesignPythonItem body = new DesignPythonItem(); + body.setType(SysFileLevel2TypeEnum.BODY.getRealName()); + body.setBody_path(modelsDotDTO.getTemplateUrl()); + response.add(body); + return response; + } + + private DesignPythonBasic coverToModelsDotBasic(DesignPythonItem designPythonItem, ModelsDotDTO modelsDotDTO) { + DesignPythonBasic basic = new DesignPythonBasic(); + basic.setSingle_overall(SingleOverallEnum.OVERALL.getRealName()); + basic.setSwitch_category(""); + basic.setSave_name(getPythonOutputPath( + StringUtils.isEmpty(designPythonItem.getPath()) ? designPythonItem.getBody_path() : designPythonItem.getPath(), + PythonToJavaApiOperationTypeEnum.DESIGN_COLLECTION)); + basic.setSelf_template(Boolean.TRUE); + basic.setScale_bag(0.7); + basic.setScale_earrings(0.16); + + basic.setBody_point_test(getMap(calculateTemplatePoint(modelsDotDTO, modelsDotDTO.getHigh(), modelsDotDTO.getWidth()))); + return basic; + } + + public DesignLibraryModelPointVO calculateTemplatePoint(ModelsDotDTO modelsDotDTO, Integer high, Integer width) { + DesignLibraryModelPointVO libraryModelPoint = new DesignLibraryModelPointVO(); + libraryModelPoint.setHandLeft(calculateTemplatePointOne(modelsDotDTO.getHandLeft(), high, width)); + libraryModelPoint.setHandRight(calculateTemplatePointOne(modelsDotDTO.getHandRight(), high, width)); + libraryModelPoint.setShoulderLeft(calculateTemplatePointOne(modelsDotDTO.getShoulderLeft(), high, width)); + libraryModelPoint.setShoulderRight(calculateTemplatePointOne(modelsDotDTO.getShoulderRight(), high, width)); + libraryModelPoint.setWaistbandLeft(calculateTemplatePointOne(modelsDotDTO.getWaistbandLeft(), high, width)); + libraryModelPoint.setWaistbandRight(calculateTemplatePointOne(modelsDotDTO.getWaistbandRight(), high, width)); + return libraryModelPoint; + } + + private List calculateTemplatePointOne(List originRatioList, Integer high, Integer width) { + originRatioList.set(0, originRatioList.get(0).multiply(BigDecimal.valueOf(width))); + originRatioList.set(1, originRatioList.get(1).multiply(BigDecimal.valueOf(high))); + return originRatioList; + } + + public JSONObject designNew(DesignPythonObjects designPythonObjects) { + // todo 限流校验 +// AccessLimitUtils.validate("design",5); + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + //关闭FastJson的引用检测 防止出现$ref 现象 + String param = JSON.toJSONString(designPythonObjects, SerializerFeature.DisableCircularReferenceDetect); + log.info("design请求python 参数:####{}", param); + RequestBody body = RequestBody.create(mediaType, param); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + accessPythonPort + "/api/design") +// .url(fastApiPythonAddress + "/api/design") +// .url(accessPythonIp + ":10200/aifda/api/v1.0/generate") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response; + String responseBody; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + AccessLimitUtils.validateOut("design"); + log.error("PythonService##design异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("design.interface.exception"); + } + //去除限流 +// AccessLimitUtils.validateOut("design"); + if (response.isSuccessful()) { + try { + if (Objects.nonNull(response.body())) { + responseBody = response.body().string(); + JSONObject responseObject = JSON.parseObject(responseBody); + log.info("PythonService##responseObject###{}", responseObject); + return responseObject; + } + throw new BusinessException("design.interface.exception"); + } catch (IOException | JSONException e) { + log.error("PythonService##design异常###{}", e.getMessage()); + throw new BusinessException("design.interface.exception"); + } + } + log.error("PythonService##design异常response###{}", response); + //生成失败 + throw new BusinessException("design.interface.exception"); + } + + public JSONObject designStream(DesignPythonObjects designPythonObjects) { + // todo 限流校验 +// AccessLimitUtils.validate("design",5); + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + //关闭FastJson的引用检测 防止出现$ref 现象 + String param = JSON.toJSONString(designPythonObjects, SerializerFeature.DisableCircularReferenceDetect); + log.info("design请求python 参数:####{}", param); + RequestBody body = RequestBody.create(mediaType, param); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + accessPythonPort + "/api/design_v2") +// .url(fastApiPythonAddress + "/api/design") +// .url(accessPythonIp + ":10200/aifda/api/v1.0/generate") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response; + String responseBody; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + AccessLimitUtils.validateOut("design"); + log.error("PythonService##design异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("design.interface.exception"); + } + //去除限流 +// AccessLimitUtils.validateOut("design"); + if (response.isSuccessful()) { + try { + if (Objects.nonNull(response.body())) { + responseBody = response.body().string(); + JSONObject responseObject = JSON.parseObject(responseBody); + log.info("PythonService##responseObject###{}", responseObject); + return responseObject; + } + throw new BusinessException("design.interface.exception"); + } catch (IOException | JSONException e) { + log.error("PythonService##design异常###{}", e.getMessage()); + throw new BusinessException("design.interface.exception"); + } + } + log.error("PythonService##design异常response###{}", response); + //生成失败 + throw new BusinessException("design.interface.exception"); + } + + /** + * 暂时未用 + */ + public String generateSketchCaption(String url) { + //限流校验 + AccessLimitUtils.validate("generateSketchCaption", 5); + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + RequestBody body = RequestBody.create(mediaType, url); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + accessPythonPort + "/aida/interrogator") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response = null; + String bodyStr = null; + try { + log.info("generateSketchCaption请求入参content###{}", url); + response = client.newCall(request).execute(); + bodyStr = response.body().string(); + } catch (IOException ioException) { + log.error("generateSketchCaption异常###{}", ExceptionUtil.getThrowableList(ioException)); + } + //去除限流 + AccessLimitUtils.validateOut("generateSketchCaption"); + if (Objects.isNull(response)) { + log.error("generateSketchCaption异常###{}", "response or body is empty!"); + throw new BusinessException("system error!"); + } + JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(response)); + Boolean result = jsonObject.getBoolean("successful"); + if (result) { + return bodyStr; + } + log.info("attribute_retrieval失败###{}", bodyStr); + //生成失败 + throw new BusinessException("system error!"); + } + + public Boolean generateSketchOrPrint(String params, String port, String servicePath) { + //限流校验 +// AccessLimitUtils.validate("generateSketchOrPrint", 5); + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); +// RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(generateToPythonDTO, SerializerFeature.WriteMapNullValue)); + RequestBody body = RequestBody.create(mediaType, params); + + log.info("generate 请求地址: {}", accessPythonIp + ":" + port + servicePath); + Request request = new Request.Builder() +// .url("http://18.167.251.121:9992") +// .url("http://127.0.0.1:5000/api/diffusion") +// .url(accessPythonIp + ":" + accessPythonPort + "/api/diffusion") +// .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_image") + .url(accessPythonIp + ":" + port + servicePath) + .method("POST", body) +// .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response = null; + String bodyString; + try { +// log.info("generateSketchOrPrint请求入参content###{}", JSON.toJSONString(generateToPythonDTO, SerializerFeature.WriteMapNullValue)); + log.info("generateSketchOrPrint请求入参content###{}", params); + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##generateSketchOrPrint异常###{}", ExceptionUtil.getThrowableList(ioException)); +// throw new BusinessException("generate.interface.error"); + throw new BusinessException(ioException.getMessage()); + } + //去除限流 +// AccessLimitUtils.validateOut("generateSketchOrPrint"); + + // 判断是否生成失败 + if (Objects.isNull(response.body())) { + log.error("PythonService##generateSketchOrPrint异常###{}", "response or body is empty!"); +// throw new BusinessException("generate.interface.error"); + throw new BusinessException("PythonService##generateSketchOrPrint异常###: response or body is empty!"); + } else if (response.code() != HttpURLConnection.HTTP_OK) { + log.error("PythonService##generateSketchOrPrint异常###{}", "Response error!Response code ## " + response.code() + " ##"); +// throw new BusinessException("generate.interface.error"); + throw new BusinessException("PythonService##generateSketchOrPrint异常### Response error!Response code ## " + response.code() + " ##"); + } else { + try { + bodyString = response.body().string(); + } catch (IOException e) { + log.error(e.getMessage()); +// throw new BusinessException("generate.interface.error"); + throw new BusinessException(e.getMessage()); + } + } + JSONObject jsonObject = JSON.parseObject(bodyString); + Boolean result = JSON.parseObject(JSON.toJSONString(response)).getBoolean("successful"); + + if (result && jsonObject.get("code").equals(200)) { + log.info("Generate##responseObject###{}", jsonObject); +// return setGenerateImageList(jsonObject.getJSONObject("data")); + return Boolean.TRUE; + } else { + log.info("generateSketchOrPrintPrint失败###{}", jsonObject); + log.info("Generate Exception! Code : " + jsonObject.get("code")); + return Boolean.FALSE; + } + } + + public Response sendPostToModel(String content, String portAndRoute, String functionName) { + + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + RequestBody body = RequestBody.create(mediaType, content); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + accessPythonPort + portAndRoute) +// .url(fastApiPythonAddress + portAndRoute) + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response = null; +// String bodyString = null; + try { + log.info(functionName + "请求入参content###{}", content); + response = client.newCall(request).execute(); +// bodyString = response.body().string(); + } catch (IOException ioException) { + log.error("PythonService##" + functionName + "异常###{}", ExceptionUtil.getThrowableList(ioException)); + } + return response; + } + +/* private List setGenerateImageList(JSONObject jsonObject) { + List imageUrlList = JSONObject.parseArray(jsonObject.get("list").toString(), String.class); + if (imageUrlList.isEmpty()) { + log.error("PythonService##generateSketchOrPrint异常###{}", "diffusion response list is null"); + // 如果这里返回为空,是判断出错还是返回给前端空 + throw new BusinessException("The data returned on the python side is empty"); + } + + return imageUrlList; + }*/ + /** 废弃状态 */ + public String composeLayers(List layersDetail) { + HashMap> layers = new HashMap<>(); + HashMap>> content = new HashMap<>(); + layers.put("layers", layersDetail); + content.put("0", layers); + String jsonString = JSON.toJSONString(content, SerializerFeature.WriteNullStringAsEmpty); + + // todo 添加限流 + Response response = this.sendPostToModel(jsonString, "/api/preview_control", "composeLayers"); + // todo 结束限流 + + String bodyString; + // 生成失败 + if (Objects.isNull(response) || Objects.isNull(response.body())) { + log.error("PythonService##composeLayers异常###{}", "response or body is empty!"); + throw new BusinessException("compose-layer.interface.exception"); + } else if (response.code() != HttpURLConnection.HTTP_OK) { + log.error("PythonService##composeLayers异常###{}", "Response error!Response code ## " + response.code() + " ##"); + throw new BusinessException("compose-layer.interface.exception"); + } else { + try { + bodyString = response.body().string(); + } catch (IOException e) { + throw new BusinessException("compose-layer.interface.exception"); + } + } + JSONObject jsonObject = JSON.parseObject(bodyString); + Boolean result = JSON.parseObject(JSON.toJSONString(response)).getBoolean("successful"); + if (result && jsonObject.get("msg").equals("OK!")) { + return getCompositeImage(jsonObject.getJSONObject("code")); + } + log.info("composeLayers 失败###{}", jsonObject); + //生成失败 + throw new BusinessException("compose-layer.interface.exception"); + } + + private String getCompositeImage(JSONObject jsonObject) { + JSONObject item0 = jsonObject.getJSONObject("0"); + return item0.getString("synthesis_url"); + } + + public String getClothCategory(String path, String gender) { + HashMap content = new HashMap<>(); + content.put("sketch_img_url", path); + content.put("colony", gender); + List> contents = Collections.singletonList(content); + String jsonString = JSON.toJSONString(contents, SerializerFeature.WriteNullStringAsEmpty); + + // todo 添加限流 + Response response = this.sendPostToModel(jsonString, "/api/category_recognition", "getClothCategory"); + // todo 结束限流 + + String bodyString; + // 生成失败 + if (Objects.isNull(response) || Objects.isNull(response.body())) { + log.error("PythonService##GetClothCategory###{}", "response or body is empty!"); + throw new BusinessException("cloth-classification.interface.exception"); + } else if (response.code() != HttpURLConnection.HTTP_OK) { + log.error("PythonService##GetClothCategory###{}", "Response error!Response code ## " + response.code() + " ##"); + throw new BusinessException("cloth-classification.interface.exception"); + } else { + try { + bodyString = response.body().string(); + } catch (IOException e) { + throw new BusinessException("cloth-classification.interface.exception"); + } + } + JSONObject jsonObject = JSON.parseObject(bodyString); + try { + Boolean result = JSON.parseObject(JSON.toJSONString(response)).getBoolean("successful"); + if (result && jsonObject.get("msg").equals("OK!")) { +// JSONObject data = jsonObject.getJSONObject("data"); +// JSONArray list = JSONArray.parseArray(data.get("list").toString()); + JSONArray list = jsonObject.getJSONArray("data"); + JSONObject map = (JSONObject) list.get(0); + return map.get("category").toString(); + } + } catch (NullPointerException e) { + log.info("getClothCategory 失败###{},未返回category", jsonObject); + throw new BusinessException("cloth-classification.interface.exception"); + } + log.info("getClothCategory 失败###{}", jsonObject); + //生成失败 + throw new BusinessException("cloth-classification.interface.exception"); + } + + public Boolean cancelGenerateTask(String taskId, String path) { + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + String url = accessPythonIp + ":" + accessPythonPort + path + taskId; +// String url = fastApiPythonAddress + "/api/generate_cancel/" + taskId; + Request request = new Request.Builder() + .url(url) +// .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") +// .addHeader("Content-Type", "application/json") + .build(); + Response response = null; + try { + log.info("cancelGenerateTask请求入参content###{}", taskId); + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##cancelGenerateTask异常###{}", response); + return null; + } + int responseCode = response.code(); + response.close(); + + if (responseCode != HttpURLConnection.HTTP_OK) { + log.info("generate-python 取消请求失败. {}", response); + return Boolean.FALSE; + } + log.info("generate-python 取消请求成功"); + return Boolean.TRUE; + } + + public Boolean superResolution(SuperResolutionDTO superResolutionDTO) throws BusinessException { + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + + HashMap content = new HashMap<>(); + content.put("sr_image_url", superResolutionDTO.getImages()); + content.put("sr_xn", superResolutionDTO.getScale().toString()); + content.put("sr_tasks_id", superResolutionDTO.getUniqueId()); + + String jsonString = JSON.toJSONString(content, SerializerFeature.WriteNullStringAsEmpty); + RequestBody body = RequestBody.create(mediaType, jsonString); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + srServicePort + "/api/super_resolution") + .method("POST", body) + .addHeader("Content-Type", "application/json") + .build(); + Response response = null; + try { + log.info("superResolution请求入参content###{}", jsonString); + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##superResolution异常###{}", ExceptionUtil.getThrowableList(ioException)); + return null; + } + int responseCode = response.code(); + response.close(); + + if (responseCode != HttpURLConnection.HTTP_OK) { + // 基本不会有除200以外的code + log.info("superResolution 请求超分操作失败。 Response code " + response.code()); + throw new BusinessException("superResolution 请求超分操作失败。 Response code " + response.code()); + } + log.info("superResolution 请求超分操作成功"); + return Boolean.TRUE; + } + + public String promptTranslate(String text) throws BusinessException { + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + + HashMap content = new HashMap<>(); + content.put("text", text); + + String jsonString = JSON.toJSONString(content, SerializerFeature.WriteNullStringAsEmpty); + RequestBody body = RequestBody.create(mediaType, jsonString); + String path = accessPythonIp + ":" + accessPythonPort + "/api/translateToEN"; + log.info("translateToEN 请求地址: {}", path); + Request request = new Request.Builder() + .url(path) +// .url(fastApiPythonAddress + "/api/translateToEN") + .method("POST", body) + .addHeader("Content-Type", "application/json") + .build(); + Response response = null; + try { + log.info("promptTranslation请求入参content###{}", jsonString); + response = client.newCall(request).execute(); + } catch (IOException ioException) { + response.close(); + log.error("PythonService##promptTranslation异常###{}", ExceptionUtil.getThrowableList(ioException)); + return text; + } + int responseCode = response.code(); + String bodyString; + try { + bodyString = response.body().string(); + if (responseCode != HttpURLConnection.HTTP_OK) { + // 基本不会有除200以外的code + log.info("promptTranslation 用户输入翻译失败。 Response code " + responseCode); + throw new BusinessException("promptTranslation 用户输入翻译失败。 Response code " + responseCode); + } + JSONObject jsonObject = JSON.parseObject(bodyString); + Boolean result = JSON.parseObject(JSON.toJSONString(response)).getBoolean("successful"); + if (result && jsonObject.get("msg").equals("OK!")) { + String translated = jsonObject.get("data").toString(); + log.info("翻译或处理后的文本 : {}", translated); + return translated; + } + } catch (IOException e) { + log.error("promptTranslation 用户输入翻译失败; error message => " + e.getMessage()); + response.close(); + throw new RuntimeException(e); + + } finally { + response.close(); + } + + log.info("promptTranslation 用户输入翻译失败,返回用户输入"); + return text; + } + + public Boolean toProductImage(String url, String taskId, String prompt, BigDecimal imageStrength, String productType) { + // todo 限流校验 +// AccessLimitUtils.validate("design",5); + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + //关闭FastJson的引用检测 防止出现$ref 现象 + Map map = new HashMap<>(); + map.put("tasks_id", taskId); + map.put("image_url", url); + map.put("prompt", prompt); + map.put("image_strength", imageStrength); + map.put("product_type", productType); + log.info("toProductImage请求python 参数:####{}", map); + String param = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty); + System.out.println(param); + RequestBody body = RequestBody.create(mediaType, param); + Request request = new Request.Builder() +// .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_product_image") +// .url(accessPythonIp + ":9996/api/generate_product_image") + .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_product_image") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response; + String responseBody; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##toProductImage异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("toProductImage.interface.exception"); + } + if (response.isSuccessful()) { + return Boolean.TRUE; + } + log.error("PythonService##toProductImage异常response###{}", response); + //生成失败 + throw new BusinessException("toProductImage.interface.exception"); + } + + public Boolean relight(String url, String taskId, String prompt, String direction, String relightType) { + // todo 限流校验 +// AccessLimitUtils.validate("design",5); + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + //关闭FastJson的引用检测 防止出现$ref 现象 + Map map = new HashMap<>(); + map.put("tasks_id", taskId); + map.put("image_url", url); + map.put("prompt", prompt); + map.put("direction", direction); + map.put("product_type", relightType); + log.info("relightImage请求python 参数:####{}", map); + String param = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty); + log.info(param); + RequestBody body = RequestBody.create(mediaType, param); + Request request = new Request.Builder() +// .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_product_image") +// .url(accessPythonIp + ":9996/api/generate_product_image") + .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_relight_image") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response; + String responseBody; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##relightImage异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("relightImage.interface.exception"); + } + if (response.isSuccessful()) { + return Boolean.TRUE; + } + log.error("PythonService##relightImage异常response###{}", response); + //生成失败 + throw new BusinessException("relightImage.interface.exception"); + } + + public String imageToSketch(String imagePath, String bucket, String objectName, String styleCode, String styleImageUrl){ + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType paramMap = MediaType.parse("application/json"); + //关闭FastJson的引用检测 防止出现$ref 现象 + Map map = new HashMap<>(); + map.put("image_url", imagePath); + map.put("style_image_url", styleImageUrl); + map.put("default_style", styleCode); + map.put("sketch_bucket", bucket); + map.put("sketch_name", objectName); + + String param = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty); + log.info("ImageToSketch请求python 参数:####{}", param); + RequestBody body = RequestBody.create(paramMap, param); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + accessPythonPort + "/api/image2sketch") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response; + + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##ImageToSketch异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("generate.interface.error"); + } + int responseCode = response.code(); + String bodyString; + try { + bodyString = response.body().string(); + if (responseCode != HttpURLConnection.HTTP_OK) { + // 基本不会有除200以外的code + log.info("ImageToSketch 失败。 Response code {}", responseCode); + throw new BusinessException("ImageToSketch 失败。 Response code " + responseCode); + } + JSONObject jsonObject = JSON.parseObject(bodyString); + if (response.isSuccessful() && jsonObject.get("msg").equals("OK!")) { + String sketchResult = jsonObject.get("data").toString(); + log.info("ImageToSketch 结果 : {}", sketchResult); + return sketchResult; + }else { + log.info("ImageToSketch 失败。 Response code {}", responseCode); + throw new BusinessException("ImageToSketch 失败。 Response code " + responseCode); + } + } catch (IOException e) { + log.error("ImageToSketch 失败; error message => {}", e.getMessage()); + response.close(); + throw new BusinessException("generate.interface.error"); + } finally { + response.close(); + } + } + + public void bright(String url, Double brightenValue) { + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + //关闭FastJson的引用检测 防止出现$ref 现象 + Map map = new HashMap<>(); + map.put("image_url", url); + map.put("brighten_value", brightenValue); + log.info("bright请求python 参数:####{}", map); + String param = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty); + log.info(param); + RequestBody body = RequestBody.create(mediaType, param); + Request request = new Request.Builder() +// .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_product_image") +// .url(accessPythonIp + ":9996/api/generate_product_image") + .url(accessPythonIp + ":" + accessPythonPort + "/api/brighten") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response; + String responseBody; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##bright异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("bright.interface.exception"); + } + if (response.isSuccessful()) { + return; + } + log.error("PythonService##bright异常response###{}", response); + //生成失败 + throw new BusinessException("bright.interface.exception"); + } + + public JSONObject attributeRecognition(List pictureUrls,List ids, List category) { + //限流校验 + AccessLimitUtils.validate("attributeRecognition", 20); + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(300, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(300, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + Map> content = Maps.newHashMap(); + //识别图片路径数组 + content.put("upload_img_path", pictureUrls); + //识别图片id数组 + content.put("upload_img_id", ids); + content.put("upload_img_category", category); + RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); + Request request = new Request.Builder() + .url(accessPythonIp + ":9993/api/attribute") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response = null; + String bodyStr = null; + try { + log.info("识别python对应的属性标签值请求入参content###{}", JSON.toJSONString(content)); + response = client.newCall(request).execute(); + bodyStr = response.body().string(); + } catch (IOException ioException) { + log.error("PythonService###attributeRecognition异常##{}", ExceptionUtil.getThrowableList(ioException)); + } + log.info("识别python对应的属性标签值结果###{}",bodyStr.trim()); + //去除限流 + AccessLimitUtils.validateOut("attributeRecognition"); + if (Objects.isNull(response)) { + log.error("PythonService##attributeRecognition异常###{}", "response or body is empty!"); + throw new BusinessException("attribute recognition exception!"); + } + JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(response)); + Boolean result = jsonObject.getBoolean("successful"); + if (result) { + JSONObject attributeJSONObject = JSON.parseObject(bodyStr.trim()); + return attributeJSONObject; + } + log.info("识别python对应的属性标签值异常###{}", jsonObject); + //生成失败 + throw new BusinessException("Atribute recognition exception!"); + } + + public String designBatch(DesignPythonObjects designPythonObjects, Long accountId, int designNum, String taskId) { + // todo 限流校验 + // AccessLimitUtils.validate("design",5); + + // 将 designPythonObjects 写入文件 + File file = new File("design_batch_test.txt"); + try (FileWriter writer = new FileWriter(file)) { + String param = JSON.toJSONString(designPythonObjects, SerializerFeature.DisableCircularReferenceDetect); + writer.write(param); + log.info("设计请求参数已写入文件:####{}", file.getAbsolutePath()); + } catch (IOException e) { + log.error("写入文件异常:{}", e.getMessage()); + throw new BusinessException("file.write.exception"); + } + + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS) + .readTimeout(60, TimeUnit.SECONDS) + .writeTimeout(60, TimeUnit.SECONDS) + .build(); + + // 构建 multipart 表单 + RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM) + .addFormDataPart("file", "design_batch_test.txt", + RequestBody.create(MediaType.parse("text/plain"), file)) + .addFormDataPart("tasks_id", taskId) + .addFormDataPart("user_id", String.valueOf(accountId)) + .addFormDataPart("file_name", "design_batch_test" + taskId + ".json") + .addFormDataPart("total", String.valueOf(designNum)) + .build(); + + Request request = new Request.Builder() + .url("http://18.167.251.121:9994/api/design_batch_generate") + .method("POST", body) + .addHeader("Content-Type", "multipart/form-data") + .build(); + + Response response; + String responseBody; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + AccessLimitUtils.validateOut("design"); + log.error("PythonService##design异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("design.interface.exception"); + } + + if (response.isSuccessful()) { + try { + if (Objects.nonNull(response.body())) { + responseBody = response.body().string(); + JSONObject responseObject = JSON.parseObject(responseBody); + log.info("PythonService##responseObject###{}", responseObject); + return taskId; + } + throw new BusinessException("design.interface.exception"); + } catch (IOException | JSONException e) { + log.error("PythonService##design异常###{}", e.getMessage()); + throw new BusinessException("design.interface.exception"); + } + } + log.error("PythonService##design异常response###{}", response); + throw new BusinessException("design.interface.exception"); + } + + public List getSystemSketchByCategory(String category, Long brandId, Double brandScale,String style) { + //******3.1.2版本临时使用java推荐方案去解决style未使用的问题********** +// try { +// //使用新库attribute_retrieval_style,表命名修改为elementVO.getModelSex().toLowerCase() + "_" + styleCategory.toLowerCase()比如female_skirt,与传入的category保持一致 +// Integer countByStyle = attributeRetrievalMapper.getCountByStyle(category, style); +// //根据数量随机获取一个系统sketch +// if (countByStyle > 0) { +// //获取一个不大于countByStyle的随机整数 +// Integer randomNum = RandomUtils.nextInt(0, countByStyle); +// //返回格式为 dress/0902000649.jpg +// String oneSystemSketchRadom = attributeRetrievalMapper.getOneSystemSketchRadom(category, style,randomNum); +// String imgName = oneSystemSketchRadom.split("/")[1]; +// //补齐正确格式aida-sys-image/images/male/tops/mens_test_5689.png +// //裁切category前半部分 +// String sex = category.split("_")[0]; +// String realCategory = category.split("_")[1]; +// String path = "aida-sys-image/images/" + sex + "/" +realCategory +"/" +imgName; +// return Arrays.asList(path); +// } +// } catch (Exception e) { +// log.info("推荐失败:{}",e.getMessage()); +// throw new BusinessException("system.error"); +// } + //**********************end*********************************** + AuthPrincipalVo userHolder = UserContext.getUserHolder(); + + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .readTimeout(60, TimeUnit.SECONDS) + .writeTimeout(60, TimeUnit.SECONDS) + .build(); + + // 构建动态路径参数(保留两位小数) +// String url = String.format("%s:%s/recommend/%d/%s/1", +// accessPythonIp, +// accessPythonPort, +// userHolder.getId(), +// category); + String brandIdParam = (brandId != null) ? "" + brandId : "-1"; + String brandScaleParam = (brandScale != null) ? String.format("%.2f", brandScale) : "0.00"; + + String baseUrl = String.format("%s:%s/api/recommend/%d/%s", + "http://18.167.251.121", + accessPythonPort, + userHolder.getId(), + category); + +// 如果style不为空,则添加到查询参数中 + String url; + if (style != null && !style.isEmpty()) { + url = baseUrl + "?style=" + style; + } else { + url = baseUrl; + } + + log.info("Recommendation request URL: {}", url); + + Request request = new Request.Builder() + .url(url) + .get() + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .build(); + + try (Response response = client.newCall(request).execute()) { + log.info("Response status: {}", response.code()); + + if (!response.isSuccessful()) { + String errorBody = response.body() != null ? + response.body().string() : "empty response"; + log.error("Request failed with code: {}, body: {}", + response.code(), errorBody); + throw new BusinessException("Recommendation service unavailable"); + } + + // 解析图片路径数组 + String responseBody = response.body().string(); + List imagePaths = JSON.parseArray(responseBody, String.class); + + if (imagePaths == null || imagePaths.isEmpty()) { + log.warn("Empty recommendation result for {}", category); + return Collections.emptyList(); + } + + log.info("Received {} recommended images", imagePaths.size()); + return imagePaths; + + } catch (IOException e) { + log.error("Network error: {}", ExceptionUtil.getRootCauseMessage(e)); + throw new BusinessException("Failed to get recommendations: " + e.getMessage()); + } catch (JSONException e) { + log.error("Response parsing error: {}", ExceptionUtil.getMessage(e)); + throw new BusinessException("Invalid service response format"); + } + } + + public JSONObject segProduct(String url) { + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + //关闭FastJson的引用检测 防止出现$ref 现象 + Map map = new HashMap<>(); + map.put("image_url", url); + map.put("is_brand_dna", Boolean.TRUE); + log.info("bright请求python 参数:####{}", map); + String param = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty); + log.info(param); + RequestBody body = RequestBody.create(mediaType, param); + Request request = new Request.Builder() +// .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_product_image") +// .url(accessPythonIp + ":9996/api/generate_product_image") + .url(accessPythonIp + ":" + accessPythonPort + "/api/seg_product") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response; + String responseBody; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##bright异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("segProduct.interface.exception"); + } + if (response.isSuccessful()) { + try { + if (Objects.nonNull(response.body())) { + responseBody = response.body().string(); + JSONObject responseObject = JSON.parseObject(responseBody); + log.info("PythonService##responseObject###{}", responseObject); + return responseObject; + } + throw new BusinessException("segProduct.interface.exception"); + } catch (IOException | JSONException e) { + log.error("PythonService##segProduct异常###{}", e.getMessage()); + throw new BusinessException("segProduct.interface.exception"); + } + } + log.error("PythonService##segProduct异常response###{}", response); + //生成失败 + throw new BusinessException("segProduct.interface.exception"); + } + /** + * 转发 seg_anything 请求到 python 服务 + * 请求 body 由调用方组装(包含 user_id, image_path, type, points, labels, box 等) + */ + public String segAnything(JSONObject content) { + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS) + .readTimeout(60, TimeUnit.SECONDS) + .writeTimeout(60, TimeUnit.SECONDS) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); + + String url = accessPythonIp + ":" + accessPythonPort + "/api/seg_anything"; + log.info("segAnything 请求地址: {}, 参数:{}", url, JSON.toJSONString(content)); + + Request request = new Request.Builder() + .url(url) + .method("POST", body) + .addHeader("Content-Type", "application/json") + .build(); + + Response response; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##segAnything异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("segAnything.interface.exception"); + } + + if (response.isSuccessful()) { + try { + if (Objects.nonNull(response.body())) { + String responseBody = response.body().string(); + JSONObject responseObject = JSON.parseObject(responseBody); + log.info("PythonService##segAnything response###{}", responseObject); + // Extract nested output path and convert to presigned MinIO URL for frontend, return as String + try { + if (responseObject != null) { + JSONObject dataObj = responseObject.getJSONObject("data"); + if (dataObj != null) { + JSONObject inner = dataObj.getJSONObject("data"); + if (inner != null) { + String output = inner.getString("output"); + if (!StringUtil.isNullOrEmpty(output)) { + try { + String presigned = minioUtil.getPreSignedUrl(output, 24 * 60); + return presigned; + } catch (Exception e) { + log.error("Failed to generate presigned url for {}: {}", output, e.getMessage()); + throw new BusinessException("segAnything.presign.failed"); + } + } + } + } + } + } catch (Exception ex) { + log.error("PythonService##segAnything post-process error###{}", ex.getMessage()); + throw new BusinessException("segAnything.interface.exception"); + } + + throw new BusinessException("segAnything.missing.output"); + } + throw new BusinessException("segAnything.interface.exception"); + } catch (IOException | JSONException e) { + log.error("PythonService##segAnything异常###{}", e.getMessage()); + throw new BusinessException("segAnything.interface.exception"); + } + } + log.error("PythonService##segAnything异常response###{}", response); + throw new BusinessException("segAnything.interface.exception"); + } + public Boolean poseTransformation(JSONObject content, String apiUri) { + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); + + log.info("poseTransformation 请求地址: {}", accessPythonIp + ":" + accessPythonPort + apiUri); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + accessPythonPort + apiUri) + .method("POST", body) + .addHeader("Content-Type", "application/json") + .build(); + Response response = null; + String bodyString; + try { + log.info("poseTransformation请求入参content###{}", JSON.toJSONString(content)); + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##poseTransformation异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException(ioException.getMessage()); + } + + // 判断是否生成失败 + if (Objects.isNull(response.body())) { + log.error("PythonService##poseTransformation异常###{}", "response or body is empty!"); + throw new BusinessException("PythonService##poseTransformation异常###: response or body is empty!"); + } else if (response.code() != HttpURLConnection.HTTP_OK) { + log.error("PythonService##poseTransformation异常###{}", "Response error!Response code ## " + response.code() + " ##"); + throw new BusinessException("PythonService##poseTransformation异常### Response error!Response code ## " + response.code() + " ##"); + } else { + try { + bodyString = response.body().string(); + } catch (IOException e) { + log.error(e.getMessage()); + throw new BusinessException(e.getMessage()); + } + } + JSONObject jsonObject = JSON.parseObject(bodyString); + Boolean result = JSON.parseObject(JSON.toJSONString(response)).getBoolean("successful"); + + if (result && jsonObject.get("code").equals(200)) { + log.info("poseTransformation##responseObject###{}", jsonObject); + return Boolean.TRUE; + } else { + log.info("poseTransformation失败###{}", jsonObject); + log.info("poseTransformation Exception! Code : {}", jsonObject.get("code")); + return Boolean.FALSE; + } + } + + public String modifyModelProportion(String mannequinPath, Float stretch, String name, int top, int bottom) { + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + + MediaType mediaType = MediaType.parse("application/json"); + Map content = Maps.newHashMap(); + // 模特的minio地址 + content.put("mannequins", mannequinPath); + // 缩放比 + content.put("resize_pixel", stretch.toString()); + // 结果存放桶名 + content.put("bucket_name", "aida-users"); + // 模特名uuid + content.put("mannequin_name", name); + content.put("top", String.valueOf(top)); + content.put("bottom", String.valueOf(bottom)); + RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); + + log.info("modifyModelProportion 请求地址: {},\n 参数:{}", accessPythonIp + ":" + accessPythonPort + "/api/mannequins_edit", JSON.toJSONString(content)); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + accessPythonPort + "/api/mannequins_edit") + .method("POST", body) + .addHeader("Content-Type", "application/json") + .build(); + Response response = null; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##modifyModelProportion异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("generate.interface.error"); + } + int responseCode = response.code(); + String bodyString; + try { + bodyString = response.body().string(); + if (responseCode != HttpURLConnection.HTTP_OK) { + // 基本不会有除200以外的code + log.info("modifyModelProportion 失败。 Response code {}", responseCode); + throw new BusinessException("modifyModelProportion 失败。 Response code " + responseCode); + } + JSONObject jsonObject = JSON.parseObject(bodyString); + if (response.isSuccessful() && jsonObject.get("msg").equals("OK!")) { + String modifiedModel = jsonObject.get("data").toString(); + log.info("modifyModelProportion 结果 : {}", modifiedModel); + return modifiedModel; + }else { + log.info("modifyModelProportion 失败。 Response code {}", responseCode); + throw new BusinessException("modifyModelProportion 失败。 Response code " + responseCode); + } + } catch (IOException e) { + log.error("modifyModelProportion 失败; error message => {}", e.getMessage()); + response.close(); + throw new BusinessException("generate.interface.error"); + } finally { + response.close(); + } + } + + public JSONObject brandDNAGenerate(String prompt) { + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + //关闭FastJson的引用检测 防止出现$ref 现象 + Map map = new HashMap<>(); + map.put("prompt", prompt); + AuthPrincipalVo userHolder = UserContext.getUserHolder(); + map.put("user_id", userHolder.getId()); + log.info("brandDNAGenerate请求python 参数:####{}", map); + String param = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty); + log.info(param); + RequestBody body = RequestBody.create(mediaType, param); + Request request = new Request.Builder() +// .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_product_image") +// .url(accessPythonIp + ":9996/api/generate_product_image") + .url(accessPythonIp + ":" + accessPythonPort + "/api/GenerateBrand") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response; + String responseBody; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##brandDNAGenerate异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("brandDNAGenerate.interface.exception"); + } + if (response.isSuccessful()) { + try { + if (Objects.nonNull(response.body())) { + responseBody = response.body().string(); + JSONObject responseObject = JSON.parseObject(responseBody); + log.info("PythonService##responseObject###{}", responseObject); + return responseObject; + } + throw new BusinessException("brandDNAGenerate.interface.exception"); + } catch (IOException | JSONException e) { + log.error("PythonService##brandDNAGenerate异常###{}", e.getMessage()); + throw new BusinessException("brandDNAGenerate.interface.exception"); + } + } + log.error("PythonService##brandDNAGenerate异常response###{}", response); + //生成失败 + throw new BusinessException("brandDNAGenerate.interface.exception"); + } + + public List imageSegmentation(ImageSegmentation imageSegmentation) { + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + + MediaType mediaType = MediaType.parse("application/json"); + RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(imageSegmentation)); + + log.info("modifyModelProportion 请求地址: {},\n 参数:{}", accessPythonIp + ":" + accessPythonPort + "/api/clothing_seg", JSON.toJSONString(imageSegmentation)); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + accessPythonPort + "/api/clothing_seg") + .method("POST", body) + .addHeader("Content-Type", "application/json") + .build(); + Response response = null; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##imageSegmentation异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("generate.interface.error"); + } + int responseCode = response.code(); + String bodyString; + try { + bodyString = response.body().string(); + if (responseCode != HttpURLConnection.HTTP_OK) { + // 基本不会有除200以外的code + log.info("imageSegmentation 失败。 Response code {}", responseCode); + throw new BusinessException("imageSegmentation 失败。 Response code " + responseCode); + } + JSONObject jsonObject = JSON.parseObject(bodyString); + if (response.isSuccessful() && jsonObject.get("msg").equals("OK!")) { + log.info("imageSegmentation 结果 : {}", jsonObject.get("data").toString()); + List seg = JSONObject.parseObject( + jsonObject.get("data").toString(), + new TypeReference>() {} + ); + return seg; + }else { + log.info("imageSegmentation 失败。 Response code {}", responseCode); + throw new BusinessException("imageSegmentation 失败。 Response code " + responseCode); + } + } catch (IOException e) { + log.error("imageSegmentation 失败; error message => {}", e.getMessage()); + response.close(); + throw new BusinessException("generate.interface.error"); + } finally { + response.close(); + } + } + + public Boolean toProductImageBatch(String taskIdBatch, List paramList, String userId) { + // todo 限流校验 +// AccessLimitUtils.validate("design",5); + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + //关闭FastJson的引用检测 防止出现$ref 现象 + Map map = new HashMap<>(); + map.put("user_id", userId); + map.put("batch_data_list", paramList); + map.put("batch_tasks_id", taskIdBatch); + log.info("toProductImage请求python 参数:####{}", map); + String param = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty); + System.out.println(JSONObject.toJSONString(param)); + RequestBody body = RequestBody.create(mediaType, param); + Request request = new Request.Builder() +// .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_product_image") +// .url(accessPythonIp + ":9996/api/generate_product_image") + .url(accessPythonIp + ":" + accessPythonPort + "/api/batch_generate_product_image") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response; + String responseBody; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##toProductImage异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("toProductImage.interface.exception"); + } + if (response.isSuccessful()) { + return Boolean.TRUE; + } + log.error("PythonService##toProductImage异常response###{}", response); + //生成失败 + throw new BusinessException("toProductImage.interface.exception"); + } + + public Boolean relightBatch(String taskIdBatch, List paramList, String userId) { + // todo 限流校验 +// AccessLimitUtils.validate("design",5); + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + //关闭FastJson的引用检测 防止出现$ref 现象 + Map map = new HashMap<>(); + map.put("batch_tasks_id", taskIdBatch); + map.put("user_id", userId); + map.put("batch_data_list", paramList); + log.info("relightImage请求python 参数:####{}", map); + String param = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty); + log.info(param); + RequestBody body = RequestBody.create(mediaType, param); + Request request = new Request.Builder() +// .url(accessPythonIp + ":" + accessPythonPort + "/api/generate_product_image") +// .url(accessPythonIp + ":9996/api/generate_product_image") + .url(accessPythonIp + ":" + accessPythonPort + "/api/batch_generate_relight_image") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response; + String responseBody; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##relightImage异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("relightImage.interface.exception"); + } + if (response.isSuccessful()) { + return Boolean.TRUE; + } + log.error("PythonService##relightImage异常response###{}", response); + //生成失败 + throw new BusinessException("relightImage.interface.exception"); + } + + public Boolean poseTransformationBatch(String productImage, Integer poseId, String taskId) { + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + Map content = Maps.newHashMap(); + content.put("image_url", productImage); + content.put("tasks_id", taskId); + content.put("pose_id", String.valueOf(poseId)); + content.put("batch_size", 1); + RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); + + log.info("poseTransformation 请求地址: {}", accessPythonIp + ":" + accessPythonPort + "/api/batch_generate_pose_transform_image"); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + accessPythonPort + "/api/batch_generate_pose_transform_image") + .method("POST", body) + .addHeader("Content-Type", "application/json") + .build(); + Response response = null; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##poseTransferBatch异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("poseTransferBatch.interface.exception"); + } + + if (response.isSuccessful() && response.body() != null) { + String responseBody = response.body().toString(); + log.info("PythonService##poseTransferBatch返回内容###{}", responseBody); + + return Boolean.TRUE; + } + + log.error("PythonService##poseTransferBatch接口调用失败###{}", response); + throw new BusinessException("poseTransferBatch.interface.exception"); + } + + public JSONObject getProjectParam(String prompt, String fileUrl, List imageUrlList, String process) { + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + Map content = Maps.newHashMap(); + content.put("prompt", prompt); + content.put("process", process); + content.put("image_list", !CollectionUtils.isEmpty(imageUrlList) ? imageUrlList : new ArrayList<>()); + content.put("file_list", !StringUtils.isEmpty(fileUrl) ? Collections.singletonList(fileUrl) : new ArrayList<>()); + RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); + +// log.info("getProjectParam 请求地址: {}", accessPythonIp + ":" + accessPythonPort + "/api/extraction_project_info"); + log.info("getProjectParam 请求地址: {}", "http://18.167.251.121:2011/api/extraction_project_info"); + Request request = new Request.Builder() +// .url(accessPythonIp + ":" + accessPythonPort + "/api/extraction_project_info") + .url("http://18.167.251.121:2011/api/extraction_project_info") + .method("POST", body) + .addHeader("Content-Type", "application/json") + .build(); + Response response = null; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##getProjectParam异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("getProjectParam.interface.exception"); + } + String responseBody; + if (response.isSuccessful() && response.body() != null) { + try { + responseBody = response.body().string(); + JSONObject responseObject = JSON.parseObject(responseBody); + log.info("PythonService##responseObject###{}", responseObject); + return responseObject; + } catch (IOException | JSONException e) { + log.error("PythonService##getProjectParam异常###{}", e.getMessage()); + throw new BusinessException("getProjectParam.interface.exception"); + } + } + + log.error("PythonService##getProjectParam接口调用失败###{}", response); + throw new BusinessException("getProjectParam.interface.exception"); + } + + public List getPrompt(String string, int num) { + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + Map content = Maps.newHashMap(); + content.put("text", string); + content.put("num", num); + content.put("language", "english"); + RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); + + log.info("batch_prompt_optimizer 请求地址: {}", accessPythonIp + ":" + accessPythonPort + "/api/batch_prompt_optimizer"); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + "2011" + "/api/batch_prompt_optimizer") + .method("POST", body) + .addHeader("Content-Type", "application/json") + .build(); + Response response = null; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + log.error("PythonService##batch_prompt_optimizer异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("batch_prompt_optimizer.interface.exception"); + } + String responseBody; + if (response.isSuccessful() && response.body() != null) { + try { + responseBody = response.body().string(); + JSONObject responseObject = JSON.parseObject(responseBody); + JSONObject dataObject = responseObject.getJSONObject("data"); + if (dataObject != null) { + // 获取prompt_list数组 + JSONArray promptArray = dataObject.getJSONArray("prompt_list"); + if (promptArray != null) { + // 转换为List + List promptList = new ArrayList<>(); + for (int i = 0; i < promptArray.size(); i++) { + promptList.add(promptArray.getString(i)); + } + return promptList; + } + } + log.info("PythonService##responseObject###{}", responseObject); + return null; + } catch (IOException | JSONException e) { + log.error("PythonService##batch_prompt_optimizer异常###{}", e.getMessage()); + throw new BusinessException("batch_prompt_optimizer.interface.exception"); + } + } + + log.error("PythonService##batch_prompt_optimizer接口调用失败###{}", response); + throw new BusinessException("batch_prompt_optimizer.interface.exception"); + } +}