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 | def run_modelization_update_task(
project_id: str,
) -> None:
"""
Background task route for modelization update.
It performs the following actions : texts propressing, texts vectorization, constraints manager update.
Emit message to share progress, raise error and announce success.
Args:
project_id (str): The ID of the project.
"""
###
### Check parameters.
###
# Check project id : Case of unknown.
if project_id not in get_projects():
return
# Lock status file in order to check project status for this step.
with FileLock(str(DATA_DIRECTORY / project_id / "status.json.lock")):
###
### Load needed data.
###
# Load status file.
with open(DATA_DIRECTORY / project_id / "status.json", "r") as status_fileobject_r:
project_status: Dict[str, Any] = json.load(status_fileobject_r)
###
### Check parameters.
###
# Check project status.
working_state: Optional[ICGUIStates] = None
if project_status["state"] == ICGUIStates.INITIALIZATION_WITH_PENDING_MODELIZATION:
working_state = ICGUIStates.INITIALIZATION_WITH_WORKING_MODELIZATION
elif project_status["state"] == ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITH_PENDING_MODELIZATION:
working_state = ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITH_WORKING_MODELIZATION
elif project_status["state"] == ICGUIStates.IMPORT_AT_ANNOTATION_STEP_WITH_PENDING_MODELIZATION:
working_state = ICGUIStates.IMPORT_AT_ANNOTATION_STEP_WITH_WORKING_MODELIZATION
elif project_status["state"] == ICGUIStates.IMPORT_AT_CLUSTERING_STEP_WITH_PENDING_MODELIZATION:
working_state = ICGUIStates.IMPORT_AT_CLUSTERING_STEP_WITH_WORKING_MODELIZATION
elif project_status["state"] == ICGUIStates.IMPORT_AT_ITERATION_END_WITH_PENDING_MODELIZATION:
working_state = ICGUIStates.IMPORT_AT_ITERATION_END_WITH_WORKING_MODELIZATION
elif project_status["state"] == ICGUIStates.ANNOTATION_WITH_PENDING_MODELIZATION_WITHOUT_CONFLICTS:
working_state = ICGUIStates.ANNOTATION_WITH_WORKING_MODELIZATION_WITHOUT_CONFLICTS
elif project_status["state"] == ICGUIStates.ANNOTATION_WITH_PENDING_MODELIZATION_WITH_CONFLICTS:
working_state = ICGUIStates.ANNOTATION_WITH_WORKING_MODELIZATION_WITH_CONFLICTS
else:
return
# Update status.
update_project_status(
project_id=project_id,
task_progression=5,
task_detail="Lock the project for modelization update step.",
state=working_state,
)
# Get current iteration.
iteration_id: int = project_status["iteration_id"]
###
### Settings loading.
###
with FileLock(str(DATA_DIRECTORY / project_id / "status.json.lock")):
update_project_status(
project_id=project_id,
task_progression=10,
task_detail="Load settings.",
)
# Load settings file.
with open(DATA_DIRECTORY / project_id / "settings.json", "r") as settings_fileobject:
settings: Dict[str, Any] = json.load(settings_fileobject)
###
### Texts loading.
###
with FileLock(str(DATA_DIRECTORY / project_id / "status.json.lock")):
update_project_status(
project_id=project_id,
task_progression=15,
task_detail="Load texts.",
)
# Load texts
with open(DATA_DIRECTORY / project_id / "texts.json", "r") as texts_fileobject_r:
texts: Dict[str, Any] = json.load(texts_fileobject_r)
###
### Texts preprocessing.
###
with FileLock(str(DATA_DIRECTORY / project_id / "status.json.lock")):
update_project_status(
project_id=project_id,
task_progression=20,
task_detail="Preprocess texts.",
)
# Get all unpreprocessed texts.
dict_of_unpreprocessed_texts: Dict[str, str] = {
text_id_before_preprocessing: text_value_before_preprocessing["text"]
for text_id_before_preprocessing, text_value_before_preprocessing in texts.items()
}
# Preprocess all texts (even if text is deleted).
dict_of_preprocessed_texts: Dict[str, str] = preprocess(
dict_of_texts=dict_of_unpreprocessed_texts,
apply_stopwords_deletion=settings[str(iteration_id)]["preprocessing"]["apply_stopwords_deletion"],
apply_parsing_filter=settings[str(iteration_id)]["preprocessing"]["apply_parsing_filter"],
apply_lemmatization=settings[str(iteration_id)]["preprocessing"]["apply_lemmatization"],
spacy_language_model=settings[str(iteration_id)]["preprocessing"]["spacy_language_model"],
)
# Update texts with preprocessed values.
for text_id_with_preprocessing in texts.keys():
texts[text_id_with_preprocessing]["text_preprocessed"] = dict_of_preprocessed_texts[text_id_with_preprocessing]
# Store texts.
with open(DATA_DIRECTORY / project_id / "texts.json", "w") as texts_fileobject_w:
json.dump(
texts,
texts_fileobject_w,
indent=4,
)
###
### Texts vectorization.
###
with FileLock(str(DATA_DIRECTORY / project_id / "status.json.lock")):
update_project_status(
project_id=project_id,
task_progression=35,
task_detail="Vectorize texts.",
)
# Get managed preprocessed texts.
dict_of_managed_preprocessed_texts: Dict[str, str] = {
text_id_before_vectorization: text_value_before_vectorization["text_preprocessed"]
for text_id_before_vectorization, text_value_before_vectorization in texts.items()
if text_value_before_vectorization["is_deleted"] is False
}
# Vectorize texts (only if text is not deleted).
dict_of_managed_vectors: Dict[str, csr_matrix] = vectorize(
dict_of_texts=dict_of_managed_preprocessed_texts,
vectorizer_type=settings[str(iteration_id)]["vectorization"]["vectorizer_type"],
spacy_language_model=settings[str(iteration_id)]["vectorization"]["spacy_language_model"],
)
# Store vectors.
with open(DATA_DIRECTORY / project_id / "vectors.pkl", "wb") as vectors_fileobject:
pickle.dump(
dict_of_managed_vectors,
vectors_fileobject,
pickle.HIGHEST_PROTOCOL,
)
# Convert vectors into matrix.
vectors_ND: csr_matrix = vstack(
dict_of_managed_vectors[text_id_with_ND] for text_id_with_ND in dict_of_managed_vectors.keys()
)
###
### Texts vectorization in 2D.
###
with FileLock(str(DATA_DIRECTORY / project_id / "status.json.lock")):
update_project_status(
project_id=project_id,
task_progression=50,
task_detail="Reduce vectors to 2 dimensions.",
)
# Reduce vectors to 2 dimensions with TSNE.
vectors_2D: ndarray = TSNE(
n_components=2,
# learning_rate="auto", # Error on "scikit-learn==0.24.1" !
init="random",
random_state=settings[str(iteration_id)]["vectorization"]["random_seed"],
perplexity=min(30.0, vectors_ND.shape[0] - 1), # TSNE requirement.
).fit_transform(vectors_ND)
# Store 2D vectors.
with open(DATA_DIRECTORY / project_id / "vectors_2D.json", "w") as vectors_2D_fileobject:
json.dump(
{
text_id_with_2D: {
"x": float(vectors_2D[i_2D][0]),
"y": float(vectors_2D[i_2D][1]),
}
for i_2D, text_id_with_2D in enumerate(dict_of_managed_vectors.keys())
},
vectors_2D_fileobject,
indent=4,
)
###
### Texts vectorization in 3D.
###
with FileLock(str(DATA_DIRECTORY / project_id / "status.json.lock")):
update_project_status(
project_id=project_id,
task_progression=65,
task_detail="Reduce vectors to 3 dimensions.",
)
# Reduce vectors to 3 dimensions with TSNE.
vectors_3D: ndarray = TSNE(
n_components=3,
# learning_rate="auto", # Error on "scikit-learn==0.24.1" !
init="random",
random_state=settings[str(iteration_id)]["vectorization"]["random_seed"],
perplexity=min(30.0, vectors_ND.shape[0] - 1), # TSNE requirement.
).fit_transform(vectors_ND)
# Store 3D vectors.
with open(DATA_DIRECTORY / project_id / "vectors_3D.json", "w") as vectors_3D_fileobject:
json.dump(
{
text_id_with_3D: {
"x": float(vectors_3D[i_3D][0]),
"y": float(vectors_3D[i_3D][1]),
"z": float(vectors_3D[i_3D][2]),
}
for i_3D, text_id_with_3D in enumerate(dict_of_managed_vectors.keys())
},
vectors_3D_fileobject,
indent=4,
)
###
### Constraints manager regeneration.
###
with FileLock(str(DATA_DIRECTORY / project_id / "status.json.lock")):
update_project_status(
project_id=project_id,
task_progression=80,
task_detail="(Re)generate constraints manager.",
)
# Initialize constraints manager with managed texts IDs.
new_constraints_manager: BinaryConstraintsManager = BinaryConstraintsManager(
list_of_data_IDs=list(dict_of_managed_preprocessed_texts.keys())
)
# Load annotated constraints.
with open(DATA_DIRECTORY / project_id / "constraints.json", "r") as constraints_fileobject_r:
constraints: Dict[str, Any] = json.load(constraints_fileobject_r)
# First, reset `to_fix_conflict` status of all constraints.
for constraint_id in constraints.keys():
constraints[constraint_id]["to_fix_conflict"] = False
# Then, update constraints manager with "CANNOT_LINK" constraints.
for _, constraint_CL in constraints.items():
if constraint_CL["constraint_type"] == "CANNOT_LINK" and constraint_CL["is_hidden"] is False:
new_constraints_manager.add_constraint(
data_ID1=constraint_CL["data"]["id_1"],
data_ID2=constraint_CL["data"]["id_2"],
constraint_type="CANNOT_LINK",
) # No conflict can append, at this step the constraints manager handle only constraints of same type.
# Initialize conflicts counter.
number_of_conflicts: int = 0
# Finaly, update constraints manager with "MUST_LINK" constraints.
for constraint_ML_id, constraint_ML in constraints.items():
if constraint_ML["constraint_type"] == "MUST_LINK" and constraint_ML["is_hidden"] is False:
try:
new_constraints_manager.add_constraint(
data_ID1=constraint_ML["data"]["id_1"],
data_ID2=constraint_ML["data"]["id_2"],
constraint_type="MUST_LINK",
) # Conflicts can append.
except ValueError:
# Update conflicts status.
constraints[constraint_ML_id]["to_fix_conflict"] = True
number_of_conflicts += 1
# Store new constraints manager.
with open(DATA_DIRECTORY / project_id / "constraints_manager.pkl", "wb") as constraints_manager_fileobject:
pickle.dump(
new_constraints_manager,
constraints_manager_fileobject,
pickle.HIGHEST_PROTOCOL,
)
# Store updated constraints in file.
with open(DATA_DIRECTORY / project_id / "constraints.json", "w") as constraints_fileobject_w:
json.dump(constraints, constraints_fileobject_w, indent=4)
###
### Store modelization inference.
###
with FileLock(str(DATA_DIRECTORY / project_id / "status.json.lock")):
update_project_status(
project_id=project_id,
task_progression=95,
task_detail="Store modelization inference results.",
)
# Load modelization inference file.
with open(DATA_DIRECTORY / project_id / "modelization.json", "r") as modelization_fileobject_r:
modelization: Dict[str, Any] = json.load(modelization_fileobject_r)
# Get constraints transitivity.
constraints_transitivity: Dict[str, Dict[str, Dict[str, None]]] = (
new_constraints_manager._constraints_transitivity # noqa: WPS437
)
# Update modelization inference.
modelization = {}
for text_id_in_manager in new_constraints_manager.get_list_of_managed_data_IDs():
modelization[text_id_in_manager] = {
"MUST_LINK": list(constraints_transitivity[text_id_in_manager]["MUST_LINK"].keys()),
"CANNOT_LINK": list(constraints_transitivity[text_id_in_manager]["CANNOT_LINK"].keys()),
}
for component_id, component in enumerate(new_constraints_manager.get_connected_components()):
for text_id_in_component in component:
modelization[text_id_in_component]["COMPONENT"] = component_id
# Store updated modelization inference in file.
with open(DATA_DIRECTORY / project_id / "modelization.json", "w") as modelization_fileobject_w:
json.dump(modelization, modelization_fileobject_w, indent=4)
###
### End of task.
###
# Define the next state.
end_state: Optional[ICGUIStates] = None
if working_state == ICGUIStates.INITIALIZATION_WITH_WORKING_MODELIZATION:
end_state = (
ICGUIStates.CLUSTERING_TODO if (number_of_conflicts == 0) else ICGUIStates.INITIALIZATION_WITH_ERRORS
)
elif working_state == ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITH_WORKING_MODELIZATION:
end_state = (
ICGUIStates.SAMPLING_TODO if (number_of_conflicts == 0) else ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITH_ERRORS
)
elif working_state == ICGUIStates.IMPORT_AT_CLUSTERING_STEP_WITH_WORKING_MODELIZATION:
end_state = (
ICGUIStates.CLUSTERING_TODO
if (number_of_conflicts == 0)
else ICGUIStates.IMPORT_AT_CLUSTERING_STEP_WITH_ERRORS
)
elif working_state == ICGUIStates.IMPORT_AT_ITERATION_END_WITH_WORKING_MODELIZATION:
end_state = (
ICGUIStates.ITERATION_END if (number_of_conflicts == 0) else ICGUIStates.IMPORT_AT_ITERATION_END_WITH_ERRORS
)
#### elif working_state in {
#### ICGUIStates.IMPORT_AT_ANNOTATION_STEP_WITH_WORKING_MODELIZATION,
#### ICGUIStates.ANNOTATION_WITH_WORKING_MODELIZATION_WITHOUT_CONFLICTS,
#### ICGUIStates.ANNOTATION_WITH_WORKING_MODELIZATION_WITH_CONFLICTS,
#### }:
else:
end_state = (
ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION
if (number_of_conflicts == 0)
else ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS
)
# Lock status file in order to update project status.
with FileLock(str(DATA_DIRECTORY / project_id / "status.json.lock")):
update_project_status(
project_id=project_id,
task_progression=None,
task_detail=None,
state=end_state,
)
|