Commit fbe013a5 by wangfa

任务发送,下载回调

parent 0b0b41b0
<?php
namespace App\Console\Commands;
use App\Jobs\ReadDiscordMessageJob;
use App\Models\PromptTask;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
class ReadDiscordMessageCommand extends Command
{
protected $signature = 'read:discord-message';
protected $description = 'Command description';
protected string $key = 'discord_message';
public function handle()
{
while (true) {
$data = Redis::connection()->blpop($this->key, 1);
if (filled($data)) {
$data = json_decode($data[1], true);
if (filled($data)) {
dispatch(new ReadDiscordMessageJob($data));
}
}
$this->info('运行完成');
}
}
}
<?php
namespace App\Console\Commands;
use App\Jobs\DownloadImageJob;
use App\Jobs\ReadDiscordMessageJob;
use App\Models\PromptTask;
use App\Service\TaskService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
class TestsCommand extends Command
{
protected $signature = 'tests';
protected $description = '测试脚本';
public function handle()
{
// $this->apiSubmit();
// $this->readDiscordMessage();
$this->downloadImage();
}
public function downloadImage()
{
$prompt = PromptTask::find(28);
$downloadData = [
'url' => $prompt->cut_img,
'name' => Str::uuid()->toString(),
'index' => 1,
'prompt_id' => $prompt->id,
];
dispatch(new DownloadImageJob($downloadData));
}
/**
* 读取消息
*/
public function readDiscordMessage()
{
$str = '{
"message_id": 1096000262763708500,
"message_content": "**illustration, futurism,NFT art, Fluorescent color, Laser color, A cute girlwho looks up and smiles, combinationof 2d and 3d, solid color background,cel shading,Tindal effect, Non- photorealistic rendering,Transparency,color Slant, animation, blender, geometry art, acrylic painting --q 2** - <@1075605512000905297> (fast)",
"channel_id": 1090583268467945500,
"author_id": 936929561302675500,
"author_name": "Midjourney Bot",
"author_discriminator": "9282",
"guild_id": 1090583267612299300,
"guild_name": "测试服务器",
"attachment_url": "https://yunyi-tiktok.oss-cn-shenzhen.aliyuncs.com/files/download/admin/e4bfe50989519b8537f4741e0edf174e.png",
"attachment_filename": "suifeng_illustration_futurismNFT_art_Fluorescent_color_Laser_co_994d7b33-9cad-4b0d-9e71-b401e576009e.png"
}';
$data = json_decode($str, true);
dispatch(new ReadDiscordMessageJob($data));
}
/**
* 提交任务
*/
public function apiSubmit()
{
$userId = 1;
$data = [
'prompt' => 'illustration, futurism,NFT art, Fluorescent color, Laser color, A cute girlwho looks up and smiles, combinationof 2d and 3d, solid color background,cel shading,Tindal effect, Non- photorealistic rendering,Transparency,color Slant, animation, blender, geometry art, acrylic painting --q 2',
'prompt_img' => [
"http://baidu.com",
],
"prompt_num" => 5,
"type" => 2,
];
app(TaskService::class)->apiSubmit($userId, $data);
}
}
<?php
namespace App\Jobs;
use App\Models\PromptTask;
use App\Service\ExternalApiService;
use App\Service\TaskService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class DownloadImageJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public array $data = [];
public function __construct(array $data = [])
{
$this->queue = "{download-image}";
$this->data = $data;
}
public function handle()
{
$result = app(ExternalApiService::class)->downloadImage($this->data);
if (filled($result) && $result['code'] == 200) {
$data = $result['data'];
$updateData = [
'result_img_status' => TaskService::STATUS_SUCCESS,
'result_img' => $data[0] ?? '',
];
PromptTask::where('id', $this->data['prompt_id'])
->update($updateData);
}
}
}
<?php
namespace App\Jobs;
use App\Models\PromptTask;
use App\Service\TaskService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
class ReadDiscordMessageJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public array $data = [];
public function __construct(array $data = [])
{
$this->queue = "{send-discord-message}";
$this->data = $data;
}
public function handle()
{
$data = $this->data;
$content = $data['message_content'] ?? '';
preg_match('/\*\*(.*)\*\*/', $content, $matches);
if (isset($matches[1])) {
$key = app(TaskService::class)->getDiscordMessageKey($matches[1]);
$cachePrompt = Cache::get($key);
if (!empty($cachePrompt)) {
$updateData = [
'cut_status' => TaskService::STATUS_SUCCESS,
'cut_img' => $data['attachment_url'],
];
PromptTask::where('id', $cachePrompt['prompt_task_id'])
->update($updateData);
}
}
}
}
......@@ -3,11 +3,13 @@
namespace App\Jobs;
use App\Service\ExternalApiService;
use App\Service\TaskService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
class SendImagineJob implements ShouldQueue
{
......@@ -23,6 +25,14 @@ public function __construct(array $data = [])
public function handle()
{
app(ExternalApiService::class)->imagine($this->data);
$data = $this->data;
// 处理图转图
if ($data['type'] == TaskService::TYPE_IMG_TO_IMG) {
$promptImg = json_decode(($data['prompt_img'] ?? ''));
$data['prompt'] = ($promptImg[0] ?? '') . ' ' . $data['prompt'];
}
$key = app(TaskService::class)->getDiscordMessageKey($data['prompt']);
Cache::set($key, ['prompt_task_id' => $data['prompt_id']], (60 * 60 * 24));
app(ExternalApiService::class)->imagine($data);
}
}
......@@ -92,7 +92,7 @@ public function httpPost(string $url = '', array $data = [])
*/
public function downloadImage(array $data = [])
{
$url = $this->getPath('/api/download');
$url = $this->getPath('/api/download-image');
return $this->httpPost($url, $data);
}
}
......@@ -3,11 +3,13 @@
namespace App\Service;
use App\Exceptions\UserException;
use App\Jobs\DownloadImageJob;
use App\Jobs\SendImagineJob;
use App\Models\PromptTask;
use App\Models\Task;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;
class TaskService
{
......@@ -16,6 +18,14 @@ class TaskService
public const GPT_prompt_num = 1; // 指令数量
public const STATUS_SUCCESS = 1; // 成功
public const STATUS_FAIL = 2; // 失败
public const TASK_TYPE_AUTO = 1; // 自动化
public const TASK_TYPE_API = 2; // API
/**
* @param array $data
*/
......@@ -57,6 +67,7 @@ public function validateSubmitData(array $data = [])
public function submit(int $user_id = 0, array $data = [])
{
$this->validateSubmitData($data);
$data['prompt'] = str_replace('\n', '', $data['prompt']);
$task = $this->createTask($user_id, $data);
$promptTask = $this->createPromptTask($user_id, $task->id, $data);
$list['prompt_id'] = $promptTask->id;
......@@ -121,6 +132,7 @@ public function createPromptTask(int $userId = 0, int $taskId = 0, array $data =
public function apiSubmit(int $userId = 0, array $data = [])
{
$this->validateSubmitData($data);
$data['prompt'] = str_replace('\n', '', $data['prompt']);
$task = $this->createTask($userId, $data);
$promptTask = $this->createPromptTask($userId, $task->id, $data);
$sendData = [
......@@ -131,6 +143,7 @@ public function apiSubmit(int $userId = 0, array $data = [])
'prompt_img' => $task->prompt_img,
'prompt_id' => $promptTask->id,
'task_id' => $task->id,
'type' => $task->type,
];
dispatch(new SendImagineJob($sendData));
return [
......@@ -270,8 +283,6 @@ public function img_download_callback($data = [])
]);
}
}
return true;
}
......@@ -287,9 +298,12 @@ public function task_callback($user_id, $data = [])
if (empty($task_id)) {
throw new UserException('缺少id');
}
# 查询所有
$res = PromptTask::query()->where('user_id', $user_id)->where('task_id', $task_id)
->where('result_img_status', 1)->get();
$res = PromptTask::query()->where('user_id', $user_id)
->where('task_id', $task_id)
->where('result_img_status', 1)
->get();
$list = [];
foreach ($res as $item) {
......@@ -305,12 +319,13 @@ public function task_callback($user_id, $data = [])
/**
* 创建切割图片任务
*/
public function create_split_img_task($user_id, $data = [])
public function create_split_img_task(int $user_id = 0, $data = [])
{
$credentials = Arr::only($data, ['prompt_id', 'cut_id']);
$credentials = Arr::only($data, ['prompt_id', 'cut_id', 'type']);
# 必须字段
$prompt_id = $credentials['prompt_id'];
$cut_id = $credentials['cut_id'];
$type = $credentials['type'];
# 判断必须字段
if (empty($prompt_id) || empty($cut_id)) {
throw new UserException(1, '没有这个任务');
......@@ -324,14 +339,23 @@ public function create_split_img_task($user_id, $data = [])
$prompt->update([
'cut_id' => $cut_id,
]);
# 添加redis任务
$list = [
'prompt_id' => $prompt_id,
'result_img' => $prompt->result_img,
'cut_id' => $cut_id,
'callback' => config('common.split_img_callback'),
];
Redis::rpush('discord_img_split', json_encode($list));
if ((int)$type === self::TASK_TYPE_AUTO) {
# 添加redis任务
$list = [
'prompt_id' => $prompt_id,
'result_img' => $prompt->result_img,
'cut_id' => $cut_id,
'callback' => config('common.split_img_callback'),
];
Redis::rpush('discord_img_split', json_encode($list));
} else {
$downloadData = [
'url' => $prompt->cut_img,
'name' => Str::uuid()->toString(),
'index' => $cut_id
];
dispatch(new DownloadImageJob($downloadData));
}
return [
'prompt_id' => $prompt_id,
];
......@@ -385,4 +409,16 @@ public function IntervalSplitImg($data = [])
}
return [];
}
/**
* 获取消息key
*
* @param string $prompt
* @return string
*/
public function getDiscordMessageKey(string $prompt = '')
{
$prompt = md5($prompt);
return "discord_message:{$prompt}";
}
}
......@@ -18,7 +18,7 @@
// 生成图片参数
'imagine_token' => env('IMAGINE_TOKEN', 'MTA3NTYwNTUxMjAwMDkwNTI5Nw.GbEb6_.9-H-5kf501rRc0SJQa5mB-2eV1Fh2u4-rWWG_0'),
'imagine_guild_id' => env('IMAGINE_GUILD_ID', '1095628793860857957'),
'imagine_channel_id' => env('IMAGINE_CHANNEL_ID', '1095628793860857960'),
'imagine_guild_id' => env('IMAGINE_GUILD_ID', '1090583267612299324'),
'imagine_channel_id' => env('IMAGINE_CHANNEL_ID', '1090583268467945475'),
];
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment