Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 8,225 Bytes
970eef1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
import React, { useState, useRef, useEffect } from "react";
import {
Box,
Paper,
Typography,
CircularProgress,
Alert,
Button,
Stepper,
Step,
StepLabel,
} from "@mui/material";
import { useLocation } from "react-router-dom";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import PlayArrowIcon from "@mui/icons-material/PlayArrow";
import AuthContainer from "./shared/AuthContainer";
import { useThemeMode } from "../hooks/useThemeMode";
import getTheme from "../config/theme";
/**
* Component to display a stepper with three steps: Login, Upload File, and Generate
*
* @param {Object} props - Component props
* @param {number} props.activeStep - Current active step (0-based index)
* @returns {JSX.Element} Stepper component
*/
const StepsDisplay = ({ activeStep }) => {
const steps = ["Login", "Upload File", "Generate"];
return (
<Box sx={{ width: "100%", mb: 4 }}>
<Stepper activeStep={activeStep} alternativeLabel>
{steps.map((label) => (
<Step key={label}>
<StepLabel>{label}</StepLabel>
</Step>
))}
</Stepper>
</Box>
);
};
/**
* Component for creating a new benchmark, including authentication, file upload, and generation initiation
*
* @param {Object} props - Component props
* @param {Function} props.onStartGeneration - Callback when generation starts with sessionId
* @returns {JSX.Element} BenchmarkCreateForm component
*/
function BenchmarkCreateForm({ onStartGeneration }) {
const { mode } = useThemeMode();
const theme = getTheme(mode);
const [isDragging, setIsDragging] = useState(false);
const [uploadStatus, setUploadStatus] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [activeStep, setActiveStep] = useState(0);
const [sessionId, setSessionId] = useState(null);
const fileInputRef = useRef(null);
const location = useLocation();
// Check if we're coming back from an OAuth redirect
useEffect(() => {
// If we have code in URL parameters, it's an OAuth callback
const params = new URLSearchParams(window.location.search);
if (params.has("code")) {
console.log("Detected OAuth callback, cleaning URL");
// Remove the query parameters from the URL without reloading
window.history.replaceState({}, document.title, window.location.pathname);
// Check if we have auth data in localStorage after a brief delay to let OAuth process complete
setTimeout(() => {
const storedAuth = localStorage.getItem("hf_oauth");
if (storedAuth) {
console.log("Found auth data after redirect, refreshing UI state");
setActiveStep(1); // Move to next step if authenticated
}
}, 1000);
}
}, [location]);
const handleDragOver = (e) => {
e.preventDefault();
setIsDragging(true);
};
const handleDragLeave = () => {
setIsDragging(false);
};
const handleClick = () => {
fileInputRef.current.click();
};
const handleFileChange = (e) => {
const file = e.target.files[0];
if (!file) return;
// Vérifier si c'est un PDF, TXT, HTML ou MD
if (
!file.name.endsWith(".pdf") &&
!file.name.endsWith(".txt") &&
!file.name.endsWith(".html") &&
!file.name.endsWith(".md")
) {
setUploadStatus({
success: false,
message: "Only PDF, TXT, HTML and MD files are accepted",
});
return;
}
handleFileUpload(file);
};
const handleFileUpload = async (file) => {
setIsLoading(true);
setUploadStatus(null);
try {
const formData = new FormData();
formData.append("file", file);
const response = await fetch("http://localhost:3001/upload", {
method: "POST",
body: formData,
});
const result = await response.json();
if (response.ok) {
setUploadStatus({
success: true,
message: `File ${result.filename} uploaded successfully`,
});
// Store the session ID for the benchmark generation
setSessionId(result.session_id);
setActiveStep(2); // Advance to Generate step after successful upload
} else {
setUploadStatus({
success: false,
message: result.error || "Upload failed",
});
}
} catch (error) {
setUploadStatus({
success: false,
message: "Server connection error",
});
} finally {
setIsLoading(false);
}
};
const handleDrop = async (e) => {
e.preventDefault();
setIsDragging(false);
const file = e.dataTransfer.files[0];
if (!file) {
setUploadStatus({ success: false, message: "No file detected" });
return;
}
// Vérifier si c'est un PDF, TXT, HTML ou MD
if (
!file.name.endsWith(".pdf") &&
!file.name.endsWith(".txt") &&
!file.name.endsWith(".html") &&
!file.name.endsWith(".md")
) {
setUploadStatus({
success: false,
message: "Only PDF, TXT, HTML and MD files are accepted",
});
return;
}
handleFileUpload(file);
};
const handleGenerateClick = () => {
if (onStartGeneration && sessionId) {
onStartGeneration(sessionId);
}
};
return (
<>
<StepsDisplay activeStep={activeStep} />
{/* Authentication step */}
{activeStep === 0 && (
<AuthContainer
actionText="use this demo"
onSuccess={() => setActiveStep(1)}
/>
)}
{/* File upload step */}
{activeStep === 1 && (
<Paper
elevation={3}
sx={{
p: 4,
mt: 3,
mb: 3,
border: isDragging
? `2px dashed ${theme.palette.primary.main}`
: "2px dashed #ccc",
backgroundColor: isDragging ? "rgba(0, 0, 0, 0.05)" : "transparent",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
minHeight: 200,
cursor: "pointer",
transition: "all 0.3s ease",
}}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
onClick={handleClick}
>
<input
type="file"
ref={fileInputRef}
onChange={handleFileChange}
accept=".pdf,.txt,.html,.md"
style={{ display: "none" }}
/>
<CloudUploadIcon
sx={{ fontSize: 60, color: "text.secondary", mb: 1 }}
/>
<Typography variant="h6" component="div" gutterBottom>
Drag and drop your file here or click to browse
</Typography>
<Typography variant="body2" color="text.secondary">
Accepted formats: PDF, TXT, HTML, MD
</Typography>
{isLoading && (
<Box sx={{ mt: 2 }}>
<CircularProgress size={30} />
</Box>
)}
{uploadStatus && (
<Alert
severity={uploadStatus.success ? "success" : "error"}
sx={{ mt: 2, width: "100%" }}
>
{uploadStatus.message}
</Alert>
)}
</Paper>
)}
{/* Generate button step */}
{activeStep === 2 && (
<Paper
elevation={3}
sx={{
p: 4,
mt: 3,
mb: 3,
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
minHeight: 200,
}}
>
<PlayArrowIcon
sx={{ fontSize: 60, color: "text.secondary", mb: 1 }}
/>
<Typography variant="h6" component="div" gutterBottom>
Ready to generate your benchmark
</Typography>
<Button
variant="contained"
color="primary"
onClick={handleGenerateClick}
sx={{ mt: 2 }}
startIcon={<PlayArrowIcon />}
>
Generate Benchmark
</Button>
</Paper>
)}
</>
);
}
export default BenchmarkCreateForm;
|