



import datetime
import platform
import subprocess
from typing import Optional, Tuple, Union

import numpy as np






def 	_lowerCAmelCase						(				__lowerCamelCase   :     bytes		,	__lowerCamelCase   :     int     ):



 """simple docstring"""





 __SCREAMING_SNAKE_CASE       :    Optional[int]       =	F"""{sampling_rate}"""
 __SCREAMING_SNAKE_CASE       :    int       =	"1"
 __SCREAMING_SNAKE_CASE       :    Any       =	"f32le"
 __SCREAMING_SNAKE_CASE       :    Tuple       =	[
     "ffmpeg",
     "-i",
     "pipe:0",
     "-ac",
     ac,
     "-ar",
     ar,
     "-f",
     format_for_conversion,
     "-hide_banner",
     "-loglevel",
     "quiet",
     "pipe:1",
 ]

 try:
  with subprocess.Popen(__lowerCamelCase		,	stdin=subprocess.PIPE		,	stdout=subprocess.PIPE     ) as ffmpeg_process:
   __SCREAMING_SNAKE_CASE       :    str       =	ffmpeg_process.communicate(__lowerCamelCase     )
 except FileNotFoundError as error:
  raise ValueError("ffmpeg was not found but is required to load audio files from filename"     ) from error
 __SCREAMING_SNAKE_CASE       :    Optional[int]       =	output_stream[0]
 __SCREAMING_SNAKE_CASE       :    List[str]       =	np.frombuffer(__lowerCamelCase		,	np.floataa     )
 if audio.shape[0] == 0:
  raise ValueError("Malformed soundfile"     )
 return audio






def 	_lowerCAmelCase						(				__lowerCamelCase   :     int		,	__lowerCamelCase   :     float		,	__lowerCamelCase   :     str = "f32le"		,	):



 """simple docstring"""





 __SCREAMING_SNAKE_CASE       :    Optional[int]       =	F"""{sampling_rate}"""
 __SCREAMING_SNAKE_CASE       :    List[str]       =	"1"
 if format_for_conversion == "s16le":
  __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	2
 elif format_for_conversion == "f32le":
  __SCREAMING_SNAKE_CASE       :    int       =	4
 else:
  raise ValueError(F"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`"""     )

 __SCREAMING_SNAKE_CASE       :    int       =	platform.system()
 if system == "Linux":
  __SCREAMING_SNAKE_CASE       :    int       =	"alsa"
  __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	"default"
 elif system == "Darwin":
  __SCREAMING_SNAKE_CASE       :    List[Any]       =	"avfoundation"
  __SCREAMING_SNAKE_CASE       :    Optional[int]       =	":0"
 elif system == "Windows":
  __SCREAMING_SNAKE_CASE       :    List[Any]       =	"dshow"
  __SCREAMING_SNAKE_CASE       :    int       =	"default"

 __SCREAMING_SNAKE_CASE       :    Tuple       =	[
     "ffmpeg",
     "-f",
     format_,
     "-i",
     input_,
     "-ac",
     ac,
     "-ar",
     ar,
     "-f",
     format_for_conversion,
     "-fflags",
     "nobuffer",
     "-hide_banner",
     "-loglevel",
     "quiet",
     "pipe:1",
 ]
 __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	int(round(sampling_rate * chunk_length_s     )     ) * size_of_sample
 __SCREAMING_SNAKE_CASE       :    List[str]       =	_ffmpeg_stream(__lowerCamelCase		,	__lowerCamelCase     )
 for item in iterator:
  yield item






