File size: 16,978 Bytes
ffa4ae8
970eef1
 
 
 
 
 
ffa4ae8
 
 
a8a8975
 
7f7e436
 
 
 
970eef1
83106dd
970eef1
ebdfd67
ffa4ae8
 
 
 
a8a8975
7f7e436
 
970eef1
 
2c8e1bd
970eef1
 
ffa4ae8
970eef1
 
 
 
 
 
 
 
 
 
 
 
ffa4ae8
 
 
a8a8975
7f7e436
 
 
 
970eef1
 
ffa4ae8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8beb9ab
ffa4ae8
 
970eef1
ffa4ae8
 
 
970eef1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffa4ae8
970eef1
 
 
 
 
 
 
 
 
 
d6f0b38
 
 
 
 
59fb9df
d6f0b38
 
ccdd344
d6f0b38
 
970eef1
 
 
 
 
 
 
 
 
ffa4ae8
 
970eef1
 
 
 
 
2c8e1bd
970eef1
 
 
 
 
 
 
 
 
d88a570
970eef1
ffa4ae8
970eef1
ffa4ae8
970eef1
 
 
d88a570
970eef1
ffa4ae8
970eef1
 
 
 
 
 
ffa4ae8
970eef1
 
 
 
 
 
 
 
 
 
 
 
d6f0b38
970eef1
 
 
ffa4ae8
970eef1
 
 
 
 
 
 
 
 
 
d6f0b38
 
 
 
3b02faa
 
d6f0b38
 
3b02faa
d6f0b38
 
970eef1
 
 
 
 
 
ffa4ae8
 
 
 
 
 
970eef1
 
ffa4ae8
970eef1
 
 
a8a8975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f7e436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
970eef1
ffa4ae8
 
 
 
 
 
 
7e389db
ffa4ae8
970eef1
ffa4ae8
 
4a6a165
ffa4ae8
 
 
 
 
 
 
 
 
 
 
a8a8975
ffa4ae8
 
 
83106dd
ffa4ae8
 
 
 
 
 
 
7f7e436
a8a8975
 
 
7f7e436
a8a8975
 
 
 
 
 
7f7e436
a8a8975
7f7e436
a8a8975
 
7f7e436
a8a8975
7f7e436
a8a8975
 
7f7e436
a8a8975
7f7e436
 
a8a8975
7f7e436
a8a8975
 
 
ffa4ae8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
970eef1
ffa4ae8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
970eef1
83106dd
 
 
 
ffa4ae8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83106dd
 
 
 
 
 
 
ffa4ae8
83106dd
 
 
ffa4ae8
 
 
 
 
 
 
970eef1
ffa4ae8
 
 
 
 
 
 
 
 
 
 
 
970eef1
ffa4ae8
 
 
 
 
 
 
 
 
 
970eef1
ffa4ae8
 
 
7f7e436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c53adad
 
 
 
 
 
 
7f7e436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffa4ae8
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
import React, { useState, useRef } from "react";
import {
  Box,
  Paper,
  Typography,
  CircularProgress,
  Button,
  Snackbar,
  Alert,
  Grid,
  IconButton,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
} from "@mui/material";
import { alpha } from "@mui/material/styles";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import AutoFixHighIcon from "@mui/icons-material/AutoFixHigh";
import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile";
import DescriptionIcon from "@mui/icons-material/Description";
import ArticleIcon from "@mui/icons-material/Article";
import MenuBookIcon from "@mui/icons-material/MenuBook";
import DownloadIcon from "@mui/icons-material/Download";
import VisibilityIcon from "@mui/icons-material/Visibility";
import CloseIcon from "@mui/icons-material/Close";
import { useThemeMode } from "../hooks/useThemeMode";
import getTheme from "../config/theme";
import API_CONFIG from "../config/api";

