Merge pull request #47 from joelmathewthomas/feature/error-handling

Feature/error handling
This commit is contained in:
Joel Mathew Thomas
2025-03-20 22:29:06 +05:30
committed by GitHub
7 changed files with 225 additions and 153 deletions
+2
View File
@@ -1,4 +1,5 @@
import os
import shutil
import uuid
import zipfile
from django.http import FileResponse, HttpResponse
@@ -18,6 +19,7 @@ from freqsplit.input.format_checker import is_supported_format
UPLOAD_DIR = "/tmp/freqsplit"
# Ensure the temp directory exists
shutil.rmtree(UPLOAD_DIR)
os.makedirs(UPLOAD_DIR, exist_ok=True)
# Endpoint to ping server
+2 -32
View File
@@ -1,4 +1,4 @@
import { useState, useEffect, useRef } from 'react';
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
Typography,
@@ -18,12 +18,7 @@ import SpectrogramPlayer from "react-audio-spectrogram-player"
function PreviewPage() {
const navigate = useNavigate();
const { mediaFile, response } = useMediaContext();
const [error, setError] = useState(false);
const videoRef = useRef(null);
const audioClass = response.audio_class
// Supported video formats
const supportedFormats = ['video/mp4', 'video/webm', 'video/ogg'];
const isVideo = mediaFile && supportedFormats.includes(mediaFile.type);
useEffect(() => {
if (!mediaFile) {
@@ -46,32 +41,7 @@ function PreviewPage() {
</Typography>
<Box sx={{ mt: 4, mb: 4, textAlign: 'center' }}>
{isVideo ? (
<Box
sx={{
position: 'relative',
width: '100%',
maxWidth: '100%',
borderRadius: 2,
overflow: 'hidden',
bgcolor: 'black',
}}
>
<video
ref={videoRef}
src={mediaFile.url}
style={{ width: '100%', borderRadius: 8 }}
controls
onError={() => setError(true)}
/>
{error && (
<Typography color="error" sx={{ mt: 2 }}>
<ErrorIcon sx={{ mr: 1 }} />
Video format not supported. Please upload MP4, WebM, or Ogg.
</Typography>
)}
</Box>
) : mediaFile.type.startsWith('audio/') ? (
{mediaFile.type.startsWith('audio/') ? (
<Box
sx={{
display: 'flex',
+68 -20
View File
@@ -6,46 +6,65 @@ import { useMediaContext } from "../contexts/MediaContext";
import axios from "axios";
import JSZip from "jszip";
import Logs from "../components/Logs"
import Toast from "../components/Toast";
import { formatLogMessage } from "../utils/logUtils";
function ProcessingPage() {
const navigate = useNavigate();
const { mediaFile, response, setExtractedFiles, setDownloadedFileURL, setDownloadedFileSpectrogram, setLogs } = useMediaContext();
const { mediaFile, response, setExtractedFiles, setDownloadedFileURL, setDownloadedFileSpectrogram, setLogs, setToastOpen, setToastMessage } = useMediaContext();
const [progress, setProgress] = useState(0);
const [statusText, setStatusText] = useState("Analyzing media...");
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const processStep = async (url: string, log: string | null, nextStep: () => void, progressValue: number, status: string, extraData = {}) => {
try {
const showErrorToast = (message: string) => {
setToastMessage(message);
setToastOpen(true);
}
const processStep = async (
url: string,
log: string | null,
nextStep: () => void,
progressValue: number,
status: string,
extraData = {}
) => {
try {
if (log !== null) {
setLogs((prevLogs) => [...prevLogs, log]);
}
const formData = new FormData();
formData.append("file_uuid", response.file_uuid);
Object.entries(extraData).forEach(([key, value]) =>
Object.entries(extraData).forEach(([key, value]) =>
formData.append(key, String(value))
);
setStatusText(status);
const startTime = Date.now();
const res = await axios.post(url, formData, {
await axios.post(url, formData, {
headers: { "Content-Type": "multipart/form-data" },
});
if (res.status === 200 && res.data) {
const elapsedTime = Date.now() - startTime;
if (elapsedTime < 5000) await delay(5000 - elapsedTime);
setProgress(progressValue);
nextStep();
}
const elapsedTime = Date.now() - startTime;
if (elapsedTime < 5000) await delay(5000 - elapsedTime);
setProgress(progressValue);
nextStep();
} catch (error) {
console.error(`Error in step: ${url}`, error);
if (axios.isAxiosError(error)) {
if (error.response?.status === 500) {
showErrorToast(`Internal Server Error`);
} else {
showErrorToast(`Internal Server Error`);
}
} else {
showErrorToast(`Internal Server Error`);
}
}
};
const fetchZipDownload = async () => {
try {
@@ -61,7 +80,15 @@ function ProcessingPage() {
console.log("Failed to download the file");
}
} catch (error) {
console.error("Error fetching download:", error);
if (axios.isAxiosError(error)) {
if (error.response?.status === 500) {
showErrorToast(`Internal Server Error`);
} else {
showErrorToast(`Internal Server Error`);
}
} else {
showErrorToast(`Internal Server Error`);
}
}
};
@@ -118,7 +145,15 @@ function ProcessingPage() {
console.log("Failed to download the file");
}
} catch (error) {
console.error("Error fetching download:", error);
if (axios.isAxiosError(error)) {
if (error.response?.status === 500) {
showErrorToast(`Internal Server Error`);
} else {
showErrorToast(`Internal Server Error`);
}
} else {
showErrorToast(`Internal Server Error`);
}
}
};
@@ -134,7 +169,8 @@ function ProcessingPage() {
const fileURLs = [];
for (const [filename, fileData] of Object.entries(zip.files)) {
if (!fileData.dir) {
try {
if (!fileData.dir) {
const fileBlob = await fileData.async("blob");
const fileURL = URL.createObjectURL(fileBlob);
@@ -162,6 +198,17 @@ function ProcessingPage() {
}
fileURLs.push({ name: filename, url: fileURL, spectrogram: res.data.spectrogram, spec_sr: res.data.spec_sr });
}
} catch (error) {
if (axios.isAxiosError(error)) {
if (error.response?.status === 500) {
showErrorToast(`Internal Server Error`);
} else {
showErrorToast(`Internal Server Error`);
}
} else {
showErrorToast(`Internal Server Error`);
}
}
}
setExtractedFiles(fileURLs);
setProgress(100);
@@ -231,7 +278,8 @@ function ProcessingPage() {
}}
/>
<Logs />
</Container>
<Toast />
</Container>
);
}
+64 -80
View File
@@ -1,6 +1,5 @@
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
//import axios from 'axios';
import {
Typography,
Container,
@@ -13,7 +12,6 @@ import {
LinearProgress,
} from '@mui/material';
import {
Check as CheckIcon,
VolumeUp as VolumeUpIcon
} from '@mui/icons-material';
import StepperComponent from '../components/StepperComponent';
@@ -27,7 +25,6 @@ function ResultsPage() {
const navigate = useNavigate();
const { mediaFile, response, extractedFiles, downloadedFileURL, downloadedFileSpectrogram, setLogs } = useMediaContext();
const audioClass = response.audio_class
const isVideo = mediaFile?.type.includes('video');
const handleDownloadAll = () => {
if (audioClass === 'Music') {
@@ -57,17 +54,6 @@ function ResultsPage() {
}
}, [mediaFile, navigate]);
// const togglePlay = (index) => {
// if (audioRefs[index].current) {
// if (isPlaying) {
// audioRefs[index].current.pause();
// } else {
// audioRefs[index].current.play();
// }
// setIsPlaying(!isPlaying);
// }
// };
if (!mediaFile) return <LinearProgress />;
return (
@@ -75,11 +61,17 @@ function ResultsPage() {
<StepperComponent activeStep={3} />
<Paper elevation={3} sx={{ p: 4, mt: 4 }}>
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', mb: 3 }}>
<CheckIcon sx={{ color: 'success.main', fontSize: 36, mr: 1 }} />
<Typography variant="h4" color="primary">
Processing Complete!
</Typography>
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', mb: 3, overflow: "auto" }}>
<Typography
variant="h4"
color="primary"
sx={{
textAlign: "center",
width: "100%",
}}
>
Processing Complete!
</Typography>
</Box>
<Typography variant="body1" paragraph color="textSecondary" align="center">
@@ -87,82 +79,74 @@ function ResultsPage() {
</Typography>
<Box sx={{ mt: 4, mb: 4, textAlign: 'center' }}>
{isVideo ? (
<video
<Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', p: 4, bgcolor: 'rgba(0, 0, 0, 0.04)', borderRadius: 2 }}>
<VolumeUpIcon color="primary" sx={{ fontSize: 80, mb: 2 }} />
<Typography variant="h6" gutterBottom>
{mediaFile.name}
</Typography>
<Box sx={{ width: '100%', mt: 2, mb: 2, border: `1px solid gray`, p:2, borderRadius: 2 }}>
<Typography variant="body2" color="textSecondary" sx={{ mb: 1 }}>
{mediaFile.name}
</Typography>
<SpectrogramPlayer
src={mediaFile.url}
style={{ width: '100%', borderRadius: 8 }}
controls
sxx={JSON.parse(response.spectrogram)}
SampleRate={response.spec_sr}
colormap={'magma'}
settings={true}
transparent={false}
navigator={true}
/>
) : (
<Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', p: 4, bgcolor: 'rgba(0, 0, 0, 0.04)', borderRadius: 2 }}>
<VolumeUpIcon color="primary" sx={{ fontSize: 80, mb: 2 }} />
<Typography variant="h6" gutterBottom>
{mediaFile.name} (Original)
</Box>
{audioClass === "Music" ? (
<>
<Box sx={{ width: '100%', mt: 2 }}>
<Typography variant="h4" color="textPrimary" sx={{ mb: 1 }}>
Processed Files
</Typography>
<Box sx={{ width: '100%', mt: 2, mb: 2, border: `1px solid gray`, p:2, borderRadius: 2 }}>
</Box>
{extractedFiles.map((file, index) => (
<Box key={index} sx={{ width: '100%', mt: 2, border: `1px solid gray`, p:2, borderRadius: 2 }}>
<Typography variant="body2" color="textSecondary" sx={{ mb: 1 }}>
{mediaFile.name}
{file.name}
</Typography>
<SpectrogramPlayer
src={mediaFile.url}
sxx={JSON.parse(response.spectrogram)}
SampleRate={response.spec_sr}
src={file.url}
sxx={JSON.parse(file.spectrogram)}
SampleRate={file.spec_sr}
colormap={'magma'}
settings={true}
transparent={false}
navigator={true}
/>
</Box>
{audioClass === "Music" ? (
<>
<Box sx={{ width: '100%', mt: 2 }}>
<Typography variant="h6" color="textPrimary" sx={{ mb: 1 }}>
Processed Files
))}
</>
) : (
<>
<Box sx={{ width: '100%', mt: 2 }}>
<Typography variant="h6" color="textPrimary" sx={{ mb: 1 }}>
Processed File
</Typography>
</Box>
<Box sx={{ width: '100%', mt: 2, border: `1px solid gray`, p:2, borderRadius: 2 }}>
<Typography variant="body2" color="textSecondary" sx={{ mb: 1 }}>
{mediaFile?.name}
</Typography>
</Box>
{extractedFiles.map((file, index) => (
<Box key={index} sx={{ width: '100%', mt: 2, border: `1px solid gray`, p:2, borderRadius: 2 }}>
<Typography variant="body2" color="textSecondary" sx={{ mb: 1 }}>
{file.name}
</Typography>
<SpectrogramPlayer
src={file.url}
sxx={JSON.parse(file.spectrogram)}
SampleRate={file.spec_sr}
colormap={'magma'}
settings={true}
transparent={false}
navigator={true}
/>
</Box>
))}
</>
) : (
<>
<Box sx={{ width: '100%', mt: 2 }}>
<Typography variant="h6" color="textPrimary" sx={{ mb: 1 }}>
Processed File
</Typography>
</Box>
<Box sx={{ width: '100%', mt: 2, border: `1px solid gray`, p:2, borderRadius: 2 }}>
<Typography variant="body2" color="textSecondary" sx={{ mb: 1 }}>
{mediaFile?.name}
</Typography>
<SpectrogramPlayer
src={downloadedFileURL}
sxx={JSON.parse(downloadedFileSpectrogram.spectrogram)}
SampleRate={downloadedFileSpectrogram.spec_sr}
colormap={'magma'}
settings={true}
transparent={false}
navigator={true}
/>
</Box>
</>
)}
</Box>
<SpectrogramPlayer
src={downloadedFileURL}
sxx={JSON.parse(downloadedFileSpectrogram.spectrogram)}
SampleRate={downloadedFileSpectrogram.spec_sr}
colormap={'magma'}
settings={true}
transparent={false}
navigator={true}
/>
</Box>
</>
)}
</Box>
</Box>
<Grid container spacing={3} sx={{ mt: 2 }}>
<Grid item xs={12} sm={6}>
+56 -20
View File
@@ -1,6 +1,7 @@
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import Logs from "../components/Logs"
import Toast from "../components/Toast";
import axios from "axios";
import {
Typography,
@@ -13,7 +14,6 @@ import {
import {
CloudUpload as CloudUploadIcon,
VolumeUp as VolumeUpIcon,
Movie as MovieIcon,
} from "@mui/icons-material";
import StepperComponent from "../components/StepperComponent";
import { useWebSocket } from "../contexts/WebSocketContext";
@@ -24,13 +24,17 @@ function UploadPage() {
const navigate = useNavigate();
const theme = useTheme();
const { socket, isConnected } = useWebSocket();
const { setMediaFile, setResponse, setLogs } = useMediaContext();
const { setMediaFile, setResponse, setLogs, setToastOpen, setToastMessage } = useMediaContext();
const [file, setFile] = useState<File | null>(null);
const [isDragging, setIsDragging] = useState(false);
const [fileError, setFileError] = useState("");
const [upload, setUpload] = useState(false);
const [inputEnabled, setInputEnabled] = useState(false);
const showErrorToast = (message: string) => {
setToastMessage(message);
setToastOpen(true);
}
useEffect(() => {
const startLogs = async () => {
setLogs([formatLogMessage("Initializing freqsplit")]);
@@ -102,19 +106,37 @@ function UploadPage() {
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setUpload(false);
setResponse({
audio_class: "",
file_uuid: "",
sr: 0,
spectrogram: "",
spec_sr: 0
});
const selectedFile = e.target.files?.[0] || null;
const maxSize = 100 * 1024 * 1024; // 100MB in bytes
if (selectedFile) {
if (selectedFile.size > maxSize) {
showErrorToast("Max file size is 100MB!");
setFile(null);
setUpload(false);
e.target.value = "";
return;
}
}
validateAndSetFile(selectedFile);
handleUpload(selectedFile);
};
const validateAndSetFile = (file: File | null) => {
setFileError("");
if (!file) return;
const fileType = file.type;
if (!fileType.includes("audio") && !fileType.includes("video")) {
setFileError("Please upload only audio or video files.");
showErrorToast("Please upload only audio or video files.");
return;
}
@@ -131,7 +153,7 @@ function UploadPage() {
}); //
navigate('/preview');
} else {
setFileError("Please upload a file to continue.");
showErrorToast("Please upload a file to continue");
}
};
@@ -178,6 +200,16 @@ function UploadPage() {
setLogs((prevLogs) => [...prevLogs, formatLogMessage(`freqsplit/input: audio_class: ${res.data.audio_class}`)])
}
} catch (error) {
showErrorToast("Failed to upload file");
setUpload(false);
setResponse({
audio_class: "",
file_uuid: "",
sr: 0,
spectrogram: "",
spec_sr: 0
});
setFile(null);
console.error("Upload failed:", error);
}
};
@@ -205,6 +237,7 @@ function UploadPage() {
: "transparent",
transition: "all 0.3s ease",
cursor: "pointer",
overflow: "auto"
}}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
@@ -216,32 +249,34 @@ function UploadPage() {
id="fileInput"
style={{ display: "none" }}
onChange={handleFileChange}
accept="audio/*,video/*"
accept="audio/*"
disabled={!inputEnabled}
/>
<CloudUploadIcon color="primary" sx={{ fontSize: 64, mb: 2 }} />
<Typography variant="h6" gutterBottom>
<Typography
variant="h6"
gutterBottom
sx={{
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
maxWidth: "100%", // Ensure it adapts to the box size
}}
>
{file ? file.name : "Drop your file here or click to browse files"}
</Typography>
<Typography>
Max file size: 100MB
</Typography>
{file && (
<Typography variant="body2" color="textSecondary">
{file.type.includes("video") ? (
<MovieIcon sx={{ mr: 1 }} />
) : (
<VolumeUpIcon sx={{ mr: 1 }} />
)}
{file.type.includes("audio") ? <VolumeUpIcon sx={{ mr: 1 }} /> : null}
{file.type} - {(file.size / (1024 * 1024)).toFixed(2)} MB
</Typography>
)}
</Box>
{fileError && (
<Typography variant="body2" color="error" sx={{ mt: 1 }}>
{fileError}
</Typography>
)}
<Box sx={{ mt: 4, display: "flex", justifyContent: "space-between" }}>
<Button
variant="outlined"
@@ -261,6 +296,7 @@ function UploadPage() {
</Box>
</Paper>
<Logs />
<Toast />
</Container>
);
}
+26
View File
@@ -0,0 +1,26 @@
import { Snackbar, Alert } from "@mui/material";
import { useMediaContext } from "../contexts/MediaContext";
const Toast: React.FC = () => {
const { toastOpen, setToastOpen, toastMessage } = useMediaContext();
return (
<Snackbar
open={toastOpen}
autoHideDuration={4000}
onClose={() => {
setToastOpen(false);
}}
anchorOrigin={{ vertical: "top", horizontal: "right" }}
>
<Alert
onClose={() => setToastOpen(false)}
severity="error"
sx={{ width: "100%" }}
>
{toastMessage}
</Alert>
</Snackbar>
);
}
export default Toast
+7 -1
View File
@@ -13,6 +13,10 @@ interface MediaContextType {
setDownloadedFileSpectrogram: (spectrogram: {spectrogram: string, spec_sr: number}) => void;
logs: string[];
setLogs: React.Dispatch<React.SetStateAction<string[]>>;
toastOpen: boolean;
setToastOpen: ( value: boolean) => void;
toastMessage: string;
setToastMessage: ( message: string) => void;
}
@@ -34,9 +38,11 @@ export const MediaProvider: React.FC<{ children: React.ReactNode }> = ({ childre
spec_sr: 0
});
const [logs, setLogs] = useState<MediaContextType["logs"]>([""]);
const [toastOpen, setToastOpen] = useState<MediaContextType["toastOpen"]>(false);
const [toastMessage, setToastMessage] = useState<MediaContextType["toastMessage"]>("");
return (
<MediaContext.Provider value={{ mediaFile, setMediaFile, response, setResponse, extractedFiles, setExtractedFiles, downloadedFileURL, setDownloadedFileURL, downloadedFileSpectrogram, setDownloadedFileSpectrogram, logs, setLogs }}>
<MediaContext.Provider value={{ mediaFile, setMediaFile, response, setResponse, extractedFiles, setExtractedFiles, downloadedFileURL, setDownloadedFileURL, downloadedFileSpectrogram, setDownloadedFileSpectrogram, logs, setLogs, toastOpen, setToastOpen, toastMessage, setToastMessage }}>
{children}
</MediaContext.Provider>
);