def 	_lowerCAmelCase						(				__lowerCamelCase   :     int		,	__lowerCamelCase   :     float		,	__lowerCamelCase   :     Optional[int] = None		,	__lowerCamelCase   :     Optional[Union[Tuple[float, float], float]] = None		,	__lowerCamelCase   :     str = "f32le"		,	):



 """simple docstring"""





 if stream_chunk_s is not None:
  __SCREAMING_SNAKE_CASE       :    Optional[int]       =	stream_chunk_s
 else:
  __SCREAMING_SNAKE_CASE       :    List[str]       =	chunk_length_s

 __SCREAMING_SNAKE_CASE       :    Optional[int]       =	ffmpeg_microphone(__lowerCamelCase		,	__lowerCamelCase		,	format_for_conversion=__lowerCamelCase     )
 if format_for_conversion == "s16le":
  __SCREAMING_SNAKE_CASE       :    List[Any]       =	np.intaa
  __SCREAMING_SNAKE_CASE       :    List[Any]       =	2
 elif format_for_conversion == "f32le":
  __SCREAMING_SNAKE_CASE       :    int       =	np.floataa
  __SCREAMING_SNAKE_CASE       :    Optional[int]       =	4
 else:
  raise ValueError(F"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`"""     )

 if stride_length_s is None:
  __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	chunk_length_s / 6
 __SCREAMING_SNAKE_CASE       :    List[Any]       =	int(round(sampling_rate * chunk_length_s     )     ) * size_of_sample
 if isinstance(__lowerCamelCase		,	(int, float)     ):
  __SCREAMING_SNAKE_CASE       :    int       =	[stride_length_s, stride_length_s]

 __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	int(round(sampling_rate * stride_length_s[0]     )     ) * size_of_sample
 __SCREAMING_SNAKE_CASE       :    List[str]       =	int(round(sampling_rate * stride_length_s[1]     )     ) * size_of_sample
 __SCREAMING_SNAKE_CASE       :    Dict       =	datetime.datetime.now()
 __SCREAMING_SNAKE_CASE       :    Dict       =	datetime.timedelta(seconds=__lowerCamelCase     )
 for item in chunk_bytes_iter(__lowerCamelCase		,	__lowerCamelCase		,	stride=(stride_left, stride_right)		,	stream=__lowerCamelCase     ):
  # Put everything back in numpy scale
  __SCREAMING_SNAKE_CASE       :    Optional[int]       =	np.frombuffer(item["raw"]		,	dtype=__lowerCamelCase     )
  __SCREAMING_SNAKE_CASE       :    int       =	(
      item["stride"][0] // size_of_sample,
      item["stride"][1] // size_of_sample,
  )
  __SCREAMING_SNAKE_CASE       :    List[str]       =	sampling_rate
  audio_time += delta
  if datetime.datetime.now() > audio_time + 10 * delta:
   # We're late !! SKIP
   continue
  yield item






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Optional[int]		,	__lowerCamelCase   :     int		,	__lowerCamelCase   :     Tuple[int, int]		,	__lowerCamelCase   :     bool = False     ):



 """simple docstring"""





 __SCREAMING_SNAKE_CASE       :    List[Any]       =	b""
 __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	stride
 if stride_left + stride_right >= chunk_len:
  raise ValueError(
      F"""Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}"""     )
 __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	0
 for raw in iterator:
  acc += raw
  if stream and len(__lowerCamelCase     ) < chunk_len:
   __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	(_stride_left, 0)
   yield {"raw": acc[:chunk_len], "stride": stride, "partial": True}
  else:
   while len(__lowerCamelCase     ) >= chunk_len:
    # We are flushing the accumulator
    __SCREAMING_SNAKE_CASE       :    int       =	(_stride_left, stride_right)
    __SCREAMING_SNAKE_CASE       :    Any       =	{"raw": acc[:chunk_len], "stride": stride}
    if stream:
     __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	False
    yield item
    __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	stride_left
    __SCREAMING_SNAKE_CASE       :    List[str]       =	acc[chunk_len - stride_left - stride_right :]
    # Last chunk
 if len(__lowerCamelCase     ) > stride_left:
  __SCREAMING_SNAKE_CASE       :    Any       =	{"raw": acc, "stride": (_stride_left, 0)}
  if stream:
   __SCREAMING_SNAKE_CASE       :    int       =	False
  yield item






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Tuple		,	__lowerCamelCase   :     int     ):



 """simple docstring"""





 __SCREAMING_SNAKE_CASE       :    Dict       =	2**24  # 16Mo
 try:
  with subprocess.Popen(__lowerCamelCase		,	stdout=subprocess.PIPE		,	bufsize=__lowerCamelCase     ) as ffmpeg_process:
   while True:
    __SCREAMING_SNAKE_CASE       :    Optional[int]       =	ffmpeg_process.stdout.read(__lowerCamelCase     )
    if raw == b"":
     break
    yield raw
 except FileNotFoundError as error:
  raise ValueError("ffmpeg was not found but is required to stream audio files from filename"     ) from error