/**
 * Component for creating a new benchmark, including 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 [sessionId, setSessionId] = useState(null);
  const [openSnackbar, setOpenSnackbar] = useState(false);
  const [selectedDocument, setSelectedDocument] = useState(null);
  const [isDefaultDocument, setIsDefaultDocument] = useState(false);
  const [isDownloading, setIsDownloading] = useState(false);
  const [documentContent, setDocumentContent] = useState("");
  const [openContentModal, setOpenContentModal] = useState(false);
  const [isLoadingContent, setIsLoadingContent] = useState(false);
  const [modalDocument, setModalDocument] = useState(null);
  const fileInputRef = useRef(null);

  const defaultDocuments = [
    {
      id: "the-bitter-lesson",
      name: "The Bitter Lesson",
      icon: <ArticleIcon sx={{ fontSize: 40 }} />,
      description: "A seminal paper on AI development by Rich Sutton",
    },
    {
      id: "hurricane-faq",
      name: "Hurricane FAQ",
      icon: <DescriptionIcon sx={{ fontSize: 40 }} />,
      description: "Frequently asked questions about hurricanes",
    },
    {
      id: "pokemon-guide",
      name: "Pokemon Guide",
      icon: <MenuBookIcon sx={{ fontSize: 40 }} />,
      description: "A comprehensive guide for Pokemon enthusiasts",
    },
  ];

  const handleCloseSnackbar = () => {
    setOpenSnackbar(false);
  };

  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;

    // Check if it's a PDF, TXT, HTML or 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",
      });
      setOpenSnackbar(true);
      return;
    }

    // Check file size limit (1MB = 1048576 bytes)
    if (file.size > 1048576) {
      setUploadStatus({
        success: false,
        message: "File size exceeds the 1MB limit",
      });
      setOpenSnackbar(true);
      return;
    }

    handleFileUpload(file);
  };

  const handleFileUpload = async (file) => {
    setIsLoading(true);
    setUploadStatus(null);
    setIsDefaultDocument(false);
    setSelectedDocument(null);

    try {
      const formData = new FormData();
      formData.append("file", file);

      const response = await fetch(`${API_CONFIG.BASE_URL}/upload`, {
        method: "POST",
        body: formData,
      });

      const result = await response.json();

      if (response.ok) {
        setUploadStatus({
          success: true,
          message: "File uploaded successfully",
        });
        setOpenSnackbar(true);
        setSessionId(result.session_id);
        setSelectedDocument({ name: file.name });
      } else {
        setUploadStatus({
          success: false,
          message: result.detail || "Upload failed",
        });
        setOpenSnackbar(true);
      }
    } catch (error) {
      setUploadStatus({
        success: false,
        message: "Server connection error",
      });
      setOpenSnackbar(true);
    } 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" });
      setOpenSnackbar(true);
      return;
    }

    // Check if it's a PDF, TXT, HTML or 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",
      });
      setOpenSnackbar(true);
      return;
    }

    // Check file size limit (10MB = 10485760 bytes)
    if (file.size > 10485760) {
      setUploadStatus({
        success: false,
        message: "File size exceeds the 10MB limit",
      });
      setOpenSnackbar(true);
      return;
    }

    handleFileUpload(file);
  };

  const handleDefaultDocClick = (doc) => {
    setSelectedDocument(doc);
    setSessionId(doc.id);
    setIsDefaultDocument(true);
  };

  const handleGenerateClick = () => {
    if (onStartGeneration && sessionId) {
      onStartGeneration(sessionId, isDefaultDocument);
    }
  };

  const handleDownloadDocument = async (doc) => {
    setIsDownloading(true);
    try {
      const link = document.createElement("a");
      link.href = `/${doc.id}.${
        doc.id === "the-bitter-lesson"
          ? "html"
          : doc.id === "hurricane-faq"
          ? "md"
          : "txt"
      }`;
      link.setAttribute(
        "download",
        `${doc.name}.${
          doc.id === "the-bitter-lesson"
            ? "html"
            : doc.id === "hurricane-faq"
            ? "md"
            : "txt"
        }`
      );
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      console.error("Error downloading document:", error);
      setUploadStatus({
        success: false,
        message: "Error downloading document",
      });
      setOpenSnackbar(true);
    } finally {
      setIsDownloading(false);
    }
  };

  const handleViewDocument = async (doc) => {
    setIsLoadingContent(true);

    try {
      let extension = "";
      if (doc.id === "the-bitter-lesson") {
        extension = "html";
      } else if (doc.id === "hurricane-faq") {
        extension = "md";
      } else {
        extension = "txt";
      }

      // Mettre à jour l'état du document pour la modale
      setModalDocument(doc);

      const response = await fetch(`/${doc.id}.${extension}`);
      const text = await response.text();

      setDocumentContent(text);
      setOpenContentModal(true);
    } catch (error) {
      console.error("Error loading document content:", error);
      setUploadStatus({
        success: false,
        message: "Error loading document content",
      });
      setOpenSnackbar(true);
    } finally {
      setIsLoadingContent(false);
    }
  };

  const handleCloseContentModal = () => {
    setOpenContentModal(false);
    // Réinitialiser après la fermeture de la modale
    setTimeout(() => {
      setDocumentContent("");
      setModalDocument(null);
    }, 300);
  };

  return (
    <Box sx={{ mt: -2 }}>
      <Typography
        variant="subtitle1"
        component="div"
        align="center"
        sx={{ mb: 2, color: "text.secondary" }}
      >
        To create a benchmark, choose a sample document
      </Typography>

      <Grid container spacing={2} sx={{ mb: 2 }}>
        {defaultDocuments.map((doc) => (
          <Grid item xs={12} sm={4} key={doc.id}>
            <Box
              elevation={2}
              sx={{
                p: 2,
                display: "flex",
                flexDirection: "column",
                borderRadius: 1.5,
                alignItems: "center",
                cursor: "pointer",
                transition: "all 0.2s ease",
                height: "100%",
                position: "relative",
                border:
                  selectedDocument?.id === doc.id
                    ? `2px solid ${theme.palette.primary.main}`
                    : `2px solid ${theme.palette.divider}`,
                "&:hover": {
                  transform: "translateY(-2px)",
                  boxShadow: 3,
                },
              }}
              onClick={() => handleDefaultDocClick(doc)}
            >
              <Tooltip title="View content">
                <IconButton
                  onClick={(e) => {
                    e.stopPropagation();
                    handleViewDocument(doc);
                  }}
                  sx={{
                    position: "absolute",
                    top: 4,
                    right: 4,
                    color: "text.secondary",
                    opacity: 0.4,
                    "&:hover": {
                      opacity: 0.8,
                      backgroundColor: alpha(theme.palette.primary.main, 0.05),
                    },
                    padding: 0.3,
                    "& .MuiSvgIcon-root": {
                      fontSize: 16,
                    },
                  }}
                  disabled={isLoadingContent}
                >
                  {isLoadingContent && selectedDocument?.id === doc.id ? (
                    <CircularProgress size={14} />
                  ) : (
                    <VisibilityIcon />
                  )}
                </IconButton>
              </Tooltip>
              <Box sx={{ color: "primary.main", mb: 1 }}>{doc.icon}</Box>
              <Typography variant="subtitle1" component="div" gutterBottom>
                {doc.name}
              </Typography>
              <Typography
                variant="body2"
                color="text.secondary"
                align="center"
                sx={{ flexGrow: 1 }}
              >
                {doc.description}
              </Typography>
            </Box>
          </Grid>
        ))}
      </Grid>

      <Typography
        variant="subtitle1"
        component="div"
        align="center"
        sx={{ mb: 2, color: "text.secondary" }}
      >
        Or upload your own ...
      </Typography>

      <Box
        sx={{
          p: 4,
          mt: 2,
          mb: 2,
          borderRadius: 1.5,
          border:
            selectedDocument?.name && !isDefaultDocument
              ? `2px solid ${theme.palette.primary.main}`
              : isDragging
              ? `2px dashed ${theme.palette.primary.main}`
              : `2px dashed ${theme.palette.divider}`,
          backgroundColor: isDragging
            ? alpha(theme.palette.action.hover, 0.5)
            : "transparent",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          minHeight: 180,
          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" }}
        />
        {selectedDocument?.name && !isDefaultDocument ? (
          <>
            <InsertDriveFileIcon
              sx={{ fontSize: 50, color: "primary.main", mb: 1 }}
            />
            <Typography variant="h6" component="div" gutterBottom>
              {selectedDocument.name}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              Click to upload a different file
            </Typography>
          </>
        ) : (
          <>
            {isLoading ? (
              <CircularProgress size={50} sx={{ mb: 1 }} />
            ) : (
              <CloudUploadIcon
                sx={{ fontSize: 50, color: "primary.main", mb: 1 }}
              />
            )}
            <Typography variant="h6" component="div" gutterBottom>
              {isLoading
                ? "Uploading your file..."
                : "Drag and drop your file here or click to browse"}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              Accepted formats: PDF, TXT, HTML, MD
            </Typography>
          </>
        )}
      </Box>

      <Box sx={{ display: "flex", justifyContent: "center" }}>
        <Button
          variant="contained"
          color="primary"
          onClick={handleGenerateClick}
          startIcon={<AutoFixHighIcon />}
          disabled={!sessionId}
          sx={{ mt: 2 }}
        >
          Generate Benchmark
        </Button>
      </Box>

      <Snackbar
        open={openSnackbar}
        autoHideDuration={6000}
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
      >
        <Alert
          onClose={handleCloseSnackbar}
          severity={uploadStatus?.success ? "success" : "error"}
          sx={{ width: "100%" }}
        >
          {uploadStatus?.message}
        </Alert>
      </Snackbar>

      <Dialog
        open={openContentModal}
        onClose={handleCloseContentModal}
        maxWidth="md"
        fullWidth
        aria-labelledby="document-content-dialog-title"
      >
        <DialogTitle id="document-content-dialog-title">
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "flex-start",
            }}
          >
            <Box>
              {modalDocument && (
                <Typography variant="h6" sx={{ fontWeight: 600 }}>
                  {modalDocument.name}
                </Typography>
              )}
              <Typography variant="body2" color="text.secondary">
                {modalDocument &&
                  (modalDocument.id === "the-bitter-lesson"
                    ? "HTML"
                    : modalDocument.id === "hurricane-faq"
                    ? "Markdown"
                    : "Text")}
              </Typography>
            </Box>
            <Box sx={{ display: "flex", gap: 1 }}>
              {modalDocument && (
                <Tooltip title="Download document">
                  <IconButton
                    edge="end"
                    color="inherit"
                    onClick={() => handleDownloadDocument(modalDocument)}
                    disabled={isDownloading}
                    aria-label="download"
                    sx={{
                      color: "text.secondary",
                      opacity: 0.4,
                      "&:hover": {
                        opacity: 0.8,
                      },
                    }}
                  >
                    {isDownloading ? (
                      <CircularProgress size={20} />
                    ) : (
                      <DownloadIcon />
                    )}
                  </IconButton>
                </Tooltip>
              )}
              <IconButton
                edge="end"
                color="inherit"
                onClick={handleCloseContentModal}
                aria-label="close"
              >
                <CloseIcon />
              </IconButton>
            </Box>
          </Box>
        </DialogTitle>
        <DialogContent
          dividers
          sx={{
            padding: 0,
          }}
        >
          {isLoadingContent ? (
            <Box sx={{ display: "flex", justifyContent: "center", my: 4 }}>
              <CircularProgress />
            </Box>
          ) : (
            <Box
              sx={{
                maxHeight: "60vh",
                overflow: "auto",
                whiteSpace: "pre-wrap",
                fontFamily: "monospace",
                fontSize: "0.875rem",
                p: 2.5,
              }}
            >
              {documentContent}
            </Box>
          )}
        </DialogContent>
      </Dialog>
    </Box>
  );
}

export default BenchmarkCreateForm;