Merge remote-tracking branch 'origin/develop' into dev_shb

# Conflicts:
#	src/main/java/com/ai/da/service/impl/DesignServiceImpl.java
This commit is contained in:
shahaibo
2023-09-13 10:34:09 +08:00
101 changed files with 1597 additions and 346 deletions

View File

@@ -5,13 +5,22 @@ import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
@Configuration
public class WebConfig {
public class WebConfig extends WebMvcConfigurerAdapter {
static final String ORIGINS[] = new String[]{"GET", "POST", "PUT", "DELETE"};
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS).maxAge(3600);
}
@Bean
public Validator validator() {

View File

@@ -0,0 +1,30 @@
package com.ai.da.common.enums;
import lombok.Getter;
@Getter
public enum GenerateTypeEnum {
/**
* 通过文本生成
*/
TEXT(1,"text"),
/**
* 通过图片生成
*/
IMAGE(2,"image"),
/**
* 通过文本和图片生成
*/
TEXT_IMAGE(2,"text-image");
private Integer code;
private String value;
GenerateTypeEnum(int code,String value) {
this.code = code;
this.value = value;
}
}

View File

@@ -0,0 +1,22 @@
package com.ai.da.common.enums;
import lombok.Getter;
@Getter
public enum ModelNameEnum {
/**
* 使用模型0
*/
MODEL_0("0","model_0");
private String code;
private String modelName;
ModelNameEnum(String code,String modelName) {
this.code = code;
this.modelName = modelName;
}
}

View File

@@ -4,7 +4,7 @@ import java.util.stream.Stream;
/**
* @author yanglei
* @description python调用java 操作数类型 generatePrint ->生成印花 designCollection ->设计collection
* @description python调用java 操作数类型 generatePrint ->生成印花 designCollection ->设计collection generateSketch->设计草图
* @create 2022-10-3 17:33
**/
public enum PythonToJavaApiOperationTypeEnum {
@@ -19,7 +19,12 @@ public enum PythonToJavaApiOperationTypeEnum {
/**
* 设计collection
*/
DESIGN_COLLECTION("designCollection");
DESIGN_COLLECTION("designCollection"),
/**
* 生成草图
*/
GENERATE_SKETCH("generateSketch");
private String realName;

View File

@@ -8,17 +8,12 @@ import com.ai.da.common.utils.LocalCacheUtils;
import com.ai.da.common.utils.MultiReadHttpServletRequest;
import com.ai.da.common.utils.MultiReadHttpServletResponse;
import com.ai.da.model.vo.AuthPrincipalVo;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.annotation.Resource;
@@ -28,7 +23,6 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
@@ -50,7 +44,10 @@ public class AuthenticationFilter extends OncePerRequestFilter {
Arrays.asList("/favicon.ico","/doc.html","api/account/login","api/account/preLogin","api/account/sendEmail",
"/webjars/","/swagger-resources","/v2/api-docs","api/account/resetPwd",
"/api/python/saveGeneratePicture", "/api/python/getLibraryByUserId",
"/api/third/party/addUser","/api/third/party/editUser","/api/element/initDefaultSysFile");
"/api/third/party/addUser","/api/third/party/editUser","/api/element/initDefaultSysFile",
"/api/python/chatStream",
"/api/python/flush"
);
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, @NonNull HttpServletResponse httpServletResponse, @NonNull FilterChain filterChain) throws ServletException, IOException {

View File

@@ -0,0 +1,59 @@
package com.ai.da.common.utils;
public class PantoneUtils {
public static int[] rgbToHsv(int[] rgb) {
//切割rgb数组
int R = rgb[0];
int G = rgb[1];
int B = rgb[2];
//公式运算 /255
float R_1 = R / 255f;
float G_1 = G / 255f;
float B_1 = B / 255f;
//重新拼接运算用数组
float[] all = {R_1, G_1, B_1};
float max = all[0];
float min = all[0];
//循环查找最大值和最小值
for (int i = 0; i < all.length; i++) {
if (max <= all[i]) {
max = all[i];
}
if (min >= all[i]) {
min = all[i];
}
}
float C_max = max;
float C_min = min;
//计算差值
float diff = C_max - C_min;
float hue = 0f;
//判断情况计算色调H
if (diff == 0f) {
hue = 0f;
} else {
if (C_max == R_1) {
hue = (((G_1 - B_1) / diff) % 6) * 60f;
}
if (C_max == G_1) {
hue = (((B_1 - R_1) / diff) + 2f) * 60f;
}
if (C_max == B_1) {
hue = (((R_1 - G_1) / diff) + 4f) * 60f;
}
}
//计算饱和度S
float saturation;
if (C_max == 0f) {
saturation = 0f;
} else {
saturation = diff / C_max;
}
//计算明度V
float value = C_max;
int[] result = {Math.round(hue), Math.round(saturation * 100), Math.round(value * 100)};
return result;
}
}

View File

@@ -3,7 +3,6 @@ package com.ai.da.controller;
import com.ai.da.common.response.Response;
import com.ai.da.model.dto.*;
import com.ai.da.model.vo.DesignCollectionVO;
import com.ai.da.model.vo.DesignItemDetailVO;
import com.ai.da.model.vo.DesignLikeVO;
import com.ai.da.service.DesignService;
import com.alibaba.fastjson.JSONObject;

View File

@@ -1,8 +1,6 @@
package com.ai.da.controller;
import com.ai.da.common.response.Response;
import com.ai.da.mapper.entity.CollectionElement;
import com.ai.da.mapper.entity.DesignItem;
import com.ai.da.model.dto.*;
import com.ai.da.model.vo.*;
import com.ai.da.service.DesignItemService;
@@ -15,7 +13,6 @@ import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
@Api(tags = "design Detail模块")
@@ -44,8 +41,9 @@ public class DesignDetailController {
}
@ApiOperation(value = "查询design详情")
@GetMapping("/getDetail")
public Response<DesignItemDetailVO> getDetail(@ApiParam("designItemId") @RequestParam("designItemId") Long designItemId) {
return Response.success(designService.detail(designItemId));
public Response<DesignItemDetailVO> getDetail(@ApiParam("designItemId") @RequestParam("designItemId") Long designItemId,
@ApiParam("designPythonOutfitId") @RequestParam(value = "designPythonOutfitId",required = false) Long designPythonOutfitId) {
return Response.success(designService.detail(designPythonOutfitId,designItemId));
}
@ApiOperation(value = "切换系统的element")

View File

@@ -0,0 +1,49 @@
package com.ai.da.controller;
import com.ai.da.common.response.Response;
import com.ai.da.model.dto.GenerateLikeDTO;
import com.ai.da.model.dto.GenerateThroughImageTextDTO;
import com.ai.da.model.vo.GenerateCaptionVO;
import com.ai.da.model.vo.GenerateCollectionVO;
import com.ai.da.model.vo.GenerateLikeVO;
import com.ai.da.service.GenerateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
/**
* @author XP
*/
@Api(tags = "Generate模块")
@Slf4j
@RestController
@RequestMapping("/api/generate")
public class GenerateController {
@Resource
private GenerateService generateService;
@ApiOperation("自动识别sketch的caption")
@PostMapping("/caption")
public Response<GenerateCaptionVO> generateCaption(@RequestParam Long sketchElementId){
return Response.success(generateService.generateCaption(sketchElementId));
}
@ApiOperation("通过文字、图片生成图片")
@PostMapping("/sketchAndPrint")
public Response<GenerateCollectionVO> generateThroughImageText(@Valid @RequestBody GenerateThroughImageTextDTO generateThroughImageTextDTO){
return Response.success(generateService.generateThroughImageText(generateThroughImageTextDTO));
}
@ApiOperation("喜欢生成的图片")
@PostMapping("/like")
public Response<GenerateLikeVO> like(@Valid @RequestBody GenerateLikeDTO generateLikeDTO){
return Response.success(generateService.generateLike(generateLikeDTO));
}
}

View File

@@ -3,23 +3,23 @@ package com.ai.da.controller;
import com.ai.da.common.enums.CollectionLevel1TypeEnum;
import com.ai.da.common.response.Response;
import com.ai.da.common.utils.CopyUtil;
import com.ai.da.common.utils.MD5Utils;
import com.ai.da.model.dto.CollectionDeleteFileDTO;
import com.ai.da.model.dto.CollectionElementUploadDTO;
import com.ai.da.model.dto.CollectionGeneratePrintDTO;
import com.ai.da.model.dto.CollectionSavePrintDTO;
import com.ai.da.model.vo.*;
import com.ai.da.model.dto.ChatFlushDTO;
import com.ai.da.model.dto.ChatSendDTO;
import com.ai.da.model.vo.PythonLibraryVo;
import com.ai.da.model.vo.SysFileVO;
import com.ai.da.python.PythonService;
import com.ai.da.service.*;
import com.ai.da.service.ChatRobotService;
import com.ai.da.service.LibraryService;
import com.ai.da.service.SysFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -39,13 +39,27 @@ public class PythonController {
@Resource
private LibraryService libraryService;
@Resource
private ChatRobotService chatRobotService;
@ApiOperation(value = "python服务保存图片到java服务")
@PostMapping("/saveGeneratePicture")
public Response<String> upload(@RequestParam("file") MultipartFile file,
@ApiParam("操作类型 generatePrint ->生成印花 " +
"designCollection ->设计collection generateAdvancedDesign ->生成高级design")
@RequestParam(value = "operateType") String operateType) {
return Response.success(pythonService.upload(file,operateType));
@ApiParam("操作类型 generatePrint ->生成印花 " +
"designCollection ->设计collection generateAdvancedDesign ->生成高级design"+
"generateSketch -> 生成草图")
@RequestParam(value = "operateType") String operateType) {
return Response.success(pythonService.upload(file, operateType));
}
@ApiOperation(value = "python服务保存多张图片到java服务")
@PostMapping("/saveMultiGeneratePicture")
public Response<List<String>> uploadMultiple(@RequestParam("files") MultipartFile[] files,
@ApiParam("操作类型 generatePrint ->生成印花 " +
"designCollection ->设计collection generateAdvancedDesign ->生成高级design"+
"generateSketch -> 生成草图")
@RequestParam(value = "operateType") String operateType) {
return Response.success(pythonService.upload(files, operateType));
}
@ApiOperation(value = "通过文件类型获取系统文件")
@@ -56,12 +70,27 @@ public class PythonController {
@ApiOperation(value = "通过用户id获取library")
@GetMapping("/getLibraryByUserId")
public Response<Map<String,List<String>>> getLibraryByUserId(@RequestParam(value = "userId") Long userId) {
public Response<Map<String, List<String>>> getLibraryByUserId(@RequestParam(value = "userId") Long userId) {
List<PythonLibraryVo> response = CopyUtil.copyList(libraryService.selectByAccountIdAnd1TypeList(userId,
Collections.singletonList(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName())),PythonLibraryVo.class);
Collections.singletonList(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName())), PythonLibraryVo.class);
//key转小写 统一
return Response.success(response.stream().collect(Collectors.groupingBy(v ->v.getLevel2Type().toLowerCase(),
Collectors.mapping(PythonLibraryVo::getUrl,Collectors.toList()))));
return Response.success(response.stream().collect(Collectors.groupingBy(v -> v.getLevel2Type().toLowerCase(),
Collectors.mapping(PythonLibraryVo::getUrl, Collectors.toList()))));
}
@CrossOrigin
@ApiOperation(value = "发送用户输入消息")
@PostMapping("/chatStream")
public SseEmitter MessageToPythonChatStream(@RequestBody ChatSendDTO chatSendDTO) {
log.info(chatSendDTO.toString());
return chatRobotService.sendMessageToChatRobot(chatSendDTO);
}
@CrossOrigin
@ApiOperation(value = "刷新会话缓存")
@PostMapping("/flush")
public Response<String> ChatBufferFlush(@RequestBody ChatFlushDTO chatFlushDTO) {
return Response.success(chatRobotService.chatBufferFlush(chatFlushDTO));
}
}

View File

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

View File

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

View File

@@ -0,0 +1,65 @@
package com.ai.da.mapper.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.util.Date;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("t_generate")
public class Generate {
/**
* ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 用户ID
*/
private Long accountId;
/**
* Sketchboard Printboard
*/
private String level1Type;
/**
* 关联collection element id
*/
private Long collectionElementId;
/**
* caption的内容
*/
private String text;
/**
* 选择生成类型text、image、text-image
*/
private String generateType;
/**
* 模型名
*/
private String modelName;
/**
* 创建时间
*/
private Date createDate;
/**
* 更新时间
*/
private Date updateDate;
}

View File

@@ -0,0 +1,54 @@
package com.ai.da.mapper.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.util.Date;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("t_generate_detail")
public class GenerateDetail {
/**
* ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 关联 generate ID
*/
private Long generateId;
/**
* 模型返回的图片url
*/
private String url;
/**
* 是否喜欢 0dislike 1:like
*/
private Byte isLike;
/**
* 创建时间
*/
private Date createDate;
/**
* 更新时间
*/
private Date updateDate;
}

View File

@@ -27,6 +27,7 @@ public class PanTone implements Serializable {
/**
* pantone_index
*/
@TableId("pantone_index")
private Integer pantoneIndex;
/**

View File

@@ -14,7 +14,19 @@ public class AccountPreLoginDTO {
@ApiModelProperty("用户名")
private String userName;
/*新增字段*/
@NotBlank(message = "Please input email !")
@ApiModelProperty("邮箱")
private String email;
@NotBlank(message = "password cannot be empty!")
@ApiModelProperty("密码")
private String password;
@NotBlank(message = "operationType cannot be empty")
@ApiModelProperty("操作类型 LOGIN 注册 FORGET_PWD 忘记密码 BIND_MAILBOX 绑定邮箱")
private String operationType;
@ApiModelProperty("异常ip")
private String ip;
}

View File

@@ -0,0 +1,27 @@
package com.ai.da.model.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
/**
* @author aida
* @version 1.0
* @project aida_back
* @description 刷新缓存DTO
* @date 2023/7/25 16:51:16
*/
@Data
public class ChatFlushDTO {
@NotNull(message = "userId cannot be empty!")
@ApiModelProperty("用户id")
private String user_id;
@NotBlank(message = "sessionId cannot be empty!")
@ApiModelProperty("会话ID")
private String session_id;
}

View File

@@ -0,0 +1,34 @@
package com.ai.da.model.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
/**
* @author aida
* @version 1.0
* @project aida_back
* @description 机器人对话DTO
* @date 2023/7/25 16:35:55
*/
@Data
@ApiModel("chatRobot 对话")
public class ChatSendDTO {
@NotNull(message = "userId cannot be empty!")
@ApiModelProperty("用户id")
private String user_id;
@NotBlank(message = "sessionId cannot be empty!")
@ApiModelProperty("会话ID")
private String session_id;
@NotBlank(message = "Please input the message !")
@ApiModelProperty("消息")
private String message;
}

View File

@@ -0,0 +1,28 @@
package com.ai.da.model.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Data
@ApiModel("Generate like入参")
public class GenerateLikeDTO {
@NotNull(message = "generateDetail id cannot be empty!")
@ApiModelProperty("generateDetailId")
private Long generateDetailId;
@NotBlank(message = "level1Type cannot be empty!")
@ApiModelProperty("一级类型 Sketchboard Printboard")
private String level1Type;
@ApiModelProperty("当一级类型为Sketchboard时二级类型 Outwear Dress Blouse Skirt Trousers")
private String level2Type;
@NotBlank(message = "timeZone cannot be empty!")
@ApiModelProperty("本地时区,比如 'Asia/Tokyo' 东京时间 , 'Asia/Shanghai' 北京时间 由js本地获取")
private String timeZone;
}

View File

@@ -0,0 +1,39 @@
package com.ai.da.model.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
@ApiModel("GenerateThroughImageTextDTO")
public class GenerateThroughImageTextDTO {
@ApiModelProperty("caption")
String text;
@ApiModelProperty("图片在t_collection_element表中的id")
Long collectionElementId;
@NotBlank(message = "you have to choose the generate type")
@ApiModelProperty("text image text-image")
String generateType;
@ApiModelProperty("图片是update还是从library中选择")
String designType;
@NotBlank(message = "level1Type cannot be empty!")
@ApiModelProperty("Moodboard Printboard Sketchboard MarketingSketch")
String level1Type;
@ApiModelProperty("Outwear Dress Blouse Skirt Trousers")
String level2Type;
@ApiModelProperty("选择的模型名")
String version;
@NotBlank(message = "timeZone cannot be empty!")
@ApiModelProperty("本地时区,比如 'Asia/Tokyo' 东京时间 , 'Asia/Shanghai' 北京时间 由js本地获取")
String timeZone;
}

View File

@@ -3,10 +3,8 @@ package com.ai.da.model.vo;
import com.ai.da.python.vo.DesignPythonItemPrint;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Date;
import java.util.List;
@Data
@@ -26,8 +24,12 @@ public class DesignItemClothesDetailVO {
private String path;
@ApiModelProperty(" 颜色 存 RGB值 中间空格分隔 比如 58 58 169")
private String color;
// private String color;
private PantoneVO color;
@ApiModelProperty("对应的print图片对象")
private DesignPythonItemPrint printObject;
@ApiModelProperty("对应图层信息")
private List<DesignPythonOutfitVO> layersObject;
}

View File

@@ -15,6 +15,7 @@ public class DesignItemDetailVO {
private Long designItemId;
@ApiModelProperty("designItem图片")
// private DesignPythonOutfitVO designItemUrl;
private String designItemUrl;
@ApiModelProperty("design高级图片")

View File

@@ -5,6 +5,8 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
@Data
@ApiModel("designItem detail others 响应")
public class DesignItemOthersDetailVO {
@@ -19,8 +21,12 @@ public class DesignItemOthersDetailVO {
private String path;
@ApiModelProperty(" 颜色 存 RGB值 中间空格分隔 比如 58 58 169")
private String color;
// private String color;
private PantoneVO color;
@ApiModelProperty("对应的print图片的绝对路径")
private DesignPythonItemPrint printObject;
@ApiModelProperty("对应图层信息")
private List<DesignPythonOutfitVO> layersObject;
}

View File

@@ -0,0 +1,28 @@
package com.ai.da.model.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel("designItem detail layer响应")
public class DesignPythonOutfitDetailVO {
@ApiModelProperty("各图层id")
private Long id;
@ApiModelProperty("图片所属分类 earring_back/front,hairstyle_back/front,skirt_back/front,shoes_left/right,body 等")
private String imageCategory;
@ApiModelProperty("图片url")
private String imageUrl;
@ApiModelProperty("蒙版url")
private String maskUrl;
@ApiModelProperty("坐标")
private String position;
@ApiModelProperty("优先级")
private Integer priority;
}

View File

@@ -0,0 +1,37 @@
package com.ai.da.model.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel("designItem detail从python端获取的合成图+各图层响应")
public class DesignPythonOutfitVO {
/**
* ID
*/
@ApiModelProperty(value = "ID")
private Long id;
/**
* 图层
*/
@ApiModelProperty(value = "图层名")
private String imageCategory;
/**
* 对应的图片的绝对路径
*/
@ApiModelProperty(value = "对应的图片的绝对路径")
private String imageUrl;
/**
* mask_url
*/
@ApiModelProperty(value = "遮罩")
private String maskUrl;
/**
* 位置
*/
@ApiModelProperty(value = "位置")
private String position;
}

View File

@@ -0,0 +1,18 @@
package com.ai.da.model.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
@ApiModel("生成sketch的caption")
public class GenerateCaptionVO {
@ApiModelProperty("caption")
private String caption;
}

View File

@@ -0,0 +1,16 @@
package com.ai.da.model.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel("生成 ConllectionItem响应")
public class GenerateCollectionItemVO {
@ApiModelProperty("generate生成图片的id")
private Long generateItemId;
@ApiModelProperty("generate生成图片的url")
private String generateItemUrl;
}

View File

@@ -0,0 +1,30 @@
package com.ai.da.model.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
@Data
@ApiModel("generate响应vo")
public class GenerateCollectionVO {
@ApiModelProperty("generateId")
private Long generateId;
@ApiModelProperty("collection")
private Long collectionId;
@ApiModelProperty("生成的图片信息")
private List<GenerateCollectionItemVO> generatedCollectionItems;
public GenerateCollectionVO(Long generateId, Long collectionId, List<GenerateCollectionItemVO> generatedCollectionItems) {
this.generateId = generateId;
this.collectionId = collectionId;
this.generatedCollectionItems = generatedCollectionItems;
}
public GenerateCollectionVO() {
}
}

View File

@@ -0,0 +1,20 @@
package com.ai.da.model.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel("generate like 响应")
public class GenerateLikeVO {
@ApiModelProperty("like的图片加入library的id")
private Long libraryId;
public GenerateLikeVO(Long libraryId) {
this.libraryId = libraryId;
}
public GenerateLikeVO() {
}
}

View File

@@ -11,7 +11,7 @@ import javax.validation.constraints.NotBlank;
@ApiModel("潘通-响应")
public class PantoneVO {
@ApiModelProperty("id")
@ApiModelProperty("id -> pantoneIndex")
private Integer id;
@ApiModelProperty("名字")
@@ -23,10 +23,10 @@ public class PantoneVO {
@ApiModelProperty("r")
private Integer r;
@ApiModelProperty("r")
@ApiModelProperty("g")
private Integer g;
@ApiModelProperty("r")
@ApiModelProperty("b")
private Integer b;
@ApiModelProperty("h")

View File

@@ -1,6 +1,5 @@
package com.ai.da.model.vo;
import com.ai.da.model.dto.CollectionColorDTO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

View File

@@ -1,17 +1,13 @@
package com.ai.da.model.vo;
import com.ai.da.common.enums.CurrentDesignPrintPictureTypeEnum;
import com.ai.da.mapper.entity.CollectionElement;
import com.ai.da.mapper.entity.Library;
import com.ai.da.model.dto.CollectionColorDTO;
import com.ai.da.python.vo.DesignPythonItemPrint;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
import java.util.Objects;
@Data
@ApiModel("校验element响应")

View File

@@ -145,6 +145,28 @@ public class PythonService {
return null;
}
@Transactional
public List<String> upload(MultipartFile[] files, String operateType) {
List<String> paths = new ArrayList<>();
//用户信息
PythonToJavaApiOperationTypeEnum operationType = PythonToJavaApiOperationTypeEnum.uploadOf(operateType);
Assert.notNull(operationType, "unknown operateType " + operateType + "!");
String path = calculateFileUrl(operationType);
for (MultipartFile file : files) {
File generateFile = FileUtil.upload2(file, path);
Assert.notNull(generateFile,"An error occurred while processing the file, please try again later");
String linuxDomain = fileProperties.getLinuxDomain();
if (!StringUtils.isEmpty(linuxDomain)) {
//linux 系统
String oldPath = fileProperties.getSys().getPath();
paths.add(generateFile.getAbsolutePath().replace(oldPath, linuxDomain));
}
}
return paths;
}
private String calculateFileUrl(PythonToJavaApiOperationTypeEnum operationType) {
String rootPath = fileProperties.getSys().getPath();
String day = DateUtil.dateToStr(new Date(), DateUtil.YYYYMM);
@@ -1448,4 +1470,123 @@ public class PythonService {
//生成失败
throw new BusinessException("generate design exception!");
}
public String generateSketchCaption(String url) {
//限流校验
AccessLimitUtils.validate("generateSketchCaption",5);
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(30, TimeUnit.SECONDS)
.pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒)
.readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒)
.writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒)
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, url);
Request request = new Request.Builder()
.url(accessPythonIp+":2828/aida/interrogator")
.method("POST", body)
.addHeader("Authorization", "Basic YWlkbGFiOjEyMw==")
.addHeader("Content-Type", "application/json")
.build();
Response response = null;
String bodyStr = null;
try {
log.info("generateSketchCaption请求入参content###{}", url);
response = client.newCall(request).execute();
bodyStr = response.body().string();
} catch (IOException ioException) {
log.error("generateSketchCaption异常###{}", ExceptionUtil.getThrowableList(ioException));
}
//去除限流
AccessLimitUtils.validateOut("generateSketchCaption");
if (Objects.isNull(response)) {
log.error("generateSketchCaption异常###{}", "response or body is empty!");
throw new BusinessException("system error!");
}
JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(response));
Boolean result = jsonObject.getBoolean("successful");
if (result) {
return bodyStr;
}
log.info("attribute_retrieval失败###{}", bodyStr);
//生成失败
throw new BusinessException("system error!");
}
public String generateSketchOrPrint(String url, String text, int mode, String modelName) {
//限流校验
AccessLimitUtils.validate("generateSketchOrPrint",5);
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(30, TimeUnit.SECONDS)
.pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒)
.readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒)
.writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒)
.build();
MediaType mediaType = MediaType.parse("application/json");
Map<String, Object> content = Maps.newHashMap();
content.put("img_url", url);
content.put("str", text);
content.put("mode",mode);
content.put("version",modelName);
RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content));
Request request = new Request.Builder()
.url(accessPythonIp + ":2828/aida/diffusion")
.method("POST", body)
.addHeader("Authorization", "Basic YWlkbGFiOjEyMw==")
.addHeader("Content-Type", "application/json")
.build();
Response response = null;
String bodyString = null;
try {
log.info("generateSketchOrPrint请求入参content###{}", JSON.toJSONString(content));
response = client.newCall(request).execute();
bodyString = response.body().string();
} catch (IOException ioException) {
log.error("PythonService##generateSketchOrPrint异常###{}", ExceptionUtil.getThrowableList(ioException));
}
//去除限流
AccessLimitUtils.validateOut("generateSketchOrPrint");
if (Objects.isNull(response)) {
log.error("PythonService##generateSketchOrPrint异常###{}", "response or body is empty!");
throw new BusinessException("generateSketchOrPrint exception!");
}
JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(response));
Boolean result = jsonObject.getBoolean("successful");
if (result) {
return bodyString;
}
log.info("generateSketchOrPrintPrint失败###{}", jsonObject);
//生成失败
throw new BusinessException("generateSketchOrPrint exception!");
}
public String sendPostToModel(Map<String,Object> content,String portAndRoute,String functionName){
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(30, TimeUnit.SECONDS)
.pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒)
.readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒)
.writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒)
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content));
Request request = new Request.Builder()
.url(accessPythonIp + ":" + portAndRoute)
.method("POST", body)
.addHeader("Authorization", "Basic YWlkbGFiOjEyMw==")
.addHeader("Content-Type", "application/json")
.build();
Response response = null;
String bodyString = null;
try {
log.info(functionName + "请求入参content###{}", JSON.toJSONString(content));
response = client.newCall(request).execute();
bodyString = response.body().string();
} catch (IOException ioException) {
log.error("PythonService##"+ functionName +"异常###{}", ExceptionUtil.getThrowableList(ioException));
}
return bodyString;
}
}

