Merge branch 'test/stable' into release/3.0

# Conflicts:
#	src/main/java/com/ai/da/common/RabbitMQ/GenerateConsumer.java
#	src/main/java/com/ai/da/service/impl/AccountServiceImpl.java
This commit is contained in:
shahaibo
2024-07-09 23:40:58 +08:00
143 changed files with 4961 additions and 1030 deletions

9
files/COD-public-key.txt Normal file
View File

@@ -0,0 +1,9 @@
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAymkBAWixxUi9IAeMWgsq
K92AzFbe0qzzYPdkoh15ymL2A5MkYH7asnhFwclgdiFmd9a0TbZP+t/SzWW8UUzN
1pXoEp48R+eguGTt5xkJwb10+H6quVXF/Ezzid5yzVW3dcYRp8qUlFr0XBpvkK9l
FpPzh2+mwVEAsgBMXq/K50ZiX2dlkPZ7ffkVPWaK2ESIo3YgfM6dmiiza0hPWJ35
UgTH5rwJ7vN3IdOJTlkQOvrIrj2ocPcrudeEwqybIbCGhgRBwQSBsXQOO4U//rE4
VU+0LF/3uQgXkvVY1+a1JLiTncZYKGEQ/NtxM+dGtYWV2gPhQRyJ7Z77OX0XCbcn
zwIDAQAB
-----END PUBLIC KEY-----

34
pom.xml
View File

