Awell00 commited on
Commit
5a74463
·
1 Parent(s): 9361dca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -110
app.py CHANGED
@@ -36,25 +36,21 @@ def butter_bandpass(sr, order=5):
36
  Returns:
37
  tuple: The filter coefficients `b` and `a`.
38
  """
39
- try:
40
- # Calculate the Nyquist frequency
41
- nyquist = 0.5 * sr
42
 
43
- # Normalize the cutoff frequencies
44
- low = low_frequency / nyquist
45
- high = high_frequency / nyquist
46
 
47
- # Design the Butterworth bandpass filter
48
- coefficient = butter(order, [low, high], btype='band')
49
 
50
- # Extract the filter coefficients
51
- b = coefficient[0]
52
- a = coefficient[1]
53
 
54
- return b, a
55
- except Exception as e:
56
- # If an error occurs, return an error message
57
- return f"Error: {str(e)}"
58
 
59
 
60
  def butter_bandpass_filter(data, sr, order=5):
@@ -69,17 +65,13 @@ def butter_bandpass_filter(data, sr, order=5):
69
  Returns:
70
  array: The filtered audio data.
71
  """
72
- try:
73
- # Get the filter coefficients
74
- b, a = butter_bandpass(sr, order=order)
75
 
76
- # Apply the filter to the data
77
- y = lfilter(b, a, data)
78
 
79
- return y
80
- except Exception as e:
81
- # If an error occurs, return an error message
82
- return f"Error: {str(e)}"
83
 
84
 
85
  def filtered():
@@ -261,21 +253,17 @@ def dominant_frequency(signal_value):
261
  Returns:
262
  float: The dominant frequency.
263
  """
264
- try:
265
- # Perform a Fast Fourier Transform on the signal
266
- yf = fft(signal_value)
267
 
268
- # Generate the frequencies corresponding to the FFT coefficients
269
- xf = np.linspace(0.0, sample_rate / 2.0, len(signal_value) // 2)
270
 
271
- # Find the peaks in the absolute values of the FFT coefficients
272
- peaks, _ = find_peaks(np.abs(yf[0:len(signal_value) // 2]))
273
 
274
- # Return the frequency corresponding to the peak with the highest amplitude
275
- return xf[peaks[np.argmax(np.abs(yf[0:len(signal_value) // 2][peaks]))]]
276
- except Exception as e:
277
- # If an error occurs, return an error message
278
- return f"Error: {e}"
279
 
280
 
281
  def binary_to_text(binary):
@@ -291,9 +279,9 @@ def binary_to_text(binary):
291
  try:
292
  # Convert each 8-bit binary number to a character and join them together
293
  return ''.join(chr(int(binary[i:i + 8], 2)) for i in range(0, len(binary), 8))
294
- except ValueError:
295
  # If an error occurs, return an error message
296
- return f"Error: Invalid binary number '{binary}'"
297
 
298
 
299
  def decode_rs(binary_string, ecc_bytes):
@@ -307,27 +295,23 @@ def decode_rs(binary_string, ecc_bytes):
307
  Returns:
308
  str: The decoded binary string.
309
  """
310
- try:
311
- # Convert the binary string to a bytearray
312
- byte_data = bytearray(int(binary_string[i:i + 8], 2) for i in range(0, len(binary_string), 8))
313
 
314
- # Initialize a Reed-Solomon codec
315
- rs = reedsolo.RSCodec(ecc_bytes)
316
 
317
- # Decode the bytearray
318
- corrected_data_tuple = rs.decode(byte_data)
319
- corrected_data = corrected_data_tuple[0]
320
 
321
- # Remove trailing null bytes
322
- corrected_data = corrected_data.rstrip(b'\x00')
323
 
324
- # Convert the bytearray back to a binary string
325
- corrected_binary_string = ''.join(format(byte, '08b') for byte in corrected_data)
326
 
327
- return corrected_binary_string
328
- except Exception as e:
329
- # If an error occurs, return an error message
330
- return f"Error: {e}"
331
 
332
 
333
  def manchester_decoding(binary_string):
