Skip to content

Commit

Permalink
Merge pull request #286 from 5sControl/development
Browse files Browse the repository at this point in the history
Development
  • Loading branch information
Dimskay1988 authored Jun 15, 2023
2 parents ade9f65 + 7efd071 commit 02347d5
Show file tree
Hide file tree
Showing 11 changed files with 479 additions and 392 deletions.
8 changes: 4 additions & 4 deletions src/Core/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
if not SERVER_URL:
SERVER_URL = config("SERVER_URL")

PRODUCTION = os.environ.get("PRODUCTION")
if PRODUCTION is not None and PRODUCTION.lower() == "true":
PRODUCTION = True
EMULATE_DB = os.environ.get("EMULATE_DB")
if EMULATE_DB is not None and EMULATE_DB.lower() == "true":
EMULATE_DB = True
else:
PRODUCTION = False
EMULATE_DB = False

safety_control_ear_protection_description = """
Designed to ensure that the workers in a particular area are wearing ear protection to safeguard their hearing.
Expand Down
54 changes: 42 additions & 12 deletions src/Core/management/commands/startprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@

from django.core.management.base import BaseCommand

from src.Core.const import SERVER_URL
from src.Core.exceptions import SenderError, InvalidResponseError
from src.Inventory.models import Items

from src.CameraAlgorithms.models.camera import ZoneCameras
from src.CameraAlgorithms.models import Camera, CameraAlgorithm
from src.CameraAlgorithms.services.cameraalgorithm import (
camera_rtsp_link,
Expand All @@ -30,23 +32,52 @@ def start_process(self) -> None:
algorithm_obj: CameraAlgorithm = camera_algorithm.algorithm
rtsp_link: str = camera_rtsp_link(camera_obj.id)

request: Dict[str, Any] = {
"camera_url": rtsp_link,
"algorithm": algorithm_obj.name,
"server_url": SERVER_URL,
"extra": extra_params,
}

if camera_algorithm.algorithm.name == "machine_control":
all_zones = camera_algorithm.zones
cords = []
for zone_id in all_zones:
zone_camera = ZoneCameras.objects.get(id=zone_id["id"], camera=camera_obj)
coords = zone_camera.coords
coords[0]["zoneId"] = zone_camera.id
coords[0]["zoneName"] = "zone " + str(zone_camera.name)

new_object = {"coords": coords}

cords.append(new_object)

extra_params.append({"coords": coords})

if camera_algorithm.algorithm.name == "min_max_control":
algorithm_items = Items.objects.filter(camera=camera_obj)
areas = []
stelag = []

for item in algorithm_items:
extra_params.append(
{
"itemId": item.id,
"coords": item.coords,
"itemName": item.name,
}
areas.append(
{"itemId": item.id, "itemName": item.name, "coords": item.coords}
)

request: Dict[str, Any] = {
"camera_url": rtsp_link,
"algorithm": algorithm_obj.name,
"extra": extra_params,
}
all_zones = camera_algorithm.zones

for zone_id in all_zones:
zone_camera = ZoneCameras.objects.get(id=zone_id["id"], camera=camera_obj)

stelag.append(
{"zoneId": zone_camera.id, "zoneName": zone_camera.name, "coords": zone_camera.coords}
)

new_data = {
"areas": areas,
"zones": stelag
}
extra_params.append(new_data)

try:
result = send_run_request(request)
Expand All @@ -58,6 +89,5 @@ def start_process(self) -> None:
)
else:
new_process_id = result["pid"]

camera_algorithm.process_id = new_process_id
camera_algorithm.save()
18 changes: 18 additions & 0 deletions src/Reports/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,21 @@ class OperationReportSerializer(serializers.ModelSerializer):
class Meta:
model = SkanyReport
fields = ["id", "operationID", "camera_ip", "startTime", "endTime"]


class ReportByIDSerializer(serializers.ModelSerializer):
algorithm = AlgorithmSerializer()
camera = serializers.StringRelatedField()

class Meta:
model = Report
fields = [
"id",
"start_tracking",
"stop_tracking",
"violation_found",
"extra",
"status",
"algorithm",
"camera",
]
9 changes: 5 additions & 4 deletions src/Reports/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def create_skanyreport(
report_data: List[Dict],
violation_found: bool,
start_tracking: str,
end_tracking: str
end_tracking: str,
) -> None:
start_dt = datetime.strptime(start_tracking, "%Y-%m-%d %H:%M:%S.%f")
start_utc = start_dt.replace(tzinfo=timezone.utc)
Expand All @@ -53,12 +53,13 @@ def create_skanyreport(
end_gmt = end_utc.astimezone(timezone(timedelta(hours=0)))
eTime = int(end_gmt.timestamp())


skany_indeks = report_data[0].get("skany_index")
zlecenie = report_data[0].get("zlecenie")
execution_date = report_data[0].get("execution_date")

logger.warning(f"Creating Skany Report start_tracking -> {start_tracking} - {sTime}, end_tracking -> {end_tracking} - {eTime}")
logger.warning(
f"Creating Skany Report start_tracking -> {start_tracking} - {sTime}, end_tracking -> {end_tracking} - {eTime}"
)

SkanyReport.objects.create(
report=report,
Expand All @@ -68,4 +69,4 @@ def create_skanyreport(
violation_found=violation_found,
start_time=sTime,
end_time=eTime,
)
)
2 changes: 2 additions & 0 deletions src/Reports/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
ActionViewSet,
SearchReportListView,
GetOperationVideoInfo,
GetReportByID,
)


Expand All @@ -15,6 +16,7 @@

urlpatterns = [
path("report-with-photos/", ActionsWithPhotos.as_view()),
path("by-id/<int:pk>/", GetReportByID.as_view(), name="get-report-by-id"),
path(
"search/<str:algorithm_name>/<str:camera_ip>/<str:date>/<str:start_time>/<str:end_time>/",
ReportListView.as_view(),
Expand Down
51 changes: 32 additions & 19 deletions src/Reports/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,31 @@

from django.db.models import Q

from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.generics import GenericAPIView, ListAPIView, RetrieveAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.exceptions import MethodNotAllowed
from rest_framework import status, viewsets
from rest_framework.views import APIView
from rest_framework.response import Response

from src.CompanyLicense.decorators import validate_license
from src.Core.const import PRODUCTION, SERVER_URL
from src.Core.const import EMULATE_DB, SERVER_URL
from src.Core.paginators import NoPagination
from src.ImageReport.models import Image
from src.CameraAlgorithms.models import Camera
from src.CameraAlgorithms.models import Algorithm
from src.Reports.models import Report, SkanyReport
from src.Reports.serializers import ReportSerializers, OperationReportSerializer
from src.Reports.serializers import (
ReportSerializers,
OperationReportSerializer,
ReportByIDSerializer,
)
from src.Inventory.service import process_item_status
from src.Reports.service import edit_extra, create_skanyreport

logger = logging.getLogger(__name__)



class ActionViewSet(viewsets.ModelViewSet):
queryset = Report.objects.all().order_by("-id")
serializer_class = ReportSerializers
Expand Down Expand Up @@ -56,7 +59,7 @@ def post(self, request):

algorithm = Algorithm.objects.get(name=algorithm_name)
camera = Camera.objects.get(id=camera_ip)

start_tracking = data.get("start_tracking")
stop_tracking = data.get("stop_tracking")

Expand All @@ -68,16 +71,23 @@ def post(self, request):
extra = process_item_status(data.get("extra"))

elif algorithm_name == "operation_control":
if not PRODUCTION:
if 'extra' in data:
for data in data['extra']:
if 'place' in data:
logger.warning(f"Operation control extra data is {data}")
requests.post(f"{SERVER_URL}:9876/skany/create/", json=data['extra'][0])
if EMULATE_DB:
if "extra" in data:
for data in data["extra"]:
if "place" in data:
logger.warning(
f"Operation control extra data is {data}"
)
requests.post(
f"{SERVER_URL}:9876/skany/create/",
json=data["extra"][0],
)
break
else:
logger.warning(f"Operation control extra data is {data}")
requests.post(f"{SERVER_URL}:9876/operation-control/", json=data)
requests.post(
f"{SERVER_URL}:9876/operation-control/", json=data
)
extra = edit_extra(data.get("extra"), camera)
else:
extra = data.get("extra")
Expand All @@ -97,11 +107,7 @@ def post(self, request):

if algorithm_name == "operation_control":
create_skanyreport(
action,
extra,
not violation_found,
start_tracking,
stop_tracking
action, extra, not violation_found, start_tracking, stop_tracking
)

if photos:
Expand Down Expand Up @@ -148,7 +154,9 @@ def get(self, request, algorithm_name, camera_ip, date, start_time, end_time):
if camera_ip:
queryset = queryset.filter(camera__id=camera_ip)
if algorithm_name:
queryset = queryset.exclude(algorithm__name='min_max_control').filter(algorithm__name=algorithm_name)
queryset = queryset.exclude(algorithm__name="min_max_control").filter(
algorithm__name=algorithm_name
)

queryset = queryset.order_by("algorithm__name", "camera__id", "id")

Expand Down Expand Up @@ -185,7 +193,7 @@ def get_queryset(self):
algorithm_filters |= Q(algorithm__name=algorithm_name)
queryset = queryset.filter(algorithm_filters)

queryset = queryset.exclude(algorithm__name='min_max_control')
queryset = queryset.exclude(algorithm__name="min_max_control")

queryset = queryset.order_by("-id")

Expand All @@ -204,3 +212,8 @@ class GetOperationVideoInfo(ListAPIView):

def get_queryset(self):
return SkanyReport.objects.exclude(start_time__isnull=True)


class GetReportByID(RetrieveAPIView):
queryset = Report.objects.all()
serializer_class = ReportByIDSerializer
2 changes: 2 additions & 0 deletions src/newOrderView/services/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from .operations import OperationServices
from .order import OrderServises
Loading

0 comments on commit 02347d5

Please sign in to comment.