def recognize(speech_file: bytes) -> str:
    """Вернуть распознанный текст из аудиофайла с речью"""
    files: Dict[str, Tuple[str, bytes,
                           str]] = dict(speechFile=('speechFile', speech_file,
                                                    magic.from_buffer(
                                                        speech_file,
                                                        mime=True,
                                                    )), )

    try:
        response: Response = post(settings.ASYNCHRONOUS_SERVICE_URL,
                                  files=files)
    except RequestException as request_exception:
        raise exceptions.InternalServerError(
            "Can't make request to asynchronous service"
        ) from request_exception

    try:
        response_json: Dict[str, Any] = response.json()
    except ValueError as value_error:
        raise exceptions.InternalServerError(
            "Can't make request to asynchronous service") from value_error

    try:
        recognized_text: str = response_json['recognizedText']
    except KeyError as key_error:
        raise exceptions.InternalServerError(
            "Can't make request to asynchronous service") from key_error

    return recognized_text
Пример #2
0
    def post(cls, request: Request) -> Dict[str, str]:
        """Вход в систему, получение JWT"""
        login: str = request.data['login']

        try:
            user: User = User.objects.get(login=login)
        except User.DoesNotExist as does_not_exist:
            raise exceptions.UnprocessableEntityError(
                'Invalid credentials') from does_not_exist

        if not user.has_password(request.data['password']):
            raise exceptions.UnprocessableEntityError('Invalid credentials')

        token_bytes: bytes = encode(
            dict(exp=datetime.utcnow() + settings.JSON_WEB_TOKEN_LIFETIME,
                 id=user.id),
            settings.JSON_WEB_TOKEN_PRIVATE_KEY,
            algorithm='RS256',
        )

        try:
            token_string = token_bytes.decode('ascii')
        except UnicodeError as unicode_error:
            raise exceptions.InternalServerError(
                'Token contains non-ascii symbols') from unicode_error

        response: Dict[str, str] = dict(token=token_string)
        return response
 def _wrapper(view: APIView, request: Request, *args: Any,
              **kwargs: Any) -> Response:
     response_data: Dict[str, Any] = handler(view, request, *args,
                                             **kwargs)
     ser = serializer(data=response_data)
     if not ser.is_valid():
         raise exceptions.InternalServerError(str(ser.errors))
     return Response(ser.validated_data)
 def process_exception(self, request: HttpRequest,
                       exception: Exception) -> Optional[JsonResponse]:
     # pylint: disable=no-self-use,unused-argument
     """Вернуть JsonResponse или None из exception"""
     if not isinstance(exception, exceptions.PitterException):
         logger.exception(traceback.format_exc())
         return exceptions.InternalServerError(
             message=str(exception)).make_response()
     return None
Пример #5
0
 def has_password(self, password: str) -> bool:
     """Проверить пароль пользователя"""
     try:
         password_bytes = password.encode()
     except UnicodeError as unicode_error:
         raise exceptions.InternalServerError(
             'Error while encoding string') from unicode_error
     equals: bool = pbkdf2_hmac(
         self.PBKDF2_HMAC_HASH_NAME, password_bytes, self.salt_for_password,
         self.PBKDF2_HMAC_NUMBER_OF_ITERATIONS
     ) == self.hash_of_password_with_salt.tobytes()  # pylint: disable=no-member
     return equals
Пример #6
0
    def create_user(cls, login: str, password: str) -> User:
        """Создать нового пользователя"""
        try:
            password_bytes = password.encode()
        except UnicodeError as unicode_error:
            raise exceptions.InternalServerError(
                'Error while encoding string') from unicode_error

        salt_for_password = urandom(cls.SALT_FOR_PASSWORD_LENGTH)
        new_user: User = User.objects.create(
            login=login,
            hash_of_password_with_salt=pbkdf2_hmac(
                cls.PBKDF2_HMAC_HASH_NAME, password_bytes, salt_for_password,
                cls.PBKDF2_HMAC_NUMBER_OF_ITERATIONS),
            salt_for_password=salt_for_password,
            email_notifications_enabled=False,
            name=login,
        )
        return new_user