View File

@@ -0,0 +1,18 @@
package com.ai.da.service;
import com.ai.da.model.dto.ChatFlushDTO;
import com.ai.da.model.dto.ChatSendDTO;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
/**
* @author aida
* @version 1.0
* @project aida_back
* @description 对话机器人服务接口
* @date 2023/7/25 16:42:18
*/
public interface ChatRobotService {
SseEmitter sendMessageToChatRobot(ChatSendDTO chatSendDTO);
String chatBufferFlush(ChatFlushDTO chatFlushDTO);
}

View File

@@ -115,4 +115,12 @@ public interface CollectionElementService extends IService<CollectionElement> {
*/
void refreshHistoryData() ;
/**
* 当level2Type发生改变时修改levelType
* @param elementId
* @param level2Type
* @return
*/
CollectionElement editLevel2Type(Long elementId,String level2Type);
}

View File

@@ -75,5 +75,5 @@ public interface DesignService extends IService<Design> {
* @param designItemId
* @return
*/
DesignItemDetailVO detail(Long designItemId);
DesignItemDetailVO detail(Long designPythonOutfitId,Long designItemId);
}

View File

@@ -0,0 +1,16 @@
package com.ai.da.service;
import com.ai.da.model.dto.GenerateLikeDTO;
import com.ai.da.model.dto.GenerateThroughImageTextDTO;
import com.ai.da.model.vo.GenerateCaptionVO;
import com.ai.da.model.vo.GenerateCollectionVO;
import com.ai.da.model.vo.GenerateLikeVO;
public interface GenerateService {
GenerateCaptionVO generateCaption(Long sketchElementId);
GenerateCollectionVO generateThroughImageText(GenerateThroughImageTextDTO generateThroughImageTextDTO);
GenerateLikeVO generateLike(GenerateLikeDTO generateLikeDTO);
}

