Java调用Midjourney进行AI画图原生版抓包实现支持中文

news2024/11/29 8:38:20

用途介绍

Midjourney是一个目前优秀的AI画图工具,不挂梯无法直接访问

本代码主要用于搭建镜像站使用

适合人群

本代码不适合新手,建议使用过okhttp、且具有二开能力的同学使用~

实现原理

通过调用发送信息接口发送请求,通过轮询房间消息接口判断是否作图完成

发送的时候带上我们存储好的cookie信息即可

轮询房间消息接口是为了避免模拟网页实际的websocket连接,那玩意解密没解出来...

准备

1. 开通Midjourney会员的Discord账号

2. 新建很多房间(因为房间消息接口默认就50条数据,也就是说每个房间最多并行50个图片生成任务)

功能预览

上代码

代码功能:

1. 调用Midjourney生成并将生成好的内容发送微信消息给用户(这个是在微信公众号平台做的,大家做网页版的话自己改下输出到网页就可以)

2. 进行合规性检测(生成点不得了的东西后果你懂得,这里用的是百度的文本审核服务,5万次以下免费)

3. 如果用户输入是中文,就翻译为英文再发送

midjourneyLog

midjourney_log表字段如下代码所示

需要使用通用mapper哦~

package com.example.midjourney.bean.pojo;

import lombok.Data;
import tk.mybatis.mapper.annotation.NameStyle;
import tk.mybatis.mapper.code.Style;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;

@Data
@NameStyle(Style.camelhump)
@Table(name = "midjourney_log")
public class MidjourneyLog {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Integer memberId;

    private String channel;

    private String prompt;

    private Integer type;

    private Integer status;

    private String imgFile;

    private Integer roomId;

    private String uuid;

    private Date createTime;

}

MidJourneyBiz

请求唯一id没啥规律,一段时间内不一致就行,试了没啥校验

另外请求头除了cookie需要保证和 authorization、x-super-properties对应上,三者对应上实测2个月都不会掉线!

package com.example.midjourney.biz;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.example.midjourney.bean.BaiduTextCensor;
import com.example.midjourney.bean.BaiduTextCensorData;
import com.example.midjourney.bean.MidMsg;
import com.example.midjourney.bean.pojo.Discord;
import com.example.midjourney.bean.pojo.MidjourneyLog;
import com.example.midjourney.bean.pojo.RoomInfo;
import com.example.midjourney.contant.Constant;
import com.example.midjourney.enums.MedjourneyLogType;
import com.example.midjourney.service.DiscordService;
import com.example.midjourney.service.MidjourneyLogService;
import com.example.midjourney.service.MemberService;
import com.example.midjourney.service.RoomInfoService;
import com.example.midjourney.util.*;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.logging.log4j.util.Strings;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import static com.example.midjourney.contant.Constant.*;

/**
 * 启动就运行,不停刷新消息列表
 */
@Slf4j
@Service
public class MidJourneyBiz {

    private static BigDecimal bigDecimal = new BigDecimal("1099765990370980513")
            .add(new BigDecimal(System.currentTimeMillis()));

    @Resource
    private WeChatBiz weChatBiz;

    @Resource
    private TranslateBiz translateBiz;

    @Resource
    private MidjourneyLogService midjourneyLogService;

    @Resource
    private MemberService memberService;

    @Resource
    private RoomInfoService roomInfoService;

    @Resource
    private DiscordService discordService;

    public void buildImg(Long id) {
        MidjourneyLog midjourneyLog = midjourneyLogService.findById(id);
        try {
            if (midjourneyLog.getStatus() != 0) {
                return;
            }
            if (isFailMsg(midjourneyLog.getChannel(), midjourneyLog)) {
                log.info("[失败提示] 消息校验不通过 log:{}", midjourneyLog);
                sendBuildFail(midjourneyLog);
                return;
            }
            String prompt = midjourneyLog.getPrompt();
            if (midjourneyLog.getType() == MedjourneyLogType.BIG_IMG.getCode()) {
                downImg(midjourneyLog);
                return;
            }
            BaiduTextCensor censor = null;
            if (TextUtil.isHaveChinese(prompt)) {
                censor = BaiduUtil.textCensor(prompt);
            }
            prompt = cleanMsg(prompt);
            if (isBlackWord(prompt)) {
                sendSensitive(midjourneyLog);
                return;
            }
            if (Objects.isNull(censor)) {
                censor = BaiduUtil.textCensor(prompt);
            }
            midjourneyLogService.updatePrompt(midjourneyLog, prompt);
            if (censor.getConclusionType() == 2 || censor.getConclusionType() == 3) {
                sendSensitive(midjourneyLog, censor);
                return;
            }
            if (midjourneyLog.getType() == MedjourneyLogType.ITERATIVE.getCode()) {
                //暂不支持
                sendBuildFail(midjourneyLog);
                return;
            }
            RoomInfo roomInfo = roomInfoService.findIdleRoom();
            if (Objects.isNull(roomInfo)) {
                log.error("[并发超出警报] 当前并发次数已经无法满足!!!");
                sendBuildFail(midjourneyLog);
                return;
            }
            if (sendMsg(prompt, roomInfo)) {
                midjourneyLogService.updateRoom(midjourneyLog, roomInfo);
            } else {
                log.error("[发送失败] 发送信息失败,请检查");
                sendBuildFail(midjourneyLog);
            }
        } catch (Throwable t) {
            sendBuildFail(midjourneyLog);
        }
    }

