File size: 5,406 Bytes
420b22a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useState } from 'react';
import Box from '@mui/material/Box';
import Modal from '@mui/material/Modal';

import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';

import client from "../client";
import PlusIcon from '../assets/PlusIcon';

const style = {
  position: 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)',
  width: 600,
  bgcolor: 'background.paper',
  border: '5px solid #000',
  boxShadow: 24,
  p: 4,
};

export default function ModalComponent({button_styling}) {
  const [open, setOpen] = React.useState(false);
  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);
  
  const [files, setFiles] = useState({
    model: null,
    x_test: null,
    x_train: null,
    y_test: null,
    y_train: null,
    pred: null,
  });

  const handleFileChange = (e, label) => {
    const selectedFile = e.target.files[0];
    setFiles((prevFiles) => ({
      ...prevFiles,
      [label]: selectedFile,
    }));
  };

  const uploadFiles = async (model_id, datacatalog_id) => {
    try {
      const entries = Object.entries(files);
  
      for (const [label, file] of entries) {
        if (!file) {
          console.log("Not uploading file for label:", label, "because no file was selected");
          continue; // Skip if no file is selected for the label
        }
  
        const formData = new FormData();
        formData.append('file', file);
  
        await new Promise((resolve) => setTimeout(resolve, 100)); // Introduce 100ms delay
  
        await client.post(
          `/upload?param_name=${label}&model_id=${model_id}&datacatalog_id=${datacatalog_id}`, 
          formData, 
          {headers: {'Content-Type': 'multipart/form-data'}}
        );
      }
  
      console.log('File uploads successful');
    } catch (error) {
      console.error('File uploads failed:', error);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    const modelName = e.target.elements.modelName.value;
    const modelDesc = e.target.elements.modelDesc.value;
    
    client.get("/tenants")
    .then(response => { // Get tenant ID
      return response.data[0].id
    }) 
    .then((response_tenant_id) => { // 1) Create Model
      console.log(response_tenant_id)
      const createModelReqBody = {
        "name": modelName,
        "model_type": "MDL.001",
        "date_posted": new Date().toISOString(),
        "tenant_id": response_tenant_id,
        "description": modelDesc
      }
      return client.post("/model", createModelReqBody).then((response) => [response_tenant_id, response.data.id])
    })
    .then((id_array) => { // 2) Create Data Catalog
      console.log("ID of newly created model used in new datacatalog:", id_array[1])
      const dataCatalogReqBody = {
        "dataset_type": "training",
        "description": "description of the catalog",
        "is_generated_data": true,
        "tenant_id": id_array[0],
        "model_id": id_array[1],
        "name": "some catalog model name",
        "dataset_url": "https://www.example.com/dataset/data.csv",
        "model_type": "Classification",
        "name": "catalog model name",
        "parameters": {
          "additionalProp1": "string",
          "additionalProp2": "string",
          "model_name": "2/Model Name/MDL.001/training/dt_model-dac001e0-a852-4fa7-8d98-4c7c3e1d2bf1.joblib"
        }
      }
      return client.post("/datacatalog", dataCatalogReqBody).then((response) => [id_array[1], response.data.id])
    })
    .then((ids) => {return uploadFiles(ids[0], ids[1]);})
    .then(() => window.location.reload())
    .catch((error) => console.log(error))

    console.log('Model Name:', modelName);
    console.log('Description:', modelDesc);
  };

  return (
    <div>
      <a onClick={handleOpen} className='cursor-pointer'>
      <PlusIcon 
        styling = {`${button_styling} ml-12 mb-4 border-4 w-32 rounded-md inline-flex`}
        text="Add Model" />
      </a>
      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
      >
        <Box sx={style}>
          <div className='flex justify-center mb-4'>
            <h2 id="modal-modal-title" className='text-2xl '>Add Model and Serialized Data</h2>
          </div>
          <form onSubmit={handleSubmit}>
              <TextField id="outlined-basic" style={{ width: '12rem', marginRight: '1rem' }}  label="Model Name" name="modelName" variant="outlined" />
              <TextField id="outlined-basic" style={{ width: '19rem', marginBottom: '1.5rem'}} label="Description" name="modelDesc" variant="outlined" />
            {Object.entries(files).map(([label, file]) => (
              <div key={label} className='mb-2'>
                <input className="" type="file" onChange={(e) => handleFileChange(e, label)} />
                <label>{label}</label>
              </div>
            ))}
            <div className="flex justify-center">
              <Button type="submit" variant="contained" style={{ backgroundColor: '#e9e9ed', color: '#000', marginRight: '2rem'}}>Submit</Button>
              <Button onClick={handleClose} variant="contained" style={{ backgroundColor: '#e9e9ed', color: '#000' }}>Cancel</Button>
            </div>
          </form>
        </Box>
      </Modal>
    </div>
  );
}