supervisely 6.73.452__py3-none-any.whl → 6.73.513__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- supervisely/__init__.py +25 -1
- supervisely/annotation/annotation.py +8 -2
- supervisely/annotation/json_geometries_map.py +13 -12
- supervisely/api/annotation_api.py +6 -3
- supervisely/api/api.py +2 -0
- supervisely/api/app_api.py +10 -1
- supervisely/api/dataset_api.py +74 -12
- supervisely/api/entities_collection_api.py +10 -0
- supervisely/api/entity_annotation/figure_api.py +28 -0
- supervisely/api/entity_annotation/object_api.py +3 -3
- supervisely/api/entity_annotation/tag_api.py +63 -12
- supervisely/api/guides_api.py +210 -0
- supervisely/api/image_api.py +4 -0
- supervisely/api/labeling_job_api.py +83 -1
- supervisely/api/labeling_queue_api.py +33 -7
- supervisely/api/module_api.py +5 -0
- supervisely/api/project_api.py +71 -26
- supervisely/api/storage_api.py +3 -1
- supervisely/api/task_api.py +13 -2
- supervisely/api/team_api.py +4 -3
- supervisely/api/video/video_annotation_api.py +119 -3
- supervisely/api/video/video_api.py +65 -14
- supervisely/app/__init__.py +1 -1
- supervisely/app/content.py +23 -7
- supervisely/app/development/development.py +18 -2
- supervisely/app/fastapi/__init__.py +1 -0
- supervisely/app/fastapi/custom_static_files.py +1 -1
- supervisely/app/fastapi/multi_user.py +105 -0
- supervisely/app/fastapi/subapp.py +88 -42
- supervisely/app/fastapi/websocket.py +77 -9
- supervisely/app/singleton.py +21 -0
- supervisely/app/v1/app_service.py +18 -2
- supervisely/app/v1/constants.py +7 -1
- supervisely/app/widgets/__init__.py +6 -0
- supervisely/app/widgets/activity_feed/__init__.py +0 -0
- supervisely/app/widgets/activity_feed/activity_feed.py +239 -0
- supervisely/app/widgets/activity_feed/style.css +78 -0
- supervisely/app/widgets/activity_feed/template.html +22 -0
- supervisely/app/widgets/card/card.py +20 -0
- supervisely/app/widgets/classes_list_selector/classes_list_selector.py +121 -9
- supervisely/app/widgets/classes_list_selector/template.html +60 -93
- supervisely/app/widgets/classes_mapping/classes_mapping.py +13 -12
- supervisely/app/widgets/classes_table/classes_table.py +1 -0
- supervisely/app/widgets/deploy_model/deploy_model.py +56 -35
- supervisely/app/widgets/ecosystem_model_selector/ecosystem_model_selector.py +1 -1
- supervisely/app/widgets/experiment_selector/experiment_selector.py +8 -0
- supervisely/app/widgets/fast_table/fast_table.py +184 -60
- supervisely/app/widgets/fast_table/template.html +1 -1
- supervisely/app/widgets/heatmap/__init__.py +0 -0
- supervisely/app/widgets/heatmap/heatmap.py +564 -0
- supervisely/app/widgets/heatmap/script.js +533 -0
- supervisely/app/widgets/heatmap/style.css +233 -0
- supervisely/app/widgets/heatmap/template.html +21 -0
- supervisely/app/widgets/modal/__init__.py +0 -0
- supervisely/app/widgets/modal/modal.py +198 -0
- supervisely/app/widgets/modal/template.html +10 -0
- supervisely/app/widgets/object_class_view/object_class_view.py +3 -0
- supervisely/app/widgets/radio_tabs/radio_tabs.py +18 -2
- supervisely/app/widgets/radio_tabs/template.html +1 -0
- supervisely/app/widgets/select/select.py +6 -3
- supervisely/app/widgets/select_class/__init__.py +0 -0
- supervisely/app/widgets/select_class/select_class.py +363 -0
- supervisely/app/widgets/select_class/template.html +50 -0
- supervisely/app/widgets/select_cuda/select_cuda.py +22 -0
- supervisely/app/widgets/select_dataset_tree/select_dataset_tree.py +65 -7
- supervisely/app/widgets/select_tag/__init__.py +0 -0
- supervisely/app/widgets/select_tag/select_tag.py +352 -0
- supervisely/app/widgets/select_tag/template.html +64 -0
- supervisely/app/widgets/select_team/select_team.py +37 -4
- supervisely/app/widgets/select_team/template.html +4 -5
- supervisely/app/widgets/select_user/__init__.py +0 -0
- supervisely/app/widgets/select_user/select_user.py +270 -0
- supervisely/app/widgets/select_user/template.html +13 -0
- supervisely/app/widgets/select_workspace/select_workspace.py +59 -10
- supervisely/app/widgets/select_workspace/template.html +9 -12
- supervisely/app/widgets/table/table.py +68 -13
- supervisely/app/widgets/tree_select/tree_select.py +2 -0
- supervisely/aug/aug.py +6 -2
- supervisely/convert/base_converter.py +1 -0
- supervisely/convert/converter.py +2 -2
- supervisely/convert/image/image_converter.py +3 -1
- supervisely/convert/image/image_helper.py +48 -4
- supervisely/convert/image/label_studio/label_studio_converter.py +2 -0
- supervisely/convert/image/medical2d/medical2d_helper.py +2 -24
- supervisely/convert/image/multispectral/multispectral_converter.py +6 -0
- supervisely/convert/image/pascal_voc/pascal_voc_converter.py +8 -5
- supervisely/convert/image/pascal_voc/pascal_voc_helper.py +7 -0
- supervisely/convert/pointcloud/kitti_3d/kitti_3d_converter.py +33 -3
- supervisely/convert/pointcloud/kitti_3d/kitti_3d_helper.py +12 -5
- supervisely/convert/pointcloud/las/las_converter.py +13 -1
- supervisely/convert/pointcloud/las/las_helper.py +110 -11
- supervisely/convert/pointcloud/nuscenes_conv/nuscenes_converter.py +27 -16
- supervisely/convert/pointcloud/pointcloud_converter.py +91 -3
- supervisely/convert/pointcloud_episodes/nuscenes_conv/nuscenes_converter.py +58 -22
- supervisely/convert/pointcloud_episodes/nuscenes_conv/nuscenes_helper.py +21 -47
- supervisely/convert/video/__init__.py +1 -0
- supervisely/convert/video/multi_view/__init__.py +0 -0
- supervisely/convert/video/multi_view/multi_view.py +543 -0
- supervisely/convert/video/sly/sly_video_converter.py +359 -3
- supervisely/convert/video/video_converter.py +22 -2
- supervisely/convert/volume/dicom/dicom_converter.py +13 -5
- supervisely/convert/volume/dicom/dicom_helper.py +30 -18
- supervisely/geometry/constants.py +1 -0
- supervisely/geometry/geometry.py +4 -0
- supervisely/geometry/helpers.py +5 -1
- supervisely/geometry/oriented_bbox.py +676 -0
- supervisely/geometry/rectangle.py +2 -1
- supervisely/io/env.py +76 -1
- supervisely/io/fs.py +21 -0
- supervisely/nn/benchmark/base_evaluator.py +104 -11
- supervisely/nn/benchmark/instance_segmentation/evaluator.py +1 -8
- supervisely/nn/benchmark/object_detection/evaluator.py +20 -4
- supervisely/nn/benchmark/object_detection/vis_metrics/pr_curve.py +10 -5
- supervisely/nn/benchmark/semantic_segmentation/evaluator.py +34 -16
- supervisely/nn/benchmark/semantic_segmentation/vis_metrics/confusion_matrix.py +1 -1
- supervisely/nn/benchmark/semantic_segmentation/vis_metrics/frequently_confused.py +1 -1
- supervisely/nn/benchmark/semantic_segmentation/vis_metrics/overview.py +1 -1
- supervisely/nn/benchmark/visualization/evaluation_result.py +66 -4
- supervisely/nn/inference/cache.py +43 -18
- supervisely/nn/inference/gui/serving_gui_template.py +5 -2
- supervisely/nn/inference/inference.py +795 -199
- supervisely/nn/inference/inference_request.py +42 -9
- supervisely/nn/inference/predict_app/gui/classes_selector.py +83 -12
- supervisely/nn/inference/predict_app/gui/gui.py +676 -488
- supervisely/nn/inference/predict_app/gui/input_selector.py +205 -26
- supervisely/nn/inference/predict_app/gui/model_selector.py +2 -4
- supervisely/nn/inference/predict_app/gui/output_selector.py +46 -6
- supervisely/nn/inference/predict_app/gui/settings_selector.py +756 -59
- supervisely/nn/inference/predict_app/gui/tags_selector.py +1 -1
- supervisely/nn/inference/predict_app/gui/utils.py +236 -119
- supervisely/nn/inference/predict_app/predict_app.py +2 -2
- supervisely/nn/inference/session.py +43 -35
- supervisely/nn/inference/tracking/bbox_tracking.py +113 -34
- supervisely/nn/inference/tracking/tracker_interface.py +7 -2
- supervisely/nn/inference/uploader.py +139 -12
- supervisely/nn/live_training/__init__.py +7 -0
- supervisely/nn/live_training/api_server.py +111 -0
- supervisely/nn/live_training/artifacts_utils.py +243 -0
- supervisely/nn/live_training/checkpoint_utils.py +229 -0
- supervisely/nn/live_training/dynamic_sampler.py +44 -0
- supervisely/nn/live_training/helpers.py +14 -0
- supervisely/nn/live_training/incremental_dataset.py +146 -0
- supervisely/nn/live_training/live_training.py +497 -0
- supervisely/nn/live_training/loss_plateau_detector.py +111 -0
- supervisely/nn/live_training/request_queue.py +52 -0
- supervisely/nn/model/model_api.py +9 -0
- supervisely/nn/prediction_dto.py +12 -1
- supervisely/nn/tracker/base_tracker.py +11 -1
- supervisely/nn/tracker/botsort/botsort_config.yaml +0 -1
- supervisely/nn/tracker/botsort/tracker/mc_bot_sort.py +7 -4
- supervisely/nn/tracker/botsort_tracker.py +94 -65
- supervisely/nn/tracker/visualize.py +87 -90
- supervisely/nn/training/gui/classes_selector.py +16 -1
- supervisely/nn/training/train_app.py +28 -29
- supervisely/project/data_version.py +115 -51
- supervisely/project/download.py +1 -1
- supervisely/project/pointcloud_episode_project.py +37 -8
- supervisely/project/pointcloud_project.py +30 -2
- supervisely/project/project.py +14 -2
- supervisely/project/project_meta.py +27 -1
- supervisely/project/project_settings.py +32 -18
- supervisely/project/versioning/__init__.py +1 -0
- supervisely/project/versioning/common.py +20 -0
- supervisely/project/versioning/schema_fields.py +35 -0
- supervisely/project/versioning/video_schema.py +221 -0
- supervisely/project/versioning/volume_schema.py +87 -0
- supervisely/project/video_project.py +717 -15
- supervisely/project/volume_project.py +623 -5
- supervisely/template/experiment/experiment.html.jinja +4 -4
- supervisely/template/experiment/experiment_generator.py +14 -21
- supervisely/template/live_training/__init__.py +0 -0
- supervisely/template/live_training/header.html.jinja +96 -0
- supervisely/template/live_training/live_training.html.jinja +51 -0
- supervisely/template/live_training/live_training_generator.py +464 -0
- supervisely/template/live_training/sly-style.css +402 -0
- supervisely/template/live_training/template.html.jinja +18 -0
- supervisely/versions.json +28 -26
- supervisely/video/sampling.py +39 -20
- supervisely/video/video.py +40 -11
- supervisely/video_annotation/video_object.py +29 -4
- supervisely/volume/stl_converter.py +2 -0
- supervisely/worker_api/agent_rpc.py +24 -1
- supervisely/worker_api/rpc_servicer.py +31 -7
- {supervisely-6.73.452.dist-info → supervisely-6.73.513.dist-info}/METADATA +56 -39
- {supervisely-6.73.452.dist-info → supervisely-6.73.513.dist-info}/RECORD +189 -142
- {supervisely-6.73.452.dist-info → supervisely-6.73.513.dist-info}/WHEEL +1 -1
- {supervisely-6.73.452.dist-info → supervisely-6.73.513.dist-info}/entry_points.txt +0 -0
- {supervisely-6.73.452.dist-info → supervisely-6.73.513.dist-info/licenses}/LICENSE +0 -0
- {supervisely-6.73.452.dist-info → supervisely-6.73.513.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
from contextlib import contextmanager, asynccontextmanager
|
|
3
|
+
from typing import Optional, Union
|
|
4
|
+
|
|
5
|
+
from fastapi import Request
|
|
6
|
+
|
|
7
|
+
import supervisely.io.env as sly_env
|
|
8
|
+
from supervisely.api.module_api import ApiField
|
|
9
|
+
from supervisely.app.fastapi.websocket import WebsocketManager
|
|
10
|
+
from supervisely.sly_logger import logger
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _parse_int(value):
|
|
14
|
+
try:
|
|
15
|
+
return int(value)
|
|
16
|
+
except (TypeError, ValueError):
|
|
17
|
+
return None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _user_identity_from_cookie(request: Request) -> Optional[str]:
|
|
21
|
+
cookie_header = request.headers.get("cookie")
|
|
22
|
+
if not cookie_header:
|
|
23
|
+
return None
|
|
24
|
+
return hashlib.sha256(cookie_header.encode("utf-8")).hexdigest()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
async def extract_user_id_from_request(request: Request) -> Optional[Union[int, str]]:
|
|
28
|
+
"""Extract user ID from various parts of the request."""
|
|
29
|
+
if not sly_env.is_multiuser_mode_enabled():
|
|
30
|
+
return None
|
|
31
|
+
user_id = _parse_int(request.query_params.get("userId"))
|
|
32
|
+
if user_id is None:
|
|
33
|
+
header_user = _parse_int(request.headers.get("x-user-id"))
|
|
34
|
+
if header_user is not None:
|
|
35
|
+
user_id = header_user
|
|
36
|
+
if user_id is None:
|
|
37
|
+
referer = request.headers.get("referer", "")
|
|
38
|
+
if referer:
|
|
39
|
+
from urllib.parse import parse_qs, urlparse
|
|
40
|
+
|
|
41
|
+
try:
|
|
42
|
+
parsed_url = urlparse(referer)
|
|
43
|
+
query_params = parse_qs(parsed_url.query)
|
|
44
|
+
referer_user = query_params.get("userId", [None])[0]
|
|
45
|
+
user_id = _parse_int(referer_user)
|
|
46
|
+
except Exception as e:
|
|
47
|
+
logger.error(f"Error parsing userId from referer: {e}")
|
|
48
|
+
if user_id is None and "application/json" in request.headers.get("Content-Type", ""):
|
|
49
|
+
try:
|
|
50
|
+
payload = await request.json()
|
|
51
|
+
except Exception:
|
|
52
|
+
payload = {}
|
|
53
|
+
context = payload.get("context") or {}
|
|
54
|
+
user_id = _parse_int(context.get("userId") or context.get(ApiField.USER_ID))
|
|
55
|
+
if user_id is None:
|
|
56
|
+
state_payload = payload.get("state") or {}
|
|
57
|
+
user_id = _parse_int(state_payload.get("userId") or state_payload.get(ApiField.USER_ID))
|
|
58
|
+
if user_id is None:
|
|
59
|
+
user_id = _user_identity_from_cookie(request)
|
|
60
|
+
return user_id
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _session_context_impl(user_id: Optional[Union[int, str]]):
|
|
64
|
+
"""Internal implementation for session context."""
|
|
65
|
+
if not sly_env.is_multiuser_mode_enabled() or user_id is None:
|
|
66
|
+
return None
|
|
67
|
+
return sly_env.set_user_for_multiuser_app(user_id)
|
|
68
|
+
|
|
69
|
+
@contextmanager
|
|
70
|
+
def session_context(user_id: Optional[Union[int, str]]):
|
|
71
|
+
"""
|
|
72
|
+
Context manager to set and reset user context for multiuser applications.
|
|
73
|
+
Call this at the beginning of a request handling to ensure the correct user context is set in environment variables (`supervisely_multiuser_app_user_id` ContextVar).
|
|
74
|
+
"""
|
|
75
|
+
token = _session_context_impl(user_id)
|
|
76
|
+
try:
|
|
77
|
+
yield
|
|
78
|
+
finally:
|
|
79
|
+
if token is not None:
|
|
80
|
+
sly_env.reset_user_for_multiuser_app(token)
|
|
81
|
+
|
|
82
|
+
@asynccontextmanager
|
|
83
|
+
async def async_session_context(user_id: Optional[Union[int, str]]):
|
|
84
|
+
"""
|
|
85
|
+
Asynchronous context manager to set and reset user context for multiuser applications.
|
|
86
|
+
Call this at the beginning of an async request handling to ensure the correct user context is set in environment variables (`supervisely_multiuser_app_user_id` ContextVar).
|
|
87
|
+
"""
|
|
88
|
+
token = _session_context_impl(user_id)
|
|
89
|
+
try:
|
|
90
|
+
yield
|
|
91
|
+
finally:
|
|
92
|
+
if token is not None:
|
|
93
|
+
sly_env.reset_user_for_multiuser_app(token)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def remember_cookie(request: Request, user_id: Optional[Union[int, str]]):
|
|
97
|
+
"""
|
|
98
|
+
Remember user cookie for the given user ID. This is used to associate WebSocket connections with users in multiuser applications based on cookies.
|
|
99
|
+
Allows WebSocket connections to be correctly routed to the appropriate user.
|
|
100
|
+
"""
|
|
101
|
+
if not sly_env.is_multiuser_mode_enabled() or user_id is None:
|
|
102
|
+
return
|
|
103
|
+
cookie_header = request.headers.get("cookie")
|
|
104
|
+
if cookie_header:
|
|
105
|
+
WebsocketManager().remember_user_cookie(cookie_header, user_id)
|
|
@@ -1,23 +1,25 @@
|
|
|
1
|
+
import hashlib
|
|
1
2
|
import inspect
|
|
2
3
|
import json
|
|
3
4
|
import os
|
|
4
5
|
import signal
|
|
5
6
|
import sys
|
|
6
7
|
import time
|
|
7
|
-
from contextlib import suppress
|
|
8
|
+
from contextlib import contextmanager, suppress
|
|
8
9
|
from contextvars import ContextVar
|
|
9
10
|
from functools import wraps
|
|
10
11
|
from pathlib import Path
|
|
11
12
|
from threading import Event as ThreadingEvent
|
|
12
13
|
from threading import Thread
|
|
13
14
|
from time import sleep
|
|
14
|
-
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional
|
|
15
|
+
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
|
|
15
16
|
|
|
16
17
|
import arel
|
|
17
18
|
import jinja2
|
|
18
19
|
import numpy as np
|
|
19
20
|
import psutil
|
|
20
21
|
from async_asgi_testclient import TestClient
|
|
22
|
+
from cachetools import TTLCache
|
|
21
23
|
from fastapi import (
|
|
22
24
|
Depends,
|
|
23
25
|
FastAPI,
|
|
@@ -32,6 +34,7 @@ from fastapi.responses import JSONResponse
|
|
|
32
34
|
from fastapi.routing import APIRouter
|
|
33
35
|
from fastapi.staticfiles import StaticFiles
|
|
34
36
|
|
|
37
|
+
import supervisely.app.fastapi.multi_user as multi_user
|
|
35
38
|
import supervisely.io.env as sly_env
|
|
36
39
|
from supervisely._utils import (
|
|
37
40
|
is_debug_with_sly_net,
|
|
@@ -68,6 +71,10 @@ HEALTH_ENDPOINTS = ["/health", "/is_ready"]
|
|
|
68
71
|
# Context variable for response time
|
|
69
72
|
response_time_ctx: ContextVar[float] = ContextVar("response_time", default=None)
|
|
70
73
|
|
|
74
|
+
# Mapping from user_id to Api instance
|
|
75
|
+
_USER_API_CACHE = TTLCache(maxsize=500, ttl=60 * 15) # Cache up to 15 minutes
|
|
76
|
+
|
|
77
|
+
|
|
71
78
|
class ReadyzFilter(logging.Filter):
|
|
72
79
|
def filter(self, record):
|
|
73
80
|
if "/readyz" in record.getMessage() or "/livez" in record.getMessage():
|
|
@@ -623,18 +630,30 @@ def create(
|
|
|
623
630
|
shutdown(process_id, before_shutdown_callbacks)
|
|
624
631
|
|
|
625
632
|
if headless is False:
|
|
626
|
-
|
|
627
633
|
@app.post("/data")
|
|
628
634
|
async def send_data(request: Request):
|
|
629
|
-
|
|
630
|
-
|
|
635
|
+
if not sly_env.is_multiuser_mode_enabled():
|
|
636
|
+
data = DataJson()
|
|
637
|
+
response = JSONResponse(content=dict(data))
|
|
638
|
+
return response
|
|
639
|
+
user_id = await multi_user.extract_user_id_from_request(request)
|
|
640
|
+
multi_user.remember_cookie(request, user_id)
|
|
641
|
+
with multi_user.session_context(user_id):
|
|
642
|
+
data = DataJson()
|
|
643
|
+
response = JSONResponse(content=dict(data))
|
|
631
644
|
return response
|
|
632
645
|
|
|
633
646
|
@app.post("/state")
|
|
634
647
|
async def send_state(request: Request):
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
648
|
+
if not sly_env.is_multiuser_mode_enabled():
|
|
649
|
+
state = StateJson()
|
|
650
|
+
response = JSONResponse(content=dict(state))
|
|
651
|
+
else:
|
|
652
|
+
user_id = await multi_user.extract_user_id_from_request(request)
|
|
653
|
+
multi_user.remember_cookie(request, user_id)
|
|
654
|
+
with multi_user.session_context(user_id):
|
|
655
|
+
state = StateJson()
|
|
656
|
+
response = JSONResponse(content=dict(state))
|
|
638
657
|
gettrace = getattr(sys, "gettrace", None)
|
|
639
658
|
if (gettrace is not None and gettrace()) or is_development():
|
|
640
659
|
response.headers["x-debug-mode"] = "1"
|
|
@@ -813,41 +832,59 @@ def _init(
|
|
|
813
832
|
async def get_state_from_request(request: Request, call_next):
|
|
814
833
|
# Start timer for response time measurement
|
|
815
834
|
start_time = time.perf_counter()
|
|
816
|
-
if headless is False:
|
|
817
|
-
await StateJson.from_request(request)
|
|
818
|
-
|
|
819
|
-
if not ("application/json" not in request.headers.get("Content-Type", "")):
|
|
820
|
-
# {'command': 'inference_batch_ids', 'context': {}, 'state': {'dataset_id': 49711, 'batch_ids': [3120204], 'settings': None}, 'user_api_key': 'XXX', 'api_token': 'XXX', 'instance_type': None, 'server_address': 'https://app.supervisely.com'}
|
|
821
|
-
content = await request.json()
|
|
822
|
-
|
|
823
|
-
request.state.context = content.get("context")
|
|
824
|
-
request.state.state = content.get("state")
|
|
825
|
-
request.state.api_token = content.get(
|
|
826
|
-
"api_token",
|
|
827
|
-
(
|
|
828
|
-
request.state.context.get("apiToken")
|
|
829
|
-
if request.state.context is not None
|
|
830
|
-
else None
|
|
831
|
-
),
|
|
832
|
-
)
|
|
833
|
-
# logger.debug(f"middleware request api_token {request.state.api_token}")
|
|
834
|
-
request.state.server_address = content.get(
|
|
835
|
-
"server_address", sly_env.server_address(raise_not_found=False)
|
|
836
|
-
)
|
|
837
|
-
# request.state.server_address = sly_env.server_address(raise_not_found=False)
|
|
838
|
-
# logger.debug(f"middleware request server_address {request.state.server_address}")
|
|
839
|
-
# logger.debug(f"middleware request context {request.state.context}")
|
|
840
|
-
# logger.debug(f"middleware request state {request.state.state}")
|
|
841
|
-
if request.state.server_address is not None and request.state.api_token is not None:
|
|
842
|
-
request.state.api = Api(request.state.server_address, request.state.api_token)
|
|
843
|
-
else:
|
|
844
|
-
request.state.api = None
|
|
845
835
|
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
836
|
+
async def _process_request(request: Request, call_next):
|
|
837
|
+
if "application/json" in request.headers.get("Content-Type", ""):
|
|
838
|
+
content = await request.json()
|
|
839
|
+
request.state.context = content.get("context")
|
|
840
|
+
request.state.state = content.get("state")
|
|
841
|
+
request.state.api_token = content.get(
|
|
842
|
+
"api_token",
|
|
843
|
+
(
|
|
844
|
+
request.state.context.get("apiToken")
|
|
845
|
+
if request.state.context is not None
|
|
846
|
+
else None
|
|
847
|
+
),
|
|
848
|
+
)
|
|
849
|
+
request.state.server_address = content.get(
|
|
850
|
+
"server_address", sly_env.server_address(raise_not_found=False)
|
|
851
|
+
)
|
|
852
|
+
if (
|
|
853
|
+
request.state.server_address is not None
|
|
854
|
+
and request.state.api_token is not None
|
|
855
|
+
):
|
|
856
|
+
request.state.api = Api(
|
|
857
|
+
request.state.server_address, request.state.api_token
|
|
858
|
+
)
|
|
859
|
+
if sly_env.is_multiuser_mode_enabled():
|
|
860
|
+
user_id = sly_env.user_from_multiuser_app()
|
|
861
|
+
if user_id is not None:
|
|
862
|
+
_USER_API_CACHE[user_id] = request.state.api
|
|
863
|
+
else:
|
|
864
|
+
request.state.api = None
|
|
865
|
+
|
|
866
|
+
try:
|
|
867
|
+
response = await call_next(request)
|
|
868
|
+
except Exception as exc:
|
|
869
|
+
need_to_handle_error = is_production()
|
|
870
|
+
response = await process_server_error(
|
|
871
|
+
request, exc, need_to_handle_error
|
|
872
|
+
)
|
|
873
|
+
|
|
874
|
+
return response
|
|
875
|
+
|
|
876
|
+
if not sly_env.is_multiuser_mode_enabled():
|
|
877
|
+
if headless is False:
|
|
878
|
+
await StateJson.from_request(request)
|
|
879
|
+
response = await _process_request(request, call_next)
|
|
880
|
+
else:
|
|
881
|
+
user_id = await multi_user.extract_user_id_from_request(request)
|
|
882
|
+
multi_user.remember_cookie(request, user_id)
|
|
883
|
+
|
|
884
|
+
with multi_user.session_context(user_id):
|
|
885
|
+
if headless is False:
|
|
886
|
+
await StateJson.from_request(request, local=False)
|
|
887
|
+
response = await _process_request(request, call_next)
|
|
851
888
|
# Calculate response time and set it for uvicorn logger in ms
|
|
852
889
|
elapsed_ms = round((time.perf_counter() - start_time) * 1000)
|
|
853
890
|
response_time_ctx.set(elapsed_ms)
|
|
@@ -1277,3 +1314,12 @@ def call_on_autostart(
|
|
|
1277
1314
|
|
|
1278
1315
|
def get_name_from_env(default="Supervisely App"):
|
|
1279
1316
|
return os.environ.get("APP_NAME", default)
|
|
1317
|
+
|
|
1318
|
+
def session_user_api() -> Optional[Api]:
|
|
1319
|
+
"""Returns the API instance for the current session user."""
|
|
1320
|
+
if not sly_env.is_multiuser_mode_enabled():
|
|
1321
|
+
return Api.from_env()
|
|
1322
|
+
user_id = sly_env.user_from_multiuser_app()
|
|
1323
|
+
if user_id is None:
|
|
1324
|
+
return None
|
|
1325
|
+
return _USER_API_CACHE.get(user_id, None)
|
|
@@ -1,5 +1,10 @@
|
|
|
1
|
-
|
|
1
|
+
import hashlib
|
|
2
|
+
import time
|
|
3
|
+
from typing import Dict, List, Optional, Tuple, Union
|
|
4
|
+
|
|
2
5
|
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
|
6
|
+
|
|
7
|
+
import supervisely.io.env as sly_env
|
|
3
8
|
from supervisely.app.singleton import Singleton
|
|
4
9
|
|
|
5
10
|
|
|
@@ -8,6 +13,9 @@ class WebsocketManager(metaclass=Singleton):
|
|
|
8
13
|
self.app = None
|
|
9
14
|
self.path = path
|
|
10
15
|
self.active_connections: List[WebSocket] = []
|
|
16
|
+
self._connection_users: Dict[WebSocket, Optional[Union[int, str]]] = {}
|
|
17
|
+
self._cookie_user_map: Dict[str, Tuple[Union[int, str], float]] = {}
|
|
18
|
+
self._cookie_ttl_seconds = 60 * 60
|
|
11
19
|
|
|
12
20
|
def set_app(self, app: FastAPI):
|
|
13
21
|
if self.app is not None:
|
|
@@ -17,17 +25,42 @@ class WebsocketManager(metaclass=Singleton):
|
|
|
17
25
|
|
|
18
26
|
async def connect(self, websocket: WebSocket):
|
|
19
27
|
await websocket.accept()
|
|
28
|
+
user_id = self._resolve_user_id(websocket)
|
|
20
29
|
self.active_connections.append(websocket)
|
|
30
|
+
self._connection_users[websocket] = user_id
|
|
21
31
|
|
|
22
32
|
def disconnect(self, websocket: WebSocket):
|
|
23
|
-
self.active_connections
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
33
|
+
if websocket in self.active_connections:
|
|
34
|
+
self.active_connections.remove(websocket)
|
|
35
|
+
self._connection_users.pop(websocket, None)
|
|
36
|
+
|
|
37
|
+
def remember_user_cookie(
|
|
38
|
+
self, cookie_header: Optional[str], user_id: Optional[Union[int, str]]
|
|
39
|
+
):
|
|
40
|
+
if cookie_header is None or user_id is None:
|
|
41
|
+
return
|
|
42
|
+
fingerprint = self._cookie_fingerprint(cookie_header)
|
|
43
|
+
if fingerprint is None:
|
|
44
|
+
return
|
|
45
|
+
self._purge_cookie_cache()
|
|
46
|
+
self._cookie_user_map[fingerprint] = (user_id, time.monotonic())
|
|
47
|
+
|
|
48
|
+
async def broadcast(self, d: dict, user_id: Optional[Union[int, str]] = None):
|
|
49
|
+
if sly_env.is_multiuser_mode_enabled():
|
|
50
|
+
if user_id is None:
|
|
51
|
+
user_id = sly_env.user_from_multiuser_app()
|
|
52
|
+
if user_id is None:
|
|
53
|
+
targets = list(self.active_connections)
|
|
54
|
+
else:
|
|
55
|
+
targets = [
|
|
56
|
+
connection
|
|
57
|
+
for connection in self.active_connections
|
|
58
|
+
if self._connection_users.get(connection) == user_id
|
|
59
|
+
]
|
|
60
|
+
else:
|
|
61
|
+
targets = list(self.active_connections)
|
|
62
|
+
|
|
63
|
+
for connection in list(targets):
|
|
31
64
|
await connection.send_json(d)
|
|
32
65
|
|
|
33
66
|
async def endpoint(self, websocket: WebSocket):
|
|
@@ -37,3 +70,38 @@ class WebsocketManager(metaclass=Singleton):
|
|
|
37
70
|
data = await websocket.receive_text()
|
|
38
71
|
except WebSocketDisconnect:
|
|
39
72
|
self.disconnect(websocket)
|
|
73
|
+
|
|
74
|
+
def _resolve_user_id(self, websocket: WebSocket) -> Optional[int]:
|
|
75
|
+
if not sly_env.is_multiuser_mode_enabled():
|
|
76
|
+
return None
|
|
77
|
+
query_user = websocket.query_params.get("userId")
|
|
78
|
+
if query_user is not None:
|
|
79
|
+
try:
|
|
80
|
+
return int(query_user)
|
|
81
|
+
except ValueError:
|
|
82
|
+
pass
|
|
83
|
+
fingerprint = self._cookie_fingerprint(websocket.headers.get("cookie"))
|
|
84
|
+
if fingerprint is None:
|
|
85
|
+
return None
|
|
86
|
+
cached = self._cookie_user_map.get(fingerprint)
|
|
87
|
+
if cached is None:
|
|
88
|
+
return None
|
|
89
|
+
user_id, ts = cached
|
|
90
|
+
if time.monotonic() - ts > self._cookie_ttl_seconds:
|
|
91
|
+
self._cookie_user_map.pop(fingerprint, None)
|
|
92
|
+
return None
|
|
93
|
+
return user_id
|
|
94
|
+
|
|
95
|
+
@staticmethod
|
|
96
|
+
def _cookie_fingerprint(cookie_header: Optional[str]) -> Optional[str]:
|
|
97
|
+
if not cookie_header:
|
|
98
|
+
return None
|
|
99
|
+
return hashlib.sha256(cookie_header.encode("utf-8")).hexdigest()
|
|
100
|
+
|
|
101
|
+
def _purge_cookie_cache(self) -> None:
|
|
102
|
+
if not self._cookie_user_map:
|
|
103
|
+
return
|
|
104
|
+
cutoff = time.monotonic() - self._cookie_ttl_seconds
|
|
105
|
+
expired = [key for key, (_, ts) in self._cookie_user_map.items() if ts < cutoff]
|
|
106
|
+
for key in expired:
|
|
107
|
+
self._cookie_user_map.pop(key, None)
|
supervisely/app/singleton.py
CHANGED
|
@@ -1,11 +1,32 @@
|
|
|
1
|
+
import supervisely.io.env as sly_env
|
|
2
|
+
|
|
3
|
+
|
|
1
4
|
class Singleton(type):
|
|
2
5
|
_instances = {}
|
|
6
|
+
_nested_instances = {}
|
|
3
7
|
|
|
4
8
|
def __call__(cls, *args, **kwargs):
|
|
5
9
|
local = kwargs.pop("__local__", False)
|
|
6
10
|
if local is False:
|
|
7
11
|
if cls not in cls._instances:
|
|
8
12
|
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
|
|
13
|
+
|
|
14
|
+
if sly_env.is_multiuser_mode_enabled():
|
|
15
|
+
from supervisely.app.content import DataJson, StateJson
|
|
16
|
+
from copy import deepcopy
|
|
17
|
+
|
|
18
|
+
# Initialize nested instances dict once
|
|
19
|
+
nested_instances = cls._nested_instances.setdefault(cls, {})
|
|
20
|
+
|
|
21
|
+
user_id = sly_env.user_from_multiuser_app()
|
|
22
|
+
if user_id is not None and cls in (StateJson, DataJson):
|
|
23
|
+
if user_id not in nested_instances:
|
|
24
|
+
# Create new instance and copy data
|
|
25
|
+
instance = super(Singleton, cls).__call__(*args, **kwargs)
|
|
26
|
+
instance.update(deepcopy(dict(cls._instances[cls])))
|
|
27
|
+
nested_instances[user_id] = instance
|
|
28
|
+
|
|
29
|
+
return nested_instances[user_id]
|
|
9
30
|
return cls._instances[cls]
|
|
10
31
|
else:
|
|
11
32
|
return super(Singleton, cls).__call__(*args, **kwargs)
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
# isort: skip_file
|
|
2
|
+
|
|
1
3
|
import json
|
|
2
4
|
import os
|
|
3
5
|
import time
|
|
@@ -12,7 +14,8 @@ import queue
|
|
|
12
14
|
import re
|
|
13
15
|
|
|
14
16
|
from supervisely.worker_api.agent_api import AgentAPI
|
|
15
|
-
|
|
17
|
+
|
|
18
|
+
# from supervisely.worker_proto import worker_api_pb2 as api_proto # Import moved to methods where needed
|
|
16
19
|
from supervisely.function_wrapper import function_wrapper
|
|
17
20
|
from supervisely._utils import take_with_default
|
|
18
21
|
from supervisely.sly_logger import logger as default_logger
|
|
@@ -30,7 +33,6 @@ from supervisely._utils import _remove_sensitive_information
|
|
|
30
33
|
from supervisely.worker_api.agent_rpc import send_from_memory_generator
|
|
31
34
|
from supervisely.io.fs_cache import FileCache
|
|
32
35
|
|
|
33
|
-
|
|
34
36
|
# https://www.roguelynn.com/words/asyncio-we-did-it-wrong/
|
|
35
37
|
|
|
36
38
|
|
|
@@ -390,6 +392,13 @@ class AppService:
|
|
|
390
392
|
)
|
|
391
393
|
|
|
392
394
|
def publish_sync(self, initial_events=None):
|
|
395
|
+
try:
|
|
396
|
+
from supervisely.worker_proto import worker_api_pb2 as api_proto
|
|
397
|
+
except Exception as e:
|
|
398
|
+
from supervisely.app.v1.constants import PROTOBUF_REQUIRED_ERROR
|
|
399
|
+
|
|
400
|
+
raise ImportError(PROTOBUF_REQUIRED_ERROR) from e
|
|
401
|
+
|
|
393
402
|
if initial_events is not None:
|
|
394
403
|
for event_obj in initial_events:
|
|
395
404
|
event_obj["api_token"] = os.environ[API_TOKEN]
|
|
@@ -507,6 +516,13 @@ class AppService:
|
|
|
507
516
|
self._error = error
|
|
508
517
|
|
|
509
518
|
def send_response(self, request_id, data):
|
|
519
|
+
try:
|
|
520
|
+
from supervisely.worker_proto import worker_api_pb2 as api_proto
|
|
521
|
+
except Exception as e:
|
|
522
|
+
from supervisely.app.v1.constants import PROTOBUF_REQUIRED_ERROR
|
|
523
|
+
|
|
524
|
+
raise ImportError(PROTOBUF_REQUIRED_ERROR) from e
|
|
525
|
+
|
|
510
526
|
out_bytes = json.dumps(data).encode("utf-8")
|
|
511
527
|
self.api.put_stream_with_data(
|
|
512
528
|
"SendGeneralEventData",
|
supervisely/app/v1/constants.py
CHANGED
|
@@ -7,4 +7,10 @@ SHARED_DATA = '/sessions'
|
|
|
7
7
|
|
|
8
8
|
STOP_COMMAND = "stop"
|
|
9
9
|
|
|
10
|
-
IMAGE_ANNOTATION_EVENTS = ["manual_selected_figure_changed"]
|
|
10
|
+
IMAGE_ANNOTATION_EVENTS = ["manual_selected_figure_changed"]
|
|
11
|
+
|
|
12
|
+
# Error message for missing or incompatible protobuf dependencies
|
|
13
|
+
PROTOBUF_REQUIRED_ERROR = (
|
|
14
|
+
"protobuf is required for agent/worker/app_v1 functionality. "
|
|
15
|
+
"Please install supervisely with agent extras: pip install 'supervisely[agent]'"
|
|
16
|
+
)
|
|
@@ -104,6 +104,8 @@ from supervisely.app.widgets.pie_chart.pie_chart import PieChart
|
|
|
104
104
|
from supervisely.app.widgets.timeline.timeline import Timeline
|
|
105
105
|
from supervisely.app.widgets.nodes_flow.nodes_flow import NodesFlow
|
|
106
106
|
from supervisely.app.widgets.dialog.dialog import Dialog
|
|
107
|
+
from supervisely.app.widgets.modal.modal import Modal
|
|
108
|
+
from supervisely.app.widgets.activity_feed.activity_feed import ActivityFeed
|
|
107
109
|
from supervisely.app.widgets.draggable.draggable import Draggable
|
|
108
110
|
from supervisely.app.widgets.tooltip.tooltip import Tooltip
|
|
109
111
|
from supervisely.app.widgets.image_annotation_preview.image_annotation_preview import (
|
|
@@ -129,6 +131,9 @@ from supervisely.app.widgets.classes_mapping_preview.classes_mapping_preview imp
|
|
|
129
131
|
)
|
|
130
132
|
from supervisely.app.widgets.classes_list_selector.classes_list_selector import ClassesListSelector
|
|
131
133
|
from supervisely.app.widgets.classes_list_preview.classes_list_preview import ClassesListPreview
|
|
134
|
+
from supervisely.app.widgets.select_class.select_class import SelectClass
|
|
135
|
+
from supervisely.app.widgets.select_tag.select_tag import SelectTag
|
|
136
|
+
from supervisely.app.widgets.select_user.select_user import SelectUser
|
|
132
137
|
from supervisely.app.widgets.tags_list_selector.tags_list_selector import TagsListSelector
|
|
133
138
|
from supervisely.app.widgets.tags_list_preview.tags_list_preview import TagsListPreview
|
|
134
139
|
from supervisely.app.widgets.members_list_selector.members_list_selector import MembersListSelector
|
|
@@ -161,3 +166,4 @@ from supervisely.app.widgets.dropdown_checkbox_selector.dropdown_checkbox_select
|
|
|
161
166
|
from supervisely.app.widgets.ecosystem_model_selector.ecosystem_model_selector import (
|
|
162
167
|
EcosystemModelSelector,
|
|
163
168
|
)
|
|
169
|
+
from supervisely.app.widgets.heatmap.heatmap import Heatmap
|
|
File without changes
|