Skip to content

app

  • Name: cognitivefactory.interactive_clustering_gui.app
  • Description: Definition of FastAPI application and routes for interactive clustering graphical user interface.
  • Author: Erwan Schild
  • Created: 22/10/2021
  • Licence: CeCILL-C License v1.0 (https://cecill.info/licences.fr.html)

alive() async

Tell if the API is alive/healthy.

Returns:

Name Type Description
Response Response

An HTTP response with either 200 or 503 codes.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
@app.get(
    "/alive",
    tags=["app state"],
    status_code=status.HTTP_200_OK,
)
async def alive() -> Response:  # pragma: no cover
    """
    Tell if the API is alive/healthy.

    Returns:
        Response: An HTTP response with either 200 or 503 codes.
    """

    try:
        # Assert the volume can be reached.
        pathlib.Path(DATA_DIRECTORY / ".available").touch()
        # Or anything else asserting the API is healthy.
    except OSError:
        return Response(status_code=status.HTTP_503_SERVICE_UNAVAILABLE)
    return Response(status_code=status.HTTP_200_OK)

annotate_constraint(project_id=Path(..., description='The ID of the project.'), constraint_id=Path(..., description='The ID of the constraint.'), constraint_type=Query(None, description='The type of constraint to annotate. Defaults to `None`.')) async

Annotate a constraint.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')
constraint_id str

The ID of the constraint.

Path(..., description='The ID of the constraint.')
constraint_type Optional[ConstraintsValues]

The type of constraint to annotate. Defaults to None.

Query(None, description='The type of constraint to annotate. Defaults to `None`.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

HTTPException

Raises HTTP_404_NOT_FOUND if the constraint with id constraint_id to annotate doesn't exist.

HTTPException

Raises HTTP_403_FORBIDDEN if the current status of the project doesn't allow modification.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains the ID of annotated constraint.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
@app.put(
    "/api/projects/{project_id}/constraints/{constraint_id}/annotate",
    tags=["Constraints"],
    status_code=status.HTTP_202_ACCEPTED,
)
async def annotate_constraint(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
    constraint_id: str = Path(
        ...,
        description="The ID of the constraint.",
    ),
    constraint_type: Optional[ConstraintsValues] = Query(
        None,
        description="The type of constraint to annotate. Defaults to `None`.",
    ),
) -> Dict[str, Any]:
    """
    Annotate a constraint.

    Args:
        project_id (str): The ID of the project.
        constraint_id (str): The ID of the constraint.
        constraint_type (Optional[ConstraintsValues]): The type of constraint to annotate. Defaults to `None`.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the constraint with id `constraint_id` to annotate doesn't exist.
        HTTPException: Raises `HTTP_403_FORBIDDEN` if the current status of the project doesn't allow modification.

    Returns:
        Dict[str, Any]: A dictionary that contains the ID of annotated constraint.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # 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:
            project_status: Dict[str, Any] = json.load(status_fileobject)

        # Load constraints file.
        with open(DATA_DIRECTORY / project_id / "constraints.json", "r") as constraints_fileobject_r:
            constraints: Dict[str, Any] = json.load(constraints_fileobject_r)

        ###
        ### Check parameters.
        ###

        # Check constraint id.
        if constraint_id not in constraints.keys():
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="In project with id '{project_id_str}', the constraint with id '{constraint_id_str}' to annotate doesn't exist.".format(
                    project_id_str=str(project_id),
                    constraint_id_str=str(constraint_id),
                ),
            )

        # Check status.
        if (
            project_status["state"] != ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION  # noqa: WPS514
            and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
            and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS
        ):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="The project with id '{project_id_str}' doesn't allow modification during this state (state='{state_str}').".format(
                    project_id_str=str(project_id),
                    state_str=str(project_status["state"]),
                ),
            )

        ###
        ### Update data.
        ###

        # Update status by forcing "outdated" status.
        if project_status["state"] == ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION:
            project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
        #### elif project_status["state"] == ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS:
        ####    project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
        #### elif project_status["state"] == ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS:
        ####    project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS

        # Update constraints by updating the constraint history.
        constraints[constraint_id]["constraint_type_previous"].append(constraints[constraint_id]["constraint_type"])

        # Update constraints by annotating the constraint.
        constraints[constraint_id]["constraint_type"] = constraint_type
        constraints[constraint_id]["date_of_update"] = datetime.now().timestamp()

        # Force annotation status.
        constraints[constraint_id]["to_annotate"] = False

        ###
        ### Store updated data.
        ###

        # Store updated status in file.
        with open(DATA_DIRECTORY / project_id / "status.json", "w") as status_fileobject_w:
            json.dump(project_status, status_fileobject_w, indent=4)

        # 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)

    # Return statement.
    return {
        "project_id": project_id,
        "constraint_id": constraint_id,
        "detail": "In project with id '{project_id_str}', the constraint with id '{constraint_id_str}' has been annotated at `{constraint_type_str}`.".format(
            project_id_str=str(project_id),
            constraint_id_str=str(constraint_id),
            constraint_type_str="None" if (constraint_type is None) else str(constraint_type.value),
        ),
    }

approve_all_constraints(project_id=Path(..., description='The ID of the project.')) async

Approve all constraints.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

HTTPException

Raises HTTP_403_FORBIDDEN if the current status of the project doesn't allow constraints approbation.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains the confirmation of constraints approbation.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
@app.post(
    "/api/projects/{project_id}/constraints/approve",
    tags=["Constraints"],
    status_code=status.HTTP_201_CREATED,
)
async def approve_all_constraints(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
) -> Dict[str, Any]:
    """
    Approve all constraints.

    Args:
        project_id (str): The ID of the project.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.
        HTTPException: Raises `HTTP_403_FORBIDDEN` if the current status of the project doesn't allow constraints approbation.

    Returns:
        Dict[str, Any]: A dictionary that contains the confirmation of constraints approbation.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # Lock status file in order to check project status for this step.
    with FileLock(str(DATA_DIRECTORY / project_id / "status.json.lock")):
        # Load status file.
        with open(DATA_DIRECTORY / project_id / "status.json", "r") as status_fileobject:
            project_status: Dict[str, Any] = json.load(status_fileobject)

        # Check status.
        if project_status["state"] != ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="The project with id '{project_id_str}' doesn't allow constraints approbation during this state (state='{state_str}').".format(
                    project_id_str=str(project_id),
                    state_str=str(project_status["state"]),
                ),
            )

        ###
        ### Update data.
        ###

        # Update status to clustering step.
        project_status["state"] = ICGUIStates.CLUSTERING_TODO

        ###
        ### Store updated data.
        ###

        # Store updated status in file.
        with open(DATA_DIRECTORY / project_id / "status.json", "w") as status_fileobject_w:
            json.dump(project_status, status_fileobject_w, indent=4)

    # Return statement.
    return {
        "project_id": project_id,
        "detail": "In project with id '{project_id_str}', the constraints have been approved.".format(
            project_id_str=str(project_id),
        ),
    }

comment_constraint(project_id=Path(..., description='The ID of the project.'), constraint_id=Path(..., description='The ID of the constraint.'), constraint_comment=Query(..., description='The comment of constraint.', max_length=256)) async

Comment a constraint.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')
constraint_id str

The ID of the constraint.

Path(..., description='The ID of the constraint.')
constraint_comment str

The comment of constraint.

Query(..., description='The comment of constraint.', max_length=256)

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

HTTPException

Raises HTTP_404_NOT_FOUND if the constraint with id constraint_id to annotate doesn't exist.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains the ID of commented constraint.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
@app.put(
    "/api/projects/{project_id}/constraints/{constraint_id}/comment",
    tags=["Constraints"],
    status_code=status.HTTP_202_ACCEPTED,
)
async def comment_constraint(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
    constraint_id: str = Path(
        ...,
        description="The ID of the constraint.",
    ),
    constraint_comment: str = Query(
        ...,
        description="The comment of constraint.",
        # min_length=0,
        max_length=256,
    ),
) -> Dict[str, Any]:
    """
    Comment a constraint.

    Args:
        project_id (str): The ID of the project.
        constraint_id (str): The ID of the constraint.
        constraint_comment (str): The comment of constraint.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the constraint with id `constraint_id` to annotate doesn't exist.

    Returns:
        Dict[str, Any]: A dictionary that contains the ID of commented constraint.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # 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 constraints file.
        with open(DATA_DIRECTORY / project_id / "constraints.json", "r") as constraints_fileobject_r:
            constraints: Dict[str, Any] = json.load(constraints_fileobject_r)

        ###
        ### Check parameters.
        ###

        # Check constraint id.
        if constraint_id not in constraints.keys():
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="In project with id '{project_id_str}', the constraint with id '{constraint_id_str}' to annotate doesn't exist.".format(
                    project_id_str=str(project_id),
                    constraint_id_str=str(constraint_id),
                ),
            )

        ###
        ### Update data.
        ###

        # Update constraints by commenting the constraint.
        constraints[constraint_id]["comment"] = constraint_comment

        ###
        ### Store updated data.
        ###

        # 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)

    # Return statement.
    return {
        "project_id": project_id,
        "constraint_id": constraint_id,
        "constraint_comment": constraint_comment,
        "detail": "In project with id '{project_id_str}', the constraint with id '{constraint_id_str}' has been commented.".format(
            project_id_str=str(project_id),
            constraint_id_str=str(constraint_id),
        ),
    }

create_project(project_name=Query(..., description='The name of the project. Should not be an empty string.', min_length=3, max_length=64), dataset_file=File(..., description="The dataset file to load. Use a `.csv` (`;` separator) or `.xlsx` file. Please use a list of texts in the first column, without header, with encoding 'utf-8'.")) async

Create a project.

Parameters:

Name Type Description Default
project_name str

The name of the project. Should not be an empty string.

Query(..., description='The name of the project. Should not be an empty string.', min_length=3, max_length=64)
dataset_file UploadFile

The dataset file to load. Use a .csv (; separator) or .xlsx file. Please use a list of texts in the first column, without header, with encoding 'utf-8'.

File(..., description="The dataset file to load. Use a `.csv` (`;` separator) or `.xlsx` file. Please use a list of texts in the first column, without header, with encoding 'utf-8'.")

Raises:

Type Description
HTTPException

Raises HTTP_400_BAD_REQUEST if parameters project_name or dataset_file are invalid.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains the ID of the created project.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
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
@app.post(
    "/api/projects",
    tags=["Projects"],
    status_code=status.HTTP_201_CREATED,
)
async def create_project(
    project_name: str = Query(
        ...,
        description="The name of the project. Should not be an empty string.",
        min_length=3,
        max_length=64,
    ),
    dataset_file: UploadFile = File(
        ...,
        description="The dataset file to load. Use a `.csv` (`;` separator) or `.xlsx` file. Please use a list of texts in the first column, without header, with encoding 'utf-8'.",
        # TODO: max_size="8MB",
    ),
) -> Dict[str, Any]:
    """
    Create a project.

    Args:
        project_name (str): The name of the project. Should not be an empty string.
        dataset_file (UploadFile): The dataset file to load. Use a `.csv` (`;` separator) or `.xlsx` file. Please use a list of texts in the first column, without header, with encoding 'utf-8'.

    Raises:
        HTTPException: Raises `HTTP_400_BAD_REQUEST` if parameters `project_name` or `dataset_file` are invalid.

    Returns:
        Dict[str, Any]: A dictionary that contains the ID of the created project.
    """

    # Define the new project ID.
    current_timestamp: float = datetime.now().timestamp()
    current_project_id: str = str(int(current_timestamp * 10**6))

    # Check project name.
    if project_name.strip() == "":
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="The project name '{project_name_str}' is invalid.".format(
                project_name_str=str(project_name),
            ),
        )

    # Initialize variable to store loaded dataset.
    list_of_texts: List[str] = []

    # Load dataset: Case of `.csv` with `;` separator.
    if dataset_file.content_type in {"text/csv", "application/vnd.ms-excel"}:
        # "text/csv" == ".csv"
        # "application/vnd.ms-excel" == ".xls"
        try:  # noqa: WPS229  # Found too long `try` body length
            dataset_csv: pd.Dataframe = pd.read_csv(
                filepath_or_buffer=dataset_file.file,
                sep=";",
                header=None,  # No header expected in the csv file.
            )
            list_of_texts = dataset_csv[dataset_csv.columns[0]].tolist()
        except Exception:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="The dataset file is invalid. `.csv` file, with `;` separator, must contain a list of texts in the first column, with no header.",
            )
    # Load dataset: Case of `.xlsx`.
    elif dataset_file.content_type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
        # "application/vnd.ms-excel" == ".xlsx"
        try:  # noqa: WPS229  # Found too long `try` body length
            dataset_xlsx: pd.Dataframe = pd.read_excel(
                io=dataset_file.file.read(),
                engine="openpyxl",
                header=None,  # No header expected in the xlsx file.
            )
            list_of_texts = dataset_xlsx[dataset_xlsx.columns[0]].tolist()
        except Exception:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="The dataset file is invalid. `.xlsx` file must contain a list of texts in the first column, with no header.",
            )

    # Load dataset: case of not supported type.
    else:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="The file type '{dataset_file_type}' is not supported. Please use '.csv' (`;` separator) or '.xlsx' file.".format(
                dataset_file_type=str(dataset_file.content_type),
            ),
        )

    # Create the directory and subdirectories of the new project.
    os.mkdir(DATA_DIRECTORY / current_project_id)

    # Initialize storage of metadata.
    with open(DATA_DIRECTORY / current_project_id / "metadata.json", "w") as metadata_fileobject:
        json.dump(
            {
                "project_id": current_project_id,
                "project_name": str(project_name.strip()),
                "creation_timestamp": current_timestamp,
            },
            metadata_fileobject,
            indent=4,
        )

    # Initialize storage of status.
    with open(DATA_DIRECTORY / current_project_id / "status.json", "w") as status_fileobject:
        json.dump(
            {
                "iteration_id": 0,  # Use string format for JSON serialization in dictionaries.
                "state": ICGUIStates.INITIALIZATION_WITHOUT_MODELIZATION,
                "task": None,  # "progression", "detail".
            },
            status_fileobject,
            indent=4,
        )

    # Initialize storage of texts.
    with open(DATA_DIRECTORY / current_project_id / "texts.json", "w") as texts_fileobject:
        json.dump(
            {
                str(i): {
                    "text_original": str(text),  # Will never be changed.
                    "text": str(text),  # Can be change by renaming.
                    "text_preprocessed": str(text),  # Will be preprocessed during `Modelizationpdate` task.
                    "is_deleted": False,
                }
                for i, text in enumerate(list_of_texts)
            },
            texts_fileobject,
            indent=4,
        )

    # Initialize storage of constraints.
    with open(DATA_DIRECTORY / current_project_id / "constraints.json", "w") as constraints_fileobject:
        json.dump(
            {},  # Dict[str, Any]
            constraints_fileobject,
            indent=4,
        )

    # Initialize storage of modelization inference assignations.
    with open(DATA_DIRECTORY / current_project_id / "modelization.json", "w") as modelization_fileobject:
        json.dump(
            {str(i): {"MUST_LINK": [str(i)], "CANNOT_LINK": [], "COMPONENT": i} for i in range(len(list_of_texts))},
            modelization_fileobject,
            indent=4,
        )

    # Initialize settings storage.
    with open(DATA_DIRECTORY / current_project_id / "settings.json", "w") as settings_fileobject:
        json.dump(
            {
                "0": {
                    "preprocessing": default_PreprocessingSettingsModel().to_dict(),
                    "vectorization": default_VectorizationSettingsModel().to_dict(),
                    "clustering": default_ClusteringSettingsModel().to_dict(),
                },
            },
            settings_fileobject,
            indent=4,
        )

    # Initialize storage of sampling results.
    with open(DATA_DIRECTORY / current_project_id / "sampling.json", "w") as sampling_fileobject:
        json.dump({}, sampling_fileobject, indent=4)  # Dict[str, List[str]]

    # Initialize storage of clustering results.
    with open(DATA_DIRECTORY / current_project_id / "clustering.json", "w") as clustering_fileobject:
        json.dump({}, clustering_fileobject, indent=4)  # Dict[str, Dict[str, str]]

    # Return the ID of the created project.
    return {
        "project_id": current_project_id,
        "detail": (
            "The project with name '{project_name_str}' has been created. It has the id '{project_id_str}'.".format(
                project_name_str=str(project_name),
                project_id_str=str(current_project_id),
            )
        ),
    }

delete_project(project_id=Path(..., description='The ID of the project to delete.')) async

Delete a project.

Parameters:

Name Type Description Default
project_id str

The ID of the project to delete.

Path(..., description='The ID of the project to delete.')

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains the ID of the deleted project.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
@app.delete(
    "/api/projects/{project_id}",
    tags=["Projects"],
    status_code=status.HTTP_202_ACCEPTED,
)
async def delete_project(
    project_id: str = Path(
        ...,
        description="The ID of the project to delete.",
    ),
) -> Dict[str, Any]:
    """
    Delete a project.

    Args:
        project_id (str): The ID of the project to delete.

    Returns:
        Dict[str, Any]: A dictionary that contains the ID of the deleted project.
    """

    # Delete the project.
    if os.path.isdir(DATA_DIRECTORY / project_id):
        shutil.rmtree(DATA_DIRECTORY / project_id, ignore_errors=True)

    # Return the deleted project id.
    return {
        "project_id": project_id,
        "detail": "The deletion of project with id '{project_id_str}' is accepted.".format(
            project_id_str=str(project_id),
        ),
    }

delete_text(project_id=Path(..., description='The ID of the project.'), text_id=Path(..., description='The ID of the text.')) async

Delete a text.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')
text_id str

The ID of the text.

Path(..., description='The ID of the text.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

HTTPException

Raises HTTP_404_NOT_FOUND if the text with id text_id to delete doesn't exist.

HTTPException

Raises HTTP_403_FORBIDDEN if the current status of the project doesn't allow modification.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains the ID of deleted text.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
@app.put(
    "/api/projects/{project_id}/texts/{text_id}/delete",
    tags=["Texts"],
    status_code=status.HTTP_202_ACCEPTED,
)
async def delete_text(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
    text_id: str = Path(
        ...,
        description="The ID of the text.",
    ),
) -> Dict[str, Any]:
    """
    Delete a text.

    Args:
        project_id (str): The ID of the project.
        text_id (str): The ID of the text.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the text with id `text_id` to delete doesn't exist.
        HTTPException: Raises `HTTP_403_FORBIDDEN` if the current status of the project doesn't allow modification.

    Returns:
        Dict[str, Any]: A dictionary that contains the ID of deleted text.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # 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:
            project_status: Dict[str, Any] = json.load(status_fileobject)

        # Load texts file.
        with open(DATA_DIRECTORY / project_id / "texts.json", "r") as texts_fileobject_r:
            texts: Dict[str, Any] = json.load(texts_fileobject_r)

        # Load constraints file.
        with open(DATA_DIRECTORY / project_id / "constraints.json", "r") as constraints_fileobject_r:
            constraints: Dict[str, Any] = json.load(constraints_fileobject_r)

        ###
        ### Check parameters.
        ###

        # Check text id.
        if text_id not in texts.keys():
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="In project with id '{project_id_str}', the text with id '{text_id_str}' to delete doesn't exist.".format(
                    project_id_str=str(project_id),
                    text_id_str=str(text_id),
                ),
            )

        # Check status.
        if (
            project_status["state"] != ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION  # noqa: WPS514
            and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
            and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS
        ):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="The project with id '{project_id_str}' doesn't allow modification during this state (state='{state_str}').".format(
                    project_id_str=str(project_id),
                    state_str=str(project_status["state"]),
                ),
            )

        ###
        ### Update data.
        ###

        # Update status by forcing "outdated" status.
        if project_status["state"] == ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION:
            project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
        #### elif project_status["state"] == ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS:
        ####    project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
        #### elif project_status["state"] == ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS:
        ####    project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS

        # Update texts by deleting the text.
        texts[text_id]["is_deleted"] = True

        # Update constraints by hidding those associated with the deleted text.
        for constraint_id, constraint_value in constraints.items():
            data_id1: str = constraint_value["data"]["id_1"]
            data_id2: str = constraint_value["data"]["id_2"]

            if text_id in {
                data_id1,
                data_id2,
            }:
                constraints[constraint_id]["is_hidden"] = True

        ###
        ### Store updated data.
        ###

        # Store updated status in file.
        with open(DATA_DIRECTORY / project_id / "status.json", "w") as status_fileobject_w:
            json.dump(project_status, status_fileobject_w, indent=4)

        # Store updated texts in file.
        with open(DATA_DIRECTORY / project_id / "texts.json", "w") as texts_fileobject_w:
            json.dump(texts, texts_fileobject_w, indent=4)

        # 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)

    # Return statement.
    return {
        "project_id": project_id,
        "text_id": text_id,
        "detail": "In project with id '{project_id_str}', the text with id '{text_id_str}' has been deleted. Several constraints have been hidden.".format(
            project_id_str=str(project_id),
            text_id_str=str(text_id),
        ),
    }