View File

@@ -2,10 +2,13 @@ package com.ai.da.service;
import com.ai.da.mapper.entity.TDesignPythonOutfitDetail;
import com.ai.da.model.vo.DesignPythonOutfitVO;
import com.ai.da.model.vo.TDesignPythonOutfitDetailVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* design item详情表 服务类
*
@@ -23,4 +26,12 @@ public interface ITDesignPythonOutfitDetailService extends IService<TDesignPytho
*/
IPage<TDesignPythonOutfitDetailVO> selectTDesignPythonOutfitDetailPage(IPage<TDesignPythonOutfitDetailVO> page, TDesignPythonOutfitDetailVO tDesignPythonOutfitDetail);
/**
* 通过DesignPythonOutfitId获取designPythonOutfitDetail
* @param designPythonOutfitId
* @return
*/
List<TDesignPythonOutfitDetail> getDetailByDesignPythonOutfitId(Long designPythonOutfitId);
DesignPythonOutfitVO convertToDesignPythonOutfitVO(TDesignPythonOutfitDetail detail);
}

View File

@@ -6,6 +6,7 @@ import com.ai.da.model.vo.PantoneVO;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
import java.util.Map;
/**
* 服务类
@@ -41,6 +42,10 @@ public interface PanToneService extends IService<PanTone> {
*/
PantoneVO getByRGB(Integer r,Integer g,Integer b);
Map<String,PantoneVO> getPantoneByRgbBatch(List<String> colors);
PantoneVO getPantoneByRgb(String color);
/**
* 根据hsv批量查询
* @param rgbByHsvBatch

View File

@@ -1,12 +1,9 @@
package com.ai.da.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ai.da.common.config.exception.BusinessException;
import com.ai.da.common.constant.TokenConstant;
import com.ai.da.common.enums.LoginTypeEnum;
import com.ai.da.common.enums.OperationTypeEnum;
import com.ai.da.common.httpdata.token.TokenQuery;
import com.ai.da.common.security.jwt.JWTTokenHelper;
import com.ai.da.common.utils.*;
import com.ai.da.mapper.AccountMapper;
@@ -19,25 +16,18 @@ import com.ai.da.model.vo.AuthPrincipalVo;
import com.ai.da.service.AccountLoginLogService;
import com.ai.da.service.AccountService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.util.RequestUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
@@ -64,15 +54,49 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
public AccountPreLoginVO preLogin(AccountPreLoginDTO accountDTO) {
log.info("aida预先登入accountDTO###{}", JSON.toJSONString(accountDTO));
Account account = getOneByUserName(accountDTO.getUserName());
Assert.isTrue(Objects.nonNull(account),"User does not exist!");
Assert.isTrue(Objects.nonNull(account), "User does not exist!");
//用户有效期校验
validateUserValidaExpire(account);
if("Third-000000".equals(account.getUserPassword())){
if ("Third-000000".equals(account.getUserPassword())) {
account.setUserPassword(accountDTO.getPassword());
accountMapper.updateById(account);
}else{
Assert.isTrue(account.getUserPassword().equals(accountDTO.getPassword()),"Password error !");
} else {
Assert.isTrue(account.getUserPassword().equals(accountDTO.getPassword()), "Password error !");
}
/*发送邮件*/
OperationTypeEnum operationTypeEnum = OperationTypeEnum.of(accountDTO.getOperationType());
log.info(account.getUserEmail());
log.info(accountDTO.getEmail());
Assert.isTrue(account.getUserEmail().equals(accountDTO.getEmail()), "Email error !");
Assert.notNull(operationTypeEnum, "Unknown operation type!");
String randomVerifyCode = RandomsUtil.generateVerifyCode(100000L, 999999L);
LocalCacheUtils.setVerifyCodeCache(
accountDTO.getOperationType() + "_" + accountDTO.getEmail(), randomVerifyCode);
Boolean result = Boolean.FALSE;
switch (operationTypeEnum) {
case LOGIN:
Assert.notNull(accountDTO, "Email not registered!");
result = SendEmailUtil.send(accountDTO.getEmail(), null,
SendEmailUtil.LOGIN_TEMPLATE_ID, randomVerifyCode);
break;
case FORGET_PWD:
Assert.notNull(accountDTO, "Email not registered!");
result = SendEmailUtil.send(accountDTO.getEmail(), null,
SendEmailUtil.UPDATE_PWD_TEMPLATE_ID, randomVerifyCode);
break;
case EXCEPTION_IP:
Assert.notNull(accountDTO, "Email not registered!");
result = SendEmailUtil.send(accountDTO.getEmail(), accountDTO.getIp(),
SendEmailUtil.EXCEPTION_ID_TEMPLATE_ID, randomVerifyCode);
break;
case BIND_MAILBOX:
result = SendEmailUtil.send(accountDTO.getEmail(), null,
SendEmailUtil.BIND_MAILBOX_TEMPLATE_ID, randomVerifyCode);
break;
default:
Assert.notNull(operationTypeEnum, "Unknown operation type!");
}
Assert.isTrue(result, "Failed to send mail");
return new AccountPreLoginVO(account.getId());
}
@@ -81,10 +105,10 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
public AccountLoginVO login(AccountLoginDTO accountLoginDTO, HttpServletRequest request) {
log.info("aida确认登入###accountLoginDTO###{}", JSON.toJSONString(accountLoginDTO));
Account accountExist = getOneByEmail(accountLoginDTO.getEmail().trim());
Assert.notNull(accountExist,"User does not exist!");
Assert.notNull(accountExist, "User does not exist!");
LoginTypeEnum accountType = LoginTypeEnum.of(accountLoginDTO.getLoginType());
if (Objects.isNull(accountType)|| accountType.equals(LoginTypeEnum.PASSWORD)) {
if (Objects.isNull(accountType) || accountType.equals(LoginTypeEnum.PASSWORD)) {
throw new BusinessException("Unknown login type!");
}
//用户有效期校验
@@ -95,8 +119,8 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
case PASSWORD:
Assert.isTrue(StringUtils.isNotBlank(accountLoginDTO.getPassword()), "Please input a password !");
account = getOneByUserName(accountLoginDTO.getUserName());
Assert.isTrue(Objects.nonNull(account),"User does not exist!");
Assert.isTrue(account.getUserPassword().equals(accountLoginDTO.getPassword()),"Password error !");
Assert.isTrue(Objects.nonNull(account), "User does not exist!");
Assert.isTrue(account.getUserPassword().equals(accountLoginDTO.getPassword()), "Password error !");
// Assert.isTrue(StringUtils.isBlank(
// LocalCacheUtils.getTokenCache(String.valueOf(account.getId()))),"该用户已登入");
break;
@@ -108,9 +132,9 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
throw new BusinessException("Email not registered!");
}
//校验邮箱验证码
String verifyCode = LocalCacheUtils.getVerifyCodeCache( OperationTypeEnum.LOGIN.name() + "_" +accountLoginDTO.getEmail());
String verifyCode = LocalCacheUtils.getVerifyCodeCache(OperationTypeEnum.LOGIN.name() + "_" + accountLoginDTO.getEmail());
Assert.isTrue(StringUtils.isNotBlank(verifyCode), "The verification code has expired!");
if(!"921314".equals(accountLoginDTO.getEmailVerifyCode())){
if (!"921314".equals(accountLoginDTO.getEmailVerifyCode())) {
Assert.isTrue(verifyCode.equals(accountLoginDTO.getEmailVerifyCode()), "Verification code error!");
}
break;
@@ -118,34 +142,36 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
}
AccountLoginVO response = CopyUtil.copyObject(account, AccountLoginVO.class);
response.setEmail(account.getUserEmail());
String token =LocalCacheUtils.getTokenCache(String.valueOf(account.getId()));
if(StringUtils.isNotBlank(token)){
String token = LocalCacheUtils.getTokenCache(String.valueOf(account.getId()));
if (StringUtils.isNotBlank(token)) {
//用户已登入
response.setToken(token);
}else{
response.setToken(createAccountToken(account.getId(),account.getUserName()));
} else {
response.setToken(createAccountToken(account.getId(), account.getUserName()));
}
response.setUserId(account.getId());
//判断是否常用ip 不是则发邮件提示
calculateExceptionIp(RequestInfoUtil.getIpAddress(request),account);
calculateExceptionIp(RequestInfoUtil.getIpAddress(request), account);
return response;
}
private void validateUserValidaExpire(Account account){
private void validateUserValidaExpire(Account account) {
Long currentTime = new Date().getTime();
if(Objects.nonNull(account.getValidStartTime())){
Assert.isTrue(currentTime >= account.getValidStartTime(),"User expired !" );
if (Objects.nonNull(account.getValidStartTime())) {
Assert.isTrue(currentTime >= account.getValidStartTime(), "User expired !");
}
if(Objects.nonNull(account.getValidEndTime())){
Assert.isTrue(currentTime <= account.getValidEndTime(),"User expired !" );
if (Objects.nonNull(account.getValidEndTime())) {
Assert.isTrue(currentTime <= account.getValidEndTime(), "User expired !");
}
}
private void calculateExceptionIp(String ip ,Account account ){
private void calculateExceptionIp(String ip, Account account) {
//必须先绑定邮箱才可以发有异常ip邮件提醒
if(StringUtils.isNotBlank(account.getUserEmail())){
if (StringUtils.isNotBlank(account.getUserEmail())) {
List<AccountLoginLog> accountLoginLogs = accountLoginLogService.getByUserId(account.getId());
if(CollectionUtil.isNotEmpty(accountLoginLogs)){
if (CollectionUtil.isNotEmpty(accountLoginLogs)) {
List<String> existIps = accountLoginLogs.stream().map(AccountLoginLog::getIp).collect(Collectors.toList());
if(!existIps.contains(ip)){
if (!existIps.contains(ip)) {
//非常用ip,没有出现过
EmailSendDTO emailSendDTO = new EmailSendDTO();
emailSendDTO.setEmail(account.getUserEmail());
@@ -156,11 +182,12 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
}
}
//保存登入日志
accountLoginLogService.saveLoginLog(ip,account.getId());
accountLoginLogService.saveLoginLog(ip, account.getId());
}
private String createAccountToken(Long userId,String userName){
private String createAccountToken(Long userId, String userName) {
String token = LocalCacheUtils.getTokenCache(String.valueOf(userId));
if(StringUtils.isNotBlank(token)){
if (StringUtils.isNotBlank(token)) {
return token;
}
AuthPrincipalVo principal = new AuthPrincipalVo();
@@ -174,14 +201,14 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
@Override
public Boolean bindEmail(AccountBindEmailDTO accountBindEmailDTO) {
Account account = getOneByUserId(accountBindEmailDTO.getUserId());
Assert.notNull(account,"User does not exist !");
Assert.isTrue(StringUtils.isBlank(account.getUserEmail()),"User has bound mailbox !");
Assert.notNull(account, "User does not exist !");
Assert.isTrue(StringUtils.isBlank(account.getUserEmail()), "User has bound mailbox !");
//校验邮箱验证码
String verifyCode = LocalCacheUtils.getVerifyCodeCache(OperationTypeEnum.BIND_MAILBOX.name() + "_" + accountBindEmailDTO.getUserEmail());
Assert.isTrue(StringUtils.isNotBlank(verifyCode), "The verification code has expired !");
Assert.isTrue(verifyCode.equals(accountBindEmailDTO.getEmailVerifyCode()), "Verification code error !");
//绑定
updatePwdByUserId(accountBindEmailDTO.getUserEmail(),accountBindEmailDTO.getUserId());
updatePwdByUserId(accountBindEmailDTO.getUserEmail(), accountBindEmailDTO.getUserId());
return Boolean.TRUE;
}
@@ -206,6 +233,7 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
accountNew.setUserPassword(pwd);
accountMapper.update(accountNew, queryWrapper);
}
private void updatePwdByUserId(String email, Long userId) {
QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id", userId);
@@ -227,6 +255,7 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
queryWrapper.eq("user_name", userName);
return accountMapper.selectOne(queryWrapper);
}
private Account getOneByUserId(Long userId) {
QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id", userId);
@@ -240,9 +269,9 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
Assert.notNull(operationTypeEnum, "Unknown operation type!");
Account emailAccount = getOneByEmail(emailSendDTO.getEmail());
String randomVerifyCode =RandomsUtil.generateVerifyCode(100000L,999999L);
String randomVerifyCode = RandomsUtil.generateVerifyCode(100000L, 999999L);
LocalCacheUtils.setVerifyCodeCache(
emailSendDTO.getOperationType() + "_" + emailSendDTO.getEmail(),randomVerifyCode);
emailSendDTO.getOperationType() + "_" + emailSendDTO.getEmail(), randomVerifyCode);
Boolean result = Boolean.FALSE;
switch (operationTypeEnum) {
case LOGIN:
@@ -275,7 +304,7 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
public Boolean logout(AccountLogoutDTO accountLogoutDTO) {
//jwt本身失效比较难做 统一用缓存实现 删除缓存就失效
String token = LocalCacheUtils.getTokenCache(String.valueOf(accountLogoutDTO.getUserId()));
if(StringUtils.isNotBlank(token)){
if (StringUtils.isNotBlank(token)) {
LocalCacheUtils.delTokenCache(String.valueOf(accountLogoutDTO.getUserId()));
}
return Boolean.TRUE;
@@ -284,7 +313,7 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
@Override
public Boolean isLogin(AccountLogoutDTO accountLogoutDTO) {
String token = LocalCacheUtils.getTokenCache(String.valueOf(accountLogoutDTO.getUserId()));
if(StringUtils.isNotBlank(token)){
if (StringUtils.isNotBlank(token)) {
return Boolean.TRUE;
}
return Boolean.FALSE;
@@ -299,52 +328,52 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
account.setValidStartTime(Long.valueOf(accountAddDTO.getValidStartTime()));
account.setValidEndTime(Long.valueOf(accountAddDTO.getValidEndTime()));
account.setCreateDate(new Date());
return accountMapper.insert(account)>0;
return accountMapper.insert(account) > 0;
}
@Override
public Boolean editUser(AccountEditDTO accountEditDTO) {
if(Objects.isNull(accountEditDTO)|| ObjectUtils.isAllFieldNull(accountEditDTO)){
if (Objects.isNull(accountEditDTO) || ObjectUtils.isAllFieldNull(accountEditDTO)) {
throw new BusinessException("The edited account information cannot be blank!");
}
QueryWrapper<Account> queryTotal = new QueryWrapper<>();
Account account = new Account();
//校验
if(StringUtils.isNotBlank(accountEditDTO.getNewEmail())){
Assert.isTrue(StringUtils.isNotBlank(accountEditDTO.getOldEmail()),"oldEmail cannot be empty!");
queryTotal.eq("user_email",accountEditDTO.getOldEmail());
if (StringUtils.isNotBlank(accountEditDTO.getNewEmail())) {
Assert.isTrue(StringUtils.isNotBlank(accountEditDTO.getOldEmail()), "oldEmail cannot be empty!");
queryTotal.eq("user_email", accountEditDTO.getOldEmail());
Account accountSelect = accountMapper.selectOne(queryTotal);
Assert.notNull(accountSelect,"oldEmail does not exist!");
Assert.notNull(accountSelect, "oldEmail does not exist!");
account.setUserEmail(accountEditDTO.getNewEmail());
}
if(StringUtils.isNotBlank(accountEditDTO.getNewUserName())){
Assert.isTrue(StringUtils.isNotBlank(accountEditDTO.getOldUserName()),"oldUserName cannot be empty!");
queryTotal.eq("user_name",accountEditDTO.getOldUserName());
if (StringUtils.isNotBlank(accountEditDTO.getNewUserName())) {
Assert.isTrue(StringUtils.isNotBlank(accountEditDTO.getOldUserName()), "oldUserName cannot be empty!");
queryTotal.eq("user_name", accountEditDTO.getOldUserName());
Account accountSelect = accountMapper.selectOne(queryTotal);
Assert.notNull(accountSelect,"oldUserName does not exist!");
Assert.notNull(accountSelect, "oldUserName does not exist!");
account.setUserName(accountEditDTO.getNewUserName());
}
if(StringUtils.isNotBlank(accountEditDTO.getNewValidStartTime())){
Assert.isTrue(StringUtils.isNotBlank(accountEditDTO.getOldUserName()),"oldUserName cannot be empty!");
queryTotal.eq("user_name",accountEditDTO.getOldUserName());
if (StringUtils.isNotBlank(accountEditDTO.getNewValidStartTime())) {
Assert.isTrue(StringUtils.isNotBlank(accountEditDTO.getOldUserName()), "oldUserName cannot be empty!");
queryTotal.eq("user_name", accountEditDTO.getOldUserName());
Account accountSelect = accountMapper.selectOne(queryTotal);
Assert.notNull(accountSelect,"oldUserName does not exist!");
Assert.notNull(accountSelect, "oldUserName does not exist!");
account.setValidStartTime(Long.valueOf(accountEditDTO.getNewValidStartTime()));
}
if(StringUtils.isNotBlank(accountEditDTO.getNewValidEndTime())){
Assert.isTrue(StringUtils.isNotBlank(accountEditDTO.getOldUserName()),"oldUserName cannot be empty!");
queryTotal.eq("user_name",accountEditDTO.getOldUserName());
if (StringUtils.isNotBlank(accountEditDTO.getNewValidEndTime())) {
Assert.isTrue(StringUtils.isNotBlank(accountEditDTO.getOldUserName()), "oldUserName cannot be empty!");
queryTotal.eq("user_name", accountEditDTO.getOldUserName());
Account accountSelect = accountMapper.selectOne(queryTotal);
Assert.notNull(accountSelect,"oldUserName does not exist!");
Assert.notNull(accountSelect, "oldUserName does not exist!");
account.setValidEndTime(Long.valueOf(accountEditDTO.getNewValidEndTime()));
}
Account accountSelect = accountMapper.selectOne(queryTotal);
Assert.notNull(accountSelect,"oldAccount does not exist!");
accountMapper.update(account,queryTotal);
Assert.notNull(accountSelect, "oldAccount does not exist!");
accountMapper.update(account, queryTotal);
return null;
}
}

View File

@@ -0,0 +1,99 @@
package com.ai.da.service.impl;
import com.ai.da.model.dto.ChatFlushDTO;
import com.ai.da.model.dto.ChatSendDTO;
import com.ai.da.service.ChatRobotService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author aida
* @version 1.0
* @project ChatRobot
* @description 请求python Chat Stream 接口服务实现类
* @date 2023/7/10 10:41:45
*/
@Slf4j
@Service
public class ChatRobotServiceImpl implements ChatRobotService {
// @Value("")
String chatStreamUrl = "http://18.167.251.121:6789/api/chat_stream";
String chatBufferFlushUrl = "http://18.167.251.121:6789/api/chat_flush";
RestTemplate restTemplate = new RestTemplate();
Gson gson = new GsonBuilder().create();
private final ExecutorService executorService = Executors.newSingleThreadExecutor();
Integer timeout = 99999999;
@Override
public SseEmitter sendMessageToChatRobot(ChatSendDTO chatSendDTO) {
SseEmitter emitter = new SseEmitter();
String requestBody = gson.toJson(chatSendDTO);
executorService.execute(() -> {
try {
// 这里根据你的业务逻辑,从服务获取数据
// 示例:从服务获取数据并逐条发送给客户端
URL urlObj = new URL(chatStreamUrl);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
log.info(line);
emitter.send(line);
// Thread.sleep(1000);
}
reader.close();
} else {
System.out.println("Request failed with status code: " + responseCode);
}
connection.disconnect();
emitter.complete();
} catch (Exception e) {
emitter.completeWithError(e);
}
});
return emitter;
}
@Override
public String chatBufferFlush(ChatFlushDTO chatFlushDTO) {
log.info(chatBufferFlushUrl);
return String.valueOf(restTemplate.postForEntity(chatBufferFlushUrl, chatFlushDTO, String.class));
}
}

View File

@@ -24,6 +24,7 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import io.netty.util.internal.StringUtil;
import javafx.scene.chart.ValueAxis;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.LICENSE;
@@ -570,4 +571,17 @@ public class CollectionElementServiceImpl extends ServiceImpl<CollectionElementM
}
return Boolean.TRUE;
}
@Override
public CollectionElement editLevel2Type(Long elementId, String level2Type){
CollectionElement collectionElement = null;
if(!Objects.isNull(elementId)){
collectionElement = collectionElementMapper.selectById(elementId);
if (StringUtil.isNullOrEmpty(collectionElement.getLevel2Type()) || !(collectionElement.getLevel2Type()).equals(level2Type)){
collectionElement.setLevel2Type(level2Type);
updateById(collectionElement);
}
}
return collectionElement;
}
}

View File

@@ -157,6 +157,7 @@ public class DesignItemServiceImpl extends ServiceImpl<DesignItemMapper, DesignI
LibraryModelPoint modelPoint = libraryModelPointService.getById(design.getTemplateId());
Assert.notNull(modelPoint,"template does not exists!");
Library library = libraryService.getById(modelPoint.getLibraryId());
// ??和上面重复
Assert.notNull(modelPoint,"template does not exists!");
designLibraryModelPointVO = collectionElementService.calculateTemplatePoint(modelPoint,library.getHigh(),library.getWidth(),library.getUrl());
}
@@ -170,6 +171,7 @@ public class DesignItemServiceImpl extends ServiceImpl<DesignItemMapper, DesignI
//designSingle
DesignCollectionItemVO response = saveSingleDesignItemAndDetail(objects,design.getId(),designSingleDTO.getDesignItemId(),
design.getCollectionId(),userInfo,designSingleDTO.getTimeZone());
// ??
designItem.setDesignUrl(response.getDesignItemUrl());
return response;
}

View File

@@ -16,7 +16,6 @@ import com.ai.da.mapper.entity.Collection;
import com.ai.da.model.dto.*;
import com.ai.da.model.vo.*;
import com.ai.da.python.PythonService;
import com.ai.da.python.vo.DesignPythonItem;
import com.ai.da.python.vo.DesignPythonItemPrint;
import com.ai.da.python.vo.DesignPythonObject;
import com.ai.da.python.vo.DesignPythonObjects;
@@ -27,6 +26,7 @@ import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@@ -81,6 +81,8 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
@Resource
private ITDesignPythonOutfitDetailService designPythonOutfitDetailService;
@Resource
private PanToneService panToneService;
@Resource
private PythonTAllInfoService pythonTAllInfoService;
@Value("${minio.endpoint}")
private String endpoint;
@@ -679,18 +681,27 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
}
@Override
public DesignItemDetailVO detail(Long designItemId) {
public DesignItemDetailVO detail(Long designPythonOutfitId,Long designItemId) {
DesignItem designItem = designItemService.getById(designItemId);
Assert.notNull(designItem,"design item does not exist!");
Design design = getById(designItem.getDesignId());
Assert.notNull(design,"design does not exist!");
List<DesignItemDetail> designItemDetails = designItemDetailService.selectByDesignItemId(designItemId);
Assert.notEmpty(designItemDetails,"designItemDetails does not exist!");
// 添加判断designPythonOutfitId是否存在
TDesignPythonOutfit designPythonOutfit = new TDesignPythonOutfit();
Boolean flag = Boolean.FALSE;
if (Objects.nonNull(designPythonOutfitId)){
designPythonOutfit = designPythonOutfitService.getById(designPythonOutfitId);
Assert.notNull(designPythonOutfit,"designPythonOutfit does not exist!");
flag = Boolean.TRUE;
}
DesignItemDetailVO response = new DesignItemDetailVO();
response.setSingleOverall(design.getSingleOverall());
response.setSwitchCategory(design.getSwitchCategory());
response.setDesignItemId(designItemId);
response.setDesignItemUrl(designItem.getDesignUrl());
// response.setDesignItemUrl(designItem.getDesignUrl());
response.setHighDesignUrl(designItem.getHighDesignUrl());
List<DesignItemDetail> filterDetail = designItemDetails.stream()
.filter(f -> OUTWEAR_DRESS_BLOUSE.contains(f.getType()) || SKIRT_TROUSERS.contains(f.getType()))
@@ -708,13 +719,14 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
}));
//single 和 Models(模特)时候 系统元素为空
List<DesignItemDetail> filterDetail2 =designItemDetails.stream()
.filter(f -> SYS_HAIRSTYLE_SHOES.contains(f.getType()) )
// .filter(f -> SYS_HAIRSTYLE_SHOES.contains(f.getType()) )
.filter(f -> SYS_HAIRSTYLE_SHOES_BODY.contains(f.getType()) )
.collect(Collectors.toList());
response.setOthers(CopyUtil.copyList(filterDetail2,DesignItemOthersDetailVO.class,(o,d)->{
d.setId(o.getBusinessId());
d.setPrintObject(new DesignPythonItemPrint());
}));
return response;
return editDesignItemLayer(flag,designPythonOutfit,designItem.getDesignUrl(),editResponseColor(designItemDetails,response));
}
private String converTypeToLevel1(String type){
if(StringUtils.isEmpty(type)){
@@ -754,5 +766,84 @@ public class DesignServiceImpl extends ServiceImpl<DesignMapper, Design> impleme
return design.getId();
}
private DesignItemDetailVO editResponseColor(List<DesignItemDetail> designItemDetails,DesignItemDetailVO designItemDetailVO){
/*designItemDetails.forEach(d -> {
if (!StringUtil.isNullOrEmpty(d.getColor())){
PantoneVO pantoneByRgb = panToneService.getPantoneByRgb(d.getColor());
DesignItemClothesDetailVO clothesDetailVO = designItemDetailVO.getClothes().stream()
.filter(v -> v.getId().equals(d.getBusinessId()))
.findFirst().orElse(null);
if (Objects.nonNull(clothesDetailVO)){
clothesDetailVO.setColor(pantoneByRgb);
} else {
DesignItemOthersDetailVO othersDetailVO = designItemDetailVO.getOthers().stream()
.filter(v -> v.getId().equals(d.getBusinessId()))
.findFirst().orElse(null);
if (Objects.nonNull(othersDetailVO)) {
othersDetailVO.setColor(pantoneByRgb);
}
}
}
});*/
HashMap<Long, String> businessIdColor = new HashMap<>();
designItemDetails.forEach(designItemDetail -> {
if (!StringUtil.isNullOrEmpty(designItemDetail.getColor())){
businessIdColor.put(designItemDetail.getBusinessId(),designItemDetail.getColor());
}
});
Map<String, PantoneVO> pantoneByRgbBatch = panToneService.getPantoneByRgbBatch(new ArrayList<>(businessIdColor.values()));
designItemDetailVO.getClothes().forEach(c -> {
PantoneVO pantoneVO = pantoneByRgbBatch.get(businessIdColor.get(c.getId()));
c.setColor(pantoneVO);
});
designItemDetailVO.getOthers().forEach(o -> {
PantoneVO pantoneVO = pantoneByRgbBatch.get(businessIdColor.get(o.getId()));
o.setColor(pantoneVO);
});
return designItemDetailVO;
}
private DesignItemDetailVO editDesignItemLayer(Boolean flag,TDesignPythonOutfit designPythonOutfit,String designItemUrl,DesignItemDetailVO designItemDetailVO){
ArrayList<DesignPythonOutfitVO> detailsVO = new ArrayList<>();
if (flag){
// 1、判断designPythonOutfitId查出的图层信息是否为空不允许为空系统内部错误
List<TDesignPythonOutfitDetail> details = designPythonOutfitDetailService.getDetailByDesignPythonOutfitId(designPythonOutfit.getId());
Assert.notEmpty(details,"Some errors occurred, please restart the design");
details.forEach(detail -> {
detailsVO.add(designPythonOutfitDetailService.convertToDesignPythonOutfitVO(detail));
});
// 2、将查询出的图层信息填充到designItemDetailVO中
designItemDetailVO.setDesignItemUrl(designPythonOutfit.getDesignUrl());
// 2.1 填充clothes
designItemDetailVO.getClothes().forEach(c -> {
String type = c.getType().toLowerCase();
List<DesignPythonOutfitVO> outfitVOS = detailsVO.stream().filter(detail -> detail.getImageCategory().equals(type + "_back") ||
detail.getImageCategory().equals(type + "_front")).collect(Collectors.toList());
c.setLayersObject(outfitVOS);
});
// 2.2 填充others
designItemDetailVO.getOthers().forEach(o -> {
String type = o.getType().toLowerCase();
List<DesignPythonOutfitVO> outfitVOS = detailsVO.stream().filter(detail -> detail.getImageCategory().equals(type + "_back") ||
detail.getImageCategory().equals(type + "_front") ||
detail.getImageCategory().equals("body")).collect(Collectors.toList());
o.setLayersObject(outfitVOS);
});
}else{
designItemDetailVO.setDesignItemUrl(designItemUrl);
}
return designItemDetailVO;
}
}

View File

@@ -0,0 +1,177 @@
package com.ai.da.service.impl;
import cn.hutool.core.lang.Assert;
import com.ai.da.common.context.UserContext;
import com.ai.da.common.enums.CollectionLevel1TypeEnum;
import com.ai.da.common.enums.GenerateTypeEnum;
import com.ai.da.common.enums.ModelNameEnum;
import com.ai.da.common.utils.DateUtil;
import com.ai.da.common.utils.MD5Utils;
import com.ai.da.mapper.CollectionElementMapper;
import com.ai.da.mapper.GenerateDetailMapper;
import com.ai.da.mapper.GenerateMapper;
import com.ai.da.mapper.entity.*;
import com.ai.da.model.dto.GenerateLikeDTO;
import com.ai.da.model.dto.GenerateThroughImageTextDTO;
import com.ai.da.model.vo.*;
import com.ai.da.python.PythonService;
import com.ai.da.service.CollectionElementService;
import com.ai.da.service.GenerateService;
import com.ai.da.service.LibraryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.netty.util.internal.StringUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;
@Service
public class GenerateServiceImpl extends ServiceImpl<GenerateMapper,Generate> implements GenerateService {
@Resource
private CollectionElementMapper collectionElementMapper;
@Resource
private GenerateDetailMapper generateDetailMapper;
@Resource
private LibraryService libraryService;
@Resource
private PythonService pythonService;
@Resource
private CollectionElementService collectionElementService;
@Override
public GenerateCaptionVO generateCaption(Long sketchElementId) {
CollectionElement collectionElement = collectionElementMapper.selectById(sketchElementId);
Assert.notNull(collectionElement,"System error!Please reselect the sketch");
Assert.isTrue("Sketchboard".equals(collectionElement.getLevel1Type()) && !StringUtil.isNullOrEmpty(collectionElement.getUrl())
,"System error!Please reselect the sketch");
String url = collectionElement.getUrl();
// String caption = pythonService.generateSketchCaption(url);
GenerateCaptionVO recognized_caption = new GenerateCaptionVO("recognized caption");
return recognized_caption;
}
@Override
public GenerateCollectionVO generateThroughImageText(GenerateThroughImageTextDTO generateThroughImageTextDTO) {
// 1、获取用户信息
AuthPrincipalVo userHolder = UserContext.getUserHolder();
Long accountId = userHolder.getId();
// 2、判断必须入参是否为非空
Generate generate = new Generate();
generate.setAccountId(accountId);
generate.setGenerateType(generateThroughImageTextDTO.getGenerateType());
generate.setModelName(StringUtil.isNullOrEmpty(generateThroughImageTextDTO.getVersion()) ? ModelNameEnum.MODEL_0.getCode() : generateThroughImageTextDTO.getVersion());
generate.setCreateDate(DateUtil.getByTimeZone(generateThroughImageTextDTO.getTimeZone()));
generate.setLevel1Type(generateThroughImageTextDTO.getLevel1Type());
String text = generateThroughImageTextDTO.getText();
Long elementId = generateThroughImageTextDTO.getCollectionElementId();
validateGeneraType(generate,text,elementId);
// 3、将请求信息落库
// 3.1 sketch或print在t_collection_element表中的信息是否需要更新 如 level2Type
CollectionElement collectionElement = collectionElementService.editLevel2Type(elementId, generateThroughImageTextDTO.getLevel2Type());
// 3.2 将本次generate的请求信息添加到t_generate表中
save(generate);
// 4、向模型发起请求
int mode = GenerateTypeEnum.TEXT.getValue().equals(generate.getGenerateType()) ? GenerateTypeEnum.TEXT.getCode() : GenerateTypeEnum.TEXT_IMAGE.getCode();
// String generatedSketchUrl = pythonService.generateSketchOrPrint(collectionElement.getUrl(),text,mode,generateThroughImageTextDTO.getVersion());
List<String> generatedSketchUrl = Arrays.asList("testUrl1","testUrl2","testUrl3","testUrl4");
// 5、处理模型返回的数据
// 5.1 将相应的url保存到数据库
List<GenerateCollectionItemVO> generatedCollectionItems = new ArrayList<>();
generatedSketchUrl.forEach(item -> {
GenerateDetail generateDetail = new GenerateDetail();
generateDetail.setUrl(item);
generateDetail.setGenerateId(generate.getId());
generateDetail.setCreateDate(DateUtil.getByTimeZone(generateThroughImageTextDTO.getTimeZone()));
generateDetailMapper.insert(generateDetail);
GenerateCollectionItemVO generateCollectionItemVO = new GenerateCollectionItemVO();
generateCollectionItemVO.setGenerateItemId(generateDetail.getId());
generateCollectionItemVO.setGenerateItemUrl(item);
generatedCollectionItems.add(generateCollectionItemVO);
});
// 6、将模型返回的图片地址返回给前端
Long collectionId = Objects.isNull(collectionElement) ? null : collectionElement.getCollectionId();
return new GenerateCollectionVO(generate.getId(),collectionId,generatedCollectionItems);
}
private void validateGeneraType(Generate generate,String text,Long elementId){
switch(generate.getGenerateType()){
case "text":
Assert.notNull(text,"Please input the caption");
generate.setText(text);
break;
case "image":
Assert.notNull(elementId,"Please choose a image");
generate.setCollectionElementId(elementId);
break;
case "text-image":
Assert.isTrue(!StringUtil.isNullOrEmpty(text) && Objects.nonNull(elementId),
"Please input the caption and choose a image");
generate.setText(text);
generate.setCollectionElementId(elementId);
default:
}
}
@Override
public GenerateLikeVO generateLike(GenerateLikeDTO generateLikeDTO) {
// 1、判断参数是否正确
// 1.1 必须参数是否非空
if(CollectionLevel1TypeEnum.SKETCH_BOARD.getRealName().equals(generateLikeDTO.getLevel1Type()) ){
Assert.isTrue(!StringUtil.isNullOrEmpty(generateLikeDTO.getLevel2Type()),"level2Type cannot be empty");
}
// 1.2 判断参数是否真实有效
Long generateDetailId = generateLikeDTO.getGenerateDetailId();
GenerateDetail generateDetail = generateDetailMapper.selectById(generateDetailId);
Assert.notNull(generateDetail,"generateItem does not exist");
Generate generate = getById(generateDetail.getGenerateId());
Assert.isTrue(generateLikeDTO.getLevel1Type().equals(generate.getLevel1Type()),"level1Type does not match");
// 2、将like的图片信息存入library
AuthPrincipalVo userInfo = UserContext.getUserHolder();
Long accountId = userInfo.getId();
Library library = setLibrary(accountId, generateLikeDTO, generateDetail.getUrl());
libraryService.save(library);
// 3、更新generateDetail表的isLike列
updateLikeStatus(generateLikeDTO.getGenerateDetailId(),(byte)1);
return new GenerateLikeVO(library.getId());
}
public Library setLibrary(Long accountId,GenerateLikeDTO generateLikeDTO,String imageUrl){
Library library = new Library();
library.setAccountId(accountId);
library.setLevel1Type(generateLikeDTO.getLevel1Type());
library.setLevel2Type(StringUtil.isNullOrEmpty(generateLikeDTO.getLevel2Type()) ? null : generateLikeDTO.getLevel2Type());
library.setName(DateUtil.dateToStr(new Date(),DateUtil.YYYY_MM_DD));
library.setUrl(imageUrl);
library.setMd5(MD5Utils.encryptFile(imageUrl,Boolean.FALSE));
library.setCreateDate(DateUtil.getByTimeZone(generateLikeDTO.getTimeZone()));
return library;
}
public void updateLikeStatus(Long generateDetailId,Byte hasLike){
QueryWrapper<GenerateDetail> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id", generateDetailId);
GenerateDetail generateDetail = new GenerateDetail();
generateDetail.setIsLike(hasLike);
generateDetailMapper.update(generateDetail,queryWrapper);
}
}

View File

@@ -3,7 +3,7 @@ package com.ai.da.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.ai.da.common.config.exception.BusinessException;
import com.ai.da.common.utils.CopyUtil;
import com.ai.da.mapper.entity.Collection;
import com.ai.da.common.utils.PantoneUtils;
import com.ai.da.mapper.entity.ColorLookupTable;
import com.ai.da.mapper.entity.PanTone;
import com.ai.da.mapper.PanToneMapper;
@@ -15,17 +15,12 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.netty.util.internal.StringUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -35,6 +30,8 @@ public class PanToneServiceImpl extends ServiceImpl<PanToneMapper, PanTone> impl
@Resource
private PanToneMapper panToneMapper;
@Resource
private PanToneService panToneService;
@Resource
private ColorLoopUpTableService colorLoopUpTableService;
@Override
@@ -74,6 +71,55 @@ public class PanToneServiceImpl extends ServiceImpl<PanToneMapper, PanTone> impl
return coverPanToneToVo(panTones);
}
@Override
public Map<String,PantoneVO> getPantoneByRgbBatch(List<String> colors){
HashMap<Integer,String> colorValueRgb = new HashMap<>();
HashMap<Integer,String> colorIndexRgb = new HashMap<>();
ArrayList<Integer> values = new ArrayList<>();
colors.forEach(color -> {
int[] rgb = Arrays.stream(color.split("\\s+")).mapToInt(Integer::parseInt).toArray();
int[] hsv = PantoneUtils.rgbToHsv(rgb);
int value = (hsv[0] * 101 *101)+ (hsv[1]*101) +hsv[2];
colorValueRgb.put(value,color);
values.add(value);
});
List<ColorLookupTable> colorValueList = colorLoopUpTableService.getByColorValueList(values);
colorValueList.forEach(colorValue ->{
colorIndexRgb.put(colorValue.getColorIndex(),colorValueRgb.get(colorValue.getColorValue()));
});
List<PanTone> panTones = panToneService.listByIds(colorIndexRgb.keySet());
ArrayList<PantoneVO> pantoneVOS = new ArrayList<>();
panTones.forEach(panTone -> {
pantoneVOS.add(coverPanToneToVo(panTone));
});
HashMap<String, PantoneVO> colorPantoneVO = new HashMap<>();
pantoneVOS.forEach(pantoneVO -> {
colorPantoneVO.put(colorIndexRgb.get(pantoneVO.getId()),pantoneVO);
});
return colorPantoneVO;
}
@Override
public PantoneVO getPantoneByRgb(String color){
GetRgbByHsvBatchDTO getRgbByHsvBatchDTO = new GetRgbByHsvBatchDTO();
if (!StringUtil.isNullOrEmpty(color)){
int[] rgb = Arrays.stream(color.split("\\s+")).mapToInt(Integer::parseInt).toArray();
int[] hsv = PantoneUtils.rgbToHsv(rgb);
getRgbByHsvBatchDTO.setH(hsv[0]);
getRgbByHsvBatchDTO.setS(hsv[1]);
getRgbByHsvBatchDTO.setV(hsv[2]);
}
return getByHSV(getRgbByHsvBatchDTO.getH(),getRgbByHsvBatchDTO.getS(),getRgbByHsvBatchDTO.getV());
}
@Override
public List<PantoneVO> getRgbByHsvBatch(List<GetRgbByHsvBatchDTO> hsvBatch) {
if(hsvBatch.size() >15){

View File

@@ -1,13 +1,19 @@
package com.ai.da.service.impl;
import com.ai.da.common.utils.CopyUtil;
import com.ai.da.mapper.TDesignPythonOutfitDetailMapper;
import com.ai.da.mapper.entity.TDesignPythonOutfitDetail;
import com.ai.da.model.vo.DesignPythonOutfitVO;
import com.ai.da.model.vo.TDesignPythonOutfitDetailVO;
import com.ai.da.service.ITDesignPythonOutfitDetailService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.util.List;
import java.util.Objects;
/**
* design item详情表 服务实现类
*
@@ -22,4 +28,21 @@ public class TDesignPythonOutfitDetailServiceImpl extends ServiceImpl<TDesignPyt
return page.setRecords(baseMapper.selectTDesignPythonOutfitDetailPage(page, tDesignPythonOutfitDetail));
}
@Override
public List<TDesignPythonOutfitDetail> getDetailByDesignPythonOutfitId(Long designPythonOutfitId){
QueryWrapper<TDesignPythonOutfitDetail> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("design_python_outfit_id",designPythonOutfitId);
return baseMapper.selectList(queryWrapper);
}
@Override
public DesignPythonOutfitVO convertToDesignPythonOutfitVO(TDesignPythonOutfitDetail detail){
if (Objects.isNull(detail)) {
return null;
}
return CopyUtil.copyObject(detail,DesignPythonOutfitVO.class);
}
}