♻️ refactored code

This commit is contained in:
2025-02-27 18:46:15 +08:00
parent 0e1b7c32b0
commit 41fdc58c4e
66 changed files with 4178 additions and 1167 deletions

View File

@@ -0,0 +1,162 @@
<template>
<transition name="slide-fade">
<div v-show="props.selected.length > 0" class="photo-toolbar-header">
<div class="photo-toolbar-left">
<AButton type="text" shape="circle" size="large" class="photo-toolbar-btn" @click="clearSelected">
<template #icon>
<CloseOutlined class="photo-toolbar-icon"/>
</template>
</AButton>
<span style="font-size: 16px;font-weight: bold">
已选择 {{ props.selected.length }} 张照片
</span>
<AButton type="text" shape="default" class="photo-toolbar-btn" size="middle" @click="selectAll"
:disabled="isAllSelected">
全选
</AButton>
</div>
<div class="photo-toolbar-right">
<AButton type="text" shape="default" size="middle" class="photo-toolbar-btn">
<template #icon>
<PlusSquareOutlined class="photo-toolbar-icon"/>
</template>
添加到
</AButton>
<AButton type="text" shape="default" size="middle" class="photo-toolbar-btn">
<template #icon>
<DownloadOutlined class="photo-toolbar-icon"/>
</template>
下载原图
</AButton>
<AButton type="text" shape="default" size="middle" class="photo-toolbar-btn">
<template #icon>
<ShareAltOutlined class="photo-toolbar-icon"/>
</template>
分享
</AButton>
<AButton type="text" shape="default" size="middle" class="photo-toolbar-btn" @click="deleteImages">
<template #icon>
<DeleteOutlined class="photo-toolbar-icon"/>
</template>
删除
</AButton>
</div>
</div>
</transition>
</template>
<script setup lang="ts">
import useStore from "@/store";
import {Image, ImageList, ImageRecord} from "@/types/image";
import {deletedImagesApi} from "@/api/storage";
const props = defineProps({
selected: {
type: Array as () => number[],
default: () => []
},
imageList: {
type: Array as () => ImageList,
default: () => []
}
});
const imageStore = useStore().image;
const uploadStore = useStore().upload;
const clearSelected = () => {
imageStore.selected = [];
};
const selectAll = () => {
imageStore.selected = props.imageList.flatMap((record: ImageRecord) => record.list.map((image: Image) => image.id));
};
const deleteImages = async () => {
const res: any = await deletedImagesApi(props.selected, uploadStore.storageSelected?.[0], uploadStore.storageSelected?.[1]);
if (res.code === 200) {
imageStore.selected = [];
}
};
const isAllSelected = computed(() => {
// 确保 props.imageList 是一个数组
const imageList = props.imageList || [];
return props.selected.length === imageList.flatMap((record: ImageRecord) => record.list).length;
});
onBeforeUnmount(() => {
imageStore.selected = [];
});
</script>
<style scoped lang="scss">
.photo-toolbar-header {
position: fixed;
width: calc(100% - 220px);
height: 70px;
top: 70px;
z-index: 4;
display: flex;
box-sizing: border-box;
justify-content: space-between;
align-items: center;
background-image: linear-gradient(45deg, #5789ff, #5c7bff 100%);
color: #fff;
box-shadow: 0 3px 10px 0 rgba(0, 0, 0, .06);
padding: 0 20px;
.photo-toolbar-left {
width: 50%;
height: 100%;
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-start;
gap: 20px;
}
.photo-toolbar-right {
height: 100%;
width: 50%;
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-end;
gap: 30px;
}
.photo-toolbar-icon {
font-size: 20px;
font-weight: bold;
color: #fff;
}
.photo-toolbar-btn {
font-size: 16px;
font-weight: bold;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
}
}
.slide-fade-enter-active, .slide-fade-leave-active {
transition: all 0.5s ease;
}
.slide-fade-enter-from, .slide-fade-leave-to { /* .slide-fade-leave-active 在离开之前 */
transform: translateY(-20px);
opacity: 0;
}
.slide-fade-enter-from {
transform: translateY(-30px);
opacity: 0;
}
.slide-fade-enter-to {
transform: translateY(0);
opacity: 1;
}
</style>

View File

@@ -0,0 +1,334 @@
<template>
<ADrawer v-model:open="upload.openUploadDrawer" placement="right" title="上传照片" width="40%" @close="cancelUpload">
<template #extra>
<AFlex :vertical="false" align="center" gap="large" justify="center">
<ASelect size="middle" style="width: 150px" placeholder="选择上传的相册"
:options="albumList"
v-model:value="upload.albumSelected"
:allow-clear="true"
:field-names="{label: 'name', value: 'id'}"
>
</ASelect>
</AFlex>
</template>
<div class="upload-container">
<AUploadDragger
v-model:fileList="fileList"
:beforeUpload="beforeUpload"
:customRequest="customUploadRequest"
:directory="false"
:maxCount="10"
:multiple="true"
:disabled="predicting"
:progress="progress"
@remove="removeFile"
@reject="rejectFile"
:openFileDialogOnClick="true"
accept="image/*"
list-type="picture"
method="post"
name="file"
>
<p class="ant-upload-drag-icon">
<FileImageOutlined/>
</p>
<p v-show="!predicting" class="ant-upload-text">单击或拖动文件到此区域以上传</p>
<p v-show="!predicting" class="ant-upload-hint">
支持单次或批量上传严禁上传非法图片违者将受到法律惩戒
</p>
<p v-show="predicting" class="ant-upload-hint">
AI 正在识别图片请稍候...
</p>
<AProgress :stroke-color="{'0%': '#108ee9','100%': '#87d068',}" :percent="progressPercent"
:status="progressStatus"
:show-info="true" size="small" type="line" v-show="predicting" style="width: 80%"/>
</AUploadDragger>
<AEmpty :image="empty" v-if="fileList.length === 0">
<template #description>
<span style="color: #999999;font-size: 16px;font-weight: 500;line-height: 1.5;">
上传列表为空可直接拖动文件到此区域上传
</span>
</template>
</AEmpty>
</div>
</ADrawer>
</template>
<script lang="ts" setup>
import useStore from "@/store";
import type {UploadProps} from 'ant-design-vue';
import {message} from "ant-design-vue";
import {initNSFWJs, predictNSFW} from "@/utils/tfjs/nsfw.ts";
import i18n from "@/locales";
import {NSFWJS} from "nsfwjs";
import {animePredictImagePro} from "@/utils/tfjs/anime_classifier_pro.ts";
import {cocoSsdPredict} from "@/utils/tfjs/mobilenet.ts";
import {predictLandscape} from "@/utils/tfjs/landscape_recognition.ts";
import {useRequest} from 'alova/client';
import {albumListApi, uploadFile} from "@/api/storage";
import imageCompression from "browser-image-compression";
import exifr from 'exifr';
import isScreenshot from "@/utils/imageUtils/isScreenshot.ts";
import {getCategoryByLabel} from "@/constant/coco_ssd_label_category.ts";
import {generateThumbnail} from "@/utils/imageUtils/generateThumb.ts";
import empty from "@/assets/svgs/empty.svg";
const predicting = ref<boolean>(false);
const progressPercent = ref<number>(0);
const progressStatus = ref<string>('active');
// 压缩图片配置
const options = {
maxSizeMB: 0.2,
maxWidthOrHeight: 750,
maxIteration: 2,
useWebWorker: true,
};
const upload = useStore().upload;
const image: HTMLImageElement = document.createElement('img');
const fileList = ref([]);
const progress: UploadProps['progress'] = {
strokeColor: {
'0%': '#108ee9',
'100%': '#87d068',
},
strokeWidth: 3,
format: (percent: any) => `${parseFloat(percent.toFixed(2))}%`,
class: 'progress-bar',
};
/**
* 图片上传前的校验
* @param file
* @param fileList
*/
async function beforeUpload(file: File, fileList: File[]) {
predicting.value = true;
upload.clearPredictResult();
progressPercent.value = 0; // 初始化进度条
progressStatus.value = 'active'; // 开始状态
// 压缩图片
const compressedFile = await imageCompression(file, options);
// 创建图片对象
image.src = URL.createObjectURL(compressedFile);
// 获取图片宽高
image.onload = () => {
const {width, height} = image;
upload.predictResult.width = width;
upload.predictResult.height = height;
};
// 更新进度条函数,逐步增加
const smoothUpdateProgress = async (targetPercent, duration) => {
const increment = (targetPercent - progressPercent.value) / (duration / 50);
return new Promise((resolve) => {
const interval = setInterval(() => {
if (progressPercent.value >= targetPercent) {
clearInterval(interval);
resolve(false);
} else {
progressPercent.value = Math.min(progressPercent.value + increment, targetPercent);
}
}, 50);
});
};
try {
// NSFW 检测
const nsfw: NSFWJS = await initNSFWJs();
await smoothUpdateProgress(30, 500); // 平滑更新进度条
const isNSFW: boolean = await predictNSFW(nsfw, image);
await smoothUpdateProgress(50, 500); // 平滑更新进度条
if (isNSFW) {
message.error(i18n.global.t('comment.illegalImage'));
progressPercent.value = 100; // 重置进度条
progressStatus.value = 'exception'; // 异常状态
fileList.pop(); // 清空文件列表
predicting.value = false;
return false;
}
// 提取 EXIF 数据
const gpsData: any = await extractGPSExifData(file);
if (gpsData) {
upload.predictResult.longitude = gpsData.longitude;
upload.predictResult.latitude = gpsData.latitude;
}
// 判断是否为截图
upload.predictResult.isScreenshot = await isScreenshot(file);
// 动漫类型识别
const prediction: string = await animePredictImagePro(image);
await smoothUpdateProgress(70, 500); // 平滑更新进度条
// 如果是动漫类型,直接返回
if ((prediction === 'Furry' || prediction === 'Anime')) {
upload.predictResult.isAnime = true;
predicting.value = false;
progressPercent.value = 100; // 直接完成
return true;
}
//目标检测和风景检测并行处理
const [cocoResults, landscape] = await Promise.all([
cocoSsdPredict(image), // 目标检测
predictLandscape(image), // 风景检测
]);
await smoothUpdateProgress(100, 500); // 平滑更新进度条
if (cocoResults.length > 0) {
// 取置信度最高的结果
// 如果只有一个结果,直接取第一个
if (cocoResults.length === 1) {
upload.predictResult.topCategory = getCategoryByLabel(cocoResults[0].class);
upload.predictResult.tagName = cocoResults[0].class;
} else {
// 多个结果时,按 score 排序,取置信度最高的结果
const sortedResults = cocoResults.sort((a, b) => b.score - a.score);
upload.predictResult.topCategory = getCategoryByLabel(sortedResults[0].class);
upload.predictResult.tagName = sortedResults[0].class;
}
}
upload.predictResult.landscape = landscape as 'building' | 'forest' | 'glacier' | 'mountain' | 'sea' | 'street' | null;
predicting.value = false;
return true;
} catch (error) {
console.error('识别过程中发生错误:', error);
predicting.value = false;
progressPercent.value = 0; // 重置进度条
return false;
}
}
const {uploading, send: submitFile, abort} = useRequest(uploadFile, {
immediate: false,
debounce: 500,
});
/**
* 自定义上传请求
* @param file
*/
async function customUploadRequest(file: any) {
const compressedFile = await imageCompression(file.file, options);
// 生成缩略图
const {binaryData, width, height, size} = await generateThumbnail(compressedFile);
upload.predictResult.thumb_w = width;
upload.predictResult.thumb_h = height;
upload.predictResult.thumb_size = size;
const formData = new FormData();
formData.append("file", file.file);
if (binaryData) {
formData.append("thumbnail", binaryData);
}
formData.append("data", JSON.stringify({
provider: upload.storageSelected?.[0],
bucket: upload.storageSelected?.[1],
fileType: file.file.type,
albumId: upload.albumSelected ? upload.albumSelected : 0,
...upload.predictResult,
}));
watch(
() => uploading.value,
(upload) => {
if (upload && upload.loaded && upload.total) {
file.onProgress({percent: Number(Math.round((upload.loaded / upload.total) * 100).toFixed(2))}, file);
}
},
);
submitFile(formData).then((response: any) => {
if (response && response.code === 200) {
file.onSuccess(response.data, file);
} else {
file.onError(response.data, file);
}
}).catch(file.onError);
}
/**
* 取消上传
*/
function cancelUpload() {
abort();
fileList.value = [];
upload.clearPredictResult();
predicting.value = false;
progressPercent.value = 0; // 重置进度条
}
/**
* 拒绝文件回调
* @param fileList
*/
function rejectFile(fileList: any) {
fileList.value.pop();
}
/**
* 删除文件
* @param file
*/
function removeFile(file: any) {
fileList.value = fileList.value.filter((item: any) => item.uid !== file.uid);
}
/**
* 提取 EXIF 数据
* @param {File} file - 图片文件
* @returns {Promise<Object|null>} - 返回所有 EXIF 数据或 null如果格式不支持或提取失败
*/
async function extractGPSExifData(file) {
const supportedFormats = ['image/jpeg', 'image/tiff', 'image/iiq', 'image/heif', 'image/heic', 'image/avif', 'image/png'];
// 判断文件格式是否支持
if (!supportedFormats.includes(file.type)) {
return null;
}
const options: any = {
ifd0: false,
exif: false,
gps: ['GPSLatitudeRef', 'GPSLatitude', 0x0003, 0x0004],
interop: false,
ifd1: false // thumbnail
};
// 提取GPS EXIF 数据
const gpsData = await exifr.parse(file, options);
if (!gpsData) {
return null;
}
const {latitude, longitude} = gpsData;
if (latitude && longitude) {
return {latitude, longitude};
}
return null;
}
const albumList = ref<any[]>([]);
async function getAlbumList(type: number = 0, sort: boolean = true) {
const res: any = await albumListApi(type, sort);
if (res && res.code === 200) {
albumList.value = res.data.albums;
}
}
onMounted(() => {
getAlbumList();
});
</script>
<style lang="less" scoped>
</style>

View File

@@ -0,0 +1,69 @@
<template>
<Spin size="middle" :spinning="imageStore.imageListLoading" indicator="spin-dot" tip="loading..." :rotate="true">
<div style="width:100%;height:100%;" v-if="props.imageList">
<div v-for="(itemList, index) in props.imageList" :key="index">
<span style="margin-left: 10px;font-size: 13px">{{ itemList.date }}</span>
<AImagePreviewGroup>
<Vue3JustifiedLayout v-model:list="itemList.list" :options="imageStore.JustifiedLayoutOptions"
style="line-height: 0 !important;">
<template #default="{ item }">
<CheckCard :key="index"
class="photo-item"
margin="0"
border-radius="0"
v-model="imageStore.selected"
:showHoverCircle="true"
:iconSize="20"
:showSelectedEffect="true"
:value="item.id">
<AImage :src="item.thumbnail"
:alt="item.file_name"
:key="index"
:height="200"
:preview="{
src: item.url,
}"
loading="lazy">
<template #previewMask>
</template>
</AImage>
</CheckCard>
</template>
</Vue3JustifiedLayout>
</AImagePreviewGroup>
</div>
</div>
<div v-if="!imageStore.imageListLoading && !props.imageList" class="empty-content">
<AEmpty :image="empty"
:image-style="{
height: '100%',
width: '100%',
}">
<template #description>
<span style="color: #999999;font-size: 16px;font-weight: 500;line-height: 1.5;">
还没检测到任何图片快去上传吧
</span>
</template>
</AEmpty>
</div>
</Spin>
</template>
<script setup lang="ts">
import Vue3JustifiedLayout from "vue3-justified-layout";
import 'vue3-justified-layout/dist/style.css';
import empty from "@/assets/svgs/empty.svg";
import useStore from "@/store";
const props = defineProps({
imageList: {
type: Array as () => any[],
default: () => []
}
});
const imageStore = useStore().image;
</script>
<style scoped lang="scss">
</style>