TASK:mixi;

This commit is contained in:
shahaibo
2024-08-26 16:36:44 +08:00
parent 76992a0fb7
commit f2a7a8c774
3 changed files with 2935 additions and 2951 deletions

View File

@@ -570,17 +570,17 @@ public class PythonService {
public JSONObject getAIRecommend(AIRecommendDTO aiRecommendDTO) {
//限流校验
AccessLimitUtils.validate("similarityMatch", 20);
// AccessLimitUtils.validate("similarityMatch", 20);
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(30, TimeUnit.SECONDS)
.connectTimeout(300, TimeUnit.SECONDS)
.pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒)
.readTimeout(300, TimeUnit.SECONDS)//读取超时(单位:秒)
.writeTimeout(300, TimeUnit.SECONDS)//写入超时(单位:秒)
.build();
MediaType mediaType = MediaType.parse("application/json");
Map<String, Object> content = Maps.newHashMap();
content.put("input_message", "recommend three outfits");
content.put("user_id", "user456");
content.put("input_message", "recommend four outfits");
content.put("user_id", aiRecommendDTO.getUserId());
content.put("image_urls", "");
RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content));
@@ -594,13 +594,13 @@ public class PythonService {
Response response = null;
String bodyStr = null;
try {
log.info("获取python获取相似商品请求入参content###{}", JSON.toJSONString(content));
log.info("获取python获取AI推荐请求入参content###{}", JSON.toJSONString(content));
response = client.newCall(request).execute();
bodyStr = response.body().string();
} catch (IOException ioException) {
log.error("PythonService##similarityMatch异常###{}", ExceptionUtil.getThrowableList(ioException));
}
log.info("识获取python获取相似商品请求结果###{}", bodyStr.trim());
log.info("识获取python获取AI推荐请求结果###{}", bodyStr.trim());
//去除限流
AccessLimitUtils.validateOut("similarityMatch");
if (Objects.isNull(response)) {
@@ -613,8 +613,8 @@ public class PythonService {
JSONObject parseObject = JSON.parseObject(bodyStr.trim());
return parseObject;
}
log.info("获取python获取相似商品请求异常###{}", jsonObject);
log.info("获取python获取AI推荐请求异常###{}", jsonObject);
//生成失败
throw new BusinessException("SimilarityMatch exception.");
throw new BusinessException("AI recommendation exception.");
}
}

View File