download_project(background_tasks, project_id=Path(..., description='The ID of the project to download.')) async

Download a project in a zip archive.

Parameters:

Name Type Description Default
background_tasks BackgroundTasks

A background task to run after the return statement.

required
project_id str

The ID of the project to download.

Path(..., description='The ID of the project to download.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

Returns:

Name Type Description
FileResponse FileResponse

A zip archive of the project.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
@app.get(
    "/api/projects/{project_id}/download",
    tags=["Projects"],
    response_class=FileResponse,
    status_code=status.HTTP_200_OK,
)
async def download_project(
    background_tasks: BackgroundTasks,
    project_id: str = Path(
        ...,
        description="The ID of the project to download.",
    ),
) -> FileResponse:
    """
    Download a project in a zip archive.

    Args:
        background_tasks (BackgroundTasks): A background task to run after the return statement.
        project_id (str): The ID of the project to download.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.

    Returns:
        FileResponse: A zip archive of the project.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # Define archive name.
    archive_name: str = "archive-{project_id_str}.zip".format(project_id_str=str(project_id))
    archive_path: pathlib.Path = DATA_DIRECTORY / project_id / archive_name

    # Zip the project in an archive.
    with zipfile.ZipFile(archive_path, "w", zipfile.ZIP_DEFLATED) as archive_filewriter:
        archive_filewriter.write(DATA_DIRECTORY / project_id / "metadata.json", arcname="metadata.json")
        archive_filewriter.write(DATA_DIRECTORY / project_id / "status.json", arcname="status.json")
        archive_filewriter.write(DATA_DIRECTORY / project_id / "texts.json", arcname="texts.json")
        archive_filewriter.write(DATA_DIRECTORY / project_id / "constraints.json", arcname="constraints.json")
        archive_filewriter.write(DATA_DIRECTORY / project_id / "settings.json", arcname="settings.json")
        archive_filewriter.write(DATA_DIRECTORY / project_id / "sampling.json", arcname="sampling.json")
        archive_filewriter.write(DATA_DIRECTORY / project_id / "clustering.json", arcname="clustering.json")
        archive_filewriter.write(DATA_DIRECTORY / project_id / "modelization.json", arcname="modelization.json")
        if "vectors_2D.json" in os.listdir(DATA_DIRECTORY / project_id):
            archive_filewriter.write(DATA_DIRECTORY / project_id / "vectors_2D.json", arcname="vectors_2D.json")
        if "vectors_3D.json" in os.listdir(DATA_DIRECTORY / project_id):
            archive_filewriter.write(DATA_DIRECTORY / project_id / "vectors_3D.json", arcname="vectors_3D.json")

    # Define a backgroundtask to clear archive after downloading.
    def clear_after_download_project():  # noqa: WPS430 (nested function)
        """
        Delete the archive file.
        """

        # Delete archive file.
        if os.path.exists(archive_path):  # pragma: no cover
            os.remove(archive_path)

    # Add the background task.
    background_tasks.add_task(
        func=clear_after_download_project,
    )

    # Return the zip archive of the project.
    return FileResponse(
        archive_path,
        media_type="application/x-zip-compressed",
        filename=archive_name,
    )

get_constrained_clustering_results(project_id=Path(..., description='The ID of the project.'), iteration_id=Query(None, description='The ID of project iteration. If `None`, get the current iteration. Defaults to `None`.')) async

Get constrained clustering results.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')
iteration_id Optional[int]

The ID of project iteration. If None, get the current iteration. Defaults to None.

Query(None, description='The ID of project iteration. If `None`, get the current iteration. Defaults to `None`.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

HTTPException

Raises HTTP_404_NOT_FOUND if the iteration with id iteration_id doesn't exist.

HTTPException

Raises HTTP_403_FORBIDDEN if the status of the project hasn't completed its clustering step.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains clustering result.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
@app.get(
    "/api/projects/{project_id}/clustering",
    tags=["Constrained clustering"],
    status_code=status.HTTP_200_OK,
)
async def get_constrained_clustering_results(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
    iteration_id: Optional[int] = Query(
        None,
        description="The ID of project iteration. If `None`, get the current iteration. Defaults to `None`.",
    ),
) -> Dict[str, Any]:
    """
    Get constrained clustering results.

    Args:
        project_id (str, optional): The ID of the project.
        iteration_id (Optional[int], optional): The ID of project iteration. If `None`, get the current iteration. Defaults to `None`.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the iteration with id `iteration_id` doesn't exist.
        HTTPException: Raises `HTTP_403_FORBIDDEN` if the status of the project hasn't completed its clustering step.

    Returns:
        Dict[str, Any]: A dictionary that contains clustering result.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # Load status file.
    with open(DATA_DIRECTORY / project_id / "status.json", "r") as status_fileobject:
        project_status: Dict[str, Any] = json.load(status_fileobject)

    # Load clustering.
    with open(DATA_DIRECTORY / project_id / "clustering.json", "r") as clustering_fileobject:
        project_clustering: Dict[str, Dict[str, Any]] = json.load(clustering_fileobject)

    # Set iteration id if needed.
    if iteration_id is None:
        if (
            project_status["iteration_id"] == 0
            or project_status["state"] == ICGUIStates.ITERATION_END
            or project_status["state"] == ICGUIStates.IMPORT_AT_ITERATION_END_WITHOUT_MODELIZATION
            or project_status["state"] == ICGUIStates.IMPORT_AT_ITERATION_END_WITH_PENDING_MODELIZATION
            or project_status["state"] == ICGUIStates.IMPORT_AT_ITERATION_END_WITH_WORKING_MODELIZATION
            or project_status["state"] == ICGUIStates.IMPORT_AT_ITERATION_END_WITH_ERRORS
        ):
            iteration_id = project_status["iteration_id"]
        else:
            iteration_id = project_status["iteration_id"] - 1

    # Check project status.
    if (
        iteration_id == project_status["iteration_id"]
        and project_status["state"] != ICGUIStates.ITERATION_END
        and project_status["state"] != ICGUIStates.IMPORT_AT_ITERATION_END_WITHOUT_MODELIZATION
        and project_status["state"] != ICGUIStates.IMPORT_AT_ITERATION_END_WITH_PENDING_MODELIZATION
        and project_status["state"] != ICGUIStates.IMPORT_AT_ITERATION_END_WITH_WORKING_MODELIZATION
        and project_status["state"] != ICGUIStates.IMPORT_AT_ITERATION_END_WITH_ERRORS
    ):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="The project with id '{project_id_str}' hasn't completed its clustering step on iteration '{iteration_id_str}'.".format(
                project_id_str=str(project_id),
                iteration_id_str=str(iteration_id),
            ),
        )

    # Otherwise check that requested iteration id exist.
    if str(iteration_id) not in project_clustering.keys():
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' has no iteration with id '{iteration_id_str}'.".format(
                project_id_str=str(project_id),
                iteration_id_str=str(iteration_id),
            ),
        )

    # Return the project clustering.
    return {
        "project_id": project_id,
        "iteration_id": iteration_id,
        "clustering": project_clustering[str(iteration_id)],
    }

get_constraints(project_id=Path(..., description='The ID of the project.'), without_hidden_constraints=Query(True, description='The option to not return hidden constraints. Defaults to `True`.'), sorted_by=Query(ConstraintsSortOptions.ID, description='The option to sort constraints. Defaults to `ID`.'), sorted_reverse=Query(False, description='The option to reverse constraints order. Defaults to `False`.')) async

Get constraints.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')
without_hidden_constraints bool

The option to not return hidden constraints. Defaults to True.

Query(True, description='The option to not return hidden constraints. Defaults to `True`.')
sorted_by ConstraintsSortOptions

The option to sort constraints. Defaults to ID.

Query(ID, description='The option to sort constraints. Defaults to `ID`.')
sorted_reverse bool

The option to reverse constraints order. Defaults to False.

