All files / src/pages/flowsheet-page/flowsheet/PropertiesSidebar/MachineLearning UploadCSV.tsx

45.45% Statements 10/22
0% Branches 0/2
42.85% Functions 3/7
47.61% Lines 10/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                3x   3x 3x     1x       1x 1x 1x                         3x       3x                                       3x                                          
import { Button } from "@/ahuora-design-system/ui/button";
import {
  useCoreMlCreateMutation,
  useCoreMlUploadMlModelCreateMutation,
} from "@/api/apiStore.gen";
import CSVUploader from "@/pages/flowsheet-page/multi-steady-state/CSVUploader";
import { FolderOpen } from "lucide-react";
import Papa from "papaparse";
import { useRef } from "react";
 
interface UploadCSVProps {
  simulationObject: number;
  progress: number;
}
 
export default function UploadCSV(props: UploadCSVProps) {
  const fileInputRef = useRef<HTMLInputElement | null>(null);
 
  const [createMLModel] = useCoreMlCreateMutation();
  const [uploadModel] = useCoreMlUploadMlModelCreateMutation();
 
  function handleUpload(file: File): void {
    Papa.parse(file, {
      worker: true,
      skipEmptyLines: true,
      complete: (result) => {
        Iif (result.error) console.error(result.error?.message);
        const data = result.data;
        createMLModel({
          mlModel: {
            simulationObject: props.simulationObject,
            csv_data: data,
            surrogate_model: {},
          },
        });
      },
      error: (error) => console.error(error),
      header: true,
    });
  }
 
  const handleImportClick = () => {
    fileInputRef.current?.click();
  };
 
  const importModel = (event) => {
    const file = event.target.files[0];
    Iif (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const jsonData = e.target.result;
          uploadModel({
            uploadModel: {
              json_data: jsonData,
              simulationObject: props.simulationObject,
            },
          });
        } catch (error) {
          alert("Invalid JSON file");
        }
      };
      reader.readAsText(file);
    }
  };
  return (
    <div className="flex flex-col gap-4">
      <p>Upload your csv dataset</p>
      <CSVUploader onUpload={handleUpload} />
      <p>or</p>
      <div>
        <input
          type="file"
          accept=".json"
          onChange={importModel}
          ref={fileInputRef}
          className="hidden"
        />
        <Button variant="outline" onClick={handleImportClick}>
          <FolderOpen />
          Import Model
        </Button>
      </div>
    </div>
  );
}