from collections.abc import Generator
from math import sin






def 	_lowerCAmelCase						(				__lowerCamelCase   :     bytes     ):



 """simple docstring"""





 if len(__lowerCamelCase     ) != 32:
  raise ValueError("Input must be of length 32"     )

 __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	b""
 for i in [3, 2, 1, 0]:
  little_endian += string_aa[8 * i : 8 * i + 8]
 return little_endian






def 	_lowerCAmelCase						(				__lowerCamelCase   :     int     ):



 """simple docstring"""





 if i < 0:
  raise ValueError("Input must be non-negative"     )

 __SCREAMING_SNAKE_CASE       :    Any       =	format(__lowerCamelCase		,	"08x"     )[-8:]
 __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	b""
 for i in [3, 2, 1, 0]:
  little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("utf-8"     )
 return little_endian_hex






def 	_lowerCAmelCase						(				__lowerCamelCase   :     bytes     ):



 """simple docstring"""





 __SCREAMING_SNAKE_CASE       :    Any       =	b""
 for char in message:
  bit_string += format(__lowerCamelCase		,	"08b"     ).encode("utf-8"     )
 __SCREAMING_SNAKE_CASE       :    List[str]       =	format(len(__lowerCamelCase     )		,	"064b"     ).encode("utf-8"     )

 # Pad bit_string to a multiple of 512 chars
 bit_string += b"1"
 while len(__lowerCamelCase     ) % 512 != 448:
  bit_string += b"0"
 bit_string += to_little_endian(start_len[32:]     ) + to_little_endian(start_len[:32]     )

 return bit_string






def 	_lowerCAmelCase						(				__lowerCamelCase   :     bytes     ):



 """simple docstring"""





 if len(__lowerCamelCase     ) % 512 != 0:
  raise ValueError("Input must have length that's a multiple of 512"     )

 for pos in range(0		,	len(__lowerCamelCase     )		,	512     ):
  __SCREAMING_SNAKE_CASE       :    int       =	bit_string[pos : pos + 512]
  __SCREAMING_SNAKE_CASE       :    Tuple       =	[]
  for i in range(0		,	512		,	32     ):
   block_words.append(int(to_little_endian(block[i : i + 32]     )		,	2     )     )
  yield block_words






def 	_lowerCAmelCase						(				__lowerCamelCase   :     int     ):



 """simple docstring"""





 if i < 0:
  raise ValueError("Input must be non-negative"     )

 __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	format(__lowerCamelCase		,	"032b"     )
 __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	""
 for c in i_str:
  new_str += "1" if c == "0" else "0"
 return int(__lowerCamelCase		,	2     )






def 	_lowerCAmelCase						(				__lowerCamelCase   :     int		,	__lowerCamelCase   :     int     ):



 """simple docstring"""





 return (a + b) % 2**32






def 	_lowerCAmelCase						(				__lowerCamelCase   :     int		,	__lowerCamelCase   :     int     ):



 """simple docstring"""





 if i < 0:
  raise ValueError("Input must be non-negative"     )
 if shift < 0:
  raise ValueError("Shift must be non-negative"     )
 return ((i << shift) ^ (i >> (32 - shift))) % 2**32