@@ -740,96 +740,80 @@ public class TAppProductService extends ServiceImpl<TProductMapper, TProduct> {
// private MinioUtil minioUtil;
public List<OutfitRecommendation> aiRecommend(AIRecommendDTO aiRecommendDTO) {
List<OutfitRecommendation> result = new ArrayList<>();
// 创建推荐对象
OutfitRecommendation recommendation = new OutfitRecommendation();
// 调用ai推荐模型
// JSONObject jsonObject = pythonService.getAIRecommend(aiRecommendDTO);
//
// // 检查jsonObject是否为null
// if (jsonObject == null) {
// throw new NullPointerException("The response from Python service is null");
// }
JSONObject jsonObject = pythonService.getAIRecommend(aiRecommendDTO);
// 检查jsonObject是否为null
if (jsonObject == null) {
throw new NullPointerException("The response from Python service is null");
}
// 从JSON对象中获取output字段
// String output = jsonObject.getString("output");
String output = "I have a great outfit recommendation for you! Here are the details:\n\n### Recommended Outfit:\n1. **Tailored Navy Blue Blazer**\n - **Description**: A single-breasted design with notched lapels and a slim fit. Features two front flap pockets and a single button closure. Made from a wool blend for a structured yet comfortable feel.\n - ![Navy Blue Blazer](fashion_items/mitu/MKTS27015_0CMY.jpg)\n\n2. **White Silk Blouse**\n - **Description**: A classic collar, button-down front, and long sleeves with buttoned cuffs. Slightly loose fit for a sophisticated and airy look.\n - ![White Silk Blouse](fashion_items/mitu/MKTS27018_0WHT.jpg)\n\n3. **High-Waisted Beige Trousers**\n - **Description**: Straight-leg trousers in a light beige color. Clean front with a concealed hook-and-bar closure, side pockets, and a slightly cropped length to show off the ankles.\n - ![Beige Trousers](fashion_items/mitu/MLSS27160_0BGE.jpg)\n\n### Reasons for Recommendation:\n- **Parisian Chic Theme**: Classic and versatile pieces that embody sophistication and elegance.\n- **Navy Blue Blazer**: Adds a touch of structure, perfect for various occasions.\n- **White Silk Blouse**: A timeless staple that pairs well with the blazer.\n- **High-Waisted Beige Trousers**: Neutral base that complements the navy and white, creating a balanced and polished ensemble.\n\nThis combination is ideal for general use and can be dressed up or down depending on the occasion. Enjoy your new look!";
String output = jsonObject.getString("output");
// String output = "Here are three outfit recommendations for you:\n" +
// "\n" +
// "1. **Garden Party or Brunch Look**:\n" +
// " - **Floral Dress**: A long floral dress with a gathered waist, featuring a wrap-style bodice and three-quarter sleeves. It's crafted from lightweight cotton with a multicolored botanical pattern, suitable for casual or semi-formal wear.\n" +
// " - **Denim Jacket**: A short denim jacket with a classic collar, button closures, and front pockets, crafted from blue denim. It adds a touch of casual chic, ideal for transitioning from day to evening.\n" +
// " - ![Floral Dress](fashion_items/mitu/images/MWSS27211_0LGN.jpg)\n" +
// " - ![Denim Jacket](fashion_items/mitu/images/MLSS27109_0DBL.jpg)\n" +
// "\n" +
// "2. **Casual Summer Day**:\n" +
// " - **Mid-Length Dress**: Featuring short sleeves and a shirt collar, crafted from lightweight blue fabric with white stripes and floral embroidery. It includes a belted waist and tiered skirt for a casual, summery style.\n" +
// " - **Tropical Top**: A sleeveless top with a round neckline and a tropical leaf print in green and beige on a white background, perfect for a sunny outing.\n" +
// " - ![Mid-Length Dress](fashion_items/mitu/images/MLSS27102_0BLU.jpg)\n" +
// " - ![Tropical Top](fashion_items/mitu/images/MLSS27156_0GRN.jpg)\n" +
// "\n" +
// "3. **Everyday Relaxed Look**:\n" +
// " - **White Blouse**: A long-sleeve blouse with a V-neckline and gathered cuffs, made from lightweight cotton. It offers a casual, airy style suitable for everyday wear.\n" +
// " - **Wide-Leg Pants**: Beige wide-leg pants with a striped waistband, crafted from a smooth fabric. They feature side pockets and a sleek, casual design.\n" +
// " - ![White Blouse](fashion_items/mitu/images/MKTS27002_0WHT.jpg)\n" +
// " - ![Wide-Leg Pants](fashion_items/mitu/images/MKTS27004_0BGE.jpg)\n" +
// "\n" +
// "These outfits are designed to provide comfort and style for various occasions. Enjoy your new looks!";
List<String> urls = extractBracketContents(output);
Map<String, String> map = new HashMap<>();
for (String url : urls) {
if (url.contains("/")) {
String[] split = url.split("/");
String s = split[split.length - 1];
if (s.contains(".")) {
String[] split1 = s.split("\\.");
String pictureName = split1[0];
QueryWrapper<TProduct> qw = new QueryWrapper<>();
qw.lambda().like(TProduct::getPictureName, pictureName);
List<TProduct> productList = productMapper.selectList(qw);
if (!CollectionUtils.isEmpty(productList)) {
String pictureUrl = productList.get(0).getPictureUrl();
String presignedUrl = minioUtil.getPresignedUrl(pictureUrl, 24 * 60);
map.put(url, presignedUrl);
recommendation.addImageUrl(presignedUrl);
String[] parts = output.split("\\n\\n");
int length = parts.length;
String start = parts[0];
String end = parts[length - 1];
if (length >= 3) {
for (int i = 1; i < (length - 1); i++) {
OutfitRecommendation outfitRecommendation = new OutfitRecommendation();
String part = parts[i];
List<String> urls = extractBracketContents(part);
Map<String, String> map = new HashMap<>();
for (String url : urls) {
if (url.contains("/")) {
String[] split = url.split("/");
String s = split[split.length - 1];
if (s.contains(".")) {
String[] split1 = s.split("\\.");
String pictureName = split1[0];
QueryWrapper<TProduct> qw = new QueryWrapper<>();
qw.lambda().like(TProduct::getPictureName, pictureName);
List<TProduct> productList = productMapper.selectList(qw);
if (!CollectionUtils.isEmpty(productList)) {
String pictureUrl = productList.get(0).getPictureUrl();
String presignedUrl = minioUtil.getPresignedUrl(pictureUrl, 24 * 60);
map.put(url, presignedUrl);
outfitRecommendation.addImageUrl(presignedUrl);
}
}
}
}
for (String s : map.keySet()) {
part = part.replace(s, map.get(s));
}
String recommendOutput = start + "\n\n" + part + "\n\n" + end;
outfitRecommendation.setMarkdownContent(recommendOutput);
result.add(outfitRecommendation);
}
}
for (String s : map.keySet()) {
output = output.replace(s, map.get(s));
}
System.out.println(output);
// // 解析output字符串
// String[] parts = output.split("\n\n");
//
// // 创建Markdown格式内容
// StringBuilder markdownBuilder = new StringBuilder();
//
// // 处理描述部分
// if (parts.length > 1) {
// markdownBuilder.append("### Outfit Description:\n");
// markdownBuilder.append(parts[1]).append("\n\n");
// }
//
// // 处理推荐理由部分
// markdownBuilder.append("### Reasons for Recommendation:\n");
// StringBuilder reasonsBuilder = new StringBuilder();
// for (int i = 2; i < parts.length; i++) {
// if (parts[i].contains("![") && parts[i].contains("](") && parts[i].contains(")")) {
// // 找到图像URL部分
// try {
// String imageUrlPart = parts[i];
// String imageUrl = imageUrlPart.substring(imageUrlPart.indexOf("](") + 2, imageUrlPart.indexOf(")"));
// recommendation.addImageUrl(imageUrl);
//
// // 添加到Markdown
// markdownBuilder.append(imageUrlPart).append("\n\n");
// } catch (StringIndexOutOfBoundsException e) {
// // 捕获异常并继续处理剩余的部分
// e.printStackTrace();
// }
// } else {
// reasonsBuilder.append(parts[i]).append("\n\n");
// }
// }
// recommendation.setReasons(reasonsBuilder.toString().trim());
//
// // 将推荐理由添加到Markdown
// markdownBuilder.append(recommendation.getReasons()).append("\n\n");
// 设置Markdown内容
recommendation.setMarkdownContent(output);
// recommendation.setMarkdownContent(output + output + output + output + output);
// System.out.println(markdownBuilder.toString().trim());
List<OutfitRecommendation> result = new ArrayList<>();
result.add(recommendation);
result.add(recommendation);
result.add(recommendation);
result.add(recommendation);
return result;
}