DefineCorpus.vue 8.25 KB
Newer Older
1
<template>
Quentin David's avatar
Quentin David committed
2
  <v-container class="my-5">
3
4
    <v-card outlined class="my-5 px-6">
      <v-card-title class="justify-center py-6">
Quentin David's avatar
Quentin David committed
5
        <h1 class="display-3"> {{ $t('corpus-choice' )}}</h1>
6
      </v-card-title>
7
      <AddCorpus
Quentin David's avatar
Quentin David committed
8
        @chosen-selection-update="updateSelection($event)"
9
      />
Quentin David's avatar
Quentin David committed
10
      <CorpusParameters
11
        v-show="showParameters"
Quentin David's avatar
Quentin David committed
12
        :corpusId="corpusId"
13
14
        @corpus-parameters-update="updateCorpusParameters($event)"
      />
15
    </v-card>
16
17
18
19
20
21
22
23
    <!-- Alerts -->
    <div>
      <v-alert type="info" v-if="!valid"> {{ buttonMessage }}
      </v-alert>
      <v-alert type="error" dismissible v-model="errorMessageToggle"> {{ errorMessage }}
      </v-alert>
    </div>
    <v-btn :disabled="!valid" color="success" block @click="submitCorpus"> {{ $t('next') }} </v-btn>
24
25
26
27
  </v-container>
</template>

<script>
28
import axios from '@/plugins/axios';
29

30
31
32
import AddCorpus from '@/components/DefineCorpus/AddCorpus';
import CorpusParameters from '@/components/DefineCorpus/CorpusParameters';

Quentin David's avatar
Quentin David committed
33
34
const FILE_INPUT = 0, TEXT_INPUT = 1, PROFILE_CORPUS = 2, PUBLIC_CORPUS = 3;