Query(False, description='The option to reverse constraints order. Defaults to `False`.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains constraints.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
@app.get(
    "/api/projects/{project_id}/constraints",
    tags=["Constraints"],
    status_code=status.HTTP_200_OK,
)
async def get_constraints(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
    without_hidden_constraints: bool = Query(
        True,
        description="The option to not return hidden constraints. Defaults to `True`.",
    ),
    sorted_by: ConstraintsSortOptions = Query(
        ConstraintsSortOptions.ID,
        description="The option to sort constraints. Defaults to `ID`.",
    ),
    sorted_reverse: bool = Query(
        False,
        description="The option to reverse constraints order. Defaults to `False`.",
    ),
    # TODO: filter_text
    # TODO: limit_size + offset
) -> Dict[str, Any]:
    """
    Get constraints.

    Args:
        project_id (str): The ID of the project.
        without_hidden_constraints (bool, optional): The option to not return hidden constraints. Defaults to `True`.
        sorted_by (ConstraintsSortOptions, optional): The option to sort constraints. Defaults to `ID`.
        sorted_reverse (bool, optional): The option to reverse constraints order. Defaults to `False`.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.

    Returns:
        Dict[str, Any]: A dictionary that contains constraints.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    ###
    ### Load needed data.
    ###

    # Load constraints.
    with open(DATA_DIRECTORY / project_id / "constraints.json", "r") as constraints_fileobject:
        constraints: Dict[str, Any] = {
            constraint_id: constraint_value
            for constraint_id, constraint_value in json.load(constraints_fileobject).items()
            if (without_hidden_constraints is False or constraint_value["is_hidden"] is False)
        }

    # Load texts.
    with open(DATA_DIRECTORY / project_id / "texts.json", "r") as texts_fileobject:
        texts: Dict[str, Any] = json.load(texts_fileobject)

    ###
    ### Sort constraints.
    ###

    # Define the values selection method.
    def get_value_for_constraints_sorting(  # noqa: WPS430 (nested function)
        constraint_to_sort: Tuple[str, Dict[str, Any]]
    ) -> Any:
        """Return the values expected for constraints sorting.

        Args:
            constraint_to_sort (Tuple[str, Dict[str, Any]]): A constraint (from `.items()`).

        Returns:
            Any: The expected values of the constraint need for the sort.
        """
        # By constraint id.
        if sorted_by == ConstraintsSortOptions.ID:
            return constraint_to_sort[0]
        # By texts.
        if sorted_by == ConstraintsSortOptions.TEXT:
            return (
                texts[constraint_to_sort[1]["data"]["id_1"]]["text"],
                texts[constraint_to_sort[1]["data"]["id_2"]]["text"],
            )
        # By constraint type.
        if sorted_by == ConstraintsSortOptions.CONSTRAINT_TYPE:
            return (
                constraint_to_sort[1]["constraint_type"] is None,
                constraint_to_sort[1]["constraint_type"] == "CANNOT_LINK",
                constraint_to_sort[1]["constraint_type"] == "MUST_LINK",
            )
        # By date of update.
        if sorted_by == ConstraintsSortOptions.DATE_OF_UPDATE:
            return constraint_to_sort[1]["date_of_update"] if constraint_to_sort[1]["date_of_update"] is not None else 0
        # By iteration of sampling.
        if sorted_by == ConstraintsSortOptions.ITERATION_OF_SAMPLING:
            return constraint_to_sort[1]["iteration_of_sampling"]
        # To annotation.
        if sorted_by == ConstraintsSortOptions.TO_ANNOTATE:
            return constraint_to_sort[1]["to_annotate"] is False
        # To review.
        if sorted_by == ConstraintsSortOptions.TO_REVIEW:
            return constraint_to_sort[1]["to_review"] is False
        # To fix conflict.
        #### if sorted_by == ConstraintsSortOptions.TO_FIX_CONFLICT:
        return constraint_to_sort[1]["to_fix_conflict"] is False

    # Sorted the constraints to return.
    sorted_constraints: Dict[str, Any] = dict(
        sorted(
            constraints.items(),
            key=get_value_for_constraints_sorting,
            reverse=sorted_reverse,
        )
    )

    # Return the requested constraints.
    return {
        "project_id": project_id,
        "constraints": sorted_constraints,
        # Get the request parameters.
        "parameters": {
            "without_hidden_constraints": without_hidden_constraints,
            "sorted_by": sorted_by.value,
            "sorted_reverse": sorted_reverse,
        },
    }

get_constraints_sampling_results(project_id=Path(..., description='The ID of the project.'), iteration_id=Query(None, description='The ID of project iteration. If `None`, get the current iteration. Defaults to `None`.')) async

Get constraints sampling results.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')
iteration_id Optional[int]

The ID of project iteration. If None, get the current iteration. Defaults to None.

Query(None, description='The ID of project iteration. If `None`, get the current iteration. Defaults to `None`.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

HTTPException

Raises HTTP_404_NOT_FOUND if the iteration with id iteration_id doesn't exist.

HTTPException

Raises HTTP_403_FORBIDDEN if the status of the project hasn't completed its sampling step.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains sampling result.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
@app.get(
    "/api/projects/{project_id}/sampling",
    tags=["Constraints sampling"],
    status_code=status.HTTP_200_OK,
)
async def get_constraints_sampling_results(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
    iteration_id: Optional[int] = Query(
        None,
        description="The ID of project iteration. If `None`, get the current iteration. Defaults to `None`.",
    ),
) -> Dict[str, Any]:
    """
    Get constraints sampling results.

    Args:
        project_id (str, optional): The ID of the project.
        iteration_id (Optional[int], optional): The ID of project iteration. If `None`, get the current iteration. Defaults to `None`.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the iteration with id `iteration_id` doesn't exist.
        HTTPException: Raises `HTTP_403_FORBIDDEN` if the status of the project hasn't completed its sampling step.

    Returns:
        Dict[str, Any]: A dictionary that contains sampling result.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # Load settings.
    with open(DATA_DIRECTORY / project_id / "settings.json", "r") as settings_fileobject:
        project_settings: Dict[str, Dict[str, Any]] = json.load(settings_fileobject)

    # Load status file.
    with open(DATA_DIRECTORY / project_id / "status.json", "r") as status_fileobject:
        project_status: Dict[str, Any] = json.load(status_fileobject)

    # Get current iteration id if needed.
    if iteration_id is None:
        if project_status["iteration_id"] == 0:
            iteration_id = 0
        elif (
            project_status["state"] == ICGUIStates.SAMPLING_TODO  # noqa: WPS514
            or project_status["state"] == ICGUIStates.SAMPLING_PENDING
            or project_status["state"] == ICGUIStates.SAMPLING_WORKING
            or project_status["state"] == ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITHOUT_MODELIZATION
            or project_status["state"] == ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITH_PENDING_MODELIZATION
            or project_status["state"] == ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITH_WORKING_MODELIZATION
            or project_status["state"] == ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITH_ERRORS
        ):
            iteration_id = project_status["iteration_id"] - 1
        else:
            iteration_id = project_status["iteration_id"]

    # Case of iteration `0`.
    if iteration_id == 0:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="The iteration `0` has no sampling step.",
        )

    # Check project status.
    if iteration_id == project_status["iteration_id"] and (
        project_status["state"] == ICGUIStates.SAMPLING_TODO  # noqa: WPS514
        or project_status["state"] == ICGUIStates.SAMPLING_PENDING
        or project_status["state"] == ICGUIStates.SAMPLING_WORKING
        or project_status["state"] == ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITHOUT_MODELIZATION
        or project_status["state"] == ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITH_PENDING_MODELIZATION
        or project_status["state"] == ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITH_WORKING_MODELIZATION
        or project_status["state"] == ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITH_ERRORS
    ):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="The project with id '{project_id_str}' hasn't completed its sampling step on iteration '{iteration_id_str}'.".format(
                project_id_str=str(project_id),
                iteration_id_str=str(iteration_id),
            ),
        )

    # Otherwise check that requested iteration id exist.
    if str(iteration_id) not in project_settings.keys():
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' has no iteration with id '{iteration_id_str}'.".format(
                project_id_str=str(project_id),
                iteration_id_str=str(iteration_id),
            ),
        )

    # Load the sampling results.
    with open(DATA_DIRECTORY / project_id / "sampling.json", "r") as sampling_fileobject:
        # Return the project sampling.
        return {
            "project_id": project_id,
            "iteration_id": iteration_id,
            "sampling": json.load(sampling_fileobject)[str(iteration_id)],
        }

get_html_constraint_annotation_page(request, project_id=Path(..., description='The ID of the project.'), constraint_id=Path(..., description='The ID of the constraint.')) async

Get HTML constraint annotation page.

Parameters:

Name Type Description Default
request Request

The request context.

required
project_id str

The ID of the project.

Path(..., description='The ID of the project.')
constraint_id str

The ID of the constraint.

Path(..., description='The ID of the constraint.')

Returns:

Name Type Description
Response Response

The requested page.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
@app.get(
    "/gui/projects/{project_id}/constraints/{constraint_id}",
    tags=["Constraints"],
    response_class=Response,
    status_code=status.HTTP_200_OK,
)
async def get_html_constraint_annotation_page(
    request: Request,
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
    constraint_id: str = Path(
        ...,
        description="The ID of the constraint.",
    ),
) -> Response:
    """
    Get HTML constraint annotation page.

    Args:
        request (Request):  The request context.
        project_id (str): The ID of the project.
        constraint_id (str): The ID of the constraint.

    Returns:
        Response: The requested page.
    """

    # Return HTML constraints page.
    try:
        return templates.TemplateResponse(
            name="constraint_annotation.html",
            context={
                "request": request,
                # Get the project ID.
                "project_id": project_id,
                # Get the constraints ID.
                "constraint_id": constraint_id,
                # Get the project metadata (ID, name, creation date).
                "metadata": (await get_metadata(project_id=project_id))["metadata"],
                # Get the project status (iteration, step name and status, modelization state and conflict).
                "status": (await get_status(project_id=project_id))["status"],
                # Get the project texts.
                "texts": (
                    await get_texts(
                        project_id=project_id,
                        without_deleted_texts=False,
                        sorted_by=TextsSortOptions.ID,
                        sorted_reverse=False,
                    )
                )["texts"],
                "texts_html_escaped": {  # TODO: Escape HTML for javascript
                    text_id: {  # Force HTML escape.
                        key: html.escape(value) if key in {"text_original", "text", "text_preprocessed"} else value
                        for key, value in text_value.items()
                    }
                    for text_id, text_value in (
                        await get_texts(
                            project_id=project_id,
                            without_deleted_texts=False,
                            sorted_by=TextsSortOptions.ID,
                            sorted_reverse=False,
                        )
                    )["texts"].items()
                },
                # Get the project constraints.
                "constraints": (
                    await get_constraints(
                        project_id=project_id,
                        without_hidden_constraints=False,
                        sorted_by=ConstraintsSortOptions.TO_ANNOTATE,
                        sorted_reverse=False,
                    )
                )["constraints"],
                # Get the project clustering result.
                "clusters": (await get_constrained_clustering_results(project_id=project_id, iteration_id=None))[
                    "clustering"
                ],
                # Get the project modelization inference result.
                "modelization": (await get_modelization(project_id=project_id))["modelization"],
            },
            status_code=status.HTTP_200_OK,
        )

    # Case of error: Return HTML error page.
    except HTTPException as error:
        # Return HTML error page.
        return templates.TemplateResponse(
            name="error.html",
            context={
                "request": request,
                "status_code": error.status_code,
                "detail": error.detail,
            },
            status_code=error.status_code,
        )

get_html_constraints_page(request, project_id=Path(..., description='The ID of the project.'), sorted_by=Query(ConstraintsSortOptions.ITERATION_OF_SAMPLING, description='The option to sort constraints. Defaults to `ITERATION_OF_SAMPLING`.'), sorted_reverse=Query(False, description='The option to reverse constraints order. Defaults to `False`.')) async

Get HTML constraints page.

Parameters:

Name Type Description Default
request Request

The request context.

required
project_id str

The ID of the project.

Path(..., description='The ID of the project.')
sorted_by ConstraintsSortOptions

The option to sort constraints. Defaults to ITERATION_OF_SAMPLING.

Query(ITERATION_OF_SAMPLING, description='The option to sort constraints. Defaults to `ITERATION_OF_SAMPLING`.')
sorted_reverse bool

The option to reverse constraints order. Defaults to False.

Query(False, description='The option to reverse constraints order. Defaults to `False`.')

Returns:

Name Type Description
Response Response

The requested page.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
@app.get(
    "/gui/projects/{project_id}/constraints",
    tags=["Constraints"],
    response_class=Response,
    status_code=status.HTTP_200_OK,
)
async def get_html_constraints_page(
    request: Request,
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
    sorted_by: ConstraintsSortOptions = Query(
        ConstraintsSortOptions.ITERATION_OF_SAMPLING,
        description="The option to sort constraints. Defaults to `ITERATION_OF_SAMPLING`.",
    ),
    sorted_reverse: bool = Query(
        False,
        description="The option to reverse constraints order. Defaults to `False`.",
    ),
    # TODO: filter_text
    # TODO: limit_size + offset
) -> Response:
    """
    Get HTML constraints page.

    Args:
        request (Request): The request context.
        project_id (str): The ID of the project.
        sorted_by (ConstraintsSortOptions, optional): The option to sort constraints. Defaults to `ITERATION_OF_SAMPLING`.
        sorted_reverse (bool, optional): The option to reverse constraints order. Defaults to `False`.

    Returns:
        Response: The requested page.
    """

    # Return HTML constraints page.
    try:
        return templates.TemplateResponse(
            name="constraints.html",
            context={
                "request": request,
                # Get the project ID.
                "project_id": project_id,
                # Get the request parameters.
                "parameters": {
                    "without_hidden_constraints": True,
                    "sorted_by": sorted_by.value,
                    "sorted_reverse": sorted_reverse,
                },
                # Get the project metadata (ID, name, creation date).
                "metadata": (await get_metadata(project_id=project_id))["metadata"],
                # Get the project status (iteration, step name and status, modelization state and conflict).
                "status": (await get_status(project_id=project_id))["status"],
                # Get the project texts.
                "texts": (
                    await get_texts(
                        project_id=project_id,
                        without_deleted_texts=False,
                        sorted_by=TextsSortOptions.ID,
                        sorted_reverse=False,
                    )
                )["texts"],
                # Get the project constraints.
                "constraints": (
                    await get_constraints(
                        project_id=project_id,
                        without_hidden_constraints=True,
                        sorted_by=sorted_by,
                        sorted_reverse=sorted_reverse,
                    )
                )["constraints"],
            },
            status_code=status.HTTP_200_OK,
        )

    # Case of error: Return HTML error page.
    except HTTPException as error:
        # Return HTML error page.
        return templates.TemplateResponse(
            name="error.html",
            context={
                "request": request,
                "status_code": error.status_code,
                "detail": error.detail,
            },
            status_code=error.status_code,
        )

get_html_help_page(request) async

Get HTML help page.

Parameters:

Name Type Description Default
request Request

The request context.

required

Returns:

Name Type Description
Response Response

The requested page.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
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
@app.get(
    "/gui/help",
    tags=["Home and Documentation"],
    response_class=Response,
    status_code=status.HTTP_200_OK,
)
async def get_html_help_page(
    request: Request,
) -> Response:
    """
    Get HTML help page.

    Args:
        request (Request): The request context.

    Returns:
        Response: The requested page.
    """

    # Return HTML help page.
    return templates.TemplateResponse(
        name="help.html",
        context={
            "request": request,
        },
        status_code=status.HTTP_200_OK,
    )

get_html_project_home_page(request, project_id=Path(..., description='The ID of the project.')) async

Get HTML project home page.