@@ -340,21 +324,17 @@ def manchester_decoding(binary_string):
340
  Returns:
341
  str: The decoded binary string.
342
  """
343
- try:
344
- decoded_string = ''
345
- for i in tqdm(range(0, len(binary_string), 2), desc="Decoding"):
346
- if i + 1 < len(binary_string):
347
- if binary_string[i] == '0' and binary_string[i + 1] == '1':
348
- decoded_string += '0'
349
- elif binary_string[i] == '1' and binary_string[i + 1] == '0':
350
- decoded_string += '1'
351
- else:
352
- print("Error: Invalid Manchester Encoding")
353
- return None
354
- return decoded_string
355
- except Exception as e:
356
- # If an error occurs, return an error message
357
- return f"Error: {e}"
358
 
359
 
360
  def signal_to_binary_between_times(filename):
@@ -367,47 +347,43 @@ def signal_to_binary_between_times(filename):
367
  Returns:
368
  str: The binary string.
369
  """
370
- try:
371
- # Get the start and end times of the signal of interest
372
- start_time, end_time = frame_analyse(filename)
373
-
374
- # Read the audio file
375
- sr, data = read(filename)
376
-
377
- # Calculate the start and end samples of the signal of interest
378
- start_sample = int((start_time - 0.007) * sr)
379
- end_sample = int((end_time - 0.007) * sr)
380
- binary_string = ''
381
-
382
- # Convert each sample to a binary digit
383
- for i in tqdm(range(start_sample, end_sample, int(sr * bit_duration))):
384
- signal_value = data[i:i + int(sr * bit_duration)]
385
- frequency = dominant_frequency(signal_value)
386
- if np.abs(frequency - low_frequency) < np.abs(frequency - high_frequency):
387
- binary_string += '0'
388
- else:
389
- binary_string += '1'
390
-
391
- # Find the start and end indices of the binary string
392
- index_start = binary_string.find("1000001")
393
- substrings = ["0111110", "011110"]
394
- index_end = -1
395
- for substring in substrings:
396
- index = binary_string.find(substring)
397
- if index != -1:
398
- index_end = index
399
- break
400
-
401
- print("Binary String:", binary_string)
402
- binary_string_decoded = manchester_decoding(binary_string[index_start + 7:index_end])
403
-
404
- # Decode the binary string
405
- decoded_binary_string = decode_rs(binary_string_decoded, 20)
406
-
407
- return decoded_binary_string
408
- except Exception as e:
409
- # If an error occurs, return an error message
410
- return f"Error: {e}"
411
 
412
 
413
  def receive():
 
36
  Returns:
37
  tuple: The filter coefficients `b` and `a`.
38
  """
39
+ # Calculate the Nyquist frequency
40
+ nyquist = 0.5 * sr
 
41
 
42
+ # Normalize the cutoff frequencies
43
+ low = low_frequency / nyquist
44
+ high = high_frequency / nyquist
45
 
46
+ # Design the Butterworth bandpass filter
47
+ coefficient = butter(order, [low, high], btype='band')
48
 
49
+ # Extract the filter coefficients
50
+ b = coefficient[0]
51
+ a = coefficient[1]
52
 
53
+ return b, a
 
 
 
54
 
55
 
56
  def butter_bandpass_filter(data, sr, order=5):
 
65
  Returns:
66
  array: The filtered audio data.
67
  """
68
+ # Get the filter coefficients
69
+ b, a = butter_bandpass(sr, order=order)
 
70
 
71
+ # Apply the filter to the data
72
+ y = lfilter(b, a, data)
73
 
74
+ return y
 
 
 
75
 
76
 
77
  def filtered():
 
253
  Returns:
254
  float: The dominant frequency.