@@ -28,7 +28,19 @@
<jaxb-core>4.0.0</jaxb-core>
<activation>1.1.1</activation>
<easy-captcha>1.6.2</easy-captcha>
<aws.java.sdk.version>2.20.43</aws.java.sdk.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>${aws.java.sdk.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
@@ -239,6 +251,28 @@
<version>25.0.0</version>
</dependency>
<!-- aws s3 -->
<!-- S3 dependency -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3-transfer-manager</artifactId>
<version>2.17.103-PREVIEW</version>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>kms</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3control</artifactId>
</dependency>
</dependencies>
<build>

View File

@@ -44,6 +44,10 @@ public class GenerateConsumer {
@Value("${redis.key.generateResult}")
private String generateResultKey;
@Value("${redis.key.toProductImageResultKey}")
private String toProductImageResultKey;
@Value("${redis.key.relightResultKey}")
private String relightResultKey;
public void generate(Message msg, Channel channel, String consumerName) {
log.info("============start listening==========");
@@ -63,23 +67,14 @@ public class GenerateConsumer {
} catch (IOException ex) {
log.error("手动确认,不返回队列重新消费");
}
// 2.2 将该消息从取消列表中删除
// redisUtil.removeFromSet(cancelSetKey, uniqueId);
} else {
// GenerateCollectionVO generateCollectionVO = generateService.generateThroughImageText(generateThroughImageTextDTO);
generateService.generateThroughImageText(generateThroughImageTextDTO);
// 将消息从redis排队队列中删除,需保证被消费的消息存储到db之后再从redis删除
redisUtil.removeFromZSet(consumptionOrderKey, uniqueId);
/*if (!Objects.isNull(generateCollectionVO)) {
HashMap<String, String> generateResult = new HashMap<>();
generateResult.put(uniqueId, JSONObject.toJSONString(generateCollectionVO));
// 将结果存在redis中 ,为空时不要存
redisUtil.addToMap(resultMapKey, generateResult);
}*/
}
} catch (BusinessException e) {
log.error(e.getMsg());
} catch (Exception e) {
log.error(e.getMessage());
// channel.basicNack() 为不确认deliveryTag对应的消息第二个参数是否应用于多消息第三个参数是否requeue
try {
// 第二个参数是否批量确认消息当传false时只确认当前 deliveryTag对应的消息;当传true时会确认当前及之前所有未确认的消息。
@@ -94,7 +89,7 @@ public class GenerateConsumer {
}
// 将入参和错误信息存入数据库
String exceptionMessage = JSONObject.toJSONString(generateThroughImageTextDTO) +
" Exception message " + e.getMsg();
" Exception message " + e.getMessage();
HashMap<String, String> exceptionInfo = new HashMap<>();
exceptionInfo.put(String.valueOf(uniqueId), exceptionMessage);
// 存redis
@@ -154,63 +149,169 @@ public class GenerateConsumer {
}
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
// @RabbitHandler
// public void generateConsumer1(Message msg, Channel channel) {
// generate(msg, channel, "consumer 1");
// }
//
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
// @RabbitHandler
// public void generateConsumer2(Message msg, Channel channel) {
// generate(msg, channel, "consumer 2");
// }
//
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
// @RabbitHandler
// public void generateConsumer3(Message msg, Channel channel) {
// generate(msg, channel, "consumer 3");
// }
//
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
// @RabbitHandler
// public void generateConsumer4(Message msg, Channel channel) {
// generate(msg, channel, "consumer 4");
// }
//
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
// @RabbitHandler
// public void generateConsumer5(Message msg, Channel channel) {
// generate(msg, channel, "consumer 5");
// }
//
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
// @RabbitHandler
// public void generateConsumer6(Message msg, Channel channel) {
// generate(msg, channel, "consumer 6");
// }
//
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
// @RabbitHandler
// public void generateConsumer7(Message msg, Channel channel) {
// generate(msg, channel, "consumer 7");
// }
//
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
// @RabbitHandler
// public void generateConsumer8(Message msg, Channel channel) {
// generate(msg, channel, "consumer 8");
// }
//
// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
// @RabbitHandler
// public void generateConsumer9(Message msg, Channel channel) {
// generate(msg, channel, "consumer 9");
// }
//
// @RabbitListener(queues = MQConfig.GENERATE_RESULT_QUEUE)
// @RabbitHandler
// public void getGenerateResult(Message msg, Channel channel) {
// processGenerateResult(msg, channel);
// }
public void processToProductImageResult(Message msg, Channel channel) {
log.info("============processToProductImageResult listening==========");
long start = System.currentTimeMillis();
Map<String, String> generateResult = JSONObject.parseObject(msg.getBody(), Map.class);
log.info("toProductImage response : {}", generateResult);
try {
log.info("tasks_id : {} start ", generateResult.get("tasks_id"));
if (generateResult.get("status").equals("SUCCESS")) {
String url = generateResult.get("image_url");
String taskId = generateResult.get("tasks_id");
String category = generateResult.get("category");
generateService.processToProductImageResult(taskId, url, category);
} else {
// 修改redis中的数据状态为exception
String key = toProductImageResultKey + ":" + generateResult.get("tasks_id");
redisUtil.addToString(key, new Gson().toJson(new GenerateResultVO(generateResult.get("tasks_id"), null, null, "Fail")), CommonConstant.GENERATE_RESULT_EXPIRE_TIME);
// 将异常信息存到exception中
HashMap<String, String> exceptionInfo = new HashMap<>();
exceptionInfo.put(generateResult.get("tasks_id"), generateResult.get("data"));
// 存redis
redisUtil.addToMap(exceptionMapKey, exceptionInfo);
}
} catch (Exception e) {
log.error(e.getMessage());
try {
channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
// 将消息从redis排队队列中删除,需保证被消费的消息存储到db之后再从redis删除
redisUtil.removeFromZSet(consumptionOrderKey, generateResult.get("tasks_id"));
} catch (IOException exception) {
log.error("手动确认,取消返回队列,不再重新消费");
}
// 将入参和错误信息存入数据库
String exceptionMessage = JSONObject.toJSONString(generateResult) +
" Exception message " + e.getMessage();
HashMap<String, String> exceptionInfo = new HashMap<>();
exceptionInfo.put(String.valueOf(generateResult.get("tasks_id")), exceptionMessage);
// 存redis
redisUtil.addToMap(exceptionMapKey, exceptionInfo);
}
long end = System.currentTimeMillis();
log.info("tasks_id : {}, end , message : {}, 执行时长: {} 毫秒", generateResult.get("tasks_id"), generateResult.get("message"), (end - start));
log.info("============ProcessToProductImageResult End listening==========");
}
private void processRelightResult(Message msg, Channel channel) {
log.info("============processRelightResult listening==========");
long start = System.currentTimeMillis();
Map<String, String> generateResult = JSONObject.parseObject(msg.getBody(), Map.class);
log.info("toProductImage response : {}", generateResult);
try {
log.info("tasks_id : {} start ", generateResult.get("tasks_id"));
if (generateResult.get("status").equals("SUCCESS")) {
String url = generateResult.get("image_url");
String taskId = generateResult.get("tasks_id");
String category = generateResult.get("category");
generateService.processRelightResult(taskId, url, category);
} else {
// 修改redis中的数据状态为exception
String key = relightResultKey + ":" + generateResult.get("tasks_id");
redisUtil.addToString(key, new Gson().toJson(new GenerateResultVO(generateResult.get("tasks_id"), null, null, "Fail")), CommonConstant.GENERATE_RESULT_EXPIRE_TIME);
// 将异常信息存到exception中
HashMap<String, String> exceptionInfo = new HashMap<>();
exceptionInfo.put(generateResult.get("tasks_id"), generateResult.get("data"));
// 存redis
redisUtil.addToMap(exceptionMapKey, exceptionInfo);
}
} catch (Exception e) {
log.error(e.getMessage());
try {
channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
// 将消息从redis排队队列中删除,需保证被消费的消息存储到db之后再从redis删除
redisUtil.removeFromZSet(consumptionOrderKey, generateResult.get("tasks_id"));
} catch (IOException exception) {
log.error("手动确认,取消返回队列,不再重新消费");
}
// 将入参和错误信息存入数据库
String exceptionMessage = JSONObject.toJSONString(generateResult) +
" Exception message " + e.getMessage();
HashMap<String, String> exceptionInfo = new HashMap<>();
exceptionInfo.put(String.valueOf(generateResult.get("tasks_id")), exceptionMessage);
// 存redis
redisUtil.addToMap(exceptionMapKey, exceptionInfo);
}
long end = System.currentTimeMillis();
log.info("tasks_id : {}, end , message : {}, 执行时长: {} 毫秒", generateResult.get("tasks_id"), generateResult.get("message"), (end - start));
log.info("============ProcessRelightResult End listening==========");
}
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
@RabbitHandler
public void generateConsumer1(Message msg, Channel channel) {
generate(msg, channel, "consumer 1");
}
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
@RabbitHandler
public void generateConsumer2(Message msg, Channel channel) {
generate(msg, channel, "consumer 2");
}
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
@RabbitHandler
public void generateConsumer3(Message msg, Channel channel) {
generate(msg, channel, "consumer 3");
}
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
@RabbitHandler
public void generateConsumer4(Message msg, Channel channel) {
generate(msg, channel, "consumer 4");
}
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
@RabbitHandler
public void generateConsumer5(Message msg, Channel channel) {
generate(msg, channel, "consumer 5");
}
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
@RabbitHandler
public void generateConsumer6(Message msg, Channel channel) {
generate(msg, channel, "consumer 6");
}
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
@RabbitHandler
public void generateConsumer7(Message msg, Channel channel) {
generate(msg, channel, "consumer 7");
}
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
@RabbitHandler
public void generateConsumer8(Message msg, Channel channel) {
generate(msg, channel, "consumer 8");
}
@RabbitListener(queues = MQConfig.GENERATE_QUEUE)
@RabbitHandler
public void generateConsumer9(Message msg, Channel channel) {
generate(msg, channel, "consumer 9");
}
@RabbitListener(queues = MQConfig.GENERATE_RESULT_QUEUE)
@RabbitHandler
public void getGenerateResult(Message msg, Channel channel) {
processGenerateResult(msg, channel);
}
@RabbitListener(queues = MQConfig.TO_PRODUCT_IMAGE_RESULT_QUEUE)
@RabbitHandler
public void getToProductImageResult(Message msg, Channel channel) {
processToProductImageResult(msg, channel);
}
@RabbitListener(queues = MQConfig.RELIGHT_RESULT_QUEUE)
@RabbitHandler
public void getRelightResult(Message msg, Channel channel) {
processRelightResult(msg, channel);
}
}

View File

@@ -13,16 +13,22 @@ public class MQConfig {
// ==================================================================
// public static final String GENERATE_QUEUE = "generate-queue-local";
public static final String GENERATE_QUEUE = "generate-queue-prod";
// public static final String GENERATE_QUEUE = "generate-queue-prod";
//
// public static final String SR_QUEUE = "SR-queue-local";
public static final String SR_QUEUE = "SR-queue-prod";
public static final String SR_QUEUE = "SR-queue-prod";
// public static final String SR_QUEUE = "SR-queue-prod";
//
// public static final String SR_RESULT_QUEUE = "SuperResolution-local";
public static final String SR_RESULT_QUEUE = "SuperResolution-prod";
public static final String SR_RESULT_QUEUE = "SuperResolution-prod";
// public static final String SR_RESULT_QUEUE = "SuperResolution-prod";
//
// public static final String GENERATE_RESULT_QUEUE = "GenerateImage-local";
public static final String GENERATE_RESULT_QUEUE = "GenerateImage-prod";
public static final String TO_PRODUCT_IMAGE_RESULT_QUEUE = "ToProductImage-prod";
public static final String RELIGHT_RESULT_QUEUE = "Relight-prod";
public MQConfig() {
}

View File

@@ -1,11 +1,13 @@
package com.ai.da.common.config;
import com.ai.da.common.utils.ExcelReader;
import com.ai.da.common.utils.MinioUtil;
import com.ai.da.common.utils.SendEmailUtil;
import com.ai.da.mapper.primary.AccountMapper;
import com.ai.da.mapper.primary.TrialOrderMapper;
import com.ai.da.mapper.primary.entity.Account;
import com.ai.da.mapper.primary.entity.TrialOrder;
import com.ai.da.mapper.primary.*;
import com.ai.da.mapper.primary.entity.*;
import com.ai.da.mapper.secondary.AttributeRetrievalMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
@@ -17,15 +19,28 @@ import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Component
public class MyTaskScheduler {
@PostConstruct
public void test() {
// clearMinio();
// addSystemFileStyle();
}
@Resource
private AccountMapper accountMapper;
@@ -34,7 +49,7 @@ public class MyTaskScheduler {
// 定时任务,每十五天执行一次
// @Scheduled(cron = "0 0 0 ? * MON")
@Scheduled(cron = "0 0 0 */15 * ?")
// @Scheduled(cron = "0 0 0 */15 * ?")
public void checkExpiry() {
// 检测正式用户是否快要过期
QueryWrapper<Account> qw = new QueryWrapper<>();
@@ -68,10 +83,10 @@ public class MyTaskScheduler {
}
}
}
@Scheduled(cron = "0 0 8 * * ?")
// @Scheduled(cron = "0 0 8 * * ?")
public void sendTrialOrderExcelToManagements() {
// 获取前一天日期
LocalDate yesterday = LocalDate.now().minusDays(1);
LocalDate yesterday = LocalDate.now().minusDays(3);
// 查询前一天的试用订单
QueryWrapper<TrialOrder> qw = new QueryWrapper<>();
@@ -134,4 +149,174 @@ public class MyTaskScheduler {
SendEmailUtil.sendNoExcelEmail("kimwong@code-create.com.hk", null);
}
}
@Resource
private UserLikeGroupMapper userLikeGroupMapper;
@Resource
private UserLikeMapper userLikeMapper;
@Resource
private TDesignPythonOutfitMapper designPythonOutfitMapper;
@Resource
private TDesignPythonOutfitDetailMapper designPythonOutfitDetailMapper;
@Resource
private DesignItemMapper designItemMapper;
@Resource
private DesignItemDetailMapper designItemDetailMapper;
@Resource
private MinioUtil minioUtil;
public void clearMinio() {
// 获取当前所有history
QueryWrapper<UserLikeGroup> userLikeGroupQueryWrapper = new QueryWrapper<>();
List<UserLikeGroup> userLikeGroupList = userLikeGroupMapper.selectList(userLikeGroupQueryWrapper);
List<Long> userLikeGroupIdList = userLikeGroupList.stream().map(UserLikeGroup::getId).collect(Collectors.toList());
QueryWrapper<UserLike> userLikeQueryWrapper = new QueryWrapper<>();
userLikeQueryWrapper.lambda().in(UserLike::getUserLikeGroupId, userLikeGroupIdList);
// 所有喜欢的图片
List<UserLike> userLikes = userLikeMapper.selectList(userLikeQueryWrapper);
List<Long> designOutfitIdList = userLikes.stream().map(UserLike::getDesignOutfitId).collect(Collectors.toList());
QueryWrapper<TDesignPythonOutfit> designPythonOutfitQueryWrapper = new QueryWrapper<>();
designPythonOutfitQueryWrapper.lambda().notIn(TDesignPythonOutfit::getId, designOutfitIdList);
List<TDesignPythonOutfit> tDesignPythonOutfits = designPythonOutfitMapper.selectList(designPythonOutfitQueryWrapper);
// int i = 0;
// for (TDesignPythonOutfit tDesignPythonOutfit : tDesignPythonOutfits) {
// String designUrl = tDesignPythonOutfit.getDesignUrl();
// if (StringUtils.isNotBlank(designUrl)) {
// minioUtil.deleteObject(designUrl);
// i ++;
// }
// QueryWrapper<TDesignPythonOutfitDetail> designPythonOutfitDetailQueryWrapper = new QueryWrapper<>();
// designPythonOutfitDetailQueryWrapper.lambda().eq(TDesignPythonOutfitDetail::getDesignPythonOutfitId, tDesignPythonOutfit.getId());
// List<TDesignPythonOutfitDetail> tDesignPythonOutfitDetails = designPythonOutfitDetailMapper.selectList(designPythonOutfitDetailQueryWrapper);
// for (TDesignPythonOutfitDetail tDesignPythonOutfitDetail : tDesignPythonOutfitDetails) {
// if (!tDesignPythonOutfitDetail.getImageCategory().equals("body")) {
// if (StringUtils.isNotBlank(tDesignPythonOutfitDetail.getImageUrl())) {
// minioUtil.deleteObject(tDesignPythonOutfitDetail.getImageUrl());
// i ++;
// }
// if (StringUtils.isNotBlank(tDesignPythonOutfitDetail.getMaskUrl())) {
// minioUtil.deleteObject(tDesignPythonOutfitDetail.getMaskUrl());
// i ++;
// }
// }
// }
// }
System.out.println("i");
// List<Long> designItemIdList = userLikes.stream().map(UserLike::getDesignItemId).collect(Collectors.toList());
// QueryWrapper<DesignItem> designItemQueryWrapper = new QueryWrapper<>();
// designItemQueryWrapper.lambda().in(DesignItem::getId,designItemIdList);
// List<DesignItem> designItems = designItemMapper.selectList(designItemQueryWrapper);
// for (DesignItem designItem : designItems) {
// QueryWrapper<DesignItemDetail> designItemDetailQueryWrapper = new QueryWrapper<>();
// designItemDetailQueryWrapper.lambda().eq(DesignItemDetail::getDesignItemId, designItem.getId());
// List<DesignItemDetail> designItemDetails = designItemDetailMapper.selectList(designItemDetailQueryWrapper);
// for (DesignItemDetail designItemDetail : designItemDetails) {
//
// }
// }
}
@Resource
private AttributeRetrievalMapper attributeRetrievalMapper;
public void addSystemFileStyle() {
ExecutorService executorService = Executors.newFixedThreadPool(5);
try {
String[] filePaths = {
"C:\\Users\\10233\\Documents\\WeChat Files\\wxid_h7l9im0r8ql922\\FileStorage\\File\\2024-06\\style\\Blouse style output updated25.6.2024.xlsx",
"C:\\Users\\10233\\Documents\\WeChat Files\\wxid_h7l9im0r8ql922\\FileStorage\\File\\2024-06\\style\\Dress style output updated25.6.2024.xlsx",
"C:\\Users\\10233\\Documents\\WeChat Files\\wxid_h7l9im0r8ql922\\FileStorage\\File\\2024-06\\style\\Outerwear style output.xlsx",
"C:\\Users\\10233\\Documents\\WeChat Files\\wxid_h7l9im0r8ql922\\FileStorage\\File\\2024-06\\style\\Skirt style output .xlsx",
"C:\\Users\\10233\\Documents\\WeChat Files\\wxid_h7l9im0r8ql922\\FileStorage\\File\\2024-06\\style\\Trousers style output.xlsx"
};
for (String filePath : filePaths) {
executorService.submit(() -> processExcelFile(filePath));
}
} finally {
executorService.shutdown();
try {
if (!executorService.awaitTermination(60, TimeUnit.MINUTES)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
}
}
}
private void processExcelFile(String filePath) {
System.out.println("线程开始");
try {
List<List<String>> excelData = ExcelReader.readExcel(filePath);
String tableName = getTableNameFromFilePath(filePath);
String prefix = getPrefixFromFilePath(filePath);
for (List<String> columnData : excelData) {
String style = columnData.get(0);
for (int i = 1; i < columnData.size(); i++) {
String fileName = columnData.get(i);
if (StringUtils.isBlank(fileName)) {
continue;
}
if ("X".equals(style)) {
attributeRetrievalMapper.updateStyleByFileName("X", prefix + fileName, tableName);
System.out.println(fileName);
} else {
attributeRetrievalMapper.updateStyleByFileName(style, prefix + fileName, tableName);
System.out.println(fileName);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private String getTableNameFromFilePath(String filePath) {
if (filePath.contains("Blouse")) {
return "female_top";
} else if (filePath.contains("Dress")) {
return "female_dress";
} else if (filePath.contains("Outerwear")) {
return "female_outwear";
} else if (filePath.contains("Skirt")) {
return "female_skirt";
} else if (filePath.contains("Trousers")) {
return "female_pants";
}
return "";
}
private String getPrefixFromFilePath(String filePath) {
if (filePath.contains("Blouse")) {
return "blouse/";
} else if (filePath.contains("Dress")) {
return "dress/";
} else if (filePath.contains("Outerwear")) {
return "outwear/";
} else if (filePath.contains("Skirt")) {
return "skirt/";
} else if (filePath.contains("Trousers")) {
return "trousers/";
}
return "";
}
// public static List<String> getFileNames(String directoryPath) {
// List<String> fileNames = new ArrayList<>();
// Path path = Paths.get(directoryPath);
//
// try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
// for (Path entry : stream) {
// if (Files.isRegularFile(entry)) {
// fileNames.add(entry.getFileName().toString());
// }
// }
// } catch (IOException e) {
// System.err.println("Error reading directory: " + e.getMessage());
// }
//
// return fileNames;
// }
}

View File

@@ -11,4 +11,26 @@ public class CommonConstant {
// 单位 秒 一天过期 in redis
public static final Long GENERATE_RESULT_EXPIRE_TIME = 24 * 60 * 60L;
public static class Numbers{
public static final Integer NUMBER_10 = 10;
public static final Integer NUMBER_1000 = 1000;
public static final Integer NUMBER_10080 = 10080;
}
public static final String GENERATE_PATH = "/api/generate_image";
public static final String GENERATE_SINGLE_LOGO = "/api/generate_single_logo";
public static final String GENERATE_SLOGAN = "/api/slogan";
public static final String GENERATE_CANCEL = "/api/generate_cancel/";
public static final String GENERATE_LOGO_SINGLE_CANCEL = "/api/generate_single_logo_cancel/";
public static final String PYTHON_PORT_9996 = "9996";
public static final String PYTHON_PORT_9997 = "9997";
}

View File

@@ -1,5 +1,7 @@
package com.ai.da.common.enums;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
/**
@@ -36,7 +38,18 @@ public enum CollectionLevel2TypeEnum {
* 男装下装
*/
BOTTOMS("Bottoms"),
;
/**
* 印花-logo
*/
LOGO("Logo"),
/**
* 印花-slogan
*/
SLOGAN("Slogan"),
/**
* 印花-图案
*/
Pattern("Pattern");
private String realName;
@@ -51,4 +64,8 @@ public enum CollectionLevel2TypeEnum {
public static CollectionLevel2TypeEnum of(String realName) {
return Stream.of(CollectionLevel2TypeEnum.values()).filter(v -> v.getRealName().equals(realName)).findFirst().orElse(null);
}
public static List<String> printType() {
return Arrays.asList(LOGO.getRealName(), SLOGAN.getRealName(), Pattern.getRealName());
}
}

View File

@@ -8,19 +8,29 @@ import lombok.Getter;
public enum CreditsEventsEnum {
PRICE("price","6"),
// PRICE("price","0.1"),
BUY_CREDITS("Buy Credits","600"),
BUY_CREDITS("Buy Credits","60"),
// BUY_CREDITS("Buy Credits","10"),
INIT("init", "500"),
// 每月更新
INIT_YEARLY("init_yearly", "6000"),
INIT_MONTHLY("init_monthly", "5000"),
INIT_TRIAL("init_trial", "100"),
INIT_WEEKLY("init_weekly","6000"),
DAILY_CHECKIN("Daily Check-In", "20"),
// SUPER_RESOLUTION("Super Resolution","30"),
SUPER_RESOLUTION("Super Resolution","10"),
SLOGAN("Slogan","10"),
LOGO("Logo","5"),
PATTERN("Pattern","5"),
MOOD_BOARD("MoodBoard","5"),
SKETCH_BOARD("SketchBoard","5"),
TO_PRODUCT_IMAGE("ToProductImage","5"),
RELIGHT("Relight","5"),
QUESTIONNAIRE("Questionnaire","100"),
SOCIAL_MEDIA_SHARING("Social Media Sharing","20"),
// SUPER_RESOLUTION("Super Resolution","300"),
SUPER_RESOLUTION("Super Resolution","5"),
OTHER("Other","10");
OTHER("Other","5");
private String name;

View File

@@ -48,8 +48,9 @@ public class AuthenticationFilter extends OncePerRequestFilter {
"/api/third/party/addUser","/api/third/party/addTrialUser", "/api/third/party/editUser", "/api/element/initDefaultSysFile",
"/api/third/party/addNoLoginRequiredNew","/api/third/party/deleteNoLoginRequiredNew",
"/api/third/party/existNoLoginRequired","/api/third/party/getRedirectUrl",
// "/api/python/chatStream",
"/api/python/flush","/api/account/healthy","/api/ali-pay/trade/notify","/api/paypal/ipn/back","/api/alipay-hk/trade/notify"
"/api/python/flush","/api/account/healthy","/api/ali-pay/trade/notify","/api/paypal/ipn/back","/api/alipay-hk/trade/notify",
"/api/portfolio/page", "/api/portfolio/detail", "/api/portfolio/commentPage", "/api/portfolio/viewsIncrease",
"/api/account/designWorksRegister","/api/account/questionnaire"
);
@Override

View File

@@ -0,0 +1,31 @@
package com.ai.da.common.task;
import com.ai.da.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
@Slf4j
public class AccountTask {
@Resource
private AccountService accountService;
/** 每周日晚上刷新 年付用户、月付用户的积分 */
@Scheduled(cron = "59 59 23 ? * SUN")
// @Scheduled(cron = "59 59 23 * * ?")
public void refreshCreditsMonthly(){
log.info("每周日晚115959刷新付费用户积分为 6000");
accountService.refreshCreditsWeekly();
}
// todo 多久执行一次?
@Scheduled(cron = "0 */5 * * * *") // Run every 5 minutes
public void getPaidUser(){
// 获取code-create 表中 指定日期之后 订单状态为wc-processing的订单
accountService.extendValidityForCC();
}
}

View File

@@ -23,7 +23,7 @@ public class PaypalTask {
@Resource
private PayPalCheckoutService payPalCheckoutService;
@Scheduled(cron = "0/30 * * * * ?")
// @Scheduled(cron = "0/30 * * * * ?")
public void orderConfirm() throws SerializeException {
log.info("PayPal orderConfirm 被执行......");

View File

@@ -50,6 +50,9 @@ public class AlipayHKEncryptionUtil {
@Value("${alipayHK.rsaPublicKey}")
private String publicKeyPath;
@Value("${alipayHK.CODPublicKey}")
private String CODPublicKeyPath;
/**
* 加密
@@ -70,7 +73,8 @@ public class AlipayHKEncryptionUtil {
// The path to the rsa private key file, DO NOT save this key to a publicly accessible location
// 使用私钥创建数字签名
// Mode, aes-128-cbc for 128bit key
String mode = "aes-128-cbc";
// String mode = "aes-128-cbc";
String mode = "aes-256-cbc";
// Padding mode
String padding = "pkcs7";
// signature alogrithm
@@ -84,18 +88,11 @@ public class AlipayHKEncryptionUtil {
requestMessage.setRequest_uuid(UUID.randomUUID().toString());
// HashMap<String, Object> param = new HashMap<>();
requestMessage.setParameters(param);
/*String orderRef = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
param.put("order_ref", orderRef);
param.put("amount", 208.12);
param.put("subject", "四月帳單 April Bill");
param.put("wallet", "ALIPAYHK");
param.put("segment_id", segmentId);
param.put("payment_solution", "WAP");*/
// Serialize message body
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String content = gson.toJson(requestMessage);
log.info("alipay-hk request 加密前:{}", content);
// Secure random iv 获取随机种子
SecureRandom secureRandom = new SecureRandom();
@@ -153,7 +150,7 @@ public class AlipayHKEncryptionUtil {
// Encode to json
String jsonEncoded = JSONObject.toJSONString(alipayHKRequestDTO);
log.info(jsonEncoded);
log.info("alipay-hk request 加密加签后:{}",jsonEncoded);
// String info = AlipayHKRequestUtil.createOrder(alipayHKRequestDTO);
// log.info(info);
@@ -341,18 +338,25 @@ public class AlipayHKEncryptionUtil {
Base64.Decoder decoder = Base64.getDecoder();
// Verify key
try {
// PublicKey publicKey = readPublicKey(new File(publicKeyPath));
InputStreamReader isrPub = new InputStreamReader(new FileInputStream(publicKeyPath));
// 从指定的路径读取公钥文件
InputStreamReader isrPub = new InputStreamReader(new FileInputStream(CODPublicKeyPath));
PEMParser pemParserPub = new PEMParser(isrPub);
// 使用 PEMParser 解析公钥文件
SubjectPublicKeyInfo pubInfo = (SubjectPublicKeyInfo) pemParserPub.readObject();
// 从 SubjectPublicKeyInfo 创建 AsymmetricKeyParameter 对象
AsymmetricKeyParameter pubKey = PublicKeyFactory.createKey(pubInfo);
// Verifying
// Verifying; 创建 RSADigestSigner 对象并使用 SHA-256 作为摘要算法
RSADigestSigner verifier = new RSADigestSigner(new SHA256Digest());
// 初始化 RSADigestSigner设置为验证模式并提供公钥参数
verifier.init(false, pubKey);
byte[] signMessageForVerifing = data.getBytes();
byte[] signatureBase64ForVerifing = decoder.decode(signatureBase64);
verifier.update(signMessageForVerifing, 0, signMessageForVerifing.length);
Boolean verifyResult = verifier.verifySignature(signatureBase64ForVerifing);
// 将要验证的数据转换为字节数组
byte[] signMessageForVerifying = data.getBytes();
// 将 Base64 编码的签名转换为字节数组
byte[] signatureBase64ForVerifying = decoder.decode(signatureBase64);
// 使用签名器更新要验证的数据
verifier.update(signMessageForVerifying, 0, signMessageForVerifying.length);
// 验证签名并返回结果
Boolean verifyResult = verifier.verifySignature(signatureBase64ForVerifying);
return verifyResult;
} catch (Exception e) {
throw new RuntimeException(e);

View File

@@ -17,7 +17,7 @@ import org.springframework.stereotype.Component;
@Component
public class AlipayHKRequestUtil {
public String createOrder(AlipayHKRequestDTO alipayHKRequestDTO) throws IOException {
public String requestAlipayHK(AlipayHKRequestDTO alipayHKRequestDTO) {
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(30, TimeUnit.SECONDS)
.pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒)
@@ -29,7 +29,7 @@ public class AlipayHKRequestUtil {
log.info("Alipay-HK send request unix timestamp: {}", epochMilli);
String jsonString = JSONObject.toJSONString(alipayHKRequestDTO, SerializerFeature.WriteMapNullValue);
log.info(jsonString);
// log.info(jsonString);
RequestBody body = RequestBody.create(mediaType, jsonString);

View File

@@ -0,0 +1,33 @@
package com.ai.da.common.utils;
import lombok.Data;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Data
public class ExcelReader {
public static List<List<String>> readExcel(String filePath) throws IOException {
List<List<String>> data = new ArrayList<>();
try (FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(fis)) {
Sheet sheet = workbook.getSheetAt(0);
int numberOfColumns = sheet.getRow(0).getLastCellNum();
for (int i = 0; i < numberOfColumns; i++) {
List<String> columnData = new ArrayList<>();
for (Row row : sheet) {
columnData.add(row.getCell(i).getStringCellValue());
}
data.add(columnData);
}
}
return data;
}
}

View File

@@ -8,6 +8,8 @@ import io.minio.http.Method;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
@@ -26,6 +28,7 @@ import java.util.stream.Collectors;
* @description minio工具类
* @version3.0
*/
@Slf4j
@Component
public class MinioUtil {
@Autowired
@@ -370,7 +373,7 @@ public class MinioUtil {
* @param expiry 过期时间(单位:分)
* @return 文件的临时URL如果出现异常则返回null
*/
public String getPresignedUrl(String bucketName, String fileName, int expiry) {
public String getPreSignedUrl(String bucketName, String fileName, int expiry) {
try {
return minioClient.getPresignedObjectUrl(
GetPresignedObjectUrlArgs.builder()
@@ -386,7 +389,7 @@ public class MinioUtil {
}
}
public String getPresignedUrl(String path, int expiry) {
public String getPreSignedUrl(String path, int expiry) {
if (LocalCacheUtils.getPresignedUrlCache(path) != null) {
return LocalCacheUtils.getPresignedUrlCache(path);
} else {
@@ -396,12 +399,28 @@ public class MinioUtil {
int index = path.indexOf("/");
String bucketName = path.substring(0, index);
String fileName = path.substring(index + 1);
String presignedUrl = getPresignedUrl(bucketName, fileName, expiry);
String presignedUrl = getPreSignedUrl(bucketName, fileName, expiry);
LocalCacheUtils.setPresignedUrlCache(path, presignedUrl);
return presignedUrl;
}
}
public String getPreSignedUrl(String path, int expiry, boolean resetCache) {
if (resetCache || LocalCacheUtils.getPresignedUrlCache(path) == null) {
if (!path.contains("/")) {
throw new BusinessException("The path is error!");
}
int index = path.indexOf("/");
String bucketName = path.substring(0, index);
String fileName = path.substring(index + 1);
String presignedUrl = getPreSignedUrl(bucketName, fileName, expiry);
LocalCacheUtils.setPresignedUrlCache(path, presignedUrl);
return presignedUrl;
} else {
return LocalCacheUtils.getPresignedUrlCache(path);
}
}
/**
* 将桶名、文件名从url中分离出来
*
@@ -419,7 +438,7 @@ public class MinioUtil {
fileName.append("/");
}
}
return getPresignedUrl(bucketName, String.valueOf(fileName), expiry);
return getPreSignedUrl(bucketName, String.valueOf(fileName), expiry);
}
public boolean doesObjectExist(String bucketName, String objectName) {
@@ -437,11 +456,33 @@ public class MinioUtil {
}
}
public String base64Upload(String base64, String bucketName){
public String base64UploadToPath(String base64, String bucketName, String path){
String[] parts = base64.split(",");
String imageType = parts[0].split("/")[1].split(";")[0];
String base64Data = parts[1];
return uploadImageFromBase64(bucketName, base64Data, imageType);
byte[] imageBytes = Base64.getDecoder().decode(base64Data);
String fileName;
if (!StringUtil.isNullOrEmpty(path)){
fileName = path + "." + imageType; // or any other image format
}else {
fileName = UUID.randomUUID() + "." + imageType;
}
try (InputStream in = new ByteArrayInputStream(imageBytes)) {
minioClient.putObject(PutObjectArgs.builder()
.bucket(bucketName)
.object(fileName)
.stream(in, in.available(), -1)
.contentType("image/" + imageType) // Set the content type according to your image format
.build()
);
return bucketName + "/" + fileName;
} catch (Exception e) {
log.error(e.getMessage());
return null; // or throw an exception
}
}
}

View File

@@ -7,10 +7,12 @@ import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Slf4j
@Component
@@ -164,4 +166,54 @@ public class RedisUtil {
redisTemplate.delete(key);
}
public final static String PORTFOLIO_LIKE_KEY = "portfolio:like:";
public void likePost(Long portfolioId, Long userId) {
redisTemplate.opsForSet().add(PORTFOLIO_LIKE_KEY + portfolioId, String.valueOf(userId));
}
public Long getLikeCount(Long portfolioId) {
String key = PORTFOLIO_LIKE_KEY + portfolioId;
return redisTemplate.opsForSet().size(key);
}
public List<Long> getLikedPortfolios(Long userId) {
// 获取所有包含PORTFOLIO_LIKE_KEY的键
Set<String> likedPortfolios = redisTemplate.keys(PORTFOLIO_LIKE_KEY + "*");
// 如果没有喜欢的,返回空列表
if (likedPortfolios == null || likedPortfolios.isEmpty()) {
return new ArrayList<>();
}
// 过滤出包含指定用户ID的键并提取投资组合ID
return likedPortfolios.stream()
.filter(key -> redisTemplate.opsForSet().isMember(key, String.valueOf(userId)))
.map(key -> Long.valueOf(key.replace(PORTFOLIO_LIKE_KEY, "")))
.collect(Collectors.toList());
}
public void unLikePost(Long portfolioId, Long userId) {
redisTemplate.opsForSet().remove(PORTFOLIO_LIKE_KEY + portfolioId, userId.toString());
}
// 检查用户是否喜欢某个作品
public boolean isPostLikedByUser(Long portfolioId, Long userId) {
String key = PORTFOLIO_LIKE_KEY + portfolioId;
Boolean isMember = redisTemplate.opsForSet().isMember(key, userId.toString());
return isMember != null && isMember;
}
public final static String PORTFOLIO_VIEW_KEY = "portfolio:view:";
public void increaseViewCount(Long portfolioId) {
String key = PORTFOLIO_VIEW_KEY + portfolioId;
redisTemplate.opsForValue().increment(key);
}
public Long getViewCount(Long portfolioId) {
String key = PORTFOLIO_VIEW_KEY + portfolioId;
return redisTemplate.opsForValue().increment(key, 0);
}
}

View File

@@ -0,0 +1,364 @@
package com.ai.da.common.utils;
import com.ai.da.common.config.exception.BusinessException;
import com.ai.da.common.constant.CommonConstant;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.model.*;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;
import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest;
import javax.annotation.PostConstruct;
import java.io.*;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Component
public class S3Util {
@Value("${aws.s3.accessKeyId}")
private String accessKeyId;
@Value("${aws.s3.secretKey}")
private String secretKey;
@Value("${aws.s3.regionName}")
private String region;
public static String S3_ACCESS_KEY_ID = null;
public static String S3_SECRET_KEY = null;
public static String S3_REGION = null;
@PostConstruct
public void init() {
S3_ACCESS_KEY_ID = accessKeyId;
S3_SECRET_KEY = secretKey;
S3_REGION = region;
}
private static S3Client s3Client;
private static S3Presigner s3Presigner;
/**
* @return software.amazon.awssdk.services.s3.S3Client
* @description: 获取S3客户端对象
*/
public synchronized S3Client getS3Client() {
if (null == s3Client) {
s3Client = S3Client.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(S3_ACCESS_KEY_ID, S3_SECRET_KEY)))
// .endpointOverride(URI.create(S3_URI))
.serviceConfiguration(item -> item.pathStyleAccessEnabled(true).checksumValidationEnabled(false))
.region(Region.of(S3_REGION))
.build();
}
return s3Client;
}
/**
* @return software.amazon.awssdk.services.s3.presigner.S3Presigner
* @description: 获取预签名对象
*/
public synchronized S3Presigner getS3PreSigner() {
if (null == s3Presigner) {
s3Presigner = S3Presigner.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(S3_ACCESS_KEY_ID, S3_SECRET_KEY)))
// .endpointOverride(URI.create(S3_URI))
.serviceConfiguration(S3Configuration.builder()
.checksumValidationEnabled(false)
.pathStyleAccessEnabled(true)
.build())
.region(Region.of(S3_REGION))
.build();
}
return s3Presigner;
}
public String uploadImageFromBase64(String bucketName, String base64Image, String imageType) {
S3Client s3Client = getS3Client();
byte[] imageBytes = Base64.getDecoder().decode(base64Image);
String fileName = UUID.randomUUID() + "." + imageType; // or any other image format
try (InputStream in = new ByteArrayInputStream(imageBytes)) {
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.bucket(bucketName)
.contentType("image/png")
.contentLength((long) in.available())
.key(fileName)
.acl(ObjectCannedACL.PUBLIC_READ)
.build();
s3Client.putObject(putObjectRequest, RequestBody.fromInputStream(in, in.available()));
log.info("uploadImageFromBase64 上传的位置:桶 - {},路径 - {}", bucketName, fileName);
return bucketName + "/" + fileName;
} catch (Exception e) {
e.printStackTrace();
return null; // or throw an exception
}
}
public String upload(String bucketName, String path, MultipartFile file) {
S3Client s3Client = getS3Client();
try {
String fileName = file.getOriginalFilename();
assert fileName != null;
String[] split = fileName.split("\\.");
if (split.length > 1) {
fileName = path + "/" + UUID.randomUUID() + "." + split[split.length - 1];
} else {
fileName = path + "/" + UUID.randomUUID();
}
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.bucket(bucketName)
.contentType(file.getContentType())
.contentLength(file.getSize())
.key(fileName)
.acl(ObjectCannedACL.PUBLIC_READ)
.build();
s3Client.putObject(putObjectRequest, RequestBody.fromInputStream(file.getInputStream(), file.getSize()));
log.info("upload 上传的位置:桶 - {},路径 - {}", bucketName, fileName);
return bucketName + "/" + fileName;
} catch (Exception e) {
log.error("上传文件到S3失败 异常:{}", e.getMessage());
return null;
}
}
// todo
public String upload(String bucketName, String path, MultipartFile file, String copy) {
S3Client s3Client = getS3Client();
InputStream in = null;
try {
in = file.getInputStream();
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.bucket(bucketName)
.contentType(file.getContentType())
.contentLength(file.getSize())
.key(path)
.acl(ObjectCannedACL.PUBLIC_READ)
.build();
s3Client.putObject(putObjectRequest, RequestBody.fromInputStream(file.getInputStream(), file.getSize()));
log.info("upload-copy 上传的位置:桶 - {},路径 - {}", bucketName, path);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bucketName + "/" + path;
}
public InputStream download(String path) {
if (!path.contains("/")) {
throw new BusinessException("the.path.is.error");
}
int index = path.indexOf("/");
String bucketName = path.substring(0, index);
String objectName = path.substring(index + 1);
return download(bucketName, objectName);
}
public InputStream download(String bucketName, String objectName) {
try {
S3Client s3Client = getS3Client();
GetObjectRequest objectRequest = GetObjectRequest
.builder()
.key(objectName)
.bucket(bucketName)
.build();
// ResponseBytes<GetObjectResponse> objectBytes = s3.getObjectAsBytes(objectRequest);
ResponseBytes<GetObjectResponse> objectAsBytes = s3Client.getObjectAsBytes(objectRequest);
byte[] data = objectAsBytes.asByteArray();
log.info("download 下载图片位置:桶 - {},路径 - {}", bucketName, objectName);
return new ByteArrayInputStream(data);
/*// Write the data to a local file.
File myFile = new File("files/images.png");
OutputStream os = new FileOutputStream(myFile);
os.write(data);
System.out.println("Successfully obtained bytes from an S3 object");
os.close();
return null;*/
// return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
} catch (Exception e) {
log.error("");
throw new BusinessException("");
}
}
public void deleteObject(String path) {
if (!path.contains("/")) {
throw new BusinessException("The path is error!");
}
int index = path.indexOf("/");
String bucketName = path.substring(0, index);
String objectName = path.substring(index + 1);
deleteObject(bucketName, objectName);
}
public void deleteObject(String bucketName, String objectName) {
try {
S3Client s3Client = getS3Client();
DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest
.builder()
.key(objectName)
.bucket(bucketName)
.build();
s3Client.deleteObject(deleteObjectRequest);
log.info("Object " + objectName + " successfully removed from bucket " + bucketName);
} catch (Exception e) {
e.printStackTrace();
log.info("Error while removing object " + objectName + " from bucket " + bucketName + ": " + e.getMessage());
}
}
public String getPreSignedUrl(String path, int expiry) {
if (LocalCacheUtils.getPresignedUrlCache(path) != null) {
return LocalCacheUtils.getPresignedUrlCache(path);
} else {
if (!path.contains("/")) {
throw new BusinessException("The path is error!");
}
int index = path.indexOf("/");
String bucketName = path.substring(0, index);
String fileName = path.substring(index + 1);
String preSignedUrl = getPreSignatureUrl(bucketName, fileName, expiry);
LocalCacheUtils.setPresignedUrlCache(path, preSignedUrl);
return preSignedUrl;
}
}
/**
* @param keyName key名称: test/2022/06/123.pdf
* @param signatureDurationTime 有效期 单位:秒
* @return java.lang.String
* @description: 生成预签名URL
*/
public String getPreSignatureUrl(String bucket, String keyName, Integer signatureDurationTime) {
String preSignatureUrl = "";
try {
S3Presigner s3PreSigner = getS3PreSigner();
S3Client s3Client = getS3Client();
setObjectAcl(s3Client, bucket, keyName, ObjectCannedACL.PUBLIC_READ);
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.bucket(bucket)
.key(keyName)
.build();
//设置预签名URL可访问时间
signatureDurationTime = Optional.ofNullable(signatureDurationTime)
.map(item -> {
if (item.intValue() > CommonConstant.Numbers.NUMBER_10080) {
item = CommonConstant.Numbers.NUMBER_10080;
}
return item;
})
.orElse(CommonConstant.Numbers.NUMBER_10);
GetObjectPresignRequest getObjectPresignRequest = GetObjectPresignRequest.builder()
.signatureDuration(Duration.ofMinutes(signatureDurationTime))
.getObjectRequest(getObjectRequest)
.build();
PresignedGetObjectRequest presignedGetObjectRequest =
s3PreSigner.presignGetObject(getObjectPresignRequest);
preSignatureUrl = String.valueOf(presignedGetObjectRequest.url());
} catch (Exception e) {
log.error("生成预签名URL失败异常{}", e.getMessage());
}
return preSignatureUrl;
}
public static void setObjectAcl(S3Client s3, String bucketName, String keyName, ObjectCannedACL acl) {
PutObjectAclRequest aclRequest = PutObjectAclRequest.builder()
.bucket(bucketName)
.key(keyName)
.acl(acl)
.build();
s3.putObjectAcl(aclRequest);
}
public boolean doesObjectExist(String bucketName, String objectName) {
try {
S3Client s3Client = getS3Client();
HeadObjectRequest headObjectRequest = HeadObjectRequest.builder()
.bucket(bucketName)
.key(objectName)
.build();
HeadObjectResponse headObjectResponse = s3Client.headObject(headObjectRequest);
return true;
} catch (Exception e) {
log.info("指定文件 {}/{} 不存在", bucketName, objectName);
// 如果发生异常,说明文件不存在或者出现了其他错误
return false;
}
}
public String base64UploadToPath(String base64, String bucketName, String path) {
S3Client s3Client = getS3Client();
String[] parts = base64.split(",");
String imageType = parts[0].split("/")[1].split(";")[0];
String base64Data = parts[1];
byte[] imageBytes = Base64.getDecoder().decode(base64Data);
String fileName;
if (!StringUtil.isNullOrEmpty(path)) {
fileName = path + "." + imageType; // or any other image format
} else {
fileName = UUID.randomUUID() + "." + imageType;
}
try (InputStream in = new ByteArrayInputStream(imageBytes)) {
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.bucket(bucketName)
.contentType("image/" + imageType)
.contentLength((long) in.available())
.key(fileName)
.acl(ObjectCannedACL.PUBLIC_READ)
.build();
s3Client.putObject(putObjectRequest, RequestBody.fromInputStream(in, in.available()));
log.info("base64UploadToPath 上传的位置:桶 - {},路径 - {}", bucketName, fileName);
return bucketName + "/" + fileName;
} catch (Exception e) {
e.printStackTrace();
return null; // or throw an exception
}
}
public List<String> listAllBucket() {
S3Client s3Client = getS3Client();
ListBucketsResponse listBucketsResponse = s3Client.listBuckets();
List<Bucket> buckets = listBucketsResponse.buckets();
return buckets.stream().map(Bucket::name).collect(Collectors.toList());
}
}

View File

@@ -57,6 +57,7 @@ public class SendEmailUtil {
* 登入模板id
*/
public static Long LOGIN_TEMPLATE_ID = 58020L;
public static Long PORTFOLIO_REGISTER_ID = 124847L;
/**
* 修改密码模板id
*/
@@ -450,7 +451,143 @@ public class SendEmailUtil {
}
}
private final static Long QUESTIONNAIRE_FEEDBACK_EN_ID = 124151L;
private final static Long QUESTIONNAIRE_FEEDBACK_CN_ID = 124156L;
public static void questionnaireRelatedNotify(String userName, String email, String language){
try {
// 实例化一个认证对象
Credential cred = new Credential(SECRET_ID, SECRET_KEy);
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint("ses.tencentcloudapi.com");
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);
SesClient client = new SesClient(cred, "ap-hongkong", clientProfile);
SendEmailRequest req = new SendEmailRequest();
req.setFromEmailAddress(CODE_CREATE_SEND_ADDRESS);
req.setDestination(new String[]{email});
// 根据邮件类型设置不同的主题和模板
Template template = new Template();
String subject = "Thank You for Completing the AiDA System Survey";
template.setTemplateID(QUESTIONNAIRE_FEEDBACK_EN_ID);
if (language.equals("CN")) {
subject = "感谢您完成AiDA系统问卷调查";
template.setTemplateID(QUESTIONNAIRE_FEEDBACK_CN_ID);
}
JSONObject parameter = new JSONObject();
parameter.put("userName", userName);
template.setTemplateData(parameter.toJSONString());
req.setSubject(subject);
req.setTemplate(template);
// 发送邮件
SendEmailResponse resp = client.SendEmail(req);
log.info("短信发送结果res###{}", SendEmailResponse.toJsonString(resp));
} catch (TencentCloudSDKException e) {
log.info("邮件发送失败###{}", e.toString());
throw new BusinessException("failed.to.send.mail");
}
}
private final static Long NEW_USER_PAYMENT_NOTIFICATION_EN = 124889L;
private final static Long NEW_USER_PAYMENT_NOTIFICATION_CN = 124888L;
private final static Long RENEWAL_NOTIFICATION_FOR_OLD_USER_EN = 124892L;
private final static Long RENEWAL_NOTIFICATION_FOR_OLD_USER_CN = 124891L;
public static void notificationForPaidUser(String receiverAddress, int emailType, String country, String userName, String date){
try {
// 实例化一个认证对象
Credential cred = new Credential(SECRET_ID, SECRET_KEy);
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint("ses.tencentcloudapi.com");
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);
SesClient client = new SesClient(cred, "ap-hongkong", clientProfile);
SendEmailRequest req = new SendEmailRequest();
req.setFromEmailAddress(SEND_ADDRESS);
req.setDestination(new String[]{receiverAddress});
// 根据邮件类型设置不同的主题和模板
String subject = "";
Template template = new Template();
JSONObject parameter = new JSONObject();
switch (emailType) {
// 新用户
case 1:
subject = "Welcome to AiDA!";
if (country.equals("China")) {
template.setTemplateID(NEW_USER_PAYMENT_NOTIFICATION_CN);
}else {
template.setTemplateID(NEW_USER_PAYMENT_NOTIFICATION_EN);
}
parameter.put("userName", userName);
parameter.put("email", receiverAddress);
break;
// 续费用户
case 2:
subject = "Account renewal notification";
if (country.equals("China")) {
template.setTemplateID(RENEWAL_NOTIFICATION_FOR_OLD_USER_CN);
}else {
template.setTemplateID(RENEWAL_NOTIFICATION_FOR_OLD_USER_EN);
}
break;
default:
break;
}
parameter.put("userName", userName);
parameter.put("date", date);
template.setTemplateData(parameter.toJSONString());
req.setSubject(subject);
req.setTemplate(template);
// 发送邮件
SendEmailResponse resp = client.SendEmail(req);
log.info("短信发送结果res###{}", SendEmailResponse.toJsonString(resp));
} catch (TencentCloudSDKException e) {
log.info("邮件发送失败###{}", e.toString());
throw new BusinessException("failed.to.send.mail");
}
}
public static Boolean designWorksRegister(String userEmail, String randomVerifyCode) {
try {
// 实例化一个认证对象入参需要传入腾讯云账户secretIdsecretKey,此处还需注意密钥对的保密
// 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
Credential cred = new Credential(SECRET_ID, SECRET_KEy);
// 实例化一个http选项可选的没有特殊需求可以跳过
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint("ses.tencentcloudapi.com");
// 实例化一个client选项可选的没有特殊需求可以跳过
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);
// 实例化要请求产品的client对象,clientProfile是可选的
SesClient client = new SesClient(cred, "ap-hongkong", clientProfile);
// 实例化一个请求对象,每个接口都会对应一个request对象
SendEmailRequest req = new SendEmailRequest();
req.setFromEmailAddress(SEND_ADDRESS);
req.setDestination(new String[]{userEmail});
String subject = "Tourist registration";
req.setSubject(subject);
req.setTemplate(contractTemplate(PORTFOLIO_REGISTER_ID, randomVerifyCode, null));
// 返回的resp是一个SendEmailResponse的实例与请求对象对应
SendEmailResponse resp = client.SendEmail(req);
// 输出json格式的字符串回包
log.info("短信发送结果res###{}", SendEmailResponse.toJsonString(resp));
return Boolean.TRUE;
} catch (TencentCloudSDKException e) {
log.info("邮件发送失败###{}", e.toString());
throw new BusinessException("failed.to.send.mail");
}
}
}

View File

@@ -153,4 +153,28 @@ public class AccountController {
accountService.upgradeNotification();
return Response.success(true);
}
@CrossOrigin
@ApiOperation(value = "广场用户注册")
@PostMapping("/designWorksRegister")
public Response<Boolean> designWorksRegister(@Valid @RequestBody AccountDesignWorksRegisterDTO accountDesignWorksRegisterDTO) {
return Response.success(accountService.designWorksRegister(accountDesignWorksRegisterDTO));
}
@CrossOrigin
@ApiOperation(value = "广场用户注册")
@PostMapping("/designWorksRegisterCode")
public Response<AccountLoginVO> designWorksRegisterCode(@Valid @RequestBody AccountDesignWorksRegisterDTO accountDesignWorksRegisterDTO) {
return Response.success(accountService.designWorksRegisterCode(accountDesignWorksRegisterDTO));
}
/**
* 填写调查问卷
* @return
*/
@ApiOperation(value = "填写调查问卷")
@PostMapping("/questionnaire")
public Response<Boolean> questionnaire(@Valid @RequestBody String questionnaireInfo){
return Response.success(accountService.collectQuestionnaires(questionnaireInfo));
}
}

View File

@@ -8,7 +8,6 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;
@CrossOrigin
@RestController
@@ -21,20 +20,26 @@ public class AlipayHKController {
private AlipayHKService alipayHKService;
@ApiOperation(value = "创建订单")
@PostMapping(value = "/createOrder")
public Response<String> createOrder(@RequestParam Integer amount, @RequestParam String wallet) {
@PostMapping(value = "/createOrder/{wallet}/{amount}")
public Response<String> createOrder(@PathVariable Integer amount, @PathVariable String wallet) {
String order = alipayHKService.createOrder(amount, wallet);
return Response.success(order);
}
@ApiOperation("支付通知")
@PostMapping("/trade/notify")
public String callback(@RequestParam Map<String, String> params){
return alipayHKService.callback(params);
public String callback(@RequestBody String paramString){
log.info("alipay-hk callback parameter : {}", paramString);
return alipayHKService.callback(paramString);
}
@ApiOperation("订单查询")
@PostMapping("/trade/query/{orderRef}")
public Response<String> queryOrder(@PathVariable String orderRef){
String s = alipayHKService.queryDetail(orderRef);
return Response.success(s);
}
}

View File

@@ -27,11 +27,11 @@ public class GenerateController {
@Resource
private GenerateService generateService;
@ApiOperation("自动识别sketch的caption 暂时未上")
/*@ApiOperation("自动识别sketch的caption 暂时未上")
@PostMapping("/caption")
public Response<GenerateCaptionVO> generateCaption(@RequestParam Long sketchElementId) {
return Response.success(generateService.generateCaption(sketchElementId));
}
}*/
/*@ApiOperation("通过文字、图片生成图片")
@PostMapping("/sketchAndPrint")
@@ -63,8 +63,9 @@ public class GenerateController {
@GetMapping("/stopWaiting")
public Response<String> stopWaiting(@RequestParam("userId") Long userId,
@RequestParam("uniqueId") List<String> uniqueId,
@RequestParam("timeZone") String timeZone) {
generateService.cancelGenerate(userId, uniqueId, timeZone);
@RequestParam("timeZone") String timeZone,
@RequestParam("type") String type) {
generateService.cancelGenerate(userId, uniqueId, timeZone, type);
return Response.success("stop waiting successfully");
}

View File

@@ -163,7 +163,7 @@ public class LibraryController {
Response<String> response = new Response();
log.info("Models打点预览入参####{}", JSON.toJSONString(modelsDotDTO));
String url = libraryModelPointService.modelsDot(modelsDotDTO);
response.setData(minioUtil.getPresignedUrl(url, 24 * 60));
response.setData(minioUtil.getPreSignedUrl(url, 24 * 60));
return response;
}

View File

@@ -2,18 +2,17 @@ package com.ai.da.controller;
import com.ai.da.common.response.PageBaseResponse;
import com.ai.da.common.response.Response;
import com.ai.da.model.dto.PortfolioDTO;
import com.ai.da.model.dto.QueryPortfolioPageDTO;
import com.ai.da.model.dto.*;
import com.ai.da.model.vo.CommentVO;
import com.ai.da.model.vo.PortfolioVO;
import com.ai.da.model.vo.UserLikeChooseVO;
import com.ai.da.model.vo.UserLikeGroupVO;
import com.ai.da.service.PortfolioService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.validation.Valid;
@@ -29,16 +28,24 @@ public class PortfolioController {
@ApiOperation(value = "发布作品集")
@PostMapping("/publish")
public Response<Boolean> preLogin(@Valid @RequestBody PortfolioDTO portfolioDTO) {
return Response.success(portfolioService.publish(portfolioDTO));
public Response<Boolean> preLogin(@RequestParam("file") MultipartFile canvas, @RequestParam("data") String data) {
return Response.success(portfolioService.publish(canvas, data));
}
@ApiOperation(value = "删除作品集")
@GetMapping("/delete")
public Response<Boolean> delete(@RequestParam("id") Long id) {
return Response.success(portfolioService.delete(id));
}
@CrossOrigin
@ApiOperation(value = "作品集page")
@PostMapping("/page")
public Response<PageBaseResponse<PortfolioVO>> page(@Valid @RequestBody QueryPortfolioPageDTO query) {
return Response.success(portfolioService.page(query));
}
@CrossOrigin
@ApiOperation(value = "作品详情")
@PostMapping("/detail")
public Response<PortfolioVO> detail(@Valid @RequestBody PortfolioDTO portfolioDTO) {
@@ -56,4 +63,58 @@ public class PortfolioController {
public Response<PortfolioVO> update(@Valid @RequestBody PortfolioDTO portfolioDTO) {
return Response.success(portfolioService.update(portfolioDTO));
}
@ApiOperation(value = "广场用户注册")
@PostMapping("/designWorksRegister")
public Response<Boolean> designWorksRegister(@Valid @RequestBody DesignWorksRegisterDTO designWorksRegisterDTO) {
return Response.success(portfolioService.designWorksRegister(designWorksRegisterDTO));
}
@ApiOperation(value = "喜欢")
@GetMapping("/like")
public Response<Boolean> like(@RequestParam("id") Long id) {
return Response.success(portfolioService.like(id));
}
@ApiOperation(value = "不喜欢")
@GetMapping("/unlike")
public Response<Boolean> unlike(@RequestParam("id") Long id) {
return Response.success(portfolioService.unlike(id));
}
@ApiOperation(value = "获取点赞数")
@GetMapping("/getLikeCount")
public Response<Long> getLikeCount(@RequestParam("id") Long id) {
return Response.success(portfolioService.getLikeCount(id));
}
@ApiOperation(value = "评论")
@PostMapping("/comment")
public Response<Boolean> comment(@Valid @RequestBody CommentDTO commentDTO) {
return Response.success(portfolioService.comment(commentDTO));
}
@ApiOperation(value = "评论列表")
@PostMapping("/commentPage")
public Response<PageBaseResponse<CommentVO>> commentPage(@Valid @RequestBody CommentPageDTO commentPageDTO) {
return Response.success(portfolioService.commentPage(commentPageDTO));
}
@ApiOperation(value = "增加浏览量")
@GetMapping("/viewsIncrease")
public Response<Boolean> viewsIncrease(@RequestParam("id") Long id) {
return Response.success(portfolioService.viewsIncrease(id));
}
@ApiOperation(value = "浏览量获取")
@GetMapping("/viewsGet")
public Response<Long> viewsGet(@RequestParam("id") Long id) {
return Response.success(portfolioService.viewsGet(id));
}
@ApiOperation(value = "删除评论")
@PostMapping("/commentDelete")
public Response<Boolean> commentDelete(@Valid @RequestBody CommentDTO commentDTO) {
return Response.success(portfolioService.commentDelete(commentDTO));
}
}

View File

@@ -8,13 +8,11 @@ import com.ai.da.common.response.Response;
import com.ai.da.common.utils.CopyUtil;
import com.ai.da.common.utils.MinioUtil;
import com.ai.da.mapper.primary.TDesignPythonOutfitMapper;
import com.ai.da.mapper.primary.entity.Account;
import com.ai.da.mapper.primary.entity.Library;
import com.ai.da.mapper.primary.entity.TDesignPythonOutfit;
import com.ai.da.mapper.primary.entity.UserLikeGroup;
import com.ai.da.mapper.primary.entity.*;
import com.ai.da.model.dto.*;
import com.ai.da.model.vo.*;
import com.ai.da.service.*;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@@ -26,6 +24,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.validation.Valid;
@@ -50,6 +49,8 @@ public class SavedCollectionController {
private MinioUtil minioUtil;
@Resource
private ClassificationService classificationService;
@Resource
private PortfolioService portfolioService;
@ApiOperation(value = "History用户分页分组列表")
@PostMapping("/queryUserGroup")
@@ -119,10 +120,18 @@ public class SavedCollectionController {
List<UserLikeVO> details = groupDetailMap.get(group.getId());
for (UserLikeVO detail : details) {
TDesignPythonOutfit tDesignPythonOutfit = designPythonOutfitMapper.selectById(detail.getDesignOutfitId());
detail.setUrl(minioUtil.getPresignedUrl(tDesignPythonOutfit.getDesignUrl(), 24 * 60));
detail.setUrl(minioUtil.getPreSignedUrl(tDesignPythonOutfit.getDesignUrl(), 24 * 60));
}
userLikeGroupVO.setGroupDetails(details);
userLikeGroupVO.setSketchCount(CollectionUtils.isEmpty(details) ? 0 : details.size());
if (userLikeGroupVO.getOriginal() == 0) {
userLikeGroupVO.setOriginalAccountName(accountService.getById(userLikeGroupVO.getOriginalAccountId()).getUserName());
Portfolio byId = portfolioService.getByIdAll(userLikeGroupVO.getOriginalPortfolioId());
if (Objects.nonNull(byId)) {
String portfolioName = byId.getPortfolioName();
userLikeGroupVO.setOriginalPortfolioName(portfolioName);
}
}
return userLikeGroupVO;
}
return null;
@@ -159,4 +168,71 @@ public class SavedCollectionController {
return Response.success(userLikeGroupService.choose(userGroupId));
}
@ApiOperation(value = "exportSave")
@PostMapping("/exportSave")
public Response<Boolean> exportSave(@RequestParam("file") MultipartFile file, @RequestParam("userLikeGroupId") Long userLikeGroupId) {
return Response.success(userLikeGroupService.exportSave(file, userLikeGroupId));
}
@ApiOperation(value = "exportSearch")
@PostMapping("/exportSearch")
public Response<JSONObject> exportSearch(@Valid @RequestBody ExportSearchDTO exportSearchDTO) {
return Response.success(userLikeGroupService.exportSearch(exportSearchDTO.getUserLikeGroupId()));
}
@ApiOperation(value = "toProduct")
@PostMapping("/toProduct")
public Response<List<ToProductImageResult>> toProduct(@Valid @RequestBody ToProductImageDTO toProductImageDTO) {
return Response.success(userLikeGroupService.toProduct(toProductImageDTO));
}
@ApiOperation(value = "toProductImageElementUpload")
@PostMapping("/toProductImageElementUpload")
public Response<ToProductElementVO> toProductImageElementUpload(@RequestParam("file") MultipartFile file, @RequestParam(value = "userlikeGroupId") Long userLikeGroupId) {
return Response.success(userLikeGroupService.toProductImageElementUpload(file, userLikeGroupId));
}
@ApiOperation(value = "productImageLike")
@PostMapping("/productImageLike")
public Response<Boolean> productImageLike(@Valid @RequestBody ProductImageLikeDTO productImageLikeDTO) {
return Response.success(userLikeGroupService.productImageLike(productImageLikeDTO));
}
@ApiOperation(value = "productImageUnLike")
@PostMapping("/productImageUnLike")
public Response<Boolean> productImageUnLike(@Valid @RequestBody ProductImageLikeDTO productImageLikeDTO) {
return Response.success(userLikeGroupService.productImageUnLike(productImageLikeDTO));
}
@ApiOperation(value = "获取生成结果")
@PostMapping("/toProductImageResult")
public Response<List<MagicToolResultVO>> getToProductImageResult(@Valid @RequestBody List<String> taskIdList) {
List<MagicToolResultVO> magicToolResultVOList = userLikeGroupService.getToProductImageResultList(taskIdList);
return Response.success(magicToolResultVOList);
}
@ApiOperation(value = "画布用户上传元素")
@PostMapping("/canvasElementUpload")
public Response<CanvasElementUpload> canvasElementUpload(@RequestParam("file") MultipartFile file) {
return Response.success(userLikeGroupService.canvasElementUpload(file));
}
@ApiOperation("productImageLikeList")
@PostMapping("/productImageLikeList")
public Response<List<ToProductImageResultVO>> productImageLikeList(@Valid @RequestBody ToProductImageDTO toProductImageDTO) {
return Response.success(userLikeGroupService.productImageLikeList(toProductImageDTO));
}
@ApiOperation(value = "relight")
@PostMapping("/relight")
public Response<List<ToProductImageResult>> relight(@Valid @RequestBody ToProductImageDTO toProductImageDTO) {
return Response.success(userLikeGroupService.relight(toProductImageDTO));
}
@ApiOperation(value = "获取relight结果")
@PostMapping("/relightResult")
public Response<List<MagicToolResultVO>> getRelightResult(@Valid @RequestBody List<String> taskIdList) {
List<MagicToolResultVO> magicToolResultVOList = userLikeGroupService.getRelightResult(taskIdList);
return Response.success(magicToolResultVOList);
}
}

View File

@@ -27,11 +27,11 @@ public class ThirdPartyController {
@Resource
private AccountService accountService;
@ApiOperation(value = "Add user information")
/*@ApiOperation(value = "Add user information")
@PostMapping("/addUser")
public Response<Boolean> addUser(@Valid @RequestBody AccountAddDTO accountAddDTO) {
return Response.success(accountService.addUser(accountAddDTO));
}
}*/
@ApiOperation(value = "Edit user information")
@PostMapping("/editUser")

View File

@@ -95,8 +95,8 @@ public class WorkspaceController {
@GetMapping("/getMannequins")
@ApiOperationSupport(order = 6)
@ApiOperation(value = "获取模特")
public Response<List<ModelsVO>> getMannequins(@RequestParam("sex") String sex) {
List<ModelsVO> modelsVO = workspaceService.getMannequins(sex);
public Response<List<ModelsVO>> getMannequins(@RequestParam("sex") String sex, @RequestParam("style") String style) {
List<ModelsVO> modelsVO = workspaceService.getMannequins(sex, style);
return Response.success(modelsVO);
}

View File

@@ -27,6 +27,6 @@ public interface AccountMapper extends CommonMapper<Account> {
* @param id
* @return
*/
Account findById(String id);
// Account findById(String id);
}

View File

@@ -0,0 +1,7 @@
package com.ai.da.mapper.primary;
import com.ai.da.common.config.mybatis.plus.CommonMapper;
import com.ai.da.mapper.primary.entity.Canvas;
public interface CanvasMapper extends CommonMapper<Canvas> {
}

View File

@@ -0,0 +1,7 @@
package com.ai.da.mapper.primary;
import com.ai.da.common.config.mybatis.plus.CommonMapper;
import com.ai.da.mapper.primary.entity.Comment;
public interface CommentMapper extends CommonMapper<Comment> {
}

View File

@@ -0,0 +1,7 @@
package com.ai.da.mapper.primary;
import com.ai.da.common.config.mybatis.plus.CommonMapper;
import com.ai.da.mapper.primary.entity.ExportFile;
public interface ExportFileMapper extends CommonMapper<ExportFile> {
}

View File

@@ -4,4 +4,5 @@ import com.ai.da.common.config.mybatis.plus.CommonMapper;
import com.ai.da.mapper.primary.entity.Portfolio;
public interface PortfolioMapper extends CommonMapper<Portfolio> {
Portfolio getByIdAll(Long originalPortfolioId);
}

View File

@@ -0,0 +1,7 @@
package com.ai.da.mapper.primary;
import com.ai.da.common.config.mybatis.plus.CommonMapper;
import com.ai.da.mapper.primary.entity.Questionnaire;
public interface QuestionnaireMapper extends CommonMapper<Questionnaire> {
}

View File

@@ -0,0 +1,8 @@
package com.ai.da.mapper.primary;
import com.ai.da.common.config.mybatis.plus.CommonMapper;
import com.ai.da.mapper.primary.entity.ToProductElement;
public interface ToProductElementMapper extends CommonMapper<ToProductElement> {
}

View File

@@ -0,0 +1,7 @@
package com.ai.da.mapper.primary;
import com.ai.da.common.config.mybatis.plus.CommonMapper;
import com.ai.da.mapper.primary.entity.ToProductImageRecord;
public interface ToProductImageRecordMapper extends CommonMapper<ToProductImageRecord> {
}

View File

@@ -0,0 +1,7 @@
package com.ai.da.mapper.primary;
import com.ai.da.common.config.mybatis.plus.CommonMapper;
import com.ai.da.mapper.primary.entity.ToProductImageResult;
public interface ToProductImageResultMapper extends CommonMapper<ToProductImageResult> {
}

View File

@@ -86,4 +86,13 @@ public class Account implements Serializable {
* 积分
*/
private BigDecimal credits;
/**
* 用于区分游客与系统用户
* 0 游客
* 1 年付用户
* 2 月付用户
* 3 试用用户
*/
private Integer systemUser;
}

View File

@@ -2,6 +2,7 @@ package com.ai.da.mapper.primary.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.EqualsAndHashCode;
@@ -24,11 +25,13 @@ public class BaseEntity implements Serializable {
/**
* 创建时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private LocalDateTime createTime;
/**
* 更新时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private LocalDateTime updateTime;
/**

View File

@@ -0,0 +1,42 @@
package com.ai.da.mapper.primary.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
/**
* Attendance
*
* @author easy-generator
* @since 2022-06-13
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("canvas")
public class Canvas implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("ID")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty("url")
private String url;
@ApiModelProperty("accountId")
private Long accountId;
@ApiModelProperty("createTime")
private LocalDateTime createTime;
}

View File

@@ -0,0 +1,9 @@
package com.ai.da.mapper.primary.entity;
import lombok.Data;
@Data
public class CanvasElementUpload {
private String url;
private String minioUrl;
}

View File

@@ -75,7 +75,7 @@ public class CollectionElement implements Serializable {
*/
private String md5;
// private String gradientString;
private String gradientString;
/**
* 创建时间

View File

@@ -0,0 +1,38 @@
package com.ai.da.mapper.primary.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("comment")
public class Comment implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private Long portfolioId;
private Long accountId;
private String comment;
// 一级父节点ID
private Long parentLevel1Id;
// 二级父节点ID
private Long parentLevel2Id;
private LocalDateTime createTime;
private Integer isDeleted;
}

View File

@@ -12,6 +12,8 @@ import java.math.BigDecimal;
public class CreditsDetail extends BaseEntity {
/** 用户id */
private Long accountId;
/** 任务id或uuid */
private String taskId;
/** 积分变更事件 */
private String changeEvent;
/** 变更积分 ( + 表示加,- 表示减) */

View File

@@ -64,7 +64,7 @@ public class DesignItemDetail implements Serializable {
*/
private String color;
// private String gradientString;
private String gradientString;
/**
* 对应的print图片的绝对路径
@@ -90,6 +90,10 @@ public class DesignItemDetail implements Serializable {
* item的优先级
*/
private Integer priority;
/**
* 未分割的只上了颜色或只有overall印花的图层
*/
private String undividedLayer;
/**
* 创建时间

View File

@@ -20,6 +20,16 @@ public class DesignItemDetailPrint {
* 关联t_design_item_detail表ID
*/
private Long designItemDetailId;
/**
* 印花的类型 print || trims
*/
private String printType;
/**
* 印花二级分类 Slogan || Logo || Pattern
*/
private String level2Type;
/**
* 印花路径
*/

View File

@@ -0,0 +1,24 @@
package com.ai.da.mapper.primary.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("export_file")
public class ExportFile implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String url;
private Long userLikeGroupId;
}

View File

@@ -33,10 +33,15 @@ public class Generate {
private String uniqueId;
/**
* Sketchboard Printboard
* Sketchboard Printboard Moodboard
*/
private String level1Type;
/**
* Slogan Logo Pattern
*/
private String level2Type;
/**
* 图片来源 collection | library
*/
@@ -62,6 +67,11 @@ public class Generate {
*/
private String modelName;
/**
* Logo 种子 相同种子 相同prompt 输出一定相同
*/
private String seed;
/**
* 创建时间
*/

View File

@@ -17,7 +17,7 @@ public class PaymentInfo extends BaseEntity{
private String tradeState;//交易状态
private Long payerTotal;//支付金额(元)
private Float payerTotal;//支付金额(元)
private String content;//通知参数
}

View File

@@ -35,12 +35,24 @@ public class Portfolio implements Serializable {
@ApiModelProperty(value = "作品类型")
private String portfolioType;
@ApiModelProperty(value = "画布ID")
private Long canvasId;
@ApiModelProperty(value = "封面ID")
private Long coverId;
@ApiModelProperty(value = "作品状态1公开0隐藏")
private Integer status;
@ApiModelProperty(value = "是否允许二次创作1允许0不允许")
private Integer openSource;
private Integer original;
private Long originalAccountId;
private Long originalPortfolioId;
@ApiModelProperty(value = "作品集作者ID")
private Long accountId;

View File

@@ -0,0 +1,18 @@
package com.ai.da.mapper.primary.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("t_questionnaire")
public class Questionnaire extends BaseEntity{
/**
* 用户所填调查问卷结果
*/
private String questionnaireInfo;
/**
* 调查问卷标题
*/
private String title;
}

View File

@@ -0,0 +1,27 @@
package com.ai.da.mapper.primary.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
public class ToProductElement implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "ID")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty(value = "userLikeGroupId")
private Long userLikeGroupId;
@ApiModelProperty(value = "url")
private String url;
@ApiModelProperty(value = "createTime")
private LocalDateTime createTime;
}

View File

@@ -0,0 +1,27 @@
package com.ai.da.mapper.primary.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
public class ToProductImageRecord implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "ID")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty(value = "userLikeGroupId")
private Long userLikeGroupId;
@ApiModelProperty(value = "prompt")
private String prompt;
@ApiModelProperty(value = "createTime")
private LocalDateTime createTime;
}

View File

@@ -0,0 +1,45 @@
package com.ai.da.mapper.primary.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
public class ToProductImageResult implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "ID")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty(value = "elementId")
private Long elementId;
@ApiModelProperty(value = "elementType")
private String elementType;
@ApiModelProperty(value = "url")
private String url;
@ApiModelProperty(value = "isLike 1是0否")
private Integer isLike;
@ApiModelProperty(value = "createTime")
private LocalDateTime createTime;
@ApiModelProperty(value = "toProductImageRecordId")
private Long toProductImageRecordId;
@ApiModelProperty(value = "taskId")
private String taskId;
@ApiModelProperty(value = "userLikeGroupId")
private Long userLikeGroupId;
@ApiModelProperty(value = "generate 结果类型")
private String resultType;
}

View File

@@ -43,6 +43,12 @@ public class UserLikeGroup implements Serializable {
*/
private String name;
private Integer original;
private Long originalAccountId;
private Long originalPortfolioId;
/**
* 创建时间
*/

View File

@@ -17,9 +17,15 @@ import java.util.List;
public interface AttributeRetrievalMapper {
List<AttributeRetrieval> getSystemSketchPool(@Param("attributeRetrievalAttrDict") AttributeRetrieval attributeRetrievalAttrDict, @Param("tableName") String tableName, @Param("poolNum") int poolNum);
List<AttributeRetrieval> getSystemSketchPool(@Param("attributeRetrievalAttrDict") AttributeRetrieval attributeRetrievalAttrDict, @Param("tableName") String tableName, @Param("poolNum") int poolNum, @Param("style") String style);
AttributeRetrieval getSystemRandom(String tableName);
AttributeRetrieval getSystemRandom(String tableName, String style);
List<AttributeRetrieval> getSystemSketchPoolBySameCategory(AttributeRetrieval attributeRetrievalAttrDict, String tableName);
List<AttributeRetrieval> getSystemSketchPoolBySameCategory(AttributeRetrieval attributeRetrievalAttrDict, String tableName, String style);
Long getIdByFileName(String fileName, String tableName);
void updateStyleById(Long idByFileName, String style, String tableName);
void updateStyleByFileName(String style, String fileName, String tableName);
}

View File

@@ -18,7 +18,7 @@ public class AttributeRetrieval {
private String openingType;
private String subtype;
private String sleeve;
private String sleeve1;
private String sleeve2;
private String style;
private Integer deprecated;
}

View File

@@ -2,23 +2,27 @@ package com.ai.da.model.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
@Data
@ApiModel("AccountAdd")
@AllArgsConstructor
public class AccountAddDTO {
@NotBlank(message = "email.cannot.be.empty")
@ApiModelProperty("email")
private String email;
@ApiModelProperty("userEmail")
private String userEmail;
@NotBlank(message = "userName.cannot.be.empty")
@ApiModelProperty("userName")
private String userName;
private String country;
@NotBlank(message = "validStartTime.cannot.be.empty")
@ApiModelProperty("Start time of account validity ")
private String validStartTime;
@@ -29,4 +33,8 @@ public class AccountAddDTO {
private Integer isTrial;
private BigDecimal credits;
private Integer systemUser;
}

View File

@@ -0,0 +1,9 @@
package com.ai.da.model.dto;
import com.ai.da.mapper.primary.entity.Account;
import lombok.Data;
@Data
public class AccountDesignWorksRegisterDTO extends Account {
private String emailVerifyCode;
}

View File

@@ -7,7 +7,7 @@ public class AlipayHKCallbackDTO {
private String transaction_id;
private Long amount;
private Float amount;
private String currency;

View File

@@ -26,10 +26,10 @@ public class CollectionColorDTO {
@ApiModelProperty("潘通RGB值")
private String rgbValue;
// private Gradient gradient;
//
// private String gradientString;
private Gradient gradient;
// private String gradientMinioUrl;
private String gradientString;
private String gradientMinioUrl;
}

View File

@@ -0,0 +1,8 @@
package com.ai.da.model.dto;
import com.ai.da.mapper.primary.entity.Comment;
import lombok.Data;
@Data
public class CommentDTO extends Comment {
}

View File

@@ -0,0 +1,9 @@
package com.ai.da.model.dto;
import com.ai.da.model.vo.PageQueryBaseVo;
import lombok.Data;
@Data
public class CommentPageDTO extends PageQueryBaseVo {
private Long portfolioId;
}

View File

@@ -14,6 +14,8 @@ public class DesignCollectionPrintElementDTO {
@ApiModelProperty("design类型 用户design生成时候区别library和collection")
private String designType;
private String level2Type;
@ApiModelProperty("是否pin 1 pin 0 不pin")
private Byte isPin;

View File

@@ -26,7 +26,7 @@ public class DesignSingleItemDTO implements Serializable {
private String designType;
@NotBlank(message = "type.cannot.be.empty")
@ApiModelProperty("生成item实际对应的类型 有:outwear,dress,blouse,skirt,trousers Shoes Hairstyle Earring")
@ApiModelProperty("生成item实际对应的类型 有:Outwear,Dress,Blouse,Skirt,Trousers Shoes Hairstyle Earring")
private String type;
@ApiModelProperty("对应的图片的minIO路径")
@@ -50,7 +50,13 @@ public class DesignSingleItemDTO implements Serializable {
@ApiModelProperty("图层优先级")
private Integer priority;
// @ApiModelProperty("渐变 颜色")
// private Gradient gradient;
@ApiModelProperty("渐变 颜色")
private Gradient gradient;
@ApiModelProperty("画笔修改过的sketch图片的base64格式的数据")
private String sketchString;
@ApiModelProperty("衣服上的装饰")
private DesignSinglePrintDTO trims;
}

View File

@@ -15,12 +15,17 @@ public class DesignSinglePrintDTO implements Serializable {
// @ApiModelProperty("印花url")
// private String path;
@ApiModelProperty("single -> true,overall -> false")
private Boolean ifSingle;
/*@ApiModelProperty("single -> true,overall -> false")
private Boolean ifSingle;*/
@ApiModelProperty("印花详细")
private List<DesignSinglePrint> prints;
public DesignSinglePrintDTO() {
}
/*
public DesignSinglePrintDTO(Boolean ifSingle, List<DesignSinglePrint> prints) {
this.ifSingle = ifSingle;
this.prints = prints;
}*/
}

View File

@@ -0,0 +1,10 @@
package com.ai.da.model.dto;
import lombok.Data;
@Data
public class DesignWorksRegisterDTO {
private String userName;
private String email;
private String password;
}

View File

@@ -0,0 +1,8 @@
package com.ai.da.model.dto;
import lombok.Data;
@Data
public class ExportSaveDTO {
private String data;
}

View File

@@ -0,0 +1,8 @@
package com.ai.da.model.dto;
import lombok.Data;
@Data
public class ExportSearchDTO {
private Long userLikeGroupId;
}

View File

@@ -19,7 +19,7 @@ public class GenerateLikeDTO {
@ApiModelProperty("一级类型 Sketchboard Printboard")
private String level1Type;
@ApiModelProperty("当一级类型为Sketchboard时二级类型 Outwear Dress Blouse Skirt Trousers")
@ApiModelProperty("当一级类型为Sketchboard时二级类型 Outwear Dress Blouse Skirt Trousers当一级类型为Printboard时二级类型 Slogan Logo Pattern")
private String level2Type;
@ApiModelProperty("性别")

View File

@@ -14,24 +14,25 @@ public class GenerateThroughImageTextDTO {
@ApiModelProperty("用户id")
Long userId;
@ApiModelProperty("caption")
@ApiModelProperty("caption | prompt")
String text;
@ApiModelProperty("图片在t_collection_element表中的id")
Long collectionElementId;
@NotBlank(message = "you have to choose the generate type")
// todo 后续取消这个字段的传输,由后端自行判断相关参数是否有值
// @NotBlank(message = "you have to choose the generate type")
@ApiModelProperty("text image text-image")
String generateType;
@ApiModelProperty("图片是update还是从library中选择")
@ApiModelProperty("图片是update还是从library中选择 collection || library")
String designType;
@NotBlank(message = "level1Type cannot be empty!")
@ApiModelProperty("Moodboard Printboard Sketchboard MarketingSketch")
String level1Type;
@ApiModelProperty("Outwear Dress Blouse Skirt Trousers")
@ApiModelProperty("Outwear Dress Blouse Skirt Trousers || Logo Slogan Pattern")
String level2Type;
@ApiModelProperty("性别")
@@ -50,4 +51,10 @@ public class GenerateThroughImageTextDTO {
@NotNull(message = "Please check if the required fields are empty.(isTestUser)")
@ApiModelProperty("是否是测试用户")
Boolean isTestUser;
@ApiModelProperty("页面上用户设计的slogan所截的图片")
String sloganBase64;
@ApiModelProperty("种子 取值范围 0~500")
String seed;
}

View File

@@ -1,6 +1,5 @@
package com.ai.da.model.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@@ -26,6 +25,10 @@ public class GenerateToPythonDTO {
// taskId的最后拼接用户id
private String tasks_id;
private String seed;
private String svg;
public GenerateToPythonDTO(String tasks_id, String prompt, String image_url, String mode, String category, String gender) {
this.image_url = image_url;
this.category = category;

View File

@@ -71,4 +71,6 @@ public class ModelsDotDTO implements Serializable {
*/
private String templateUrl;
private String sex;
}

View File

@@ -2,9 +2,11 @@ package com.ai.da.model.dto;
import com.ai.da.mapper.primary.entity.Portfolio;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
@Data
public class PortfolioDTO extends Portfolio {
private Long userLikeGroupId;
}

View File

@@ -0,0 +1,10 @@
package com.ai.da.model.dto;
import lombok.Data;
import java.util.List;
@Data
public class ProductImageLikeDTO {
private List<Long> toProductImageResultId;
}

View File

@@ -11,4 +11,7 @@ import java.util.List;
@ApiModel("作品集分页查询")
public class QueryPortfolioPageDTO extends PageQueryBaseVo {
private Integer getMyPortfolio;
private Integer getLikePortfolio;
}

View File

@@ -0,0 +1,16 @@
package com.ai.da.model.dto;
import com.ai.da.model.vo.ToProductImageVO;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
@Data
public class ToProductImageDTO {
private Long userLikeGroupId;
private List<ToProductImageVO> toProductImageVOList;
private String prompt;
private BigDecimal imageStrength;
private String direction;
}

View File

@@ -2,7 +2,7 @@ package com.ai.da.model.enums;
import com.fasterxml.jackson.annotation.JsonValue;
public enum DesignElementsEnum {
public enum DesignElementsEnum implements IEnumDisplay {
EMBROIDERY("刺绣", "Embroidery"),
BEADING("钉珠", "Beading"),
PEARL("珍珠", "Pearl"),
@@ -16,6 +16,12 @@ public enum DesignElementsEnum {
private final String chinese;
private final String english;
@Override
@JsonValue
public String getValue() {
return this.english;
}
// 构造函数
DesignElementsEnum(String chinese, String english) {
this.chinese = chinese;
@@ -39,7 +45,7 @@ public enum DesignElementsEnum {
}
public static DesignElementsEnum fromName(String name) {
for (DesignElementsEnum designElement : DesignElementsEnum.values()) {
if (designElement.name().equals(name)) {
if (designElement.english.equals(name)) {
return designElement;
}
}

View File

@@ -16,7 +16,10 @@ public enum Position implements IEnumDisplay {
BLOUSE("Blouse"),
DRESS("Dress"),
TROUSERS("Trousers"),
SKIRT("Skirt");
SKIRT("Skirt"),
SLOGAN("Slogan"),
LOGO("Logo"),
PATTERN("Pattern");
private String value;

View File

@@ -1,9 +1,12 @@
package com.ai.da.model.enums;
public enum PrintboardLevel2TypeEnum {
SLOGAN("标语", "Slogan"),
import com.fasterxml.jackson.annotation.JsonValue;
public enum PrintboardLevel2TypeEnum implements IEnumDisplay {
PATTERN("图案", "Pattern"),
LOGO("标志", "Logo"),
PATTERN("图案", "Pattern");
SLOGAN("标语", "Slogan")
;
private final String chinese;
private final String english;
@@ -14,6 +17,12 @@ public enum PrintboardLevel2TypeEnum {
this.english = english;
}
@Override
@JsonValue
public String getValue() {
return this.english;
}
// 获取中文描述
public String getChinese() {
return chinese;
@@ -33,7 +42,7 @@ public enum PrintboardLevel2TypeEnum {
// 根据名称获取枚举值
public static PrintboardLevel2TypeEnum fromName(String name) {
for (PrintboardLevel2TypeEnum designElement : PrintboardLevel2TypeEnum.values()) {
if (designElement.name().equals(name)) {
if (designElement.english.equals(name)) {
return designElement;
}
}

View File

@@ -6,7 +6,7 @@ import lombok.Getter;
@Getter
public enum StyleEnum {
// 定义风格及其对应的中英文描述
NEO_CHINESE("新中式", "Neo Chinese"),
NEW_CHINESE("新中式", "New Chinese"),
COUNTRY_STYLE("田园风", "Country Style"),
FUTURISM("未来主义", "Futurism"),
MINIMALISM("极简风", "Minimalism"),

View File

@@ -0,0 +1,120 @@
package com.ai.da.model.enums;
import java.util.*;
public class StyleKeywordMapper {
private static final Map<StyleEnum, Map<String, List<String>>> styleCategoryKeywords = new HashMap<>();
static {
Map<String, List<String>> neoChineseKeywords = new HashMap<>();
neoChineseKeywords.put("Moodboard", Arrays.asList("New Chinese"));
neoChineseKeywords.put("Printboard", Arrays.asList("New Chinese", "traditional Chinese patterns", "dragons and phoenixes", "longevity peaches", "cloud patterns"));
neoChineseKeywords.put("Sketchboard", Arrays.asList("New Chinese", "blouse", "bow tie", "stand-up collars", "cross collars", "Chinese buttons"));
Map<String, List<String>> countryStyleKeywords = new HashMap<>();
countryStyleKeywords.put("Moodboard", Arrays.asList("Pastoral style"));
countryStyleKeywords.put("Printboard", Arrays.asList("fresh and natural feeling", "floral"));
countryStyleKeywords.put("Sketchboard", Arrays.asList("soft and comfortable", "chiffon", "cotton"));
Map<String, List<String>> futurismKeywords = new HashMap<>();
futurismKeywords.put("Moodboard", Arrays.asList("high-tech", "luminous"));
futurismKeywords.put("Printboard", Arrays.asList("geometric patterns", "lines and structured designs", "silver", "gold", "copper"));
futurismKeywords.put("Sketchboard", Arrays.asList("high tech", "exaggerated cutting", "three-dimensional design"));
Map<String, List<String>> minimalistKeywords = new HashMap<>();
minimalistKeywords.put("Moodboard", Arrays.asList("Minimalist style"));
minimalistKeywords.put("Printboard", Arrays.asList("Minimalist black and white"));
minimalistKeywords.put("Sketchboard", Arrays.asList("soft and breathable"));
Map<String, List<String>> lolitaKeywords = new HashMap<>();
lolitaKeywords.put("Moodboard", Arrays.asList("Lolita style"));
lolitaKeywords.put("Printboard", Arrays.asList("gentle", "cute", "elegant", "floral print"));
lolitaKeywords.put("Sketchboard", Arrays.asList("Layered skirts", "puff sleeves", "bows"));
Map<String, List<String>> y2kKeywords = new HashMap<>();
y2kKeywords.put("Moodboard", Arrays.asList("Y2K Style"));
y2kKeywords.put("Printboard", Arrays.asList("highly saturated colors", "glossy fabrics", "reflective fabrics"));
y2kKeywords.put("Sketchboard", Arrays.asList("low-waist miniskirts"));
Map<String, List<String>> businessKeywords = new HashMap<>();
businessKeywords.put("Moodboard", Arrays.asList("Business-style"));
businessKeywords.put("Printboard", Arrays.asList("colors are mostly black", "white", "gray", "dark blue", "brown", "neutral tones"));
businessKeywords.put("Sketchboard", Arrays.asList("simple and smooth lines"));
Map<String, List<String>> merladKeywords = new HashMap<>();
merladKeywords.put("Moodboard", Arrays.asList("Maillard Style"));
merladKeywords.put("Printboard", Arrays.asList("colors of Maillard-style clothing are mainly brown", "matched with tan", "reddish brown", "yellowish brown", "leopard print", "plaid"));
merladKeywords.put("Sketchboard", Arrays.asList("wide shoulder design", "extra-long cuts"));
Map<String, List<String>> outdoorFunctionalKeywords = new HashMap<>();
outdoorFunctionalKeywords.put("Moodboard", Arrays.asList("outdoor functional"));
outdoorFunctionalKeywords.put("Printboard", Arrays.asList("Simple"));
outdoorFunctionalKeywords.put("Sketchboard", Arrays.asList("multiple pocket designs"));
Map<String, List<String>> rockKeywords = new HashMap<>();
rockKeywords.put("Moodboard", Arrays.asList("rock-style"));
rockKeywords.put("Printboard", Arrays.asList("printed patterns include skulls", "flames", "music elements", "rock culture symbols"));
rockKeywords.put("Sketchboard", Arrays.asList("Leather"));
Map<String, List<String>> dopamineKeywords = new HashMap<>();
dopamineKeywords.put("Moodboard", Arrays.asList("dopamine-style"));
dopamineKeywords.put("Printboard", Arrays.asList("bright and highly saturated colors such as red", "orange", "yellow", "Cute and playful patterns such as flowers", "fruits", "animals"));
dopamineKeywords.put("Sketchboard", Arrays.asList("sequins", "beads", "metal decorations", "cheerful and lively atmosphere"));
Map<String, List<String>> gothicKeywords = new HashMap<>();
gothicKeywords.put("Moodboard", Arrays.asList("Gothic style"));
gothicKeywords.put("Printboard", Arrays.asList("deep and dark colors", "such as black", "dark purple", "dark red", "religious or mysterious patterns or prints such as crosses", "shackles", "bats", "skulls"));
gothicKeywords.put("Sketchboard", Arrays.asList("mysterious and gloomy atmosphere", "lines and layers"));
Map<String, List<String>> postApocalypticKeywords = new HashMap<>();
postApocalypticKeywords.put("Moodboard", Arrays.asList("wasteland style"));
postApocalypticKeywords.put("Printboard", Arrays.asList("damage", "graffiti", "smearing", "retro printing", "showing a shabby", "decadent", "cold appearance"));
postApocalypticKeywords.put("Sketchboard", Arrays.asList("a gloomy and heavy feeling"));
Map<String, List<String>> romanticKeywords = new HashMap<>();
romanticKeywords.put("Moodboard", Arrays.asList("Romantic style"));
romanticKeywords.put("Printboard", Arrays.asList("softness", "warmth and romance", "colors such as pink", "lavender", "light blue", "beige"));
romanticKeywords.put("Sketchboard", Arrays.asList("X-shaped and A-shaped silhouettes", "organza", "satin"));
Map<String, List<String>> wabiSabiKeywords = new HashMap<>();
wabiSabiKeywords.put("Moodboard", Arrays.asList("Wabi-Sabi style"));
wabiSabiKeywords.put("Printboard", Arrays.asList("natural materials such as wood", "stone", "hemp rope", "neutral tones and light colors"));
wabiSabiKeywords.put("Sketchboard", Arrays.asList("a quiet and peaceful atmosphere"));
styleCategoryKeywords.put(StyleEnum.NEW_CHINESE, neoChineseKeywords);
styleCategoryKeywords.put(StyleEnum.COUNTRY_STYLE, countryStyleKeywords);
styleCategoryKeywords.put(StyleEnum.FUTURISM, futurismKeywords);
styleCategoryKeywords.put(StyleEnum.MINIMALISM, minimalistKeywords);
styleCategoryKeywords.put(StyleEnum.LOLITA, lolitaKeywords);
styleCategoryKeywords.put(StyleEnum.Y2K, y2kKeywords);
styleCategoryKeywords.put(StyleEnum.BUSINESS, businessKeywords);
styleCategoryKeywords.put(StyleEnum.MERLAD, merladKeywords);
styleCategoryKeywords.put(StyleEnum.OUTDOOR_FUNCTIONAL, outdoorFunctionalKeywords);
styleCategoryKeywords.put(StyleEnum.ROCK, rockKeywords);
styleCategoryKeywords.put(StyleEnum.DOPAMINE, dopamineKeywords);
styleCategoryKeywords.put(StyleEnum.GOTHIC, gothicKeywords);
styleCategoryKeywords.put(StyleEnum.POST_APOCALYPTIC, postApocalypticKeywords);
styleCategoryKeywords.put(StyleEnum.ROMANTIC, romanticKeywords);
styleCategoryKeywords.put(StyleEnum.WABI_SABI, wabiSabiKeywords);
}
public static List<String> getKeywords(StyleEnum style, String category) {
Map<String, List<String>> categoryKeywords = styleCategoryKeywords.get(style);
if (categoryKeywords != null) {
List<String> keywords = categoryKeywords.get(category);
if (keywords != null) {
return keywords;
}
}
return Collections.emptyList();
}
public static Map<String, List<String>> getAllKeywordsByStyle(StyleEnum style) {
Map<String, List<String>> allKeywords = new HashMap<>();
allKeywords.put("Moodboard", getKeywords(style, "Moodboard"));
allKeywords.put("Printboard", getKeywords(style, "Printboard"));
allKeywords.put("Sketchboard", getKeywords(style, "Sketchboard"));
return allKeywords;
}
}

View File

@@ -32,4 +32,6 @@ public class AccountLoginVO {
@ApiModelProperty("是否完成引导")
private Integer isBeginner;
private Integer systemUser;
}

View File

@@ -0,0 +1,15 @@
package com.ai.da.model.vo;
import com.ai.da.mapper.primary.entity.Comment;
import lombok.Data;
import java.util.List;
@Data
public class CommentVO extends Comment {
private List<CommentVO> childCommentVOList;
private String userName;
private String replyTo;
}

View File

@@ -46,6 +46,9 @@ public class DesignItemClothesDetailVO {
@ApiModelProperty("print详细")
private DesignSinglePrintDTO printObject = new DesignSinglePrintDTO();
@ApiModelProperty("design elements详细")
private DesignSinglePrintDTO trims = new DesignSinglePrintDTO();
@ApiModelProperty("对应图层信息")
private List<DesignPythonOutfitVO> layersObject;
@@ -55,6 +58,9 @@ public class DesignItemClothesDetailVO {
@ApiModelProperty("渐变色信息")
private Gradient gradient;
@ApiModelProperty("未分割的图层")
private String undividedLayer;
public DesignItemClothesDetailVO() {
}

View File

@@ -13,6 +13,12 @@ import java.util.List;
@ApiModel("design single 印花详情")
public class DesignSinglePrint implements Serializable {
@ApiModelProperty("single -> true,overall -> false")
private Boolean ifSingle;
@ApiModelProperty("印花的类型 Slogan || Logo || Pattern")
private String level2Type;
@ApiModelProperty("印花是用户上传的还是从library中选的 collection/library")
private String designType;
@@ -45,12 +51,14 @@ public class DesignSinglePrint implements Serializable {
this.scale = scale;
}
public DesignSinglePrint(String path, String minIOPath, List<Double> location, Double scale, Double angle, Integer priority) {
public DesignSinglePrint(String level2Type, String path, String minIOPath, List<Double> location, Double scale, Double angle, Integer priority, Boolean ifSingle) {
this.level2Type = level2Type;
this.path = path;
this.minIOPath = minIOPath;
this.location = location;
this.scale = scale;
this.angle = angle;
this.priority = priority;
this.ifSingle = ifSingle;
}
}

View File

@@ -0,0 +1,31 @@
package com.ai.da.model.vo;
import io.swagger.annotations.ApiModel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@ApiModel("generate result 响应")
@AllArgsConstructor
@NoArgsConstructor
public class MagicToolResultVO {
private String taskId;
private Long id;
private String url;
private String status;
private String category;
private String sourceUrl;
private String resultType;
private String elementType;
private Long elementId;
}

View File

@@ -9,8 +9,23 @@ import java.util.List;
@Data
public class PortfolioVO extends Portfolio {
private String designPythonOutfitUrl;
private String canvasUrl;
private Long likeNum;
private List<CollectionElement> collectionElementList;
private List<TDesignPythonOutfit> designPythonOutfitList;
private Integer isLike;
private Long viewNums;
private String userName;
private String originalUserName;
private String originalPortfolioName;
private Integer isMine;
private Integer selected;
private Integer jumpable;
}

View File

@@ -0,0 +1,57 @@
package com.ai.da.model.vo;
import lombok.Data;
import java.util.List;
@Data
public class QuestionnaireVO {
/**
* 用户名
*/
private String userName;
/**
* 用户性别
*/
private String gender;
/**
* 职业
*/
private String occupation;
/**
* 国家
*/
private String country;
/**
* 电子邮件
*/
private String email;
/**
* 年龄区间
*/
private String age;
/**
* How has AiDA been helpful to you?
*/
private List<String> helpful;
/**
* What do you think AiDA should improve?
*/
private List<String> improve;
/**
* Will you subscribe to AiDA 3.0
*/
private String isSubscribe;
/**
* If NO, please share why:
*/
private List<String> reasonForNotSubscribe;
/**
* Are you currently using any design tools?
*/
private String designTools;
/**
* 用户所选语言
*/
private String language;
}

View File

@@ -33,4 +33,6 @@ public class SysFileVO implements Serializable {
*/
private String md5;
private String level3Type;
}

View File

@@ -0,0 +1,8 @@
package com.ai.da.model.vo;
import com.ai.da.mapper.primary.entity.ToProductElement;
import lombok.Data;
@Data
public class ToProductElementVO extends ToProductElement {
}

View File

@@ -0,0 +1,9 @@
package com.ai.da.model.vo;
import com.ai.da.mapper.primary.entity.ToProductImageResult;
import lombok.Data;
@Data
public class ToProductImageResultVO extends ToProductImageResult {
private String sourceUrl;
}

View File

@@ -0,0 +1,9 @@
package com.ai.da.model.vo;
import com.ai.da.mapper.primary.entity.ToProductImageResult;
import lombok.Data;
@Data
public class ToProductImageVO extends ToProductImageResult {
}

View File

@@ -0,0 +1,8 @@
package com.ai.da.model.vo;
import com.ai.da.mapper.primary.entity.UserLike;
import lombok.Data;
@Data
public class ToProductVO extends UserLike {
}

View File

@@ -22,4 +22,6 @@ public class UserLikeChooseVO {
private UserLikeCollectionVO collection;
private String sex;
private Integer beenPublished;
}

View File

@@ -22,6 +22,12 @@ public class UserLikeGroupVO {
@ApiModelProperty("创建者")
private String author;
private Integer original;
private Long originalAccountId;
private Long originalPortfolioId;
@ApiModelProperty("更新时间")
private Long updateDate;
@@ -31,4 +37,7 @@ public class UserLikeGroupVO {
@ApiModelProperty("分组对应的详情 一次行带出来")
private List<UserLikeVO> groupDetails;
private String originalAccountName;
private String originalPortfolioName;
}

View File

@@ -45,4 +45,6 @@ public class ValidateElementVO {
//透传sysFileVo用(attribute_retrieval 接口限定sysFile范围)
List<SysFileVO> sysFileVo;
private String modelSex;
private String style;
}

View File

@@ -8,6 +8,9 @@ import lombok.Data;
import lombok.EqualsAndHashCode;
import io.swagger.annotations.ApiModel;
import java.util.List;
import java.util.Map;
/**
* 视图实体类
*
@@ -21,7 +24,7 @@ public class WorkspaceVO extends Workspace {
private static final long serialVersionUID = 1L;
private Long currentId;
private Long styleId;
private PageBaseResponse<WorkspaceVO> page;
@@ -35,4 +38,8 @@ public class WorkspaceVO extends Workspace {
private String styleName;
private String style;
private Map<String, List<String>> allKeywordsByStyle;
}

View File

@@ -8,10 +8,7 @@ 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.CollectionElement;
import com.ai.da.mapper.primary.entity.Collocation;
import com.ai.da.mapper.primary.entity.DesignHistory;
import com.ai.da.mapper.primary.entity.Dressing;
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;
@@ -66,10 +63,12 @@ public class PythonService {
private String accessPythonIp;
@Value("${access.python.port:''}")
private String accessPythonPort;
@Value("${access.python.sr}")
private String srPythonPort;
@Value("${access.python.address}")
private String fastApiPythonAddress;
@Value("${minio.bucketName.gradient}")
private String gradientBucketName;
@Value("${access.python.generate_sr_port}")
private String srServicePort;
@Resource
private PythonTAllInfoService pythonTAllInfoService;
@@ -165,7 +164,7 @@ public class PythonService {
* @param operateType
* @return
*/
@Transactional
@Transactional(rollbackFor = Exception.class)
public String upload(MultipartFile file, String operateType) {
//用户信息
PythonToJavaApiOperationTypeEnum operationType = PythonToJavaApiOperationTypeEnum.uploadOf(operateType);
@@ -270,13 +269,13 @@ public class PythonService {
private void updateSketchNumbers(CurrentDesignPictureTypeEnum designPictureType, int[] sketchNumbers) {
switch (designPictureType) {
case PIN:
sketchNumbers[0] ++;
sketchNumbers[0]++;
break;
case NO_PIN:
sketchNumbers[2] --;
sketchNumbers[2]--;
break;
case SYS_FILE:
sketchNumbers[1] --;
sketchNumbers[1]--;
break;
}
}
@@ -316,7 +315,7 @@ public class PythonService {
Long l = RandomsUtil.randomSysFile(0l, 2l);
if (l == 0l) {
return CurrentDesignPictureTypeEnum.NO_PIN;
}else {
} else {
return CurrentDesignPictureTypeEnum.SYS_FILE;
}
}
@@ -603,7 +602,7 @@ public class PythonService {
} else if (systemScale.compareTo(BigDecimal.ONE) != 0) {
BigDecimal collectNoPinSize = BigDecimal.valueOf(collectionNoPinSize);
poolNum = collectNoPinSize.divide(systemScale, 0, RoundingMode.DOWN).intValue();
List<CollectionElement> list = getSystemSketchPool(attributeRecognition, styleCategory, elementVO.getModelSex(), poolNum);
List<CollectionElement> list = getSystemSketchPool(attributeRecognition, styleCategory, elementVO.getModelSex(), poolNum, elementVO.getStyle());
collectionElements.addAll(list);
int randomNum = RandomsUtil.randomSysFile(collectionElements.size());
if (randomNum < collectionNoPinSize) {
@@ -613,7 +612,7 @@ public class PythonService {
}
}
}
List<CollectionElement> list = getSystemSketchPool(attributeRecognition, styleCategory, elementVO.getModelSex(), poolNum);
List<CollectionElement> list = getSystemSketchPool(attributeRecognition, styleCategory, elementVO.getModelSex(), poolNum, elementVO.getStyle());
int randomNum = RandomsUtil.randomSysFile(list.size());
return coverSketchToDesignPythonItem(null, list.get(randomNum), elementVO);
}
@@ -623,7 +622,7 @@ public class PythonService {
}
private DesignPythonItem processAttributeRecognitionBySameCategory(JSONObject attributeRecognition, ValidateElementVO elementVO, String styleCategory) {
List<CollectionElement> list = getSystemSketchPoolBySameCategory(attributeRecognition, styleCategory, elementVO.getModelSex());
List<CollectionElement> list = getSystemSketchPoolBySameCategory(attributeRecognition, styleCategory, elementVO.getModelSex(), elementVO.getStyle());
int randomNum = RandomsUtil.randomSysFile(list.size());
return coverSketchToDesignPythonItem(null, list.get(randomNum), elementVO);
}
@@ -631,7 +630,7 @@ public class PythonService {
@Resource
private AttributeRetrievalMapper attributeRetrievalMapper;
private List<CollectionElement> getSystemSketchPool(JSONObject attributeRecognition, String styleCategory, String modelSex, int poolNum) {
private List<CollectionElement> getSystemSketchPool(JSONObject attributeRecognition, String styleCategory, String modelSex, int poolNum, String style) {
/**
* female trousers->female_pants
* female blouse->female_top
@@ -645,19 +644,19 @@ public class PythonService {
AttributeRetrieval attributeRetrievalAttrDict = toAttrDict(attrDictJSON);
String tableName;
tableName = getTableName(modelSex, styleCategory);
List<AttributeRetrieval> attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPool(attributeRetrievalAttrDict, tableName, poolNum);
List<AttributeRetrieval> attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPool(attributeRetrievalAttrDict, tableName, poolNum, style);
if (CollectionUtil.isEmpty(attributeRetrievalList) || attributeRetrievalList.size() < poolNum) {
attributeRetrievalAttrDict.setDesign(null);
attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPool(attributeRetrievalAttrDict, tableName, poolNum);
attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPool(attributeRetrievalAttrDict, tableName, poolNum, style);
}
if (CollectionUtil.isEmpty(attributeRetrievalList) || attributeRetrievalList.size() < poolNum) {
attributeRetrievalAttrDict.setSilhouette(null);
attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPool(attributeRetrievalAttrDict, tableName, poolNum);
attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPool(attributeRetrievalAttrDict, tableName, poolNum, style);
}
return toColoectionElementList(attributeRetrievalList, styleCategory, modelSex);
}
private List<CollectionElement> getSystemSketchPoolBySameCategory(JSONObject attributeRecognition, String styleCategory, String modelSex) {
private List<CollectionElement> getSystemSketchPoolBySameCategory(JSONObject attributeRecognition, String styleCategory, String modelSex, String style) {
/**
* female trousers->female_pants
* female blouse->female_top
@@ -713,7 +712,7 @@ public class PythonService {
}
}
List<AttributeRetrieval> attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPoolBySameCategory(attributeRetrievalAttrDict, tableName);
List<AttributeRetrieval> attributeRetrievalList = attributeRetrievalMapper.getSystemSketchPoolBySameCategory(attributeRetrievalAttrDict, tableName, style);
if (CollectionUtil.isEmpty(attributeRetrievalList)) {
System.out.println(attributeRetrievalAttrDict);
System.out.println(tableName);
@@ -793,6 +792,7 @@ public class PythonService {
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();
@@ -835,6 +835,7 @@ public class PythonService {
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")
@@ -934,7 +935,7 @@ public class PythonService {
Integer randomNum = RandomsUtil.randomSysFile(dressings.size());
String category = dressings.get(randomNum).getStyleCategory();
String tableName = getTableName(validateElementVO.getModelSex(), category);
AttributeRetrieval attributeRetrieval = attributeRetrievalMapper.getSystemRandom(tableName);
AttributeRetrieval attributeRetrieval = attributeRetrievalMapper.getSystemRandom(tableName, validateElementVO.getStyle());
CollectionElement collectionElement = toCollectionElement(attributeRetrieval, category, validateElementVO.getModelSex());
return coverSketchToDesignPythonItem(null, collectionElement, validateElementVO);
}
@@ -974,7 +975,7 @@ public class PythonService {
Integer randomNum = RandomsUtil.randomSysFile(dressings.size());
String category = dressings.get(randomNum).getStyleCategory();
String tableName = getTableName(validateElementVO.getModelSex(), category);
AttributeRetrieval attributeRetrieval = attributeRetrievalMapper.getSystemRandom(tableName);
AttributeRetrieval attributeRetrieval = attributeRetrievalMapper.getSystemRandom(tableName, validateElementVO.getStyle());
CollectionElement collectionElement = toCollectionElement(attributeRetrieval, category, validateElementVO.getModelSex());
return coverSketchToDesignPythonItem(null, collectionElement, validateElementVO);
}
@@ -1556,8 +1557,8 @@ public class PythonService {
if (SysFileLevel2TypeEnum.SHOES.getRealName().equals(type)) {
CollectionColorDTO randomColor = getRandomColor(elementVO.getColorBoards());
pythonItem.setColor(randomColor.getRgbValue());
// pythonItem.setGradient(randomColor.getGradientMinioUrl());
// pythonItem.setGradientString(randomColor.getGradientString());
pythonItem.setGradient(randomColor.getGradientMinioUrl());
pythonItem.setGradientString(randomColor.getGradientString());
}
}
}
@@ -1922,19 +1923,19 @@ public class PythonService {
designPythonItemBlouse.setIcon("none");
CollectionColorDTO randomColor = getRandomColor(elementVO.getColorBoards());
designPythonItemBlouse.setColor(randomColor.getRgbValue());
// designPythonItemBlouse.setGradient(randomColor.getGradientMinioUrl());
// designPythonItemBlouse.setGradientString(randomColor.getGradientString());
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.setIfSingle(false);
designPythonItemPrint.setPrint_path_list(Collections.singletonList(designPythonItemPrint.getPath()));
designPythonItemBlouse.setPrint(designPythonItemPrint);
designPythonItemBlouse.setPrint(new PrintToPython(designPythonItemPrint));
} else {
DesignPythonItemPrint designPythonItemPrint = new DesignPythonItemPrint();
designPythonItemPrint.setIfSingle(false);
// designPythonItemPrint.setIfSingle(false);
designPythonItemPrint.setPrint_path_list(new ArrayList<>());
designPythonItemBlouse.setPrint(designPythonItemPrint);
designPythonItemBlouse.setPrint(new PrintToPython(designPythonItemPrint));
}
return designPythonItemBlouse;
}
@@ -1951,19 +1952,19 @@ public class PythonService {
designPythonItemBlouse.setIcon("none");
CollectionColorDTO randomColor = getRandomColor(elementVO.getColorBoards());
designPythonItemBlouse.setColor(randomColor.getRgbValue());
// designPythonItemBlouse.setGradient(randomColor.getGradientMinioUrl());
// designPythonItemBlouse.setGradientString(randomColor.getGradientString());
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.setIfSingle(false);
designPythonItemPrint.setPrint_path_list(Collections.singletonList(designPythonItemPrint.getPath()));
designPythonItemBlouse.setPrint(designPythonItemPrint);
designPythonItemBlouse.setPrint(new PrintToPython(designPythonItemPrint));
} else {
DesignPythonItemPrint designPythonItemPrint = new DesignPythonItemPrint();
designPythonItemPrint.setIfSingle(false);
// designPythonItemPrint.setIfSingle(false);
designPythonItemPrint.setPrint_path_list(new ArrayList<>());
designPythonItemBlouse.setPrint(designPythonItemPrint);
designPythonItemBlouse.setPrint(new PrintToPython(designPythonItemPrint));
}
return designPythonItemBlouse;
}
@@ -2359,6 +2360,7 @@ public class PythonService {
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==")
@@ -2465,6 +2467,7 @@ public class PythonService {
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==")
@@ -2584,7 +2587,7 @@ public class PythonService {
List<DesignPythonItem> response = CopyUtil.copyList(designPythonItemDto, DesignPythonItem.class, (o, d) -> {
d.setBusinessId(o.getId());
d.setIcon("none");
d.setPrint(resolveDesignSinglePrint(o.getPrintObject(), o.getPath()));
// d.setPrint(resolveDesignSinglePrint(o.getPrintObject(), o.getPath()));
});
DesignPythonItem body = new DesignPythonItem();
body.setType(SysFileLevel2TypeEnum.BODY.getRealName());
@@ -2611,40 +2614,44 @@ public class PythonService {
designSingleItemList.forEach(designSingleItem -> {
Long businessId;
if (!designSingleIncludeLayersDTO.getIsPreview() && designSingleItem.getChanged()){
if (!designSingleIncludeLayersDTO.getIsPreview() && designSingleItem.getChanged()) {
String s = String.valueOf(designSingleItem.getId());
businessId = Long.parseLong(s.substring(0,s.length() - 3));
}else {
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("The base64 data of the image is empty");
// }
//// minioPath = minioUtil.base64Upload(colorImg, gradientBucketName);
//// designSingleItem.getGradient().setColorImg(null);
//// gradientString = JSONObject.toJSONString(designSingleItem.getGradient());
//
// // todo 当渐变色不为空时,是否需要将颜色置为 0 0 0
// }
String minioPath = null;
String gradientString = null;
if (!Objects.isNull(designSingleItem.getGradient())) {
String colorImg = designSingleItem.getGradient().getColorImg();
if (StringUtil.isNullOrEmpty(colorImg)) {
throw new BusinessException("The base64 data of the image is empty");
}
minioPath = minioUtil.base64UploadToPath(colorImg, gradientBucketName, null);
designSingleItem.getGradient().setColorImg(null);
gradientString = JSONObject.toJSONString(designSingleItem.getGradient());
// todo 当渐变色不为空时,是否需要将颜色置为 0 0 0
}
PrintToPython printToPython = resolveDesignSinglePrint(designSingleItem.getPrintObject().getPrints());
resolveDesignElement(designSingleItem.getTrims(), printToPython);
response.add(new DesignPythonItem(
designSingleItem.getType(),
designSingleItem.getPath(),
designSingleItem.getColor(),
resolveDesignSinglePrint(designSingleItem.getPrintObject(), designSingleItem.getPath()),
printToPython,
// businessId designItemDetailId python端确认没有作用,但是数据库需要存,作用:未知)
// designSingleItem.getId(),
businessId,
pythonTAllInfoService.getImageIdByPath(designSingleItem.getPath()),
designSingleItem.getOffset(),
designSingleItem.getScale(),
designSingleItem.getPriority()));
designSingleItem.getPriority(),
minioPath,
gradientString));
});
@@ -2660,36 +2667,110 @@ public class PythonService {
}
private DesignPythonItemPrint resolveDesignSinglePrint(DesignSinglePrintDTO printObject, String clothesPath) {
// 没有印花时的参数设置
if (printObject.getIfSingle().equals(Boolean.FALSE) && CollectionUtil.isEmpty(printObject.getPrints())) {
return new DesignPythonItemPrint(new ArrayList<>(), false);
private PrintToPython resolveDesignSinglePrint(List<DesignSinglePrint> printObject) {
PrintToPython printToPython = new PrintToPython();
DesignPythonItemPrint printSingle = new DesignPythonItemPrint();
DesignPythonItemPrint printOverall = new DesignPythonItemPrint();
printToPython.setSingle(printSingle);
printToPython.setOverall(printOverall);
if (printObject.isEmpty()){
return printToPython;
}
DesignPythonItemPrint print = CopyUtil.copyObject(printObject, DesignPythonItemPrint.class);
List<List<Double>> location = new ArrayList<>(printObject.getPrints().size());
List<Double> scale = new ArrayList<>(printObject.getPrints().size());
List<Double> angle = new ArrayList<>(printObject.getPrints().size());
ArrayList<String> paths = new ArrayList<>(printObject.getPrints().size());
// 没有印花时的参数设置
// 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<List<Double>> locationS = new ArrayList<>(Collections.nCopies(size, null));
List<Double> scaleS = new ArrayList<>(Collections.nCopies(size, null));
List<Double> angleS = new ArrayList<>(Collections.nCopies(size, null));
ArrayList<String> pathsS = new ArrayList<>(Collections.nCopies(size, null));
List<List<Double>> locationO = new ArrayList<>(Collections.nCopies(size, null));
List<Double> scaleO = new ArrayList<>(Collections.nCopies(size, null));
List<Double> angleO = new ArrayList<>(Collections.nCopies(size, null));
ArrayList<String> pathsO = new ArrayList<>(Collections.nCopies(size, null));
// 设置印花的位置、大小、旋转角度
List<DesignSinglePrint> prints = printObject.getPrints();
// 优先级越大越靠近顶层在传输给python的数组中越靠前
// List<DesignSinglePrint> 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();
// 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;
}
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<List<Double>> location = new ArrayList<>(Collections.nCopies(size, null));
List<Double> scale = new ArrayList<>(Collections.nCopies(size, null));
List<Double> angle = new ArrayList<>(Collections.nCopies(size, null));
ArrayList<String> paths = new ArrayList<>(Collections.nCopies(size, null));
// 设置印花的位置、大小、旋转角度
// 优先级越大越靠近顶层在传输给python的数组中越靠前
List<DesignSinglePrint> prints = trims.getPrints();
prints.forEach(p -> {
p.getLocation().set(0, p.getLocation().get(0));
p.getLocation().set(1, p.getLocation().get(1));
Integer priority = p.getPriority();
location.add(priority - 1, p.getLocation());
scale.add(priority - 1, p.getScale());
angle.add(priority - 1, p.getAngle());
paths.add(priority - 1, p.getMinIOPath());
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));
});
print.setLocation(location);
print.setPrint_scale_list(scale);
print.setPrint_angle_list(angle);
print.setPrint_path_list(paths);
return print;
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,
@@ -2756,24 +2837,28 @@ public class PythonService {
private List<DesignPythonItem> coverToModelsDotPythonItem(ModelsDotDTO modelsDotDTO) {
List<DesignPythonItem> response = Lists.newArrayList();
if (modelsDotDTO.getTemplateUrl().contains("female")) {
if (modelsDotDTO.getSex().contains("Female")) {
DesignPythonItem dress = new DesignPythonItem();
dress.setType(SysFileLevel2TypeEnum.DRESS.getRealName());
dress.setType(SysFileLevel2TypeEnum.BLOUSE.getRealName());
dress.setColor("none");
dress.setIcon("none");
DesignPythonItemPrint designPythonItemPrint = new DesignPythonItemPrint();
designPythonItemPrint.setIfSingle(false);
// designPythonItemPrint.setIfSingle(false);
designPythonItemPrint.setPrint_path_list(new ArrayList<>());
dress.setPrint(designPythonItemPrint);
dress.setPath("aida-sys-image/images/female/blouse/blouse_p5_817.jpg");
dress.setPrint(new PrintToPython(designPythonItemPrint));
dress.setPath("aida-sys-image/images/female/blouse/0628001551.jpg");
response.add(dress);
DesignPythonItem skirt = new DesignPythonItem();
skirt.setType(SysFileLevel2TypeEnum.TROUSERS.getRealName());
skirt.setType(SysFileLevel2TypeEnum.SKIRT.getRealName());
skirt.setColor("none");
skirt.setIcon("none");
skirt.setPrint(designPythonItemPrint);
skirt.setPath("aida-sys-image/images/female/trousers/trousers_974.jpg");
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.setPath("aida-sys-image/images/female/dress/0628000000.jpg");
response.add(skirt);
} else {
DesignPythonItem top = new DesignPythonItem();
@@ -2781,9 +2866,9 @@ public class PythonService {
top.setColor("none");
top.setIcon("none");
DesignPythonItemPrint designPythonItemPrint = new DesignPythonItemPrint();
designPythonItemPrint.setIfSingle(false);
// designPythonItemPrint.setIfSingle(false);
designPythonItemPrint.setPrint_path_list(new ArrayList<>());
top.setPrint(designPythonItemPrint);
top.setPrint(new PrintToPython(designPythonItemPrint));
top.setPath("aida-sys-image/images/male/tops/mens_test_10.png");
response.add(top);
@@ -2792,10 +2877,10 @@ public class PythonService {
bottom.setColor("none");
bottom.setIcon("none");
DesignPythonItemPrint designPythonItemPrint1 = new DesignPythonItemPrint();
designPythonItemPrint1.setIfSingle(false);
// designPythonItemPrint1.setIfSingle(false);
designPythonItemPrint1.setPrint_path_list(new ArrayList<>());
bottom.setPrint(designPythonItemPrint1);
bottom.setPath("aida-sys-image/images/male/bottoms/mens_test_10007.png");
bottom.setPrint(new PrintToPython(designPythonItemPrint1));
bottom.setPath("aida-sys-image/images/male/bottoms/mens_test_6252.png");
response.add(bottom);
}
@@ -2854,6 +2939,7 @@ public class PythonService {
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==")
@@ -2934,7 +3020,7 @@ public class PythonService {
throw new BusinessException("system error!");
}
public Boolean generateSketchOrPrint(GenerateToPythonDTO generateToPythonDTO) {
public Boolean generateSketchOrPrint(String params, String port, String servicePath) {
//限流校验
// AccessLimitUtils.validate("generateSketchOrPrint", 5);
OkHttpClient client = new OkHttpClient().newBuilder()
@@ -2944,13 +3030,16 @@ public class PythonService {
.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, 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(srPythonPort + "/api/generate_image")
.url(accessPythonIp + ":" + port + servicePath)
.method("POST", body)
// .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==")
.addHeader("Content-Type", "application/json")
@@ -2958,7 +3047,8 @@ public class PythonService {
Response response = null;
String bodyString;
try {
log.info("generateSketchOrPrint请求入参content###{}", JSON.toJSONString(generateToPythonDTO, SerializerFeature.WriteMapNullValue));
// 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));
@@ -2993,7 +3083,7 @@ public class PythonService {
log.info("Generate##responseObject###{}", jsonObject);
// return setGenerateImageList(jsonObject.getJSONObject("data"));
return Boolean.TRUE;
}else {
} else {
log.info("generateSketchOrPrintPrint失败###{}", jsonObject);
log.info("Generate Exception! Code : " + jsonObject.get("code"));
return Boolean.FALSE;
@@ -3012,6 +3102,7 @@ public class PythonService {
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")
@@ -3032,13 +3123,13 @@ public class PythonService {
List<String> imageUrlList = JSONObject.parseArray(jsonObject.get("list").toString(), String.class);
if (imageUrlList.isEmpty()) {
log.error("PythonService##generateSketchOrPrint异常###{}", "diffusion response list is null");
// todo 如果这里返回为空,是判断出错还是返回给前端空
// 如果这里返回为空,是判断出错还是返回给前端空
throw new BusinessException("The data returned on the python side is empty");
}
return imageUrlList;
}
/** 废弃状态 */
public String composeLayers(List<OutfitDetailPythonItem> layersDetail) {
HashMap<String, List<OutfitDetailPythonItem>> layers = new HashMap<>();
HashMap<String, HashMap<String, List<OutfitDetailPythonItem>>> content = new HashMap<>();
@@ -3110,8 +3201,9 @@ public class PythonService {
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());
// 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();
}
@@ -3124,14 +3216,15 @@ public class PythonService {
throw new BusinessException("cloth-classification.interface.exception");
}
public Boolean cancelGenerateTask(String taskId) {
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 + "/api/generate_cancel/" + taskId;
String url = accessPythonIp + ":" + accessPythonPort + path + taskId;
// String url = fastApiPythonAddress + "/api/generate_cancel/" + taskId;
Request request = new Request.Builder()
.url(url)
// .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==")
@@ -3142,14 +3235,14 @@ public class PythonService {
log.info("cancelGenerateTask请求入参content###{}", taskId);
response = client.newCall(request).execute();
} catch (IOException ioException) {
log.error("PythonService##cancelGenerateTask异常###{}", ExceptionUtil.getThrowableList(ioException));
log.error("PythonService##cancelGenerateTask异常###{}", response);
return null;
}
int responseCode = response.code();
response.close();
if (responseCode != HttpURLConnection.HTTP_OK) {
log.info("generate-python 取消请求失败");
log.info("generate-python 取消请求失败. {}", response);
return Boolean.FALSE;
}
log.info("generate-python 取消请求成功");
@@ -3173,7 +3266,7 @@ public class PythonService {
String jsonString = JSON.toJSONString(content, SerializerFeature.WriteNullStringAsEmpty);
RequestBody body = RequestBody.create(mediaType, jsonString);
Request request = new Request.Builder()
.url(srPythonPort + "/api/super_resolution")
.url(accessPythonIp + ":" + srServicePort + "/api/super_resolution")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
@@ -3211,8 +3304,11 @@ public class PythonService {
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(accessPythonIp + ":" + accessPythonPort + "/api/translateToEN")
.url(path)
// .url(fastApiPythonAddress + "/api/translateToEN")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
@@ -3252,4 +3348,93 @@ public class PythonService {
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<String, Object> 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<String, String> 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");
}
}

View File

@@ -28,14 +28,19 @@ public class DesignPythonItem {
*/
private String color;
// private String gradient;
private String gradient;
// private String gradientString;
private String gradientString;
/**
* 对应的print图片的绝对路径
*/
private DesignPythonItemPrint print;
private PrintToPython print;
/**
* trims 衣服上的装饰
*/
private DesignPythonItemElement element;
/**
* 对应的icon的绝对路径
@@ -113,8 +118,8 @@ public class DesignPythonItem {
this.image_id = image_id;
}
public DesignPythonItem(String type, String path, String color, DesignPythonItemPrint print, Long businessId,
Long image_id, List<Long> offset, Float[] resize_scale, Integer priority) {
public DesignPythonItem(String type, String path, String color, PrintToPython print, Long businessId,
Long image_id, List<Long> offset, Float[] resize_scale, Integer priority, String gradient, String gradientString) {
this.type = type;
this.path = path;
this.color = color;
@@ -125,11 +130,11 @@ public class DesignPythonItem {
this.offset = offset;
this.resize_scale = resize_scale;
this.priority = priority;
// this.gradient = gradient;
// this.gradientString = gradientString;
this.gradient = gradient;
this.gradientString = gradientString;
}
public DesignPythonItem(String type, String path, String color, DesignPythonItemPrint print, String icon, Long businessId, Long image_id) {
public DesignPythonItem(String type, String path, String color, PrintToPython print, String icon, Long businessId, Long image_id) {
this.type = type;
this.path = path;
this.color = color;

View File

@@ -0,0 +1,25 @@
package com.ai.da.python.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class DesignPythonItemElement {
@ApiModelProperty("print的位置 传 [[0.2, 0.2]]")
private List<List<Double>> location = new ArrayList<>();
private List<String> element_path_list = new ArrayList<>();
@ApiModelProperty("print的缩放比例 传 [0.2, 0.2]")
private List<Double> element_scale_list = new ArrayList<>();
@ApiModelProperty("print的旋转角度 传 [0.2, 0.2]")
private List<Double> element_angle_list = new ArrayList<>();
public DesignPythonItemElement() {
}
}

View File

@@ -4,6 +4,9 @@ import com.alibaba.fastjson.annotation.JSONField;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@Data
@@ -14,7 +17,7 @@ public class DesignPythonItemPrint {
@ApiModelProperty("图片绝对路径")
private String path;
private List<String> print_path_list;
private List<String> print_path_list = new ArrayList<>();
@ApiModelProperty("上传时候对应的类型,一级类型 Printboard ")
private String level1Type;
@@ -29,28 +32,38 @@ public class DesignPythonItemPrint {
* 是否打点
*/
@ApiModelProperty("是否打点 是传true 否则false")
private Boolean IfSingle;
private Boolean ifSingle;
@ApiModelProperty("print的位置 传 [[0.2, 0.2]]")
private List<List<Double>> location;
private List<List<Double>> location = new ArrayList<>();
@ApiModelProperty("print的缩放比例 传 [0.2, 0.2]")
private List<Double> print_scale_list;
private List<Double> print_scale_list = new ArrayList<>();
@ApiModelProperty("print的旋转角度 传 [0.2, 0.2]")
private List<Double> print_angle_list;
private List<Double> print_angle_list = new ArrayList<>();
@JSONField(name = "IfSingle")
public Boolean getIfSingle() {
return IfSingle;
return ifSingle;
}
public DesignPythonItemPrint(List<String> print_path_list, Boolean ifDesign) {
if (ifDesign){
this.print_path_list = print_path_list;
this.location = Collections.singletonList(Arrays.asList(0.0, 0.0));
this.print_scale_list = Arrays.asList(0.0, 0.0);
this.print_angle_list = Arrays.asList(0.0, 0.0);
}
}
public DesignPythonItemPrint(String singlePath, String level1Type, Float scale, Boolean ifSingle) {
this.path = singlePath;
this.level1Type = level1Type;
this.scale = scale;
IfSingle = ifSingle;
this.ifSingle = ifSingle;
}
public DesignPythonItemPrint() {
@@ -60,8 +73,4 @@ public class DesignPythonItemPrint {
this.path = path;
}
public DesignPythonItemPrint(List<String> print_path_list, Boolean ifSingle) {
this.print_path_list = print_path_list;
IfSingle = ifSingle;
}
}

Some files were not shown because too many files have changed in this diff Show More