Skip to content

Views

AudioDataViewSet

Bases: ModelViewSet

Source code in API/hardware/views.py
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
class AudioDataViewSet(viewsets.ModelViewSet):
    queryset = DataAudio.objects.all()
    serializer_class = AudioDataSerializer

    @swagger_auto_schema(
        operation_summary="Get an audio data s3 url",
        operation_description="Get an audio data",
        responses={200: "The audio data"},
        tags=["hardware"],
    )
    @action(
        detail=False,
        methods=["post"],
        url_path="get_audio_data",
        url_name="get_audio_data",
    )
    def get_audio_data(self, request):
        """Override the post method to add custom swagger documentation."""
        audio_id = request.data.get("audio_id", None)
        if audio_id is None:
            return Response(
                {"message": "audio_id is required."},
                status=status.HTTP_400_BAD_REQUEST,
            )
        audio_obj = DataAudio.objects.filter(id=audio_id).first()
        if audio_obj is None:
            return Response(
                {"message": "No audio data found."},
                status=status.HTTP_404_NOT_FOUND,
            )

        s3_client = settings.BOTO3_SESSION.client("s3")
        try:
            response = s3_client.generate_presigned_url(
                "get_object",
                Params={
                    "Bucket": settings.S3_BUCKET,
                    "Key": f"Listener/audio/{audio_obj.uid}/audio/{audio_obj.audio_file}",
                },
                ExpiresIn=3600,
            )

            return Response({"audio_url": response}, status=status.HTTP_200_OK)
        except Exception as e:
            logger.error(e)
            return Response(
                {"message": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

get_audio_data(request)

Override the post method to add custom swagger documentation.

Source code in API/hardware/views.py
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
@swagger_auto_schema(
    operation_summary="Get an audio data s3 url",
    operation_description="Get an audio data",
    responses={200: "The audio data"},
    tags=["hardware"],
)
@action(
    detail=False,
    methods=["post"],
    url_path="get_audio_data",
    url_name="get_audio_data",
)
def get_audio_data(self, request):
    """Override the post method to add custom swagger documentation."""
    audio_id = request.data.get("audio_id", None)
    if audio_id is None:
        return Response(
            {"message": "audio_id is required."},
            status=status.HTTP_400_BAD_REQUEST,
        )
    audio_obj = DataAudio.objects.filter(id=audio_id).first()
    if audio_obj is None:
        return Response(
            {"message": "No audio data found."},
            status=status.HTTP_404_NOT_FOUND,
        )

    s3_client = settings.BOTO3_SESSION.client("s3")
    try:
        response = s3_client.generate_presigned_url(
            "get_object",
            Params={
                "Bucket": settings.S3_BUCKET,
                "Key": f"Listener/audio/{audio_obj.uid}/audio/{audio_obj.audio_file}",
            },
            ExpiresIn=3600,
        )

        return Response({"audio_url": response}, status=status.HTTP_200_OK)
    except Exception as e:
        logger.error(e)
        return Response(
            {"message": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )

Text2SpeechViewSet

Bases: ModelViewSet

Source code in API/hardware/views.py
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
class Text2SpeechViewSet(viewsets.ModelViewSet):
    queryset = ResSpeech.objects.all()
    serializer_class = ResSpeechSerializer

    # retrieve it based on the mac address
    def get_queryset(self):
        queryset = ResSpeech.objects.filter(
            played=False, text2speech_file__isnull=False
        )
        home_id = self.request.query_params.get("home_id", None)
        logger.info(f"Home id: {home_id}")
        if (home_id is not None) and (home_id != "None"):
            home = Home.objects.filter(id=home_id).first()
            if not home:
                return None
            queryset = queryset.filter(
                home=home, played=False, text2speech_file__isnull=False
            )

        queryset = queryset.order_by("created_at")
        item = queryset.first()
        if item:
            item.played = True
            item.save()
        if item:
            return [item]
        else:
            return None

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        if queryset is None:
            return Response(
                {"message": "No text to speech found."},
                status=status.HTTP_404_NOT_FOUND,
            )

        item = queryset[0]

        s3_url = None
        if item.text2speech_file is not None:
            local_file = settings.AI_MEDIA_ROOT / item.text2speech_file.split("/")[-1]
            logger.info(local_file)
            if local_file.exists() and (
                settings.STORAGE_SOLUTION == settings.STORAGE_SOLUTION_VOLUME
                or settings.STORAGE_SOLUTION == settings.STORAGE_SOLUTION_LOCAL
            ):
                s3_client = settings.BOTO3_SESSION.client("s3")
                s3_key = f"Responder/tts/{item.text2speech_file.split('/')[-1]}"
                try:
                    s3_client.upload_file(
                        local_file,
                        settings.S3_BUCKET,
                        s3_key,
                    )
                except Exception as e:
                    logger.error(e)
                    logger.exception(e)
                    # response with the HttpResponse
            try:
                s3_client = settings.BOTO3_SESSION.client("s3")
                response = s3_client.generate_presigned_url(
                    "get_object",
                    Params={
                        "Bucket": settings.S3_BUCKET,
                        "Key": f"Responder/tts/{item.text2speech_file}",
                    },
                    ExpiresIn=3600,
                )
                s3_url = response
            except Exception as e:
                logger.error(e)
        data = ResSpeechSerializer(item).data
        data["tts_url"] = s3_url
        logger.info(s3_url)
        return Response(data, status=status.HTTP_200_OK)

    @swagger_auto_schema(
        operation_summary="Get speech audio s3 url",
        operation_description="Get the text to speech audio s3 url",
        responses={200: "The text to speech"},
        tags=["hardware"],
    )
    @action(
        detail=False,
        methods=["post"],
        url_path="get_text_to_speech",
        url_name="get_text_to_speech",
    )
    def get_text_to_speech(self, request):
        """Override the post method to add custom swagger documentation."""
        text2speech_id = request.data.get("text2speech_id", None)
        if text2speech_id is None:
            return Response(
                {"message": "text2speech_id is required."},
                status=status.HTTP_400_BAD_REQUEST,
            )
        text2speech_obj = ResSpeech.objects.filter(id=text2speech_id).first()
        if text2speech_obj is None:
            return Response(
                {"message": "No text to speech found."},
                status=status.HTTP_404_NOT_FOUND,
            )

        s3_client = settings.BOTO3_SESSION.client("s3")
        try:
            response = s3_client.generate_presigned_url(
                "get_object",
                Params={
                    "Bucket": settings.S3_BUCKET,
                    "Key": f"tts/{text2speech_obj.text2speech_file}",
                },
                ExpiresIn=3600,
            )

            return Response({"tts_url": response}, status=status.HTTP_200_OK)
        except Exception as e:
            logger.error(e)
            return Response(
                {"message": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

get_text_to_speech(request)

Override the post method to add custom swagger documentation.

Source code in API/hardware/views.py
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
@swagger_auto_schema(
    operation_summary="Get speech audio s3 url",
    operation_description="Get the text to speech audio s3 url",
    responses={200: "The text to speech"},
    tags=["hardware"],
)
@action(
    detail=False,
    methods=["post"],
    url_path="get_text_to_speech",
    url_name="get_text_to_speech",
)
def get_text_to_speech(self, request):
    """Override the post method to add custom swagger documentation."""
    text2speech_id = request.data.get("text2speech_id", None)
    if text2speech_id is None:
        return Response(
            {"message": "text2speech_id is required."},
            status=status.HTTP_400_BAD_REQUEST,
        )
    text2speech_obj = ResSpeech.objects.filter(id=text2speech_id).first()
    if text2speech_obj is None:
        return Response(
            {"message": "No text to speech found."},
            status=status.HTTP_404_NOT_FOUND,
        )

    s3_client = settings.BOTO3_SESSION.client("s3")
    try:
        response = s3_client.generate_presigned_url(
            "get_object",
            Params={
                "Bucket": settings.S3_BUCKET,
                "Key": f"tts/{text2speech_obj.text2speech_file}",
            },
            ExpiresIn=3600,
        )

        return Response({"tts_url": response}, status=status.HTTP_200_OK)
    except Exception as e:
        logger.error(e)
        return Response(
            {"message": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )

list_files(request)

List all the files in the S3 bucket

Source code in API/hardware/views.py
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
@api_view(["GET"])
@permission_classes([IsAuthenticated])
def list_files(request):
    """
    List all the files in the S3 bucket
    """
    from_time = request.data.get("from_time", None)
    logger.info(f"From time: {from_time}")
    if from_time is None:
        # default to 100 day ago
        from_time = datetime.now() - timedelta(days=100)
    else:
        # get the from_time from the timestamp
        from_time = datetime.fromtimestamp(float(from_time))

    audio_files = DataAudio.objects.filter(created_at__gte=from_time)
    video_files = DataVideo.objects.filter(created_at__gte=from_time)
    audio_list_json = AudioDataSerializer(audio_files, many=True).data
    video_list_json = VideoDataSerializer(video_files, many=True).data
    return Response(
        {"audio_files": audio_list_json, "video_files": video_list_json},
        status=status.HTTP_200_OK,
    )

upload_file(request)

This is for temporarily solution, as we host the centre server, and will not provide the S3 access to the general user

So to testout our system, you can use this endpoint to upload files to S3 Focus on client and AI side

Source code in API/hardware/views.py
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
@api_view(["POST"])
@permission_classes([IsAuthenticated])
def upload_file(request):
    """
    This is for temporarily solution, as we host the centre server,
    and will not provide the S3 access to the general user

    So to testout our system, you can use this endpoint to upload files to S3
    Focus on client and AI side

    """
    file = request.FILES.get("file")
    if file is None:
        return Response(
            {"message": "No file found."},
            status=status.HTTP_400_BAD_REQUEST,
        )
    s3_client = settings.BOTO3_SESSION.client("s3")
    dest_path = request.data.get("dest_path", None)
    if dest_path is None:
        return Response(
            {"message": "dest_path is required."},
            status=status.HTTP_400_BAD_REQUEST,
        )
    try:
        s3_client.upload_fileobj(
            file,
            settings.S3_BUCKET,
            dest_path,
        )
        return Response(
            {"message": "File uploaded successfully."},
            status=status.HTTP_200_OK,
        )
    except Exception as e:
        logger.error(e)
        return Response(
            {"message": str(e)},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR,
        )