255
  """
256
+ # Perform a Fast Fourier Transform on the signal
257
+ yf = fft(signal_value)
 
258
 
259
+ # Generate the frequencies corresponding to the FFT coefficients
260
+ xf = np.linspace(0.0, sample_rate / 2.0, len(signal_value) // 2)
261
 
262
+ # Find the peaks in the absolute values of the FFT coefficients
263
+ peaks, _ = find_peaks(np.abs(yf[0:len(signal_value) // 2]))
264
 
265
+ # Return the frequency corresponding to the peak with the highest amplitude
266
+ return xf[peaks[np.argmax(np.abs(yf[0:len(signal_value) // 2][peaks]))]]
 
 
 
267
 
268
 
269
  def binary_to_text(binary):
 
279
  try:
280
  # Convert each 8-bit binary number to a character and join them together
281
  return ''.join(chr(int(binary[i:i + 8], 2)) for i in range(0, len(binary), 8))
282
+ except Exception as e:
283
  # If an error occurs, return an error message
284
+ return f"Error: {e}"
285
 
286
 
287
  def decode_rs(binary_string, ecc_bytes):
 
295
  Returns:
296
  str: The decoded binary string.
297
  """
298
+ # Convert the binary string to a bytearray
299
+ byte_data = bytearray(int(binary_string[i:i + 8], 2) for i in range(0, len(binary_string), 8))
 
300
 
301
+ # Initialize a Reed-Solomon codec
302
+ rs = reedsolo.RSCodec(ecc_bytes)
303
 
304
+ # Decode the bytearray
305
+ corrected_data_tuple = rs.decode(byte_data)
306
+ corrected_data = corrected_data_tuple[0]
307
 
308
+ # Remove trailing null bytes
309
+ corrected_data = corrected_data.rstrip(b'\x00')
310
 
311
+ # Convert the bytearray back to a binary string
312
+ corrected_binary_string = ''.join(format(byte, '08b') for byte in corrected_data)
313
 
314
+ return corrected_binary_string
 
 
 
315
 
316
 
317
  def manchester_decoding(binary_string):
 
324
  Returns:
325
  str: The decoded binary string.
326
  """
327
+ decoded_string = ''
328
+ for i in tqdm(range(0, len(binary_string), 2), desc="Decoding"):
329
+ if i + 1 < len(binary_string):
330
+ if binary_string[i] == '0' and binary_string[i + 1] == '1':
331
+ decoded_string += '0'
332
+ elif binary_string[i] == '1' and binary_string[i + 1] == '0':
333
+ decoded_string += '1'
334
+ else:
335
+ print("Error: Invalid Manchester Encoding")
336
+ return None
337
+ return decoded_string
 
 
 
 
338
 
339
 
340
  def signal_to_binary_between_times(filename):
 
347
  Returns:
348
  str: The binary string.
349
  """
350
+ # Get the start and end times of the signal of interest
351
+ start_time, end_time = frame_analyse(filename)
352
+
353
+ # Read the audio file
354
+ sr, data = read(filename)
355
+
356
+ # Calculate the start and end samples of the signal of interest
357
+ start_sample = int((start_time - 0.007) * sr)
358
+ end_sample = int((end_time - 0.007) * sr)
359
+ binary_string = ''
360
+
361
+ # Convert each sample to a binary digit
362
+ for i in tqdm(range(start_sample, end_sample, int(sr * bit_duration))):
363
+ signal_value = data[i:i + int(sr * bit_duration)]
364
+ frequency = dominant_frequency(signal_value)
365
+ if np.abs(frequency - low_frequency) < np.abs(frequency - high_frequency):
366
+ binary_string += '0'
367
+ else:
368
+ binary_string += '1'
369
+
370
+ # Find the start and end indices of the binary string
371
+ index_start = binary_string.find("1000001")
372
+ substrings = ["0111110", "011110"]
373
+ index_end = -1
374
+ for substring in substrings:
375
+ index = binary_string.find(substring)
376
+ if index != -1:
377
+ index_end = index
378
+ break
379
+
380
+ print("Binary String:", binary_string)
381
+ binary_string_decoded = manchester_decoding(binary_string[index_start + 7:index_end])
382
+
383
+ # Decode the binary string
384
+ decoded_binary_string = decode_rs(binary_string_decoded, 20)
385
+
386
+ return decoded_binary_string
 
 
 
 
387
 
388
 
389
  def receive():