def 	_lowerCAmelCase						(				__lowerCamelCase   :     bytes     ):



 """simple docstring"""





 __SCREAMING_SNAKE_CASE       :    Tuple       =	preprocess(__lowerCamelCase     )

 __SCREAMING_SNAKE_CASE       :    List[Any]       =	[int(2**32 * abs(sin(i + 1     )     )     ) for i in range(64     )]

 # Starting states
 __SCREAMING_SNAKE_CASE       :    Tuple       =	0X67452301
 __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	0Xefcdab89
 __SCREAMING_SNAKE_CASE       :    Optional[int]       =	0X98badcfe
 __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	0X10325476

 __SCREAMING_SNAKE_CASE       :    List[Any]       =	[
     7,
     12,
     17,
     22,
     7,
     12,
     17,
     22,
     7,
     12,
     17,
     22,
     7,
     12,
     17,
     22,
     5,
     9,
     14,
     20,
     5,
     9,
     14,
     20,
     5,
     9,
     14,
     20,
     5,
     9,
     14,
     20,
     4,
     11,
     16,
     23,
     4,
     11,
     16,
     23,
     4,
     11,
     16,
     23,
     4,
     11,
     16,
     23,
     6,
     10,
     15,
     21,
     6,
     10,
     15,
     21,
     6,
     10,
     15,
     21,
     6,
     10,
     15,
     21,
 ]

 # Process bit string in chunks, each with 16 32-char words
 for block_words in get_block_words(__lowerCamelCase     ):
  __SCREAMING_SNAKE_CASE       :    Any       =	aa
  __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	ba
  __SCREAMING_SNAKE_CASE       :    str       =	ca
  __SCREAMING_SNAKE_CASE       :    Dict       =	da

  # Hash current chunk
  for i in range(64     ):
   if i <= 15:
    # f = (b & c) | (not_32(b) & d)     # Alternate definition for f
    __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	d ^ (b & (c ^ d))
    __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	i
   elif i <= 31:
    # f = (d & b) | (not_32(d) & c)     # Alternate definition for f
    __SCREAMING_SNAKE_CASE       :    int       =	c ^ (d & (b ^ c))
    __SCREAMING_SNAKE_CASE       :    int       =	(5 * i + 1) % 16
   elif i <= 47:
    __SCREAMING_SNAKE_CASE       :    List[str]       =	b ^ c ^ d
    __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	(3 * i + 5) % 16
   else:
    __SCREAMING_SNAKE_CASE       :    Any       =	c ^ (b | not_aa(__lowerCamelCase     ))
    __SCREAMING_SNAKE_CASE       :    str       =	(7 * i) % 16
   __SCREAMING_SNAKE_CASE       :    List[str]       =	(f + a + added_consts[i] + block_words[g]) % 2**32
   __SCREAMING_SNAKE_CASE       :    Dict       =	d
   __SCREAMING_SNAKE_CASE       :    str       =	c
   __SCREAMING_SNAKE_CASE       :    Tuple       =	b
   __SCREAMING_SNAKE_CASE       :    Optional[int]       =	sum_aa(__lowerCamelCase		,	left_rotate_aa(__lowerCamelCase		,	shift_amounts[i]     )     )

  # Add hashed chunk to running total
  __SCREAMING_SNAKE_CASE       :    Dict       =	sum_aa(__lowerCamelCase		,	__lowerCamelCase     )
  __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	sum_aa(__lowerCamelCase		,	__lowerCamelCase     )
  __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	sum_aa(__lowerCamelCase		,	__lowerCamelCase     )
  __SCREAMING_SNAKE_CASE       :    str       =	sum_aa(__lowerCamelCase		,	__lowerCamelCase     )

 __SCREAMING_SNAKE_CASE       :    List[str]       =	reformat_hex(__lowerCamelCase     ) + reformat_hex(__lowerCamelCase     ) + reformat_hex(__lowerCamelCase     ) + reformat_hex(__lowerCamelCase     )
 return digest


if __name__ == "__main__":
      import doctest

      doctest.testmod()