35
36
37
38
39
40
41
export default {
  name: 'Corpus',
  components: {
    AddCorpus,
    CorpusParameters,
  },
  data: () => ({
Quentin David's avatar
Quentin David committed
42
43
44
45
46
    // showParameters: false,
    corpusId: null,
    textInput: null,
    fileInput: null,
    activeTab : FILE_INPUT,
47
    corpusParameters: null,
Quentin David's avatar
Quentin David committed
48
    areParametersValid: false,
49
50
51
    errorMessage: null,
    errorMessageToggle: false
  }),
Quentin David's avatar
Quentin David committed
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
  computed: {
    buttonMessage: function() {
      if (this.isSelectionMade && ( this.activeTab === FILE_INPUT || this.activeTab === TEXT_INPUT) && !this.areParametersValid) {
        return 'Veuillez remplir les informations nécessaires de votre corpus pour continuer'
      }
      else {
        return 'Veuillez entrer un corpus pour continuer'
      }
    },
    // True if an item has been selected or chosen
    isSelectionMade: function() {
      return !!this.textInput || !!this.fileInput || !!this.corpusId;
    },
    // If true, then we can push the "NEXT" button and go to the treatment page
    valid: function() {
      // True is there is a corpus and that the parameters are filled (for file & text input)
      return (
        this.isSelectionMade && this.areParametersValid
      );
    },
    showParameters() {
      return this.isSelectionMade;
      //return this.corpus && ( this.activeTab === FILE_INPUT || this.activeTab === TEXT_INPUT);
    },
    // fetchedCorpus() {
    //   if (this.corpusId) {
    //     axios.get('/corpora/'+this.corpusId)
    //     .then( response => {
    //       console.log(response);
    //     })
    //     .catch( error => {
    //       console.error(error);
    //     })
    //   }
    //   return null;
    // }
  },
89
  methods: {
Quentin David's avatar
Quentin David committed
90
91
92
93
94
    reset () {
      this.textInput = null;
      this.fileInput = null;
      this.corpusId = null;
    },
95
    // Update when there is a change in the tabs
Quentin David's avatar
Quentin David committed
96
97
98
99
    updateSelection( selectedObject ) {
      // Reset all values
      this.reset()
      const { activeTab, selection } = selectedObject;
100
      this.activeTab = activeTab;
Quentin David's avatar
Quentin David committed
101
102
103
104
105
106
107
108
109
110
111
      switch (activeTab) {
        case FILE_INPUT:
          this.fileInput = selection;
          break;
        case TEXT_INPUT:
          this.textInput = selection;
          break;
        case PROFILE_CORPUS:
        case PUBLIC_CORPUS:
          this.corpusId = selection;
      }
112
113
114
115
    },
    // Update when there is a change in the parameters of the corpus
    updateCorpusParameters ( parametersObject ) {
      const { isValid, data } = parametersObject;
Quentin David's avatar
Quentin David committed
116
      this.areParametersValid = isValid;
117
118
      this.corpusParameters = data;
    },
Quentin David's avatar
Quentin David committed
119
    // Evaluate if we have to show the options or not (only for file-input & text-input)
120
    // Maybe it should show even for profile corpora or public corpora
121
122
123
124
125
    evaluateShow(activeTab, isCorpusNotUndefined) {
      if (!isCorpusNotUndefined) {
        this.showParameters = false;
      }
      else {
Quentin David's avatar
Quentin David committed
126
127
128
129
        this.showParameters = (activeTab === 'file-input' || activeTab === 'text-input');
      }
    },
    // Fetch userId if connected, else create it and store it
130
    // Not implemented yet, I put connected = true
Quentin David's avatar
Quentin David committed
131
132
    fetchUserId() {
      // TODO: verify if user connected
133
      const connected = true;
Quentin David's avatar
Quentin David committed
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

      if (connected) {
        return "connectedUserId";
      }
      else {
        let userId = localStorage.getItem('userId');
        if (!userId) {
          axios.post('/users', { status: 'Guest' })
          .then (res => {
            if (res.data.status !== "success") {
              this.triggerError(res.data.message);
              return null;
            }
            else {
              userId = res.data.data.user._id;
              localStorage.setItem('userId', userId);
            }
          })
          .catch( error => {
            this.triggerError(error);
            return null;
          });
        }
        else {
          return userId; 
        }
160
      }
161
    },
162
163
164
    // NOW: POST /corpora
    // Maybe it is better to store it in store????
    submitCorpus() {
Quentin David's avatar
Quentin David committed
165
166
167
168
169
170
171
      switch (this.activeTab) {
        case FILE_INPUT:
          this.submitFileInput();
          break;
        case TEXT_INPUT:
          this.errorMessageToggle = true;
          this.errorMessage = "NOT IMPLEMENTED YET";
172
          //this.submitTextInput();
Quentin David's avatar
Quentin David committed
173
174
175
176
177
178
179
180
181
182
183
184
185
186
          break;
        case PROFILE_CORPUS:
          this.errorMessageToggle = true;
          this.errorMessage = "NOT IMPLEMENTED YET";
          this.submitProfileCorpus();
          break;
        case PUBLIC_CORPUS:
          this.errorMessageToggle = true;
          this.errorMessage = "NOT IMPLEMENTED YET";
          this.submitPublicCorpus();
          break;
      }
    },
    submitFileInput() {
187

Quentin David's avatar
Quentin David committed
188
189
190
191
      // Build the formData
      let formData = new FormData();
      if (!this.fileInput.length) {
        formData.append('file[]', [this.fileInput]);
192
193
      }
      else {
Quentin David's avatar
Quentin David committed
194
195
196
197
198
199
200
201
202
203
        this.fileInput.forEach((e) => {
          formData.append('file[]', e);
        })
      }

      // Fetch userId or creates a new and store userId
      let userId = this.fetchUserId();
      if (!userId) {
        // ERROR HERE
        return;
204
      }
Quentin David's avatar
Quentin David committed
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222

      formData.set('userId', userId);
      axios.post('/corpora/upload',
        formData,
        { headers: { 'Content-Type': 'multipart/form-data' }}
      )
      .then( (res) => {
        if (res.data.status !== "success") {
          this.triggerError(res.data.message);
        }
        else {
          console.log("File input corpus was successfully uploaded");
          // Fake corpus Id / Session storage is cleared when the session ends (page closed)
          
          let pathList = [];
          res.data.data.uploadedFiles.forEach( el => {
            pathList.push({ source: el.path});
          });
223
          let corpus = {
Quentin David's avatar
Quentin David committed
224
            createdBy: userId,
225
            type: 'private',
Quentin David's avatar
Quentin David committed
226
227
228
229
            creationDate: Date.now(),
            metadata: this.corpusParameters,
            documents: pathList
          };
230
231
          corpus.metadata.size = res.data.data.size;
          this.postCorpus(corpus);      
Quentin David's avatar
Quentin David committed
232
233
234
235
236
        }
      })
      .catch( (error) => {
        this.triggerError(error);
      })
237
    },
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
    submitTextInput() {
      // Fetch userId or creates a new and store userId
      let userId = this.fetchUserId();
      if (!userId) {
        // ERROR HERE
        return;
      }
      // Il faudrait ici créer un fichier dans le serveur contenant le texte ajouté par l'utilisateur
      let corpus = {
        createdBy: userId,
        type: 'private',
        creationDate: Date.now(),
        metadata: this.corpusParameters,
        //documents: pathList
      };
      this.postCorpus(corpus);
    },
Quentin David's avatar
Quentin David committed
255
256
257
258
    triggerError(errorMessage) {
      console.error(errorMessage);
      this.errorMessageToggle = true;
      this.errorMessage = errorMessage;
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
    },
    postCorpus(corpus) {
      try {
        axios.post('/corpora', corpus)
        .then( res => {
          if (res.data.status !== "success") {
            this.triggerError(res.data.message);
          }
          else {
            sessionStorage.setItem('corpusId', res.data.data.corpus._id);
            this.$router.push('/pipeline');
          }
        })
      }
      catch(error) { throw Error(error); }
274
    }
275
  }
276
}
Quentin David's avatar
Quentin David committed
277
278
279
280
</script>
<i18n>
{
  "fr": {
281
    "corpus-choice": "Choix du corpus",
Quentin David's avatar
Quentin David committed
282
283
284
285
286
287
288
289
    "next": "Suivant"
  },
  "en": {
    "corpus-choice": "Chose your corpus",
    "next": "Next"
  }
}
</i18n>