    @SneakyThrows
    private void downImg(MidjourneyLog midjourneyLog) {
        MidjourneyLog lastLog = midjourneyLogService.findLastNormalLog(midjourneyLog.getMemberId());
        log.info("[下载图片] {}", lastLog);
        if (Objects.isNull(lastLog)) {
            log.info("[失败提示] 找不到上一次的图片 log:{}", midjourneyLog);
            sendBuildFail(midjourneyLog);
            return;
        }
        String imgFile = lastLog.getImgFile();
        File file = new File(imgFile);
        if (!file.exists()) {
            log.info("[失败提示] 上一次图片不存在 log:{}", lastLog);
            sendBuildFail(midjourneyLog);
            return;
        }
        cutAndSendImg(midjourneyLog, file);
    }

    private void cutAndSendImg(MidjourneyLog midjourneyLog, File oldFile) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(new FileInputStream(oldFile));
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        String msg = midjourneyLog.getPrompt().trim();
        String newFileName;
        if (msg.equalsIgnoreCase("u1")) {
            newFileName = oldFile.getPath() + "_u1.png";
            ImgUtil.cut(oldFile, FileUtil.file(newFileName),
                    new Rectangle(0, 0, width / 2, height / 2)
            );
        } else if (msg.equalsIgnoreCase("u2")) {
            newFileName = oldFile.getPath() + "_u2.png";
            ImgUtil.cut(oldFile, FileUtil.file(newFileName),
                    new Rectangle(width / 2, 0, width / 2, height / 2)
            );
        } else if (msg.equalsIgnoreCase("u3")) {
            newFileName = oldFile.getPath() + "_u3.png";
            ImgUtil.cut(oldFile, FileUtil.file(newFileName),
                    new Rectangle(0, height / 2, width / 2, height / 2)
            );
        } else if (msg.equalsIgnoreCase("u4")) {
            newFileName = oldFile.getPath() + "_u4.png";
            ImgUtil.cut(oldFile, FileUtil.file(newFileName),
                    new Rectangle(width / 2, height / 2, width / 2, height / 2)
            );
        } else {
            sendBuildFail(midjourneyLog);
            return;
        }
        String mediaId = weChatBiz.sendImg(newFileName, midjourneyLog.getChannel());
        log.info("[mediaId] {}", mediaId);
        if (Strings.isNotEmpty(mediaId)) {
            String wxId = memberService.selectWxidById(midjourneyLog.getMemberId());
            if (Strings.isEmpty(wxId)) {
                sendBuildFail(midjourneyLog);
                return;
            }
            midjourneyLogService.updateFinish(midjourneyLog);
            weChatBiz.sendImgMsg(wxId, mediaId, midjourneyLog.getChannel());
        }
    }

    private boolean isFailMsg(String channel, MidjourneyLog midjourneyLog) {
        return Objects.isNull(midjourneyLog) || Strings.isEmpty(midjourneyLog.getPrompt()) || Strings.isEmpty(channel)
                || Objects.isNull(midjourneyLog.getMemberId()) || checkNotRunMsg(midjourneyLog);
    }

    public boolean checkNotRunMsg(MidjourneyLog midjourneyLog) {
        String prompt = midjourneyLog.getPrompt();
        if (midjourneyLog.getType() == MedjourneyLogType.BIG_IMG.getCode()) {
            return !(prompt.equalsIgnoreCase("u1") || prompt.equalsIgnoreCase("u2")
                    || prompt.equalsIgnoreCase("u3") || prompt.equalsIgnoreCase("u4"));
        } else if (midjourneyLog.getType() == MedjourneyLogType.ITERATIVE.getCode()) {
            return !(prompt.equalsIgnoreCase("v1") || prompt.equalsIgnoreCase("v2")
                    || prompt.equalsIgnoreCase("v3") || prompt.equalsIgnoreCase("v4"));
        } else {
            return false;
        }
    }

    private String cleanMsg(String msg) {
        msg = msg.replace("—", "--")
                .replace("-- ", "--")
                .replace("-- ", "--")
                .replace("-- ", "--")
                .replace(",", ",")
                .replace("/", "")
                .replace("--v", " --v ")
                .replace("--niji", " --niji ")
                .replace("--ar", " --ar ")
                .replace("--aspect", " --ar ")
                .replace("--chaos", " --chaos ")
                .replace("--c", " --c ")
                .replace("--no", " --no ")
                .replace("--quality", " --quality ")
                .replace("--q", " --q ")
                .replace("--repeat", " --repeat ")
                .replace("--s", " --s ")
                .replace("--upbeta", " --upbeta ")
                .trim();
        if (TextUtil.isHaveChinese(msg)) {
            msg = translateBiz.translate(msg);
        }
        msg = msg.replace(",", ",")
                .replace("/", "")
                .replace("--v5", " --v 5 ")
                .replace("--niji5", " --niji 5 ")
                .trim();
        if (!msg.contains("--niji") && !msg.contains("--v") && msg.length() > 3) {
            msg = msg + " --v 5";
        }
        return msg;
    }

    public void sendBuildFail(MidjourneyLog midjourneyLog) {
        String wxId = memberService.selectWxidById(midjourneyLog.getMemberId());
        CallBackUtil.failCallBack(midjourneyLog.getChannel(), MIDJOURNEY, midjourneyLog.getId());
        midjourneyLogService.updateFail(midjourneyLog);
        weChatBiz.sendTextMsg(wxId, "抱歉,您的消息【" + midjourneyLog.getPrompt() + "】处理失败,已为您退换对应电量",
                midjourneyLog.getChannel());
    }

    @Scheduled(cron = "34 * * * * ? ")
    public void checkImg() {
        //房间号清理
        cleanRoomNumber();
        //查询所有进行中的任务
        List<MidjourneyLog> logs = midjourneyLogService.selectAllDoing().stream()
                .filter(log -> Objects.nonNull(log.getRoomId())).collect(Collectors.toList());
        //找到超时任务进行关闭
        List<MidjourneyLog> failLogs = logs.stream()
                .filter(log -> System.currentTimeMillis() - log.getCreateTime().getTime() > MAX_WAIT_TIME)
                .collect(Collectors.toList());
        failLogs.forEach(this::sendBuildFail);
        //剩余任务整理出来房间号
        logs.removeAll(failLogs);
        Set<Integer> roomSet = logs.stream().map(MidjourneyLog::getRoomId).collect(Collectors.toSet());
        //轮询当前进度
        for (Integer roomId : roomSet) {
            RoomInfo roomInfo = roomInfoService.findById(roomId);
            if (Objects.isNull(roomInfo)) {
                log.error("[room没找到] roomId:{} 没找到对应房间,看一下是不是挂了", roomId);
                continue;
            }
            Discord discord = discordService.findById(roomInfo.getDiscordId());
            List<MidMsg> midMsgs = readNowList(roomInfo, discord);
            log.info("[消息列表] {}", midMsgs);
            checkAndSendMsg(midMsgs, logs, roomInfo);
        }
    }

    private void cleanRoomNumber() {
        List<RoomInfo> roomInfos = roomInfoService.findAll();
        for (RoomInfo roomInfo : roomInfos) {
            int count = midjourneyLogService.selectRoomOnUse(roomInfo.getId());
            roomInfo.setNowNumber(count);
            roomInfoService.update(roomInfo);
        }
    }

    private void checkAndSendMsg(List<MidMsg> midMsgs, List<MidjourneyLog> logs, RoomInfo roomInfo) {
        List<MidjourneyLog> roomLogs = logs.stream()
                .filter(log -> log.getRoomId().equals(roomInfo.getId()))
                .collect(Collectors.toList());
        midMsgs.stream()
                .filter(this::isPrintOk)
                .forEach(m -> roomLogs.forEach(midjourey -> {
                    if (m.getContent().startsWith(MID_JOURNEY_HEAD + filterHead(midjourey.getPrompt()))) {
                        log.info("[Midjourney 配对] msg:{}  key:{}", m, midjourey.getPrompt());
                        String wxid = memberService.selectWxidById(midjourey.getMemberId());
                        String url = m.getAttachments().get(0).getUrl();
                        String localPath = Constant.FILE_PATH + UUID.randomUUID() + "." + FileUtil.getSuffix(url);
                        ImgDownUtil.getImage(url.replace("https://", "http://"), localPath);
                        localPath = localPath.replace("\\", "/");
                        if ("webp".equals(FileUtil.getSuffix(localPath))) {
                            com.example.midjourney.util.ImgUtil.webpToPng(localPath, localPath + ".png");
                            localPath = localPath + ".png";
                        }
                        String mediaId = weChatBiz.sendImg(localPath, midjourey.getChannel());
                        log.info("[mediaId] {}", mediaId);
                        if (Strings.isNotEmpty(mediaId)) {
                            weChatBiz.sendImgMsg(wxid, mediaId, midjourey.getChannel());
                            weChatBiz.sendTextMsg(wxid, "下载高清大图口令:\n\n☆左上图回复:U1\n\n☆右上图回复:U2" +
                                    "\n\n☆左下图回复:U3\n\n☆右下图回复:U4\n\n下载大图也会扣电量哦~", midjourey.getChannel());
                            midjourey.setImgFile(localPath);
                            midjourneyLogService.updateFinish(midjourey);
                        }
                    }
                }));
    }

    private String filterHead(String prompt) {
        return Lists.newArrayList(Splitter.on("--").split(prompt)).stream().findFirst().orElse("").trim();
    }

    private boolean isPrintOk(MidMsg midMsg) {
        if (Objects.isNull(midMsg)
                || Strings.isEmpty(midMsg.getContent())
                || !midMsg.getContent().contains(MID_FIND_LEFT)) {
            return false;
        }
        String str = midMsg.getContent().substring(midMsg.getContent().indexOf(MID_FIND_LEFT));
        return !str.contains("%") && !str.contains("Waiting");
    }

    private boolean isBlackWord(String msg) {
        msg = msg.toLowerCase();
        for (String s : Constant.MidjourneyBlackWord) {
            if (msg.contains(s.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

    private void sendSensitive(MidjourneyLog midjourneyLog) {
        String wxid = memberService.selectWxidById(midjourneyLog.getMemberId());
        midjourneyLogService.updateSensitive(midjourneyLog);
        weChatBiz.sendTextMsg(wxid, "【违规提示】输入内容包含违禁词,依法进行屏蔽。", midjourneyLog.getChannel());
    }

    /**
     * 审核不通过通知用户
     */
    private void sendSensitive(MidjourneyLog midjourneyLog, BaiduTextCensor censor) {
        String reason = Joiner.on("、")
                .join(Safes.of(censor.getData()).stream()
                        .map(BaiduTextCensorData::getMsg)
                        .collect(Collectors.toList()));
        reason = Strings.isEmpty(reason) ? "包含敏感信息" : reason;
        String fullText = "【违规提示】输入内容因 " + reason + " ,依法进行屏蔽。(百度提供审核能力)";
        String wxid = memberService.selectWxidById(midjourneyLog.getMemberId());
        midjourneyLogService.updateSensitive(midjourneyLog);
        weChatBiz.sendTextMsg(wxid, fullText, midjourneyLog.getChannel());
    }

    public List<MidMsg> readNowList(RoomInfo roomInfo, Discord discord) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url("https://discord.com/api/v9/channels/" + roomInfo.getDiscordChannelId() + "/messages?limit=50")
                .get()
                .addHeader("authority", "discord.com")
                .addHeader("accept", "*/*")
                .addHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
                .addHeader("authorization", discord.getAuthorization())
                .addHeader("cache-control", "no-cache")
                .addHeader("cookie", discord.getCookie())
                .addHeader("pragma", "no-cache")
                .addHeader("referer", "https://discord.com/channels/" + roomInfo.getDiscordGuildId() +
                        "/" + roomInfo.getDiscordChannelId())
                .addHeader("sec-ch-ua", "\"Not_A Brand\";v=\"99\", \"Microsoft Edge\";v=\"109\", \"Chromium\";v=\"109\"")
                .addHeader("sec-ch-ua-mobile", "?0")
                .addHeader("sec-ch-ua-platform", "\"Windows\"")
                .addHeader("sec-fetch-dest", "empty")
                .addHeader("sec-fetch-mode", "cors")
                .addHeader("sec-fetch-site", "same-origin")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 Edg/109.0.1518.70")
                .addHeader("x-debug-options", "bugReporterEnabled")
                .addHeader("x-discord-locale", "zh-CN")
                .addHeader("x-super-properties", discord.getSuperProperties())
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = Objects.requireNonNull(response.body()).string();
            response.close();
            return JSON.parseArray(string, MidMsg.class);
        } catch (Throwable t) {
            log.error("[发生意外 读取消息失败] room: {}", roomInfo);
        }
        return Lists.newArrayList();
    }

    @SneakyThrows
    public boolean sendMsg(String msg, RoomInfo roomInfo) {
        Discord discord = discordService.findById(roomInfo.getDiscordId());
        bigDecimal = bigDecimal.add(new BigDecimal(1000));
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("payload_json", "{\"type\":2,\"application_id\":\"936929561302675456\"," +
                        "\"guild_id\":\"" + roomInfo.getDiscordGuildId() + "\"," +
                        "\"channel_id\":\"" + roomInfo.getDiscordChannelId() + "\"," +
                        "\"session_id\":\"" + discord.getSessionId() + "\"," +
                        "\"data\":{\"version\":\"1077969938624553050\"," +
                        "\"id\":\"938956540159881230\"," +
                        "\"name\":\"imagine\"," +
                        "\"type\":1,\"options\":[" +
                        "{\"type\":3,\"name\":\"prompt\"," +
                        "\"value\":\"" + TextUtil.cleanString(msg) + "\"}]," +
                        "\"application_command\":" +
                        "{\"id\":\"938956540159881230\",\"application_id\":\"936929561302675456\",\"version\":" +
                        "\"1077969938624553050\",\"default_member_permissions\":null,\"type\":1,\"nsfw\":false," +
                        "\"name\":\"imagine\",\"description\":\"Create images with Midjourney\",\"dm_permission\":true," +
                        "\"contexts\":null,\"options\":[{\"type\":3,\"name\":\"prompt\"," +
                        "\"description\":\"The prompt to imagine\",\"required\":true}]}," +
                        "\"attachments\":[]},\"nonce\":\"" + bigDecimal.toString() + "\"} ")
                .build();
        Request request = new Request.Builder()
                .url("https://discord.com/api/v9/interactions")
                .method("POST", body)
                .addHeader("authority", "discord.com")
                .addHeader("accept", "*/*")
                .addHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
                .addHeader("authorization", discord.getAuthorization())
                .addHeader("cache-control", "no-cache")
                .addHeader("cookie", discord.getCookie())
                .addHeader("origin", "https://discord.com")
                .addHeader("pragma", "no-cache")
                .addHeader("referer", "https://discord.com/channels/" + roomInfo.getDiscordGuildId() +
                        "/" + roomInfo.getDiscordChannelId())
                .addHeader("sec-ch-ua", "\"Not_A Brand\";v=\"99\", \"Microsoft Edge\";v=\"109\", \"Chromium\";v=\"109\"")
                .addHeader("sec-ch-ua-mobile", "?0")
                .addHeader("sec-ch-ua-platform", "\"Windows\"")
                .addHeader("sec-fetch-dest", "empty")
                .addHeader("sec-fetch-mode", "cors")
                .addHeader("sec-fetch-site", "same-origin")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 Edg/109.0.1518.70")
                .addHeader("x-debug-options", "bugReporterEnabled")
                .addHeader("x-discord-locale", "zh-CN")
                .addHeader("x-super-properties", discord.getSuperProperties())
                .build();
        Response response = client.newCall(request).execute();
        if (response.code() == 204) {
            roomInfoService.addOnce(roomInfo);
            response.close();
            return true;
        }
        response.close();
        log.info("[midjourney发消息失败] {}", response.code());
        return false;
    }
}

MidjourneyLogService

package com.example.midjourney.service;

import com.example.midjourney.bean.pojo.MidjourneyLog;
import com.example.midjourney.bean.pojo.RoomInfo;

import java.util.List;

public interface MidjourneyLogService {

    MidjourneyLog findById(Long id);

    MidjourneyLog findLastNormalLog(Integer memberId);

    MidjourneyLog findLastNormalOrIterative(Integer memberId);

    void updateRoom(MidjourneyLog midjourneyLog, RoomInfo roomInfo);

    List<MidjourneyLog> selectAllDoing();

    void updateFail(MidjourneyLog midjourneyLog);

    void updateSensitive(MidjourneyLog midjourneyLog);

    void updatePrompt(MidjourneyLog midjourneyLog, String prompt);

    void updateFinish(MidjourneyLog midjourey);

    int selectRoomOnUse(Integer id);

}

MidjourneyLogServiceImpl

package com.example.midjourney.service.impl;

import com.example.midjourney.bean.pojo.MidjourneyLog;
import com.example.midjourney.bean.pojo.RoomInfo;
import com.example.midjourney.mapper.MidjourneyLogMapper;
import com.example.midjourney.service.MidjourneyLogService;
import com.example.midjourney.util.Safes;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MidjourneyLogServiceImpl implements MidjourneyLogService {

    @Resource
    private MidjourneyLogMapper midjourneyLogMapper;

    @Override
    public MidjourneyLog findById(Long id) {
        return midjourneyLogMapper.selectByPrimaryKey(id);
    }

    @Override
    public MidjourneyLog findLastNormalLog(Integer memberId) {
        return midjourneyLogMapper.findLastNormalLog(memberId);
    }

    @Override
    public MidjourneyLog findLastNormalOrIterative(Integer memberId) {
        return midjourneyLogMapper.findLastNormalOrIterative(memberId);
    }

    @Override
    public void updateRoom(MidjourneyLog midjourneyLog, RoomInfo roomInfo) {
        midjourneyLog.setRoomId(roomInfo.getId());
        midjourneyLogMapper.updateByPrimaryKeySelective(midjourneyLog);
    }

    @Override
    public List<MidjourneyLog> selectAllDoing() {
        MidjourneyLog midjourneyLog = new MidjourneyLog();
        midjourneyLog.setStatus(0);
        return Safes.of(midjourneyLogMapper.select(midjourneyLog));
    }

    @Override
    public void updateFail(MidjourneyLog midjourneyLog) {
        midjourneyLog.setStatus(500);
        midjourneyLogMapper.updateByPrimaryKeySelective(midjourneyLog);
    }

    @Override
    public void updateSensitive(MidjourneyLog midjourneyLog) {
        midjourneyLog.setStatus(-1);
        midjourneyLogMapper.updateByPrimaryKeySelective(midjourneyLog);
    }

    @Override
    public void updatePrompt(MidjourneyLog midjourneyLog, String prompt) {
        midjourneyLog.setPrompt(prompt);
        midjourneyLogMapper.updateByPrimaryKeySelective(midjourneyLog);
    }

    @Override
    public void updateFinish(MidjourneyLog midjourey) {
        midjourey.setStatus(1);
        midjourneyLogMapper.updateByPrimaryKeySelective(midjourey);
    }

    @Override
    public int selectRoomOnUse(Integer id) {
        return midjourneyLogMapper.selectRoomOnUse(id);
    }
}

MidjourneyLogMapper 

这里用了通用mapper插件

package com.example.midjourney.mapper;

import com.example.midjourney.bean.pojo.MidjourneyLog;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import tk.mybatis.mapper.common.Mapper;

public interface MidjourneyLogMapper extends Mapper<MidjourneyLog> {

    String COLUMN = " id, member_id AS memberId, prompt, channel, type, " +
            "status, img_file AS imgFile, room_id AS roomId ";

    @Select("SELECT " + COLUMN + " FROM midjourney_log WHERE member_id = #{memberId} AND type = 0 ORDER BY id DESC LIMIT 1")
    MidjourneyLog findLastNormalLog(@Param("memberId") Integer memberId);

    @Select("SELECT " + COLUMN + " FROM midjourney_log WHERE member_id = #{memberId} AND (type = 0 OR type = 2)" +
            " ORDER BY id DESC LIMIT 1")
    MidjourneyLog findLastNormalOrIterative(Integer memberId);

    @Select("SELECT COUNT(*) AS count FROM midjourney_log WHERE room_id = #{id} AND status = 0")
    Integer selectRoomOnUse(@Param("id") Integer id);

}

Constant

常量类可以根据需要自定调整敏感词

敏感词写上审核不过,大家自己想想脑补下吧,各种不好的词都往那个敏感词List里面自己加吧!

 

package com.example.midjourney.contant;

import com.example.midjourney.bean.UserInfo;
import com.example.midjourney.biz.WeChatBiz;
import com.example.midjourney.util.BaiduUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Constant {

    public static ExecutorService threadPool = Executors.newFixedThreadPool(20);

    public static Map<String, UserInfo> imgWordUserMap = Maps.newConcurrentMap();

    public static String MID_JOURNEY_HEAD = "**";

    public static String MID_FIND_LEFT = "** - <";

    public static String FILE_PATH = "D:\\000img\\";

    public static String CHATGPT = "chatgpt";
    public static String MIDJOURNEY = "midjourney";

    public static final String INSUFFICIENT = "insufficient_quota";

    public static Map<String, String> WX_TOKEN_CHANNEL = Maps.newHashMap();

    public static Map<String, String> WX_TOKEN_MAP = Maps.newHashMap();

    public static String BAIDU_TOKEN = BaiduUtil.queryBaiduToken();

    public static Map<String, String> CHANNEL_CALL_BACK = Maps.newHashMap();

    /**
     * 最大等待时间15分钟
     */
    public static long MAX_WAIT_TIME = 1000 * 60 * 15;

    public static List<String> MidjourneyBlackWord = Lists.newArrayList("写了审核不过,大家自己发挥想象吧...");


}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/646354.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【2023最全教程】Web自动化测试怎么做?Web自动化测试的详细流程和步骤

一、什么是web自动化测试 自动化&#xff08;Automation&#xff09;是指机器设备、系统或过程&#xff08;生产、管理过程&#xff09;在没有人或较少人的直接参与下&#xff0c;按照人的要求&#xff0c;经过自动检测、信息处理、分析判断、操纵控制&#xff0c;实现预期的目…

Spring @Autowired注入太坤肋了 我们自己写一个

1、 背景 众所周知该注解是Spring中用于依赖注入的注解&#xff0c;但是该注解只是简单根据类型的注入&#xff0c; 并且如果该类型存在多个实现类的情况下无法抉择具体哪一个实现类就会抛出错误&#xff0c;除非搭配Qualifier注解然后使用硬编码的方式去指定Bean的名字去抉择…

8年测试岗总结,软件测试常见面试题+答案,轻松避坑...

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 1、介绍一下测试流…

JAVA开发与运维(怎么通过docker部署微服务jar包)

目标&#xff1a; 通过docker的方式部署微服务。 一、背景&#xff1a; 我们通过java开发的微服务可以打成jar包&#xff0c;我们可以直接通过裸机部署&#xff0c;也可以通过docker来部署&#xff0c;本文介绍通过docker来部署微服务。 二、首先我们介绍一下docker的发展过程…

Redis高级篇—分布式缓存 持久化 主从 哨兵 分片

分布式缓存 -- 基于Redis集群解决单机Redis存在的问题 单机的Redis存在四大问题&#xff1a; 0.学习目标 1.Redis持久化 Redis有两种持久化方案&#xff1a; RDB持久化 AOF持久化 1.1.RDB持久化 RDB全称Redis Database Backup file&#xff08;Redis数据备份文件&#xff09;&a…

jetBrian_工具的使用

文章目录 Intellij IDEA新建一个IDEA项目新建Project - ClassJDK相关设置out目录和编译版本 详细设置&#xff08;感觉有用的设置&#xff09;打开是否选择项目取消自动更新设置整体主题设置菜单和窗口字体和大小设置IDEA背景图设置编辑器主题样式注释的字体颜色代码智能提示功…

Java面试知识点(全)-分布式微服务-kafka面试知识点

Java面试知识点(全) 导航&#xff1a; https://nanxiang.blog.csdn.net/article/details/130640392 注&#xff1a;随时更新 以下是一些Kafka面试题和答案&#xff1a; 文章目录 什么是Kafka&#xff1f;Kafka主题(topic)和分区(partition)有什么作用&#xff1f;Kafka的重复数…

科一 容易忘,容易混的点(三)

年龄问题 考题&#xff1a; 申请大中型客货车驾驶证年龄不得超过 &#xff1f; 公交 、 中客、大货&#xff1a; 20 大客、重型牵引&#xff1a; 22岁 C1,C2,C5 : 18岁 C6不考倒车入库 记分转入下一周期 不会清零&#xff0c;必须前去接受处罚。不然下一周期你还是扣1…

echarts象形柱图实现电量效果柱状图

首先听到象柱形图pictorialBar&#xff0c;你会不会觉得很陌生&#xff1f; 然后&#xff0c;看看官网的示例&#xff0c;显示效果很抽象&#xff0c;觉得很不实用&#xff0c;真的有人会用到吗&#xff1f; 但是&#xff0c;我再让你看看下图&#xff0c;类似电量格效果的柱状…

访问 docker 容器的 tensorboard

demo代码示例 tensorboard --logdirlog_path :return:from torch.utils.tensorboard import SummaryWriterlogger SummaryWriter(log_dir./log/boardtest/)loss [5.5, 4.1, 4.2, 3.2, 3.3, 2.9, 2.5, 1.2, 0.8, 0.6] steps [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000…

Spark SQL数据源:JDBC

文章目录 一、Spark SQL读取关系数据库二、Spark SQL JDBC连接属性三、创建数据库与表&#xff08;一&#xff09;创建数据库&#xff08;二&#xff09;创建学生表&#xff08;二&#xff09;创建成绩表 四、读取和写入数据库表&#xff08;一&#xff09;利用dbtable属性读取…

APScheduler任务调度快速入门实践

什么是APScheduler APScheduler是一个用于任务调度和定时任务管理的Python库。它提供了一个简单而灵活的方式来定义、调度和执行任务。 APScheduler的架构由以下几个核心组件组成&#xff1a; 调度器&#xff08;Scheduler&#xff09;&#xff1a;调度器负责管理任务的调度和…

初探core组件:OpenCV数据结构与基本绘图

OpenCV数据结构与基本绘图 1. 基础图像容器 Mat 1.1 数字图像存储概述 我们有多种方法从现实世界获取数字图像&#xff1a;数码相机、扫描仪、计算机断层扫描和磁共振成像等等。在每一种情况下&#xff0c;我们&#xff08;人类&#xff09;看到的都是图像。然而&#xff0c…

不可错过的Markdown编辑利器:跟随Typora,书写卓越

在现代社会中&#xff0c;快速而优雅地处理文本已经成为许多人的必备技能。尤其是对于程序员、研究者和专业撰稿人来说&#xff0c;拥有一款功能强大且易上手的文本编辑器显得尤为重要。Typora正是这样一款受到广泛好评的Markdown编辑器&#xff0c;它以简洁的界面、丰富的功能…

《实战AI低代码》AI大模型在低代码开发项目管理中的实战经验总结

目录 一、WBS任务分解 二、知识库自动生成 三、实施风险预估 随着ChatGPT大火之后,新的AI技术和模型被证明已经具备的很高的使用价值。 诸如Copilot、Midjourney、notion等产品通过AI的加持,已经让用户能够充分地在应用层面感受到了便利性。 原本几天的工作通过AI模型,可…

Web实验三 CSS基本网页布局实验

实验原理 通过定义css样式&#xff0c;理解css属性以及页面真整体结构布局的方法及设计思想。 实验目的 理解并掌握多种css选择器的使用方法 理解并掌握后代选择器的作用及使用设计方法 理解并掌握伪类的作用、意义及使用方法 理解并掌握基于div容器页面布局的方法 理解并掌握…

TANL:STRUCTURED PREDICTION AS TRANSLATION BETWEEN AUGMENTED NATURAL LANGUAGES

原文链接&#xff1a;https://openreview.net/pdf?idUS-TP-xnXI ICLR 2021 介绍 问题 大多数解决结构性预测的方法都是在预训练模型上对特定的任务进行训练&#xff0c;存在两个局限性&#xff1a; 1&#xff09;判别分类器不能很好地利用预训练模型中对于该任务标签的已知知…

这个事实已冲击并颠覆我的认知:时间不多了

我们都知道人生短暂&#xff0c;可到底是怎么个短法&#xff1f; 十年是个模糊的表述&#xff0c;我们很难在脑海里想象十年是什么概念&#xff0c;但如果换成十个冬天&#xff0c;跟父母在一起十天&#xff0c;这样描述就会更直观些。 WaitButWhy对人生的时间进行了拆解&#…

Cesium教程(十九):Cesium粒子系统

Cesium教程(十九):Cesium粒子系统 1、粒子系统 1.1 什么是粒子系统 Cesium粒子系统是一种模拟复杂物理效应的图形技术,是由小图像组成的集合,当他们在一起形成更复杂的“模糊”对象时,会形成火、烟、云或烟火等。 1.2 初始粒子系统 效果预览 完整代码 <!DOCTYPE htm…

day05--java高级编程:Junit单元测试框架、泛型,集合:集合数组互转,迭代器,增强for循环,集合工具类,数据结构简介

补充&#xff1a;Junit单元测试框架 1. 简介 概述&#xff1a; JUnit是使用Java语言实现的单元测试框架&#xff0c;它是开源的&#xff0c;Java开发者都应当学习并使用JUnit编写单元测试。此外&#xff0c;几乎所有的IDE工具都集成了JUnit&#xff0c;这样我们就可以直接在…