Commit b38c94847e2f14f62f86e242de3b907506db0bb0

Authored by cherishsince
1 parent 1b02733c

增加contentparse 工具类

yudao-module-ai/yudao-spring-boot-starter-ai/src/main/java/cn/iocoder/yudao/framework/ai/midjourney/util/MjUtil.java 0 → 100644
  1 +package cn.iocoder.yudao.framework.ai.midjourney.util;
  2 +
  3 +import cn.hutool.core.text.CharSequenceUtil;
  4 +import cn.iocoder.yudao.framework.ai.midjourney.MjMessage;
  5 +
  6 +import java.util.regex.Matcher;
  7 +import java.util.regex.Pattern;
  8 +
  9 +/**
  10 + * author: fansili
  11 + * time: 2024/4/6 19:00
  12 + */
  13 +public class MjUtil {
  14 + /**
  15 + * content正则匹配prompt和进度.
  16 + */
  17 + public static final String CONTENT_REGEX = ".*?\\*\\*(.*?)\\*\\*.+<@\\d+> \\((.*?)\\)";
  18 + public static final String CONTENT_PROGRESS_REGEX = "\\(([^)]*)\\)";
  19 +
  20 +
  21 + public static MjMessage.Content parseContent(String content) {
  22 + // "**南极应该是什么样子? --v 6.0 --style raw** - <@972721304891453450> (32%) (fast, stealth)",
  23 + // "**南极应该是什么样子? --v 6.0 --style raw** - <@972721304891453450> (fast, stealth)"
  24 + MjMessage.Content mjContent = new MjMessage.Content();
  25 + if (CharSequenceUtil.isBlank(content)) {
  26 + return null;
  27 + }
  28 + if (!content.contains("raw**")) {
  29 + return mjContent.setPrompt(content);
  30 + }
  31 + int rawIndex = content.indexOf("raw**") + 5;
  32 + String prompt = content.substring(0, rawIndex).trim();
  33 + String contentTail = content.substring(rawIndex).trim();
  34 + // 检查是否存在进度条
  35 + Pattern pattern = Pattern.compile(CONTENT_PROGRESS_REGEX);
  36 + Matcher matcher = pattern.matcher(contentTail);
  37 +
  38 + if (contentTail.contains("%")) {
  39 + if (matcher.find()) {
  40 + // 获取第一个(也是此处唯一的)捕获组的内容
  41 + String progress = matcher.group(1);
  42 + mjContent.setProgress(progress);
  43 + }
  44 + if (matcher.find()) {
  45 + String status = matcher.group(1);
  46 + mjContent.setStatus(status);
  47 + }
  48 + } else {
  49 + if (matcher.find()) {
  50 + // 获取第一个(也是此处唯一的)捕获组的内容
  51 + String status = matcher.group(1);
  52 + mjContent.setStatus(status);
  53 + }
  54 + }
  55 + mjContent.setPrompt(prompt);
  56 + // tip:contentArray
  57 + return mjContent;
  58 + }
  59 +
  60 + public static void main(String[] args) {
  61 + String content1 = "**南极应该是什么样子? --v 6.0 --style raw** - <@972721304891453450> (32%) (fast, stealth)";
  62 + String content2 = "**南极应该是什么样子? --v 6.0 --style raw** - <@972721304891453450> (fast, stealth)";
  63 +
  64 + System.err.println(parseContent(content1));;
  65 + System.err.println(parseContent(content2));;
  66 + }
  67 +
  68 +}