Parameters:

Name Type Description Default
request Request

The request context.

required
project_id str

The ID of the project.

Path(..., description='The ID of the project.')

Returns:

Name Type Description
Response Response

The requested page.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
@app.get(
    "/gui/projects/{project_id}",
    tags=["Projects"],
    response_class=Response,
    status_code=status.HTTP_200_OK,
)
async def get_html_project_home_page(
    request: Request,
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
) -> Response:
    """
    Get HTML project home page.

    Args:
        request (Request): The request context.
        project_id (str): The ID of the project.

    Returns:
        Response: The requested page.
    """

    # Return HTML project home page.
    try:
        return templates.TemplateResponse(
            name="project_home.html",
            context={
                "request": request,
                # Get the project ID.
                "project_id": project_id,
                # Get the project metadata (ID, name, creation date).
                "metadata": (await get_metadata(project_id=project_id))["metadata"],
                # Get the project status (iteration, step name and status, modelization state and conflict).
                "status": (await get_status(project_id=project_id))["status"],
                # Get the project constraints.
                "constraints": (
                    await get_constraints(
                        project_id=project_id,
                        without_hidden_constraints=True,
                        sorted_by=ConstraintsSortOptions.ITERATION_OF_SAMPLING,
                        sorted_reverse=False,
                    )
                )["constraints"],
            },
            status_code=status.HTTP_200_OK,
        )

    # Case of error: Return HTML error page.
    except HTTPException as error:
        # Return HTML error page.
        return templates.TemplateResponse(
            name="error.html",
            context={
                "request": request,
                "status_code": error.status_code,
                "detail": error.detail,
            },
            status_code=error.status_code,
        )

get_html_settings_page(request, project_id=Path(..., description='The ID of the project.'), iteration_id=Query(None, description='The ID of project iteration. If `None`, get the current iteration. Defaults to `None`.'), settings_names=Query([ICGUISettings.PREPROCESSING, ICGUISettings.VECTORIZATION, ICGUISettings.SAMPLING, ICGUISettings.CLUSTERING], description='The list of names of requested settings to return. To select multiple settings kinds, use `CTRL + clic`.')) async

Get HTML settings page.

Parameters:

Name Type Description Default
request Request

The request context.

required
project_id str

The ID of the project.

Path(..., description='The ID of the project.')
iteration_id Optional[int]

The ID of project iteration. If None, get the current iteration. Defaults to None.

Query(None, description='The ID of project iteration. If `None`, get the current iteration. Defaults to `None`.')
settings_names List[ICGUISettings]

The list of names of requested settings to return. Defaults to [ICGUISettings.PREPROCESSING, ICGUISettings.VECTORIZATION, ICGUISettings.SAMPLING, ICGUISettings.CLUSTERING,].

Query([PREPROCESSING, VECTORIZATION, SAMPLING, CLUSTERING], description='The list of names of requested settings to return. To select multiple settings kinds, use `CTRL + clic`.')

Returns:

Name Type Description
Response Response

The requested page.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
@app.get(
    "/gui/projects/{project_id}/settings",
    tags=["Settings"],
    response_class=Response,
    status_code=status.HTTP_200_OK,
)
async def get_html_settings_page(
    request: Request,
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
    iteration_id: Optional[int] = Query(
        None,
        description="The ID of project iteration. If `None`, get the current iteration. Defaults to `None`.",
    ),
    settings_names: List[ICGUISettings] = Query(
        [
            ICGUISettings.PREPROCESSING,
            ICGUISettings.VECTORIZATION,
            ICGUISettings.SAMPLING,
            ICGUISettings.CLUSTERING,
        ],
        description="The list of names of requested settings to return. To select multiple settings kinds, use `CTRL + clic`.",
    ),
) -> Response:
    """
    Get HTML settings page.

    Args:
        request (Request): The request context.
        project_id (str): The ID of the project.
        iteration_id (Optional[int], optional): The ID of project iteration. If `None`, get the current iteration. Defaults to `None`.
        settings_names (List[ICGUISettings], optional): The list of names of requested settings to return. Defaults to `[ICGUISettings.PREPROCESSING, ICGUISettings.VECTORIZATION, ICGUISettings.SAMPLING, ICGUISettings.CLUSTERING,]`.

    Returns:
        Response: The requested page.
    """

    # Return HTML project home page.
    try:  # noqa: WPS229 (too long try body)
        project_status: Dict[str, Any] = (await get_status(project_id=project_id))["status"]
        if iteration_id is None:
            iteration_id = project_status["iteration_id"]

        return templates.TemplateResponse(
            name="settings.html",
            context={
                "request": request,
                # Get the project ID.
                "project_id": project_id,
                # Get the iteration ID.
                "iteration_id": iteration_id,
                # Get the request parameters.
                "parameters": {
                    "settings_names": [settings_name.value for settings_name in settings_names],
                },
                # Get the project metadata (ID, name, creation date).
                "metadata": (await get_metadata(project_id=project_id))["metadata"],
                # Get the project status (iteration, step name and status, modelization state and conflict).
                "status": project_status,
                # Get the project settings (preprocessing, vectorization, sampling, clustering).
                "settings": (
                    await get_settings(project_id=project_id, iteration_id=iteration_id, settings_names=settings_names)
                )["settings"],
                # Get navigation information.
                "navigation": {
                    "previous": None if (iteration_id == 0) else iteration_id - 1,
                    "next": None if (iteration_id == project_status["iteration_id"]) else (iteration_id + 1),
                },
            },
            status_code=status.HTTP_200_OK,
        )

    # Case of error: Return HTML error page.
    except HTTPException as error:
        # Return HTML error page.
        return templates.TemplateResponse(
            name="error.html",
            context={
                "request": request,
                "status_code": error.status_code,
                "detail": error.detail,
            },
            status_code=error.status_code,
        )

get_html_texts_page(request, project_id=Path(..., description='The ID of the project.'), sorted_by=Query(TextsSortOptions.ALPHABETICAL, description='The option to sort texts. Defaults to `ALPHABETICAL`.'), sorted_reverse=Query(False, description='The option to reverse texts order. Defaults to `False`.')) async

Get HTML texts page.

Parameters:

Name Type Description Default
request Request

The request context.

required
project_id str

The ID of the project.

Path(..., description='The ID of the project.')
sorted_by TextsSortOptions

The option to sort texts. Defaults to ALPHABETICAL.

Query(ALPHABETICAL, description='The option to sort texts. Defaults to `ALPHABETICAL`.')
sorted_reverse bool

The option to reverse texts order. Defaults to False.

Query(False, description='The option to reverse texts order. Defaults to `False`.')

Returns:

Name Type Description
Response Response

The requested page.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
@app.get(
    "/gui/projects/{project_id}/texts",
    tags=["Texts"],
    response_class=Response,
    status_code=status.HTTP_200_OK,
)
async def get_html_texts_page(
    request: Request,
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
    sorted_by: TextsSortOptions = Query(
        TextsSortOptions.ALPHABETICAL,
        description="The option to sort texts. Defaults to `ALPHABETICAL`.",
    ),
    sorted_reverse: bool = Query(
        False,
        description="The option to reverse texts order. Defaults to `False`.",
    ),
    # TODO: filter_text
    # TODO: limit_size + offset
) -> Response:
    """
    Get HTML texts page.

    Args:
        request (Request): The request context.
        project_id (str): The ID of the project.
        sorted_by (TextsSortOptions, optional): The option to sort texts. Defaults to `ALPHABETICAL`.
        sorted_reverse (bool, optional): The option to reverse texts order. Defaults to `False`.

    Returns:
        Response: The requested page.
    """

    # Return HTML constraints page.
    try:
        return templates.TemplateResponse(
            name="texts.html",
            context={
                "request": request,
                # Get the project ID.
                "project_id": project_id,
                # Get the request parameters.
                "parameters": {
                    "without_deleted_texts": True,
                    "sorted_by": sorted_by.value,
                    "sorted_reverse": sorted_reverse,
                },
                # Get the project metadata (ID, name, creation date).
                "metadata": (await get_metadata(project_id=project_id))["metadata"],
                # Get the project status (iteration, step name and status, modelization state and conflict).
                "status": (await get_status(project_id=project_id))["status"],
                # Get the project texts.
                "texts": (
                    await get_texts(
                        project_id=project_id,
                        without_deleted_texts=False,
                        sorted_by=sorted_by,
                        sorted_reverse=sorted_reverse,
                    )
                )["texts"],
                # Get the project constraints.
                "constraints": (
                    await get_constraints(
                        project_id=project_id,
                        without_hidden_constraints=True,
                        sorted_by=ConstraintsSortOptions.ID,
                        sorted_reverse=False,
                    )
                )["constraints"],
            },
            status_code=status.HTTP_200_OK,
        )

    # Case of error: Return HTML error page.
    except HTTPException as error:
        # Return HTML error page.
        return templates.TemplateResponse(
            name="error.html",
            context={
                "request": request,
                "status_code": error.status_code,
                "detail": error.detail,
            },
            status_code=error.status_code,
        )

get_html_welcome_page(request) async

Define HTML welcome page with projects listings.

Parameters:

Name Type Description Default
request Request

The request context.

required

Returns:

Name Type Description
Response Response

The requested page.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
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
@app.get(
    "/",
    tags=["Home and Documentation"],
    response_class=Response,
    status_code=status.HTTP_200_OK,
)
async def get_html_welcome_page(
    request: Request,
) -> Response:
    """
    Define HTML welcome page with projects listings.

    Args:
        request (Request): The request context.

    Returns:
        Response: The requested page.
    """

    # Return HTML welcome page.
    return templates.TemplateResponse(
        name="welcome.html",
        context={
            "request": request,
            # Get projects and their description.
            "projects": {
                project_id: {
                    "metadata": (await get_metadata(project_id=project_id))["metadata"],
                    "status": (await get_status(project_id=project_id))["status"],
                }
                for project_id in (await get_projects())
            },
        },
        status_code=status.HTTP_200_OK,
    )

get_metadata(project_id=Path(..., description='The ID of the project.')) async

Get metadata.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains metadata.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
@app.get(
    "/api/projects/{project_id}/metadata",
    tags=["Projects"],
    status_code=status.HTTP_200_OK,
)
async def get_metadata(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
) -> Dict[str, Any]:
    """
    Get metadata.

    Args:
        project_id (str): The ID of the project.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.

    Returns:
        Dict[str, Any]: A dictionary that contains metadata.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # Load the project metadata.
    with open(DATA_DIRECTORY / project_id / "metadata.json", "r") as metadata_fileobject:
        # Return the project metadata.
        return {
            "project_id": project_id,
            "metadata": json.load(metadata_fileobject),
        }

get_modelization(project_id=Path(..., description='The ID of the project.')) async

Get modelization inference.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains modelization inference result.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
@app.get(
    "/api/projects/{project_id}/modelization",
    tags=["Data modelization"],
    status_code=status.HTTP_200_OK,
)
async def get_modelization(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
) -> Dict[str, Any]:
    """
    Get modelization inference.

    Args:
        project_id (str, optional): The ID of the project.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.

    Returns:
        Dict[str, Any]: A dictionary that contains modelization inference result.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # Load the modelization inference results.
    with open(DATA_DIRECTORY / project_id / "modelization.json", "r") as modelization_fileobject:
        # Return the project modelization inference.
        return {
            "project_id": project_id,
            "modelization": json.load(modelization_fileobject),
        }

get_next_key(key, dictionary)

Get next key in a dictionary.

Parameters:

Name Type Description Default
key str

The current key.

required
dictionary Dict[str, Any]

The dictionary.

required

Returns:

Type Description
Optional[str]

Optional[str]: The next key.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def get_next_key(key: str, dictionary: Dict[str, Any]) -> Optional[str]:
    """
    Get next key in a dictionary.

    Args:
        key (str): The current key.
        dictionary (Dict[str, Any]): The dictionary.

    Returns:
        Optional[str]: The next key.
    """
    list_of_keys: List[str] = list(dictionary.keys())
    if key in list_of_keys:
        next_key_index: int = list_of_keys.index(key) + 1
        return list_of_keys[next_key_index] if next_key_index < len(list_of_keys) else None
    return None

get_previous_key(key, dictionary)

Get previous key in a dictionary.

Parameters:

Name Type Description Default
key str

The current key.

required
dictionary Dict[str, Any]

The dictionary.

required

Returns:

Type Description
Optional[str]

Optional[str]: The previous key.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def get_previous_key(key: str, dictionary: Dict[str, Any]) -> Optional[str]:
    """
    Get previous key in a dictionary.

    Args:
        key (str): The current key.
        dictionary (Dict[str, Any]): The dictionary.

    Returns:
        Optional[str]: The previous key.
    """
    list_of_keys: List[str] = list(dictionary.keys())
    if key in list_of_keys:
        previous_key_index: int = list_of_keys.index(key) - 1
        return list_of_keys[previous_key_index] if 0 <= previous_key_index else None
    return None

get_projects() async

Get the list of existing project IDs. (A project is represented by a subfolder in .data folder.)

Returns:

Type Description
List[str]

List[str]: The list of existing project IDs.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
@app.get(
    "/api/projects",
    tags=["Projects"],
    status_code=status.HTTP_200_OK,
)
async def get_projects() -> List[str]:
    """
    Get the list of existing project IDs.
    (A project is represented by a subfolder in `.data` folder.)

    Returns:
        List[str]: The list of existing project IDs.
    """

    # Return the list of project IDs.
    return [project_id for project_id in os.listdir(DATA_DIRECTORY) if os.path.isdir(DATA_DIRECTORY / project_id)]

get_settings(project_id=Path(..., description='The ID of the project.'), iteration_id=Query(None, description='The ID of project iteration. If `None`, get the current iteration. Defaults to `None`.'), settings_names=Query([ICGUISettings.PREPROCESSING, ICGUISettings.VECTORIZATION, ICGUISettings.SAMPLING, ICGUISettings.CLUSTERING], description='The list of names of requested settings to return. To select multiple settings kinds, use `CTRL + clic`.')) async

Get settings.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')
iteration_id Optional[int]

The ID of project iteration. If None, get the current iteration. Defaults to None.

Query(None, description='The ID of project iteration. If `None`, get the current iteration. Defaults to `None`.')
settings_names List[ICGUISettings]

The list of names of requested settings to return. Defaults to [ICGUISettings.PREPROCESSING, ICGUISettings.VECTORIZATION, ICGUISettings.SAMPLING, ICGUISettings.CLUSTERING,].

Query([PREPROCESSING, VECTORIZATION, SAMPLING, CLUSTERING], description='The list of names of requested settings to return. To select multiple settings kinds, use `CTRL + clic`.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

HTTPException

Raises HTTP_404_NOT_FOUND if the iteration with id iteration_id doesn't exist.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains settings.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
@app.get(
    "/api/projects/{project_id}/settings",
    tags=["Settings"],
    status_code=status.HTTP_200_OK,
)
async def get_settings(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
    iteration_id: Optional[int] = Query(
        None,
        description="The ID of project iteration. If `None`, get the current iteration. Defaults to `None`.",
    ),
    settings_names: List[ICGUISettings] = Query(
        [
            ICGUISettings.PREPROCESSING,
            ICGUISettings.VECTORIZATION,
            ICGUISettings.SAMPLING,
            ICGUISettings.CLUSTERING,
        ],
        description="The list of names of requested settings to return. To select multiple settings kinds, use `CTRL + clic`.",
    ),
) -> Dict[str, Any]:
    """
    Get settings.

    Args:
        project_id (str): The ID of the project.
        iteration_id (Optional[int], optional): The ID of project iteration. If `None`, get the current iteration. Defaults to `None`.
        settings_names (List[ICGUISettings], optional): The list of names of requested settings to return. Defaults to `[ICGUISettings.PREPROCESSING, ICGUISettings.VECTORIZATION, ICGUISettings.SAMPLING, ICGUISettings.CLUSTERING,]`.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the iteration with id `iteration_id` doesn't exist.

    Returns:
        Dict[str, Any]: A dictionary that contains settings.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # Load settings.
    with open(DATA_DIRECTORY / project_id / "settings.json", "r") as settings_fileobject:
        project_settings: Dict[str, Dict[str, Any]] = json.load(settings_fileobject)

    # Load status file.
    with open(DATA_DIRECTORY / project_id / "status.json", "r") as status_fileobject:
        project_status: Dict[str, Any] = json.load(status_fileobject)

    # Get current iteration id if needed.
    if iteration_id is None:
        iteration_id = project_status["iteration_id"]

    # Otherwise check that requested iteration id exist.
    if str(iteration_id) not in project_settings.keys():
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' has no iteration with id '{iteration_id_str}'.".format(
                project_id_str=str(project_id),
                iteration_id_str=str(iteration_id),
            ),
        )

    # Return the requested settings.
    return {
        # Get the project ID.
        "project_id": project_id,
        # Get the iteration ID.
        "iteration_id": iteration_id,
        # Get the request parameters.
        "parameters": {
            "settings_names": [settings_name.value for settings_name in settings_names],
        },
        # Get the settings.
        "settings": {
            setting_name: settings_value
            for setting_name, settings_value in project_settings[str(iteration_id)].items()
            if setting_name in settings_names
        },
    }

get_status(project_id=Path(..., description='The ID of the project.')) async

Get status.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains status.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
@app.get(
    "/api/projects/{project_id}/status",
    tags=["Status"],
    status_code=status.HTTP_200_OK,
)
async def get_status(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
) -> Dict[str, Any]:
    """
    Get status.

    Args:
        project_id (str): The ID of the project.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.

    Returns:
        Dict[str, Any]: A dictionary that contains status.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # Load status file.
    with open(DATA_DIRECTORY / project_id / "status.json", "r") as status_fileobject:
        project_status: Dict[str, Any] = json.load(status_fileobject)
        project_status["state_details"] = get_ICGUIStates_details(state=project_status["state"])

        # Return the requested status.
        return {"project_id": project_id, "status": project_status}

get_texts(project_id=Path(..., description='The ID of the project.'), without_deleted_texts=Query(True, description='The option to not return deleted texts. Defaults to `True`.'), sorted_by=Query(TextsSortOptions.ALPHABETICAL, description='The option to sort texts. Defaults to `ALPHABETICAL`.'), sorted_reverse=Query(False, description='The option to reverse texts order. Defaults to `False`.')) async

Get texts.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')
without_deleted_texts bool

The option to not return deleted texts. Defaults to True.

Query(True, description='The option to not return deleted texts. Defaults to `True`.')
sorted_by TextsSortOptions

The option to sort texts. Defaults to ALPHABETICAL.

Query(ALPHABETICAL, description='The option to sort texts. Defaults to `ALPHABETICAL`.')
sorted_reverse bool

The option to reverse texts order. Defaults to False.

Query(False, description='The option to reverse texts order. Defaults to `False`.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains texts.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
@app.get(
    "/api/projects/{project_id}/texts",
    tags=["Texts"],
    status_code=status.HTTP_200_OK,
)
async def get_texts(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
    without_deleted_texts: bool = Query(
        True,
        description="The option to not return deleted texts. Defaults to `True`.",
    ),
    sorted_by: TextsSortOptions = Query(
        TextsSortOptions.ALPHABETICAL,
        description="The option to sort texts. Defaults to `ALPHABETICAL`.",
    ),
    sorted_reverse: bool = Query(
        False,
        description="The option to reverse texts order. Defaults to `False`.",
    ),
    # TODO: filter_text
    # TODO: limit_size + offset
) -> Dict[str, Any]:
    """
    Get texts.

    Args:
        project_id (str): The ID of the project.
        without_deleted_texts (bool): The option to not return deleted texts. Defaults to `True`.
        sorted_by (TextsSortOptions, optional): The option to sort texts. Defaults to `ALPHABETICAL`.
        sorted_reverse (bool, optional): The option to reverse texts order. Defaults to `False`.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.

    Returns:
        Dict[str, Any]: A dictionary that contains texts.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    ###
    ### Load needed data.
    ###

    # Load texts.
    with open(DATA_DIRECTORY / project_id / "texts.json", "r") as texts_fileobject:
        texts: Dict[str, Any] = {
            text_id: text_value
            for text_id, text_value in json.load(texts_fileobject).items()
            if (without_deleted_texts is False or text_value["is_deleted"] is False)
        }

    ###
    ### Sort texts.
    ###

    # Define the values selection method.
    def get_value_for_texts_sorting(text_to_sort: Tuple[str, Dict[str, Any]]) -> Any:  # noqa: WPS430 (nested function)
        """Return the values expected for texts sorting.

        Args:
            text_to_sort (Tuple[str, Dict[str, Any]]): A text (from `.items()`).

        Returns:
            Any: The expected values of the text need for the sort.
        """
        # By text id.
        if sorted_by == TextsSortOptions.ID:
            return text_to_sort[0]
        # By text value.
        if sorted_by == TextsSortOptions.ALPHABETICAL:
            return text_to_sort[1]["text_preprocessed"]
        # By deletion status.
        #### if sorted_by == TextsSortOptions.IS_DELETED:
        return text_to_sort[1]["is_deleted"]

    # Sorted the texts to return.
    sorted_texts: Dict[str, Any] = dict(
        sorted(
            texts.items(),
            key=get_value_for_texts_sorting,
            reverse=sorted_reverse,
        )
    )

    # Return the requested texts.
    return {
        "project_id": project_id,
        "texts": sorted_texts,
        # Get the request parameters.
        "parameters": {
            "without_deleted_texts": without_deleted_texts,
            "sorted_by": sorted_by.value,
            "sorted_reverse": sorted_reverse,
        },
    }

get_vectors(project_id=Path(..., description='The ID of the project.')) async

Get 2D and 3D vectors.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

HTTPException

Raises HTTP_404_NOT_FOUND if the iteration with id iteration_id doesn't exist.

HTTPException

Raises HTTP_403_FORBIDDEN if the status of the project hasn't completed its clustering step.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains clustering result.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
@app.get(
    "/api/projects/{project_id}/vectors",
    tags=["Data modelization"],
    status_code=status.HTTP_200_OK,
)
async def get_vectors(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
) -> Dict[str, Any]:
    """
    Get 2D and 3D vectors.

    Args:
        project_id (str, optional): The ID of the project.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the iteration with id `iteration_id` doesn't exist.
        HTTPException: Raises `HTTP_403_FORBIDDEN` if the status of the project hasn't completed its clustering step.

    Returns:
        Dict[str, Any]: A dictionary that contains clustering result.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # Load status file.
    with open(DATA_DIRECTORY / project_id / "status.json", "r") as status_fileobject:
        project_status: Dict[str, Any] = json.load(status_fileobject)

    # Check project status.
    if (
        project_status["state"] != ICGUIStates.SAMPLING_TODO  # noqa: WPS514
        and project_status["state"] != ICGUIStates.SAMPLING_PENDING
        and project_status["state"] != ICGUIStates.SAMPLING_WORKING
        and project_status["state"] != ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION
        and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
        and project_status["state"] != ICGUIStates.ANNOTATION_WITH_PENDING_MODELIZATION_WITHOUT_CONFLICTS
        and project_status["state"] != ICGUIStates.ANNOTATION_WITH_WORKING_MODELIZATION_WITHOUT_CONFLICTS
        and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS
        and project_status["state"] != ICGUIStates.ANNOTATION_WITH_PENDING_MODELIZATION_WITH_CONFLICTS
        and project_status["state"] != ICGUIStates.ANNOTATION_WITH_WORKING_MODELIZATION_WITH_CONFLICTS
        and project_status["state"] != ICGUIStates.CLUSTERING_TODO
        and project_status["state"] != ICGUIStates.CLUSTERING_PENDING
        and project_status["state"] != ICGUIStates.CLUSTERING_WORKING
        and project_status["state"] != ICGUIStates.ITERATION_END
    ):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="The project with id '{project_id_str}' hasn't completed its modelization update step.".format(
                project_id_str=str(project_id),
            ),
        )

    # Load the 2D vectors.
    with open(DATA_DIRECTORY / project_id / "vectors_2D.json", "r") as vectors_2D_fileobject:
        vectors_2D: Dict[str, Dict[str, float]] = json.load(vectors_2D_fileobject)  # noqa: S301  # Usage of Pickle

    # Load the 3D vectors.
    with open(DATA_DIRECTORY / project_id / "vectors_3D.json", "r") as vectors_3D_fileobject:
        vectors_3D: Dict[str, Dict[str, float]] = json.load(vectors_3D_fileobject)  # noqa: S301  # Usage of Pickle

        # Return the project vectors.
        return {
            "project_id": project_id,
            "vectors_2d": vectors_2D,
            "vectors_3d": vectors_3D,
        }

import_project(background_tasks, project_archive=File(..., description='A zip archive representing a project. Use format from `download` route.')) async

Import a project from a zip archive file.

Parameters:

Name Type Description Default
background_tasks BackgroundTasks

A background task to run after the return statement.

required
project_archive UploadFile

A zip archive representing a project. Use format from download route.

File(..., description='A zip archive representing a project. Use format from `download` route.')

Raises:

Type Description
HTTPException

Raises HTTP_400_NOT_FOUND if archive is invalid.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains the ID of the imported project.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
@app.put(
    "/api/projects",
    tags=["Projects"],
    status_code=status.HTTP_201_CREATED,
)
async def import_project(
    background_tasks: BackgroundTasks,
    project_archive: UploadFile = File(
        ...,
        description="A zip archive representing a project. Use format from `download` route.",
        # TODO: max_size="8MB",
    ),
) -> Dict[str, Any]:
    """
    Import a project from a zip archive file.

    Args:
        background_tasks (BackgroundTasks): A background task to run after the return statement.
        project_archive (UploadFile, optional): A zip archive representing a project. Use format from `download` route.

    Raises:
        HTTPException: Raises `HTTP_400_NOT_FOUND` if archive is invalid.

    Returns:
        Dict[str, Any]: A dictionary that contains the ID of the imported project.
    """

    # Check archive type.
    if project_archive.content_type != "application/x-zip-compressed":
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="The file type '{project_archive_type}' is not supported. Please use '.zip' file.".format(
                project_archive_type=str(project_archive.content_type),
            ),
        )

    # Temporarly store zip archive.
    current_timestamp: float = datetime.now().timestamp()
    new_current_project_id: str = str(int(current_timestamp * 10**6))
    import_archive_name: str = "import-{new_current_project_id_str}.zip".format(
        new_current_project_id_str=str(new_current_project_id)
    )
    import_archive_path: pathlib.Path = DATA_DIRECTORY / import_archive_name
    with open(import_archive_path, "wb") as import_archive_fileobject_w:
        shutil.copyfileobj(project_archive.file, import_archive_fileobject_w)

    # Define a backgroundtask to clear archive after importation.
    def clear_after_import_project():  # noqa: WPS430 (nested function)
        """
        Delete the archive file.
        """

        # Delete archive file.
        if os.path.exists(import_archive_path):  # pragma: no cover
            os.remove(import_archive_path)

    # Add the background task.
    background_tasks.add_task(
        func=clear_after_import_project,
    )

    # Try to open archive file.
    try:
        with zipfile.ZipFile(import_archive_path, "r") as import_archive_file:
            ###
            ### Check archive content.
            ###
            missing_files: List[str] = [
                needed_file
                for needed_file in (
                    "metadata.json",
                    "status.json",
                    "texts.json",
                    "constraints.json",
                    "settings.json",
                    "sampling.json",
                    "clustering.json",
                    "modelization.json",  # Will be recomputed during modelization step.
                    # "vectors_2D.json",  # Will be recomputed during modelization step.
                    # "vectors_3D.json",  # Will be recomputed during modelization step.
                )
                if needed_file not in import_archive_file.namelist()
            ]
            if len(missing_files) != 0:  # noqa: WPS507
                raise ValueError(
                    "The project archive file doesn't contains the following files: {missing_files_str}.".format(
                        missing_files_str=str(missing_files),
                    )
                )

            ###
            ### Check `metadata.json`.
            ###
            with import_archive_file.open("metadata.json") as metadata_fileobject_r:
                metadata: Dict[str, Any] = json.load(metadata_fileobject_r)
            metadata["project_id"] = new_current_project_id
            if (
                "project_name" not in metadata.keys()
                or not isinstance(metadata["project_name"], str)
                or "creation_timestamp" not in metadata.keys()
                or not isinstance(metadata["creation_timestamp"], float)
            ):
                raise ValueError("The project archive file has an invalid `metadata.json` file.")

            ###
            ### Check `status.json`.
            ###
            with import_archive_file.open("status.json") as status_fileobject_r:
                project_status: Dict[str, Any] = json.load(status_fileobject_r)

            # Check `status.state`.
            if "state" not in project_status.keys():
                raise ValueError("The project archive file has an invalid `status.json` file (see key `state`).")

            # Force `status.state` - Case of initialization.
            if (
                project_status["state"] == ICGUIStates.INITIALIZATION_WITHOUT_MODELIZATION  # noqa: WPS514
                or project_status["state"] == ICGUIStates.INITIALIZATION_WITH_PENDING_MODELIZATION
                or project_status["state"] == ICGUIStates.INITIALIZATION_WITH_WORKING_MODELIZATION
                or project_status["state"] == ICGUIStates.INITIALIZATION_WITH_ERRORS
            ):
                project_status["state"] = ICGUIStates.INITIALIZATION_WITHOUT_MODELIZATION
            # Force `status.state` - Case of sampling.
            elif (
                project_status["state"] == ICGUIStates.SAMPLING_TODO  # noqa: WPS514
                or project_status["state"] == ICGUIStates.SAMPLING_PENDING
                or project_status["state"] == ICGUIStates.SAMPLING_WORKING
                or project_status["state"] == ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITHOUT_MODELIZATION
                or project_status["state"] == ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITH_PENDING_MODELIZATION
                or project_status["state"] == ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITH_WORKING_MODELIZATION
                or project_status["state"] == ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITH_ERRORS
            ):
                project_status["state"] = ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITHOUT_MODELIZATION
            # Force `status.state` - Case of annotation.
            elif (
                project_status["state"] == ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION  # noqa: WPS514
                or project_status["state"] == ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
                or project_status["state"] == ICGUIStates.ANNOTATION_WITH_PENDING_MODELIZATION_WITHOUT_CONFLICTS
                or project_status["state"] == ICGUIStates.ANNOTATION_WITH_WORKING_MODELIZATION_WITHOUT_CONFLICTS
                or project_status["state"] == ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS
                or project_status["state"] == ICGUIStates.ANNOTATION_WITH_PENDING_MODELIZATION_WITH_CONFLICTS
                or project_status["state"] == ICGUIStates.ANNOTATION_WITH_WORKING_MODELIZATION_WITH_CONFLICTS
                or project_status["state"] == ICGUIStates.IMPORT_AT_ANNOTATION_STEP_WITHOUT_MODELIZATION
                or project_status["state"] == ICGUIStates.IMPORT_AT_ANNOTATION_STEP_WITH_PENDING_MODELIZATION
                or project_status["state"] == ICGUIStates.IMPORT_AT_ANNOTATION_STEP_WITH_WORKING_MODELIZATION
            ):
                project_status["state"] = ICGUIStates.IMPORT_AT_ANNOTATION_STEP_WITHOUT_MODELIZATION
            # Force `status.state` - Case of clustering.
            elif (
                project_status["state"] == ICGUIStates.CLUSTERING_TODO  # noqa: WPS514
                or project_status["state"] == ICGUIStates.CLUSTERING_PENDING
                or project_status["state"] == ICGUIStates.CLUSTERING_WORKING
                or project_status["state"] == ICGUIStates.IMPORT_AT_CLUSTERING_STEP_WITHOUT_MODELIZATION
                or project_status["state"] == ICGUIStates.IMPORT_AT_CLUSTERING_STEP_WITH_PENDING_MODELIZATION
                or project_status["state"] == ICGUIStates.IMPORT_AT_CLUSTERING_STEP_WITH_WORKING_MODELIZATION
                or project_status["state"] == ICGUIStates.IMPORT_AT_CLUSTERING_STEP_WITH_ERRORS
            ):
                project_status["state"] = ICGUIStates.IMPORT_AT_CLUSTERING_STEP_WITHOUT_MODELIZATION
            # Force `status.state` - Case of iteration end.
            elif (
                project_status["state"] == ICGUIStates.ITERATION_END  # noqa: WPS514
                or project_status["state"] == ICGUIStates.IMPORT_AT_ITERATION_END_WITHOUT_MODELIZATION
                or project_status["state"] == ICGUIStates.IMPORT_AT_ITERATION_END_WITH_PENDING_MODELIZATION
                or project_status["state"] == ICGUIStates.IMPORT_AT_ITERATION_END_WITH_WORKING_MODELIZATION
                or project_status["state"] == ICGUIStates.IMPORT_AT_ITERATION_END_WITH_ERRORS
            ):
                project_status["state"] = ICGUIStates.IMPORT_AT_ITERATION_END_WITHOUT_MODELIZATION
            # Force `state` - Case of unknown state.
            else:
                raise ValueError("The project archive file has an invalid `status.json` file (see key `state`).")

            # Force `status.task`.
            project_status["task"] = None

            # TODO: Check `texts.json`.
            with import_archive_file.open("texts.json") as texts_fileobject_r:
                texts: Dict[str, Dict[str, Any]] = json.load(texts_fileobject_r)

            # TODO: Check `constraints.json`.
            with import_archive_file.open("constraints.json") as constraints_fileobject_r:
                constraints: Dict[str, Dict[str, Any]] = json.load(constraints_fileobject_r)

            # TODO: Check `settings.json`.
            with import_archive_file.open("settings.json") as settings_fileobject_r:
                settings: Dict[str, Dict[str, Any]] = json.load(settings_fileobject_r)

            # TODO: Check `sampling.json`.
            with import_archive_file.open("sampling.json") as sampling_fileobject_r:
                sampling: Dict[str, List[str]] = json.load(sampling_fileobject_r)

            # TODO: Check `clustering.json`.
            with import_archive_file.open("clustering.json") as clustering_fileobject_r:
                clustering: Dict[str, Dict[str, str]] = json.load(clustering_fileobject_r)

            # TODO: Check `modelization.json`.
            with import_archive_file.open("modelization.json") as modelization_fileobject_r:
                modelization: Dict[str, Dict[str, Any]] = json.load(modelization_fileobject_r)

    # Error: case of custom raised errors.
    except ValueError as value_error:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(value_error),
        )

    # Error: other raised errors.
    except Exception:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="An error occurs in project import. Project archive is probably invalid.",
        )

    # Create the directory and subdirectories of the new project.
    os.mkdir(DATA_DIRECTORY / metadata["project_id"])

    # Store `metadata.json`.
    with open(DATA_DIRECTORY / metadata["project_id"] / "metadata.json", "w") as metadata_fileobject_w:
        json.dump(metadata, metadata_fileobject_w, indent=4)

    # Store `status.json`.
    with open(DATA_DIRECTORY / metadata["project_id"] / "status.json", "w") as status_fileobject_w:
        json.dump(project_status, status_fileobject_w, indent=4)

    # Store `texts.json`.
    with open(DATA_DIRECTORY / metadata["project_id"] / "texts.json", "w") as texts_fileobject_w:
        json.dump(texts, texts_fileobject_w, indent=4)

    # Store `constraints.json`.
    with open(DATA_DIRECTORY / metadata["project_id"] / "constraints.json", "w") as constraints_fileobject_w:
        json.dump(constraints, constraints_fileobject_w, indent=4)

    # Store `settings.json`.
    with open(DATA_DIRECTORY / metadata["project_id"] / "settings.json", "w") as settings_fileobject_w:
        json.dump(settings, settings_fileobject_w, indent=4)

    # Store `sampling.json`.
    with open(DATA_DIRECTORY / metadata["project_id"] / "sampling.json", "w") as sampling_fileobject_w:
        json.dump(sampling, sampling_fileobject_w, indent=4)

    # Store `clustering.json`.
    with open(DATA_DIRECTORY / metadata["project_id"] / "clustering.json", "w") as clustering_fileobject_w:
        json.dump(clustering, clustering_fileobject_w, indent=4)

    # Store `modelization.json`.
    with open(DATA_DIRECTORY / metadata["project_id"] / "modelization.json", "w") as modelization_fileobject_w:
        json.dump(modelization, modelization_fileobject_w, indent=4)

    # Return the new ID of the imported project.
    return {
        "project_id": metadata["project_id"],
        "detail": (
            "The project with name '{project_name_str}' has been imported. It has the id '{project_id_str}'.".format(
                project_name_str=str(metadata["project_name"]),
                project_id_str=str(metadata["project_id"]),
            )
        ),
    }

move_to_next_iteration(project_id=Path(..., description='The ID of the project.')) async

Move to next iteration after clustering step.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

HTTPException

Raises HTTP_403_FORBIDDEN if the project didn't complete its clustering step.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains the ID of the new iteration.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
@app.post(
    "/api/projects/{project_id}/iterations",
    tags=["Status"],
    status_code=status.HTTP_201_CREATED,
)
async def move_to_next_iteration(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
) -> Dict[str, Any]:
    """
    Move to next iteration after clustering step.

    Args:
        project_id (str): The ID of the project.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.
        HTTPException: Raises `HTTP_403_FORBIDDEN` if the project didn't complete its clustering step.

    Returns:
        Dict[str, Any]: A dictionary that contains the ID of the new iteration.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # 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)

        # Load settings file.
        with open(DATA_DIRECTORY / project_id / "settings.json", "r") as settings_fileobject_r:
            project_settings: Dict[str, Any] = json.load(settings_fileobject_r)

        # Get current iteration id.
        current_iteration_id: int = project_status["iteration_id"]

        ###
        ### Check parameters.
        ###

        # Check project status.
        if project_status["state"] != ICGUIStates.ITERATION_END:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="The project with id '{project_id_str}' hasn't completed its clustering step on iteration '{iteration_id_str}'.".format(
                    project_id_str=str(project_id),
                    iteration_id_str=str(current_iteration_id),
                ),
            )

        ###
        ### Update data.
        ###

        # Define new iteration id.
        new_iteration_id: int = current_iteration_id + 1

        # Initialize status for the new iteration.
        project_status["iteration_id"] = new_iteration_id
        project_status["state"] = ICGUIStates.SAMPLING_TODO

        # Initialize settings for the new iteration.
        project_settings[str(new_iteration_id)] = {
            "sampling": (
                default_SamplingSettingsModel().to_dict()
                if (current_iteration_id == 0)
                else project_settings[str(current_iteration_id)]["sampling"]
            ),
            "preprocessing": project_settings[str(current_iteration_id)]["preprocessing"],
            "vectorization": project_settings[str(current_iteration_id)]["vectorization"],
            "clustering": project_settings[str(current_iteration_id)]["clustering"],
        }

        ###
        ### Store updated data.
        ###

        # Store project settings.
        with open(DATA_DIRECTORY / project_id / "settings.json", "w") as settings_fileobject_w:
            json.dump(project_settings, settings_fileobject_w, indent=4)

        # Store project status.
        with open(DATA_DIRECTORY / project_id / "status.json", "w") as status_fileobject_w:
            json.dump(project_status, status_fileobject_w, indent=4)

        # Return the new iteration id.
        return {
            "project_id": project_id,
            "iteration_id": new_iteration_id,
            "detail": "The project with id '{project_id_str}' is now on iteration with id '{iteration_id_str}'.".format(
                project_id_str=str(project_id),
                iteration_id_str=str(new_iteration_id),
            ),
        }

prepare_constrained_clustering_task(background_tasks, project_id=Path(..., description='The ID of the project.')) async

Prepare constrained clustering task.

Parameters:

Name Type Description Default
background_tasks BackgroundTasks

A background task to run after the return statement.

required
project_id str

The ID of the project.

Path(..., description='The ID of the project.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

HTTPException

Raises HTTP_403_FORBIDDEN if the current status of the project doesn't allow the preparation of constrained clustering task.

HTTPException

Raises HTTP_504_GATEWAY_TIMEOUT if the task can't be prepared.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains the confirmation of the preparation of constrained clustering task.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
@app.post(
    "/api/projects/{project_id}/clustering",
    tags=["Constrained clustering"],
    status_code=status.HTTP_202_ACCEPTED,
)
async def prepare_constrained_clustering_task(
    background_tasks: BackgroundTasks,
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
) -> Dict[str, Any]:
    """
    Prepare constrained clustering task.

    Args:
        background_tasks (BackgroundTasks): A background task to run after the return statement.
        project_id (str): The ID of the project.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.
        HTTPException: Raises `HTTP_403_FORBIDDEN` if the current status of the project doesn't allow the preparation of constrained clustering task.
        HTTPException: Raises `HTTP_504_GATEWAY_TIMEOUT` if the task can't be prepared.

    Returns:
        Dict[str, Any]: A dictionary that contains the confirmation of the preparation of constrained clustering task.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # 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:
            project_status: Dict[str, Any] = json.load(status_fileobject)

        ###
        ### Check parameters.
        ###

        # Check status.
        if project_status["state"] != ICGUIStates.CLUSTERING_TODO:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="The project with id '{project_id_str}' doesn't allow the preparation of constrained clustering task during this state (state='{state_str}').".format(
                    project_id_str=str(project_id),
                    state_str=str(project_status["state"]),
                ),
            )

        ###
        ### Update data.
        ###

        # Update status by forcing "pending" status.
        project_status["state"] = ICGUIStates.CLUSTERING_PENDING

        # Prepare status by initializing "task" status.
        project_status["task"] = {
            "progression": 1,
            "detail": "Waiting for background task allocation...",
        }

        ###
        ### Store updated data.
        ###

        # Store updated status in file.
        with open(DATA_DIRECTORY / project_id / "status.json", "w") as status_fileobject_w:
            json.dump(project_status, status_fileobject_w, indent=4)

        ###
        ### Launch backgroundtask.
        ###

        # Add the background task.
        background_tasks.add_task(
            func=backgroundtasks.run_constrained_clustering_task,
            project_id=project_id,
        )

    # Return statement.
    return {  # pragma: no cover (need radis and worder)
        "project_id": project_id,
        "detail": "In project with id '{project_id_str}', the constrained clustering task has been requested and is waiting for a background task.".format(
            project_id_str=str(project_id),
        ),
    }

prepare_constraints_sampling_task(background_tasks, project_id=Path(..., description='The ID of the project.')) async

Prepare constraints sampling task.

Parameters:

Name Type Description Default
background_tasks BackgroundTasks

A background task to run after the return statement.

required
project_id str

The ID of the project.

Path(..., description='The ID of the project.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

HTTPException

Raises HTTP_403_FORBIDDEN if the current status of the project doesn't allow the preparation of constraints sampling task.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains the confirmation of the preparation of constraints sampling task.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
@app.post(
    "/api/projects/{project_id}/sampling",
    tags=["Constraints sampling"],
    status_code=status.HTTP_202_ACCEPTED,
)
async def prepare_constraints_sampling_task(
    background_tasks: BackgroundTasks,
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
) -> Dict[str, Any]:
    """
    Prepare constraints sampling task.

    Args:
        background_tasks (BackgroundTasks): A background task to run after the return statement.
        project_id (str): The ID of the project.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.
        HTTPException: Raises `HTTP_403_FORBIDDEN` if the current status of the project doesn't allow the preparation of constraints sampling task.

    Returns:
        Dict[str, Any]: A dictionary that contains the confirmation of the preparation of constraints sampling task.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # Lock status file in order to check project status for this step.
    with FileLock(str(DATA_DIRECTORY / project_id / "status.json.lock")):
        # Load status file.
        with open(DATA_DIRECTORY / project_id / "status.json", "r") as status_fileobject:
            project_status: Dict[str, Any] = json.load(status_fileobject)

        # Check status.
        if project_status["state"] != ICGUIStates.SAMPLING_TODO:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="The project with id '{project_id_str}' doesn't allow the preparation of constraints sampling task during this state (state='{state_str}').".format(
                    project_id_str=str(project_id),
                    state_str=str(project_status["state"]),
                ),
            )

        ###
        ### Update data.
        ###

        # Update status by forcing "pending" status.
        project_status["state"] = ICGUIStates.SAMPLING_PENDING

        # Prepare status by initializing "task" status.
        project_status["task"] = {
            "progression": 1,
            "detail": "Waiting for background task allocation...",
        }

        ###
        ### Store updated data.
        ###

        # Store updated status in file.
        with open(DATA_DIRECTORY / project_id / "status.json", "w") as status_fileobject_w:
            json.dump(project_status, status_fileobject_w, indent=4)

        ###
        ### Launch backgroundtask.
        ###

        # Add the background task.
        background_tasks.add_task(
            func=backgroundtasks.run_constraints_sampling_task,
            project_id=project_id,
        )

    # Return statement.
    return {  # pragma: no cover (need radis and worder)
        "project_id": project_id,
        "detail": "In project with id '{project_id_str}', the constraints sampling task has been requested and is waiting for a background task.".format(
            project_id_str=str(project_id),
        ),
    }

prepare_modelization_update_task(background_tasks, project_id=Path(..., description='The ID of the project.')) async

Prepare modelization update task.

Parameters:

Name Type Description Default
background_tasks BackgroundTasks

A background task to run after the return statement.

required
project_id str

The ID of the project.

Path(..., description='The ID of the project.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

HTTPException

Raises HTTP_403_FORBIDDEN if the current status of the project doesn't allow the preparation of modelization update task.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains the confirmation of the preparation of modelization update task.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
@app.post(
    "/api/projects/{project_id}/modelization",
    tags=["Data modelization"],
    status_code=status.HTTP_202_ACCEPTED,
)
async def prepare_modelization_update_task(
    background_tasks: BackgroundTasks,
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
) -> Dict[str, Any]:
    """
    Prepare modelization update task.

    Args:
        background_tasks (BackgroundTasks): A background task to run after the return statement.
        project_id (str): The ID of the project.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.
        HTTPException: Raises `HTTP_403_FORBIDDEN` if the current status of the project doesn't allow the preparation of modelization update task.

    Returns:
        Dict[str, Any]: A dictionary that contains the confirmation of the preparation of modelization update task.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # 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:
            project_status: Dict[str, Any] = json.load(status_fileobject)

        ###
        ### Check parameters.
        ###

        # Check status.
        if (
            project_status["state"] != ICGUIStates.INITIALIZATION_WITHOUT_MODELIZATION  # noqa: WPS514
            and project_status["state"] != ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITHOUT_MODELIZATION
            and project_status["state"] != ICGUIStates.IMPORT_AT_ANNOTATION_STEP_WITHOUT_MODELIZATION
            and project_status["state"] != ICGUIStates.IMPORT_AT_CLUSTERING_STEP_WITHOUT_MODELIZATION
            and project_status["state"] != ICGUIStates.IMPORT_AT_ITERATION_END_WITHOUT_MODELIZATION
            and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
            and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS
        ):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="The project with id '{project_id_str}' doesn't allow the preparation of modelization update task during this state (state='{state_str}').".format(
                    project_id_str=str(project_id),
                    state_str=str(project_status["state"]),
                ),
            )

        ###
        ### Update data.
        ###

        # Update status by forcing "pending" status.
        if project_status["state"] == ICGUIStates.INITIALIZATION_WITHOUT_MODELIZATION:
            project_status["state"] = ICGUIStates.INITIALIZATION_WITH_PENDING_MODELIZATION
        elif project_status["state"] == ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITHOUT_MODELIZATION:
            project_status["state"] = ICGUIStates.IMPORT_AT_SAMPLING_STEP_WITH_PENDING_MODELIZATION
        elif project_status["state"] == ICGUIStates.IMPORT_AT_ANNOTATION_STEP_WITHOUT_MODELIZATION:
            project_status["state"] = ICGUIStates.IMPORT_AT_ANNOTATION_STEP_WITH_PENDING_MODELIZATION
        elif project_status["state"] == ICGUIStates.IMPORT_AT_CLUSTERING_STEP_WITHOUT_MODELIZATION:
            project_status["state"] = ICGUIStates.IMPORT_AT_CLUSTERING_STEP_WITH_PENDING_MODELIZATION
        elif project_status["state"] == ICGUIStates.IMPORT_AT_ITERATION_END_WITHOUT_MODELIZATION:
            project_status["state"] = ICGUIStates.IMPORT_AT_ITERATION_END_WITH_PENDING_MODELIZATION
        elif project_status["state"] == ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS:
            project_status["state"] = ICGUIStates.ANNOTATION_WITH_PENDING_MODELIZATION_WITHOUT_CONFLICTS
        #### elif  project_status["state"] == ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS:
        else:
            project_status["state"] = ICGUIStates.ANNOTATION_WITH_PENDING_MODELIZATION_WITH_CONFLICTS

        # Prepare status by initializing "task" status.
        project_status["task"] = {
            "progression": 1,
            "detail": "Waiting for background task allocation...",
        }

        ###
        ### Store updated data.
        ###

        # Store updated status in file.
        with open(DATA_DIRECTORY / project_id / "status.json", "w") as status_fileobject_w:
            json.dump(project_status, status_fileobject_w, indent=4)

        ###
        ### Launch backgroundtask.
        ###

        # Add the background task.
        background_tasks.add_task(
            func=backgroundtasks.run_modelization_update_task,
            project_id=project_id,
        )

        # Return statement.
        return {  # pragma: no cover (need radis and worder)
            "project_id": project_id,
            "detail": "In project with id '{project_id_str}', the modelization update task has been requested and is waiting for a background task.".format(
                project_id_str=str(project_id),
            ),
        }

prometheus_disk_usage()

Define a metric of disk usage.

Returns:

Type Description
Callable[[Info], None]

Callable[[metrics.Info], None]: instrumentation.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def prometheus_disk_usage() -> Callable[[metrics.Info], None]:
    """
    Define a metric of disk usage.

    Returns:
        Callable[[metrics.Info], None]: instrumentation.
    """
    gaugemetric = Gauge(
        "disk_usage",
        "The disk usage in %",
    )

    def instrumentation(info: metrics.Info) -> None:  # noqa: WPS430 (nested function)
        total, used, _ = shutil.disk_usage(DATA_DIRECTORY)
        gaugemetric.set(used * 100 / total)

    return instrumentation

ready() async

Tell if the API is ready.

Returns:

Type Description
Response

An HTTP response with either 200 or 503 codes.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
@app.get(
    "/ready",
    tags=["app state"],
    status_code=status.HTTP_200_OK,
)
async def ready() -> Response:  # pragma: no cover
    """
    Tell if the API is ready.

    Returns:
        An HTTP response with either 200 or 503 codes.
    """

    # Return 200_OK if ready.
    if app.state.ready:
        return Response(status_code=status.HTTP_200_OK)

    # Return 503_SERVICE_UNAVAILABLE otherwise.
    return Response(status_code=status.HTTP_503_SERVICE_UNAVAILABLE)

rename_text(project_id=Path(..., description='The ID of the project.'), text_id=Path(..., description='The ID of the text.'), text_value=Query(..., description='The new value of the text.', min_length=3, max_length=256)) async

Rename a text.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')
text_id str

The ID of the text.

Path(..., description='The ID of the text.')
text_value str

The new value of the text.

Query(..., description='The new value of the text.', min_length=3, max_length=256)

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

HTTPException

Raises HTTP_404_NOT_FOUND if the text with id text_id to rename doesn't exist.

HTTPException

Raises HTTP_403_FORBIDDEN if the current status of the project doesn't allow modification.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains the ID of renamed text.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
@app.put(
    "/api/projects/{project_id}/texts/{text_id}/rename",
    tags=["Texts"],
    status_code=status.HTTP_202_ACCEPTED,
)
async def rename_text(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
    text_id: str = Path(
        ...,
        description="The ID of the text.",
    ),
    text_value: str = Query(
        ...,
        description="The new value of the text.",
        min_length=3,
        max_length=256,
    ),
) -> Dict[str, Any]:
    """
    Rename a text.

    Args:
        project_id (str): The ID of the project.
        text_id (str): The ID of the text.
        text_value (str): The new value of the text.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the text with id `text_id` to rename doesn't exist.
        HTTPException: Raises `HTTP_403_FORBIDDEN` if the current status of the project doesn't allow modification.

    Returns:
        Dict[str, Any]: A dictionary that contains the ID of renamed text.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # 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:
            project_status: Dict[str, Any] = json.load(status_fileobject)

        # Load texts file.
        with open(DATA_DIRECTORY / project_id / "texts.json", "r") as texts_fileobject_r:
            texts: Dict[str, Any] = json.load(texts_fileobject_r)

        ###
        ### Check parameters.
        ###

        # Check text id.
        if text_id not in texts.keys():
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="In project with id '{project_id_str}', the text with id '{text_id_str}' to rename doesn't exist.".format(
                    project_id_str=str(project_id),
                    text_id_str=str(text_id),
                ),
            )

        # Check status.
        if (
            project_status["state"] != ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION  # noqa: WPS514
            and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
            and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS
        ):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="The project with id '{project_id_str}' doesn't allow modification during this state (state='{state_str}').".format(
                    project_id_str=str(project_id),
                    state_str=str(project_status["state"]),
                ),
            )

        ###
        ### Update data.
        ###

        # Update status by forcing "outdated" status.
        if project_status["state"] == ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION:
            project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
        #### elif project_status["state"] == ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS:
        ####    project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
        #### elif project_status["state"] == ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS:
        ####    project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS

        # Update texts by renaming the new text.
        texts[text_id]["text"] = text_value

        ###
        ### Store updated data.
        ###

        # Store updated status in file.
        with open(DATA_DIRECTORY / project_id / "status.json", "w") as status_fileobject_w:
            json.dump(project_status, status_fileobject_w, indent=4)

        # Store updated texts in file.
        with open(DATA_DIRECTORY / project_id / "texts.json", "w") as texts_fileobject_w:
            json.dump(texts, texts_fileobject_w, indent=4)

    # Return statement.
    return {
        "project_id": project_id,
        "text_id": text_id,
        "text_value": text_value,
        "detail": "In project with id '{project_id_str}', the text with id '{text_id_str}' has been renamed.".format(
            project_id_str=str(project_id),
            text_id_str=str(text_id),
        ),
    }

review_constraint(project_id=Path(..., description='The ID of the project.'), constraint_id=Path(..., description='The ID of the constraint.'), to_review=Query(True, description='The choice to review or not the constraint. Defaults to `True`.')) async

Review a constraint.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')
constraint_id str

The ID of the constraint.

Path(..., description='The ID of the constraint.')
to_review str

The choice to review or not the constraint. Defaults to True.

Query(True, description='The choice to review or not the constraint. Defaults to `True`.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

HTTPException

Raises HTTP_404_NOT_FOUND if the constraint with id constraint_id to annotate doesn't exist.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains the ID of reviewed constraint.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
@app.put(
    "/api/projects/{project_id}/constraints/{constraint_id}/review",
    tags=["Constraints"],
    status_code=status.HTTP_202_ACCEPTED,
)
async def review_constraint(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
    constraint_id: str = Path(
        ...,
        description="The ID of the constraint.",
    ),
    to_review: bool = Query(
        True,
        description="The choice to review or not the constraint. Defaults to `True`.",
    ),
) -> Dict[str, Any]:
    """
    Review a constraint.

    Args:
        project_id (str): The ID of the project.
        constraint_id (str): The ID of the constraint.
        to_review (str): The choice to review or not the constraint. Defaults to `True`.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the constraint with id `constraint_id` to annotate doesn't exist.

    Returns:
        Dict[str, Any]: A dictionary that contains the ID of reviewed constraint.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # 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 constraints file.
        with open(DATA_DIRECTORY / project_id / "constraints.json", "r") as constraints_fileobject_r:
            constraints: Dict[str, Any] = json.load(constraints_fileobject_r)

        ###
        ### Check parameters.
        ###

        # Check constraint id.
        if constraint_id not in constraints.keys():
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="In project with id '{project_id_str}', the constraint with id '{constraint_id_str}' to annotate doesn't exist.".format(
                    project_id_str=str(project_id),
                    constraint_id_str=str(constraint_id),
                ),
            )

        ###
        ### Update data.
        ###

        # Update constraints by reviewing the constraint.
        constraints[constraint_id]["to_review"] = to_review

        ###
        ### Store updated data.
        ###

        # 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)

    # Return statement.
    return {
        "project_id": project_id,
        "constraint_id": constraint_id,
        "detail": "In project with id '{project_id_str}', the constraint with id '{constraint_id_str}' {review_conclusion}.".format(
            project_id_str=str(project_id),
            constraint_id_str=str(constraint_id),
            review_conclusion="need a review" if (to_review) else "has been reviewed",
        ),
    }

startup() async

Startup event.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
228
229
230
231
232
233
234
235
236
237
238
@app.on_event("startup")
async def startup() -> None:  # pragma: no cover
    """Startup event."""

    # Initialize ready state.
    app.state.ready = False

    # Apply database connection, long loading, etc.

    # Update ready state when done.
    app.state.ready = True

timestamp_to_date(timestamp, timezone_str='Europe/Paris')

From timestamp to date.

Parameters:

Name Type Description Default
timestamp float

The timstamp to convert.

required
timezone_str str

The time zone. Defaults to "Europe/Paris".

'Europe/Paris'

Returns:

Name Type Description
str str

The requested date.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
107
108
109
110
111
112
113
114
115
116
117
118
119
def timestamp_to_date(timestamp: float, timezone_str: str = "Europe/Paris") -> str:
    """
    From timestamp to date.

    Args:
        timestamp (float): The timstamp to convert.
        timezone_str (str, optional): The time zone. Defaults to `"Europe/Paris"`.

    Returns:
        str: The requested date.
    """
    timezone = tz.gettz(timezone_str)
    return datetime.fromtimestamp(timestamp, timezone).strftime("%d/%m/%Y")

timestamp_to_hour(timestamp, timezone_str='Europe/Paris')

From timestamp to hours.

Parameters:

Name Type Description Default
timestamp float

The timstamp to convert.

required
timezone_str str

The time zone. Defaults to "Europe/Paris".

'Europe/Paris'

Returns:

Name Type Description
str str

The requested hour.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
126
127
128
129
130
131
132
133
134
135
136
137
138
def timestamp_to_hour(timestamp: float, timezone_str: str = "Europe/Paris") -> str:
    """
    From timestamp to hours.

    Args:
        timestamp (float): The timstamp to convert.
        timezone_str (str, optional): The time zone. Defaults to `"Europe/Paris"`.

    Returns:
        str: The requested hour.
    """
    timezone = tz.gettz(timezone_str)
    return datetime.fromtimestamp(timestamp, timezone).strftime("%H:%M:%S")

undelete_text(project_id=Path(..., description='The ID of the project.'), text_id=Path(..., description='The ID of the text.')) async

Undelete a text.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')
text_id str

The ID of the text.

Path(..., description='The ID of the text.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

HTTPException

Raises HTTP_404_NOT_FOUND if the text with id text_id to undelete doesn't exist.

HTTPException

Raises HTTP_403_FORBIDDEN if the current status of the project doesn't allow modification.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains the ID of undeleted text.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
@app.put(
    "/api/projects/{project_id}/texts/{text_id}/undelete",
    tags=["Texts"],
    status_code=status.HTTP_202_ACCEPTED,
)
async def undelete_text(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
    text_id: str = Path(
        ...,
        description="The ID of the text.",
    ),
) -> Dict[str, Any]:
    """
    Undelete a text.

    Args:
        project_id (str): The ID of the project.
        text_id (str): The ID of the text.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the text with id `text_id` to undelete doesn't exist.
        HTTPException: Raises `HTTP_403_FORBIDDEN` if the current status of the project doesn't allow modification.

    Returns:
        Dict[str, Any]: A dictionary that contains the ID of undeleted text.
    """

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # 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:
            project_status: Dict[str, Any] = json.load(status_fileobject)

        # Load texts file.
        with open(DATA_DIRECTORY / project_id / "texts.json", "r") as texts_fileobject_r:
            texts: Dict[str, Any] = json.load(texts_fileobject_r)

        # Load constraints file.
        with open(DATA_DIRECTORY / project_id / "constraints.json", "r") as constraints_fileobject_r:
            constraints: Dict[str, Any] = json.load(constraints_fileobject_r)

        ###
        ### Check parameters.
        ###

        # Check text id.
        if text_id not in texts.keys():
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="In project with id '{project_id_str}', the text with id '{text_id_str}' to undelete doesn't exist.".format(
                    project_id_str=str(project_id),
                    text_id_str=str(text_id),
                ),
            )

        # Check status.
        if (
            project_status["state"] != ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION  # noqa: WPS514
            and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
            and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS
        ):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="The project with id '{project_id_str}' doesn't allow modification during this state (state='{state_str}').".format(
                    project_id_str=str(project_id),
                    state_str=str(project_status["state"]),
                ),
            )

        ###
        ### Update data.
        ###

        # Update status by forcing "outdated" status.
        if project_status["state"] == ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION:
            project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
        #### elif project_status["state"] == ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS:
        ####    project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
        #### elif project_status["state"] == ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS:
        ####    project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS

        # Update texts by undeleting the text.
        texts[text_id]["is_deleted"] = False

        # Update constraints by unhidding those associated with the undeleted text.
        for constraint_id, constraint_value in constraints.items():
            data_id1: str = constraint_value["data"]["id_1"]
            data_id2: str = constraint_value["data"]["id_2"]

            if text_id in {data_id1, data_id2}:
                constraints[constraint_id]["is_hidden"] = (
                    texts[data_id1]["is_deleted"] is True or texts[data_id2]["is_deleted"] is True
                )

        ###
        ### Store updated data.
        ###

        # Store updated status in file.
        with open(DATA_DIRECTORY / project_id / "status.json", "w") as status_fileobject_w:
            json.dump(project_status, status_fileobject_w, indent=4)

        # Store updated texts in file.
        with open(DATA_DIRECTORY / project_id / "texts.json", "w") as texts_fileobject_w:
            json.dump(texts, texts_fileobject_w, indent=4)

        # 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)

    # Return statement.
    return {
        "project_id": project_id,
        "text_id": text_id,
        "detail": "In project with id '{project_id_str}', the text with id '{text_id_str}' has been undeleted. Several constraints have been unhidden.".format(
            project_id_str=str(project_id),
            text_id_str=str(text_id),
        ),
    }

update_settings(project_id=Path(..., description='The ID of the project.'), preprocessing=Body(None, description='The settings for data preprocessing. Used during `modelization_update` task. Keep unchanged if empty.'), vectorization=Body(None, description='The settings for data vectorization. Used during `modelization_update` task. Keep unchanged if empty.'), sampling=Body(None, description='The settings for constraints sampling. Used during `constraints_sampling` task. Keep unchanged if empty.'), clustering=Body(None, description='The settings for constrained clustering. Used during `constrained_clustering` task. Keep unchanged if empty.')) async

Update settings.

Parameters:

Name Type Description Default
project_id str

The ID of the project.

Path(..., description='The ID of the project.')
preprocessing Optional[PreprocessingSettingsModel]

The settings for data preprocessing. Used during clustering step. Keep unchanged if empty.. Defaults to None.

Body(None, description='The settings for data preprocessing. Used during `modelization_update` task. Keep unchanged if empty.')
vectorization Optional[VectorizationSettingsModel]

The settings for data vectorization. Used during clustering step. Keep unchanged if empty.. Defaults to None.

Body(None, description='The settings for data vectorization. Used during `modelization_update` task. Keep unchanged if empty.')
sampling Optional[SamplingSettingsModel]

The settings for constraints sampling. Used during sampling step. Keep unchanged if empty.. Defaults to None.

Body(None, description='The settings for constraints sampling. Used during `constraints_sampling` task. Keep unchanged if empty.')
clustering Optional[ClusteringSettingsModel]

The settings for constrained clustering. Used during clustering step. Keep unchanged if empty. Defaults to None.

Body(None, description='The settings for constrained clustering. Used during `constrained_clustering` task. Keep unchanged if empty.')

Raises:

Type Description
HTTPException

Raises HTTP_404_NOT_FOUND if the project with id project_id doesn't exist.

HTTPException

Raises HTTP_403_FORBIDDEN if the status of the project doesn't allow settings modifications.

HTTPException

Raises HTTP_403_FORBIDDEN if parameters preprocessing, vectorization, sampling or clustering are not expected.

HTTPException

Raises HTTP_400_BAD_REQUEST if parameters preprocessing, vectorization, sampling or clustering are invalid.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary that contains the ID of updated settings.

Source code in src\cognitivefactory\interactive_clustering_gui\app.py
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
@app.put(
    "/api/projects/{project_id}/settings",
    tags=["Settings"],
    status_code=status.HTTP_201_CREATED,
)
async def update_settings(
    project_id: str = Path(
        ...,
        description="The ID of the project.",
    ),
    preprocessing: Optional[PreprocessingSettingsModel] = Body(
        None,
        description="The settings for data preprocessing. Used during `modelization_update` task. Keep unchanged if empty.",
    ),
    vectorization: Optional[VectorizationSettingsModel] = Body(
        None,
        description="The settings for data vectorization. Used during `modelization_update` task. Keep unchanged if empty.",
    ),
    sampling: Optional[SamplingSettingsModel] = Body(
        None,
        description="The settings for constraints sampling. Used during `constraints_sampling` task. Keep unchanged if empty.",
    ),
    clustering: Optional[ClusteringSettingsModel] = Body(
        None,
        description="The settings for constrained clustering. Used during `constrained_clustering` task. Keep unchanged if empty.",
    ),
) -> Dict[str, Any]:
    """
    Update settings.

    Args:
        project_id (str): The ID of the project.
        preprocessing (Optional[PreprocessingSettingsModel], optional): The settings for data preprocessing. Used during `clustering` step. Keep unchanged if empty.. Defaults to None.
        vectorization (Optional[VectorizationSettingsModel], optional): The settings for data vectorization. Used during `clustering` step. Keep unchanged if empty.. Defaults to None.
        sampling (Optional[SamplingSettingsModel], optional): The settings for constraints sampling. Used during `sampling` step. Keep unchanged if empty.. Defaults to None.
        clustering (Optional[ClusteringSettingsModel], optional): The settings for constrained clustering. Used during `clustering` step. Keep unchanged if empty. Defaults to None.

    Raises:
        HTTPException: Raises `HTTP_404_NOT_FOUND` if the project with id `project_id` doesn't exist.
        HTTPException: Raises `HTTP_403_FORBIDDEN` if the status of the project doesn't allow settings modifications.
        HTTPException: Raises `HTTP_403_FORBIDDEN` if parameters `preprocessing`, `vectorization`, `sampling` or `clustering` are not expected.
        HTTPException: Raises `HTTP_400_BAD_REQUEST` if parameters `preprocessing`, `vectorization`, `sampling` or `clustering` are invalid.

    Returns:
        Dict[str, Any]: A dictionary that contains the ID of updated settings.
    """

    # TODO: examples: https://fastapi.tiangolo.com/tutorial/schema-extra-example/#body-with-multiple-examples

    # Check project id.
    if project_id not in (await get_projects()):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="The project with id '{project_id_str}' doesn't exist.".format(
                project_id_str=str(project_id),
            ),
        )

    # 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)
        iteration_id: int = project_status["iteration_id"]

        # Load settings file.
        with open(DATA_DIRECTORY / project_id / "settings.json", "r") as settings_fileobject_r:
            project_settings: Dict[str, Any] = json.load(settings_fileobject_r)

        list_of_updated_settings: List[ICGUISettings] = []

        ###
        ### Case of preprocessing settings.
        ###
        if preprocessing is not None:
            list_of_updated_settings.append(ICGUISettings.PREPROCESSING)

            # Check project status for preprocessing.
            if (
                project_status["state"] != ICGUIStates.INITIALIZATION_WITHOUT_MODELIZATION  # noqa: WPS514
                and project_status["state"] != ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION
                and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
                and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS
            ):
                raise HTTPException(
                    status_code=status.HTTP_403_FORBIDDEN,
                    detail="The 'preprocessing' settings of project with id '{project_id_str}' cant't be modified during this state (state='{state_str}'). No changes have been taken into account.".format(
                        project_id_str=str(project_id),
                        state_str=str(project_status["state"]),
                    ),
                )

            # Update status by forcing "outdated" status.
            if project_status["state"] == ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION:
                project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
            #### elif project_status["state"] == ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS:
            ####    project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
            #### elif project_status["state"] == ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS:
            ####    project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS
            #### elif project_status["state"] == ICGUIStates.INITIALIZATION_WITHOUT_MODELIZATION:
            ####    project_status["state"] = ICGUIStates.INITIALIZATION_WITHOUT_MODELIZATION

            # Update the default settings with the parameters in the request body.
            for key_prep, value_prep in preprocessing.to_dict().items():
                project_settings[str(iteration_id)]["preprocessing"][key_prep] = value_prep

        ###
        ### Case of vectorization settings.
        ###
        if vectorization is not None:
            list_of_updated_settings.append(ICGUISettings.VECTORIZATION)

            # Check project status for vectorization.
            if (
                project_status["state"] != ICGUIStates.INITIALIZATION_WITHOUT_MODELIZATION  # noqa: WPS514
                and project_status["state"] != ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION
                and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
                and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS
            ):
                raise HTTPException(
                    status_code=status.HTTP_403_FORBIDDEN,
                    detail="The 'vectorization' settings of project with id '{project_id_str}' cant't be modified during this state (state='{state_str}'). No changes have been taken into account.".format(
                        project_id_str=str(project_id),
                        state_str=str(project_status["state"]),
                    ),
                )

            # Update status by forcing "outdated" status.
            if project_status["state"] == ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION:
                project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
            #### elif project_status["state"] == ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS:
            ####    project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
            #### elif project_status["state"] == ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS:
            ####    project_status["state"] = ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS
            #### elif project_status["state"] == ICGUIStates.INITIALIZATION_WITHOUT_MODELIZATION:
            ####    project_status["state"] = ICGUIStates.INITIALIZATION_WITHOUT_MODELIZATION

            # Update the default settings with the parameters in the request body.
            for key_vect, value_vect in vectorization.to_dict().items():
                project_settings[str(iteration_id)]["vectorization"][key_vect] = value_vect

        ###
        ### Case of sampling settings.
        ###
        if sampling is not None:
            list_of_updated_settings.append(ICGUISettings.SAMPLING)

            # Check project status for sampling.
            if project_status["state"] != ICGUIStates.SAMPLING_TODO:
                raise HTTPException(
                    status_code=status.HTTP_403_FORBIDDEN,
                    detail="The 'sampling' settings of project with id '{project_id_str}' cant't be modified during this state (state='{state_str}'). No changes have been taken into account.".format(
                        project_id_str=str(project_id),
                        state_str=str(project_status["state"]),
                    ),
                )

            # Update the default settings with the parameters in the request body.
            for key_sampl, value_sampl in sampling.to_dict().items():
                project_settings[str(iteration_id)]["sampling"][key_sampl] = value_sampl

        ###
        ### Case of clustering settings.
        ###
        if clustering is not None:
            list_of_updated_settings.append(ICGUISettings.CLUSTERING)

            # Check project status for clustering.
            if (
                project_status["state"] != ICGUIStates.INITIALIZATION_WITHOUT_MODELIZATION  # noqa: WPS514
                and project_status["state"] != ICGUIStates.INITIALIZATION_WITH_PENDING_MODELIZATION
                and project_status["state"] != ICGUIStates.INITIALIZATION_WITH_WORKING_MODELIZATION
                and project_status["state"] != ICGUIStates.SAMPLING_TODO
                and project_status["state"] != ICGUIStates.SAMPLING_PENDING
                and project_status["state"] != ICGUIStates.SAMPLING_WORKING
                and project_status["state"] != ICGUIStates.ANNOTATION_WITH_UPTODATE_MODELIZATION
                and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITHOUT_CONFLICTS
                and project_status["state"] != ICGUIStates.ANNOTATION_WITH_PENDING_MODELIZATION_WITHOUT_CONFLICTS
                and project_status["state"] != ICGUIStates.ANNOTATION_WITH_WORKING_MODELIZATION_WITHOUT_CONFLICTS
                and project_status["state"] != ICGUIStates.ANNOTATION_WITH_OUTDATED_MODELIZATION_WITH_CONFLICTS
                and project_status["state"] != ICGUIStates.ANNOTATION_WITH_PENDING_MODELIZATION_WITH_CONFLICTS
                and project_status["state"] != ICGUIStates.ANNOTATION_WITH_WORKING_MODELIZATION_WITH_CONFLICTS
                and project_status["state"] != ICGUIStates.CLUSTERING_TODO
            ):
                raise HTTPException(
                    status_code=status.HTTP_403_FORBIDDEN,
                    detail="The 'clustering' settings of project with id '{project_id_str}' cant't be modified during this state (state='{state_str}'). No changes have been taken into account.".format(
                        project_id_str=str(project_id),
                        state_str=str(project_status["state"]),
                    ),
                )

            # Update the default settings with the parameters in the request body.
            for key_clus, value_clus in clustering.to_dict().items():
                project_settings[str(iteration_id)]["clustering"][key_clus] = value_clus

        ###
        ### Store updated data.
        ###

        # Store updated status in file.
        with open(DATA_DIRECTORY / project_id / "status.json", "w") as status_fileobject_w:
            json.dump(project_status, status_fileobject_w, indent=4)

        # Store updated settings in file.
        with open(DATA_DIRECTORY / project_id / "settings.json", "w") as settings_fileobject_w:
            json.dump(project_settings, settings_fileobject_w, indent=4)

    ###
    ### Return statement.
    ###
    return {
        "project_id": project_id,
        "detail": "The project with id '{project_id_str}' has updated the following settings: {settings_str}.".format(
            project_id_str=str(project_id),
            settings_str=", ".join(list_of_updated_settings),
        ),
    }