-
-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathviews.py
More file actions
1585 lines (1340 loc) · 55.6 KB
/
views.py
File metadata and controls
1585 lines (1340 loc) · 55.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
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
576
577
578
579
580
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
613
614
615
616
617
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
658
659
660
661
662
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
739
740
741
742
743
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
from __future__ import absolute_import
import json
import logging
import os
import pathlib
import random
import subprocess
import zipfile
from datetime import datetime
from tempfile import NamedTemporaryFile
from urllib.parse import quote
import httpx
import pyogrio
from botocore.exceptions import ClientError, NoCredentialsError
# import tensorflow as tf
from celery import current_app
from celery.result import AsyncResult
from django.conf import settings
from django.core.cache import cache
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.db import connections
from django.db.models import Count, Q
from django.db.utils import OperationalError
from django.http import (
Http404,
HttpResponse,
HttpResponseBadRequest,
HttpResponseRedirect,
JsonResponse,
)
from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.utils.timezone import now
from django.views.decorators.cache import cache_page
from django.views.decorators.vary import vary_on_cookie, vary_on_headers
from django_filters.rest_framework import DjangoFilterBackend
from django_q.tasks import async_task
from django_ratelimit.decorators import ratelimit
from geojson2osm import geojson2osm
from login.authentication import OsmAuthentication
from login.hanko_helpers import HankoUserFilterMixin
from login.permissions import (
IsAdminUser,
IsOsmAuthenticated,
IsOwnerOrReadOnly,
IsStaffUser,
)
from osmconflator import conflate_geojson
from rest_framework import decorators, filters, serializers, status, viewsets
from rest_framework.decorators import api_view
from rest_framework.exceptions import ValidationError as DRFValidationError
from rest_framework.generics import ListAPIView
from rest_framework.parsers import FormParser, MultiPartParser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_gis.fields import GeometryField
from rest_framework_gis.filters import InBBoxFilter, TMSTileFilter
from shapely.geometry import box
from login.authentication import OsmAuthentication
from login.permissions import (
IsAdminUser,
IsOsmAuthenticated,
IsOwnerOrReadOnly,
IsStaffUser,
)
from .exceptions import (
ExternalServiceException,
ResourceNotFoundException,
ValidationException,
handle_validation_error,
)
from .mapswipe_client import MapswipeClient
from .mixins import (
BaseModelViewSet,
BaseSpatialViewSet,
PublicFilterMixin,
UserAssignmentMixin,
)
from .models import (
AOI,
Banner,
Dataset,
Feedback,
Label,
Model,
OsmUser,
Prediction,
Training,
UserNotification,
)
from .responses import APIResponse, APIResponseCodes
from .serializers import (
AOISerializer,
BannerSerializer,
DatasetCentroidSerializer,
DatasetSerializer,
FeedbackSerializer,
LabelSerializer,
MapswipeProjectCreateSerializer,
ModelCentroidSerializer,
ModelMetaSerializer,
ModelSerializer,
PredictionParamSerializer,
TrainingSerializer,
UserNotificationSerializer,
UserSerializer,
UserStatsSerializer,
)
from .tasks import predict_area, process_mapswipe_results, train_model
from .utils import (
degrees_to_km,
download_s3_file,
get_api_version,
get_s3_directory,
gpx_generator,
km_to_degrees,
process_rawdata,
request_rawdata,
s3_object_exists,
send_notification,
)
from .validators import validate_geojson
# @cache_page(60 * settings.CACHE_TIMEOUT_MINUTES)
@api_view(["GET"])
def health(request):
status = {
"postgresql": False,
"redis": False,
"celery_workers": {},
"load": {},
"s3": None,
}
try:
connections["default"].cursor()
status["postgresql"] = True
except OperationalError:
status["postgresql"] = False
try:
cache.set("health_check", "ok", timeout=1)
if cache.get("health_check") == "ok":
status["redis"] = True
except Exception:
status["redis"] = False
inspect_active = {}
try:
i = current_app.control.inspect(timeout=1)
inspect_registered = i.registered() or {}
inspect_active = i.active() or {}
worker_names = sorted(
set(inspect_registered.keys()) | set(inspect_active.keys())
)
workers = [
{
"name": worker_name,
"online": worker_name in inspect_active
or worker_name in inspect_registered,
"active": bool(inspect_active.get(worker_name)),
}
for worker_name in worker_names
]
active_workers_count = sum(1 for worker in workers if worker["active"])
online_workers_count = sum(1 for worker in workers if worker["online"])
status["celery_workers"] = {
"online": online_workers_count,
"active": active_workers_count,
"workers": workers,
}
except Exception:
status["celery_workers"] = {}
try:
training_by_base_model = {
base_model: {"submitted": submitted, "running": running}
for base_model, submitted, running in Training.objects.values_list(
"model__base_model"
).annotate(
submitted=Count("id", filter=Q(status="SUBMITTED")),
running=Count("id", filter=Q(status="RUNNING")),
)
}
prediction_counts = Prediction.objects.aggregate(
submitted=Count("id", filter=Q(status="SUBMITTED")),
running=Count("id", filter=Q(status="RUNNING")),
)
status["load"] = {
"training": training_by_base_model,
"prediction": {
"submitted": prediction_counts["submitted"],
"running": prediction_counts["running"],
},
}
except Exception:
status["load"] = {}
try:
if settings.USE_S3_TO_UPLOAD_MODELS:
bucket = settings.BUCKET_NAME
if bucket and settings.S3_CLIENT:
try:
settings.S3_CLIENT.head_bucket(Bucket=bucket)
status["s3"] = True
except (ClientError, NoCredentialsError):
status["s3"] = False
else:
status["s3"] = False
else:
status["s3"] = None
except Exception:
status["s3"] = False
if settings.ENABLE_MAPSWIPE_INTEGREATION:
try:
client = MapswipeClient(
backend_url=settings.MAPSWIPE_BACKEND_URL,
manager_url=settings.MAPSWIPE_MANAGER_URL,
fb_auth_url=settings.MAPSWIPE_FB_AUTH_URL,
fb_username=settings.MAPSWIPE_FB_USERNAME,
fb_password=settings.MAPSWIPE_FB_PASSWORD,
csrftoken_key=settings.MAPSWIPE_CSRFTOKEN_KEY,
)
status["mapswipe_api"] = True
except Exception:
status["mapswipe_api"] = False
status["mapswipe_backend_url"] = settings.MAPSWIPE_BACKEND_URL
status["mapswipe_manager_url"] = settings.MAPSWIPE_MANAGER_URL
status["mapswipe_web_url"] = settings.MAPSWIPE_WEB_URL
return JsonResponse({"status": status})
@api_view(["GET"])
def home(request):
version = get_api_version()
return Response(
{
"name": "fAIr API",
"version": version,
"description": "AI-Assisted Mapping",
"documentation": {
"swagger": request.build_absolute_uri("/api/swagger/"),
"redoc": request.build_absolute_uri("/api/redoc/"),
"openapi_schema": request.build_absolute_uri("/api/swagger.json"),
},
"api": {"v1": request.build_absolute_uri("/api/v1/")},
}
)
class DatasetViewSet(HankoUserFilterMixin, BaseSpatialViewSet):
"""
API endpoint for managing training datasets.
Datasets contain training areas and associated models for AI-assisted mapping.
Supports spatial filtering and full CRUD operations.
Query Parameters:
- search: Search by dataset name
- status: Filter by status (DRAFT, PUBLISHED)
- ordering: Order results by field
"""
queryset = Dataset.objects.all()
serializer_class = DatasetSerializer
public_methods = ["GET"]
filter_backends = (
DjangoFilterBackend,
filters.SearchFilter,
)
filterset_fields = ["user", "status", "id"]
search_fields = ["id", "name"]
def partial_update(self, request, *args, **kwargs):
if "offset" in request.data:
# Bypass self.get_object() to skip IsOsmAuthenticated's ownership check
# This allows ANY authenticated user to update the offset ## FIXME : I don't like this at all , for now i am allowing as a temp check later cloning of dataset would be recommended
instance = get_object_or_404(self.get_queryset(), pk=kwargs.get("pk"))
serializer = self.get_serializer(
instance, data={"offset": request.data["offset"]}, partial=True
)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
return Response(serializer.data)
return super().partial_update(request, *args, **kwargs)
@method_decorator(
ratelimit(key="user", rate="10/h", method="POST", block=True), name="create"
)
class TrainingViewSet(BaseModelViewSet):
"""
API endpoint for managing model training sessions.
Training sessions use labeled data from datasets to train AI models.
Rate-limited to 10 creations per hour per user.
"""
queryset = Training.objects.all()
http_method_names = ["get", "post", "delete"]
serializer_class = TrainingSerializer
filterset_fields = ["model", "status", "user", "id"]
ordering_fields = ["created_at", "accuracy", "id", "model", "status"]
search_fields = ["description", "id", "model__name"]
public_methods = ["GET"]
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
def create(self, request, *args, **kwargs):
return super().create(request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
data = serializer.data
data.update(
{
"feedback_count": Feedback.objects.filter(
training=instance.id, action="REJECT"
).count(),
"approved_predictions_count": Feedback.objects.filter(
training=instance.id, action="ACCEPT"
).count(),
}
)
return Response(data)
def destroy(self, request, *args, **kwargs):
return super().destroy(request, *args, **kwargs)
class FeedbackViewset(BaseSpatialViewSet):
"""
API endpoint for managing training feedback.
Feedback allows users to accept or reject predictions to improve model quality.
Supports spatial filtering by geometry.
"""
queryset = Feedback.objects.all()
serializer_class = FeedbackSerializer
bbox_filter_field = "geom"
filterset_fields = ["training", "user", "action"]
public_methods = ["GET"]
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs):
return super().retrieve(request, *args, **kwargs)
def create(self, request, *args, **kwargs):
return super().create(request, *args, **kwargs)
class ModelViewSet(HankoUserFilterMixin, BaseSpatialViewSet):
"""
API endpoint for managing AI models.
Models are trained versions that can be published for use in predictions.
Supports filtering by status, dataset, and date ranges.
"""
queryset = Model.objects.all()
serializer_class = ModelSerializer
filterset_fields = {
"status": ["exact"],
"created_at": ["exact", "gt", "gte", "lt", "lte"],
"last_modified": ["exact", "gt", "gte", "lt", "lte"],
"user": ["exact"],
"dataset": ["exact"],
"id": ["exact"],
}
ordering_fields = ["created_at", "last_modified", "id", "status"]
search_fields = ["name", "id"]
public_methods = ["GET"]
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
def create(self, request, *args, **kwargs):
return super().create(request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs):
return super().retrieve(request, *args, **kwargs)
def update(self, request, *args, **kwargs):
return super().update(request, *args, **kwargs)
def partial_update(self, request, *args, **kwargs):
return super().partial_update(request, *args, **kwargs)
def destroy(self, request, *args, **kwargs):
return super().destroy(request, *args, **kwargs)
class ModelCentroidView(ListAPIView):
queryset = Model.objects.filter(status=0) ## only deliver the published model
serializer_class = ModelCentroidSerializer
filter_backends = (
# InBBoxFilter,
DjangoFilterBackend,
filters.SearchFilter,
)
filterset_fields = ["id"]
search_fields = ["name"]
pagination_class = None
class DatasetCentroidView(ListAPIView):
queryset = Dataset.objects.filter(status=0) ## only deliver the active datasets
serializer_class = DatasetCentroidSerializer
filter_backends = (
# InBBoxFilter,
DjangoFilterBackend,
filters.SearchFilter,
)
filterset_fields = ["id"]
search_fields = ["name", "id"]
pagination_class = None
class UsersView(ListAPIView):
authentication_classes = [OsmAuthentication]
permission_classes = [IsAdminUser, IsStaffUser]
queryset = OsmUser.objects.all()
serializer_class = UserStatsSerializer
filter_backends = (
DjangoFilterBackend,
filters.SearchFilter,
)
filterset_fields = ["osm_id"]
search_fields = ["username", "osm_id"]
class AOIViewSet(BaseModelViewSet):
"""
API endpoint for managing Areas of Interest (AOI).
AOIs define geographic regions within datasets for labeling and training.
"""
queryset = AOI.objects.all()
serializer_class = AOISerializer
filterset_fields = ["dataset"]
public_methods = ["GET"]
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
def create(self, request, *args, **kwargs):
return super().create(request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs):
return super().retrieve(request, *args, **kwargs)
def update(self, request, *args, **kwargs):
return super().update(request, *args, **kwargs)
def partial_update(self, request, *args, **kwargs):
return super().partial_update(request, *args, **kwargs)
def destroy(self, request, *args, **kwargs):
return super().destroy(request, *args, **kwargs)
class LabelViewSet(BaseSpatialViewSet):
"""
API endpoint for managing training labels.
Labels are geographic features used to train AI models.
Supports spatial filtering and GeoJSON upload.
"""
queryset = Label.objects.all()
serializer_class = LabelSerializer
bbox_filter_field = "geom"
pagination_class = None
filterset_fields = ["aoi", "aoi__dataset"]
public_methods = ["GET"]
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs):
return super().retrieve(request, *args, **kwargs)
def create(self, request, *args, **kwargs):
serializer = LabelSerializer(data=request.data)
if serializer.is_valid():
aoi_id = serializer.validated_data.get("aoi")
geom = serializer.validated_data.get("geom")
existing_label = Label.objects.filter(aoi=aoi_id, geom=geom).first()
if existing_label:
serializer = LabelSerializer(existing_label, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
else:
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class LabelUploadView(APIView):
authentication_classes = [OsmAuthentication]
permission_classes = [IsOsmAuthenticated]
parser_classes = (MultiPartParser, FormParser)
def post(self, request, aoi_id, *args, **kwargs):
geojson_file = request.FILES.get("geojson_file")
if geojson_file:
try:
geojson_data = json.load(geojson_file)
self.validate_geojson(geojson_data)
async_task(
"core.views.process_labels_geojson",
geojson_data,
aoi_id,
)
return Response(
{"status": "GeoJSON file is being processed"},
status=status.HTTP_202_ACCEPTED,
)
except (json.JSONDecodeError, ValidationException) as e:
raise e
raise handle_validation_error("geojson_file", "No GeoJSON file provided")
def validate_geojson(self, geojson_data):
return validate_geojson(geojson_data)
def validate_geojson(self, geojson_data):
if geojson_data.get("type") != "FeatureCollection":
raise handle_validation_error(
"geojson_type",
"Invalid GeoJSON type. Expected 'FeatureCollection'",
geojson_data.get("type"),
)
if "features" not in geojson_data or not isinstance(
geojson_data["features"], list
):
raise handle_validation_error(
"geojson_features", "Invalid GeoJSON format. 'features' must be a list"
)
if not geojson_data["features"]:
raise handle_validation_error(
"geojson_features", "GeoJSON 'features' list is empty"
)
first_feature = geojson_data["features"][0]
if first_feature.get("type") != "Feature":
raise handle_validation_error(
"geojson_feature_type",
"Invalid GeoJSON feature type. Expected 'Feature'",
first_feature.get("type"),
)
if "geometry" not in first_feature or "properties" not in first_feature:
raise handle_validation_error(
"geojson_feature_format",
"Invalid GeoJSON feature format. 'geometry' and 'properties' are required",
)
first_feature["properties"]["aoi"] = self.kwargs.get("aoi_id")
serializer = LabelSerializer(data=first_feature)
if not serializer.is_valid():
raise ValidationException(
message="Label validation failed",
details={"serializer_errors": serializer.errors},
)
def process_labels_geojson(geojson_data, aoi_id):
obj = get_object_or_404(AOI, id=aoi_id)
try:
obj.label_status = AOI.DownloadStatus.RUNNING
obj.save()
for feature in geojson_data["features"]:
feature["properties"]["aoi"] = aoi_id
serializer = LabelSerializer(data=feature)
if serializer.is_valid():
serializer.save()
obj.label_status = AOI.DownloadStatus.DOWNLOADED
obj.label_fetched = datetime.utcnow()
obj.save()
except Exception as ex:
obj.label_status = AOI.DownloadStatus.NOT_DOWNLOADED
obj.save()
logging.error(ex)
class RawdataApiAOIView(APIView):
authentication_classes = [OsmAuthentication]
permission_classes = [IsOsmAuthenticated]
def post(self, request, aoi_id, *args, **kwargs):
"""Downloads available osm data as labels within given AOI
Args:
request (_type_): _description_
aoi_id (_type_): _description_
Returns:
status: Success/Failed
"""
obj = get_object_or_404(AOI, id=aoi_id)
async_task("core.views.process_rawdata_task", obj.geom.geojson, aoi_id)
return Response("Processing started", status=status.HTTP_202_ACCEPTED)
def process_rawdata_task(geom_geojson, aoi_id):
obj = get_object_or_404(AOI, id=aoi_id)
try:
obj.label_status = AOI.DownloadStatus.RUNNING
obj.save()
file_download_url = request_rawdata(geom_geojson)
process_rawdata(file_download_url, aoi_id)
obj.label_status = AOI.DownloadStatus.DOWNLOADED
obj.label_fetched = datetime.utcnow()
obj.save()
except Exception as ex:
obj.label_status = AOI.DownloadStatus.NOT_DOWNLOADED
obj.save()
raise ex
@api_view(["GET"])
def download_training_data(request, dataset_id: int):
"""Used for Delivering our training folder to user.
Returns zip file if it is present on our server if not returns error
"""
file_path = os.path.join(
settings.TRAINING_WORKSPACE, f"dataset_{dataset_id}", "input"
)
zip_temp_path = os.path.join(
settings.TRAINING_WORKSPACE, f"dataset_{dataset_id}.zip"
)
directory = pathlib.Path(file_path)
if os.path.exists(directory):
zf = zipfile.ZipFile(zip_temp_path, "w", zipfile.ZIP_DEFLATED)
for file_path in directory.iterdir():
zf.write(file_path, arcname=file_path.name)
zf.close()
if os.path.exists(zip_temp_path):
response = HttpResponse(open(zip_temp_path, "rb"))
response.headers["Content-Type"] = "application/x-zip-compressed"
response.headers["Content-Disposition"] = (
f"attachment; filename=training_{dataset_id}_all_data.zip"
)
return response
else:
# "error": "File Doesn't Exist or has been cleared up from system",
return HttpResponse(status=204)
else:
# "error": "Dataset haven't been downloaded or doesn't exist",
return HttpResponse(status=204)
# @api_view(["POST"])
# def geojson2osmconverter(request):
# try:
# geojson_data = json.loads(request.body)["geojson"]
# except json.JSONDecodeError:
# return HttpResponseBadRequest("Invalid input")
# osm_xml = geojson2osm(geojson_data)
# return HttpResponse(osm_xml, content_type="application/xml")
@api_view(["POST"])
def ConflateGeojson(request):
try:
geojson_data = json.loads(request.body)["geojson"]
except json.JSONDecodeError:
return HttpResponseBadRequest("Invalid input")
conflated_geojson = conflate_geojson(
geojson_data, remove_conflated=True, api_url=settings.EXPORT_TOOL_API_URL
)
return Response(conflated_geojson, status=200)
@api_view(["GET"])
@ratelimit(key="user_or_ip", rate="30/m", method="GET", block=False)
def run_task_status(request, run_id: str):
cache_key = f"task_status_{run_id}"
cached_result = cache.get(cache_key)
if cached_result:
return Response(cached_result)
task_result = AsyncResult(run_id, app=current_app)
if task_result.failed():
result = {
"id": run_id,
"status": task_result.state,
"error": str(task_result.result),
"traceback": str(task_result.traceback),
}
cache.set(cache_key, result, 2)
return Response(result)
if task_result.state in ("PENDING", "STARTED"):
log_file = os.path.join(settings.LOG_PATH, f"run_{run_id}.log")
output = ""
if os.path.exists(log_file):
try:
from collections import deque
with open(log_file, "r") as f:
lines = deque(f, maxlen=settings.LOG_LINE_STREAM_TRUNCATE_VALUE)
output = "".join(lines)
except Exception as e:
output = str(e)
result = {
"id": run_id,
"status": task_result.state,
"result": task_result.result,
"traceback": output,
}
cache.set(cache_key, result, 2)
return Response(result)
result = {
"id": run_id,
"status": task_result.state,
"result": task_result.result,
}
cache.set(cache_key, result, 2)
return Response(result)
DEFAULT_TILE_SIZE = 256
@api_view(["POST"])
@decorators.authentication_classes([OsmAuthentication])
@decorators.permission_classes([IsOsmAuthenticated])
def publish_training(request, training_id: int):
"""Publishes training for model"""
training_instance = get_object_or_404(Training, id=training_id)
model_instance = get_object_or_404(Model, id=training_instance.model.id)
if training_instance.status != "FINISHED":
return Response("Training is not FINISHED", status=409)
if model_instance.base_model == "RAMP":
if training_instance.accuracy < 70:
return Response(
"Can't publish the training since its accuracy is below 70%", status=403
)
else:
if training_instance.accuracy < 5:
return Response(
"Can't publish the training since its accuracy is below 5%", status=403
)
# Check if the current user is the owner of the model
if model_instance.user != request.user:
return Response("You are not allowed to publish this training", status=403)
model_instance.published_training = training_instance.id
model_instance.status = 0
model_instance.save()
return Response("Training Published", status=status.HTTP_201_CREATED)
class GenerateGpxView(APIView):
def get(self, request, aoi_id: int):
aoi = get_object_or_404(AOI, id=aoi_id)
geom_json = json.loads(aoi.geom.json)
gpx_xml = gpx_generator(geom_json)
return HttpResponse(gpx_xml, content_type="application/xml")
class TrainingWorkspaceView(APIView):
@method_decorator(cache_page(60 * settings.CACHE_TIMEOUT_MINUTES))
@method_decorator(vary_on_headers("access-token"))
def get(self, request, lookup_dir):
parent = settings.PARENT_BUCKET_FOLDER
lookup = (lookup_dir or "").strip("/")
encoded_file_path = quote(lookup) if lookup else ""
s3_prefix = (
f"{parent}/{encoded_file_path}/" if encoded_file_path else f"{parent}/"
)
try:
data = get_s3_directory(settings.BUCKET_NAME, s3_prefix)
except Exception as e:
return Response({"Error": str(e)}, status=500)
return Response(data, status=status.HTTP_200_OK)
class TrainingWorkspaceDownloadView(APIView):
def get(self, request, lookup_dir):
s3_key = os.path.join(settings.PARENT_BUCKET_FOLDER, lookup_dir)
bucket_name = settings.BUCKET_NAME
if not s3_object_exists(bucket_name, s3_key):
return Response("File not found in S3", status=404)
presigned_url = download_s3_file(bucket_name, s3_key)
# ?url_only=true
url_only = request.query_params.get("url_only", "false").lower() == "true"
if url_only:
return Response({"result": presigned_url})
else:
return HttpResponseRedirect(presigned_url)
class BannerViewSet(viewsets.ModelViewSet):
"""
API endpoint for managing notification banners.
Banners are time-bound messages displayed to users.
Read access is public, write operations require admin/staff permissions.
"""
queryset = Banner.objects.all()
serializer_class = BannerSerializer
authentication_classes = [OsmAuthentication]
permission_classes = [IsAdminUser, IsStaffUser]
pagination_class = None
public_methods = ["GET"]
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs):
return super().retrieve(request, *args, **kwargs)
def create(self, request, *args, **kwargs):
return super().create(request, *args, **kwargs)
def update(self, request, *args, **kwargs):
return super().update(request, *args, **kwargs)
def destroy(self, request, *args, **kwargs):
return super().destroy(request, *args, **kwargs)
def get_queryset(self):
now = timezone.now()
return Banner.objects.filter(start_date__lte=now).filter(
end_date__gte=now
) | Banner.objects.filter(end_date__isnull=True)
@cache_page(60 * settings.CACHE_TIMEOUT_MINUTES)
@api_view(["GET"])
def get_kpi_stats(request):
total_models_with_status_published = Model.objects.filter(status=0).count()
total_registered_users = OsmUser.objects.count()
total_accepted_predictions = Feedback.objects.filter(action="ACCEPT").count()
total_feedback_labels = Feedback.objects.filter(action="REJECT").count()
data = {
"total_models_published": total_models_with_status_published,
"total_registered_users": total_registered_users,
"total_accepted_predictions": total_accepted_predictions,
"total_feedback_labels": total_feedback_labels,
}
return Response(data)
class UserNotificationViewSet(ReadOnlyModelViewSet):
"""
API endpoint for user notifications.
Allows users to view their notifications. Read-only.
Use separate endpoints to mark as read.
"""
authentication_classes = [OsmAuthentication]
permission_classes = [IsOsmAuthenticated]
serializer_class = UserNotificationSerializer
filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
filterset_fields = ["is_read"]
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs):
return super().retrieve(request, *args, **kwargs)
ordering = ["-created_at"]
ordering_fields = ["created_at", "read_at", "is_read"]
def get_queryset(self):
return UserNotification.objects.filter(user=self.request.user)
class MarkNotificationAsRead(APIView):
authentication_classes = [OsmAuthentication]
permission_classes = [IsOsmAuthenticated]
def post(self, request, notification_id, format=None):
try:
notification = UserNotification.objects.get(
id=notification_id, user=request.user
)
if notification.is_read:
return Response(
{"detail": "Notification is already marked as read."},
status=status.HTTP_200_OK,
)
notification.is_read = True
notification.read_at = timezone.now()
notification.save()
return Response(
{"detail": "Notification marked as read."}, status=status.HTTP_200_OK
)
except UserNotification.DoesNotExist:
return Response(
{"detail": "Notification not found."}, status=status.HTTP_404_NOT_FOUND
)
class MarkAllNotificationsAsRead(APIView):
authentication_classes = [OsmAuthentication]
permission_classes = [IsOsmAuthenticated]
def post(self, request, format=None):
unread_notifications = UserNotification.objects.filter(
user=request.user, is_read=False
)
if not unread_notifications.exists():
return Response(
{"detail": "No unread notifications found."},
status=status.HTTP_404_NOT_FOUND,
)
unread_notifications.update(is_read=True, read_at=timezone.now())
return Response(
{"detail": "All unread notifications marked as read."},
status=status.HTTP_200_OK,
)
class TerminateTrainingView(APIView):
authentication_classes = [OsmAuthentication]
permission_classes = [IsOsmAuthenticated]
def post(self, request, training_id, format=None):
try:
training_instance = Training.objects.get(id=training_id, user=request.user)
task_id = training_instance.task_id
if not task_id:
return Response(
{"detail": "No task associated with this training."},
status=status.HTTP_400_BAD_REQUEST,
)
task = AsyncResult(task_id, app=current_app)
if (
task.state in ["PENDING", "STARTED", "RETRY", "FAILURE"]
and training_instance.status != "FAILED"
):
current_app.control.revoke(task_id, terminate=True)
training_instance.status = "FAILED"
training_instance.finished_at = now()
training_instance.save()
send_notification(training_instance, "Cancelled")
return Response(
{"detail": "Training task cancelled successfully."},
status=status.HTTP_200_OK,
)
else:
return Response(
{
"detail": f"Task cannot be cancelled. Current state: {task.state}"