Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update TrainModelZone.tsx with Image Compression #71

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 46 additions & 14 deletions components/TrainModelZone.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { SubmitHandler, useForm } from "react-hook-form";
import { FaFemale, FaImages, FaMale, FaRainbow } from "react-icons/fa";
import * as z from "zod";
import { fileUploadFormSchema } from "@/types/zod";
import imageCompression from 'browser-image-compression';

type FormInput = z.infer<typeof fileUploadFormSchema>;

Expand All @@ -47,13 +48,17 @@ export default function TrainModelZone() {

const onDrop = useCallback(
async (acceptedFiles: File[]) => {
const newFiles: File[] =
acceptedFiles.filter(
(file: File) => !files.some((f) => f.name === file.name)
) || [];

// Check for duplicate files and compress each file asynchronously
const uniqueCompressedFiles: File[] = [];
for (const file of acceptedFiles) {
const compressedFile = await compressImage(file);
if (!files.some((f) => f.name === file.name)) {
uniqueCompressedFiles.push(compressedFile);
}
}

// if user tries to upload more than 10 files, display a toast
if (newFiles.length + files.length > 10) {
if (uniqueCompressedFiles.length + files.length > 10) {
toast({
title: "Too many images",
description:
Expand All @@ -62,21 +67,21 @@ export default function TrainModelZone() {
});
return;
}

// display a toast if any duplicate files were found
if (newFiles.length !== acceptedFiles.length) {
if (uniqueCompressedFiles.length !== acceptedFiles.length) {
toast({
title: "Duplicate file names",
description:
"Some of the files you selected were already added. They were ignored.",
duration: 5000,
});
}

// check that in total images do not exceed a combined 4.5MB
const totalSize = files.reduce((acc, file) => acc + file.size, 0);
const newSize = newFiles.reduce((acc, file) => acc + file.size, 0);

const newSize = uniqueCompressedFiles.reduce((acc, file) => acc + file.size, 0);
if (totalSize + newSize > 4.5 * 1024 * 1024) {
toast({
title: "Images exceed size limit",
Expand All @@ -86,9 +91,10 @@ export default function TrainModelZone() {
});
return;
}

setFiles([...files, ...newFiles]);


// Append the compressed files to the state
setFiles([...files, ...uniqueCompressedFiles]);

toast({
title: "Images selected",
description: "The images were successfully selected.",
Expand All @@ -105,6 +111,32 @@ export default function TrainModelZone() {
[files]
);

const compressImage = async (file: File) => {
try {
const maxSizeMB = 1;
const maxWidthOrHeight = 1920;

const originalSizeMB = file.size / (1024 * 1024);

const compressedFile = await imageCompression(file, {
maxSizeMB: maxSizeMB,
maxWidthOrHeight: maxWidthOrHeight,
});

const compressedSizeMB = compressedFile.size / (1024 * 1024);
const reductionPercentage = ((originalSizeMB - compressedSizeMB) / originalSizeMB) * 100;

console.log(
`Original size: ${originalSizeMB.toFixed(2)} MB, Compressed size: ${compressedSizeMB.toFixed(2)} MB, Reduction: ${reductionPercentage.toFixed(2)}%`
);

return compressedFile;
} catch (error) {
console.error('Error compressing image:', error);
return file;
}
};

const trainModel = useCallback(async () => {
setIsLoading(true);
const formData = new FormData();
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"@types/formidable": "^3.4.2",
"@types/node-fetch": "^2.6.4",
"autoprefixer": "10.4.14",
"browser-image-compression": "^2.0.2",
"busboy": "^1.6.0",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
Expand Down