28 lines
No EOL
814 B
Python
28 lines
No EOL
814 B
Python
|
|
# decoder.py
|
|
import numpy as np
|
|
from utils import index_to_char
|
|
from codebook import construct_codebook
|
|
|
|
def decode_message(Y, codebook):
|
|
Y1, Y2 = Y[::2], Y[1::2]
|
|
scores = []
|
|
for i, c in enumerate(codebook):
|
|
c1, c2 = c[::2], c[1::2]
|
|
s1 = np.sqrt(10) * np.dot(Y1, c1) + np.dot(Y2, c2)
|
|
s2 = np.dot(Y1, c1) + np.sqrt(10) * np.dot(Y2, c2)
|
|
scores.append(max(s1, s2))
|
|
return np.argmax(scores)
|
|
|
|
def signal_to_text(Y, codebook, r=6):
|
|
_, n, _, _ = construct_codebook(r, 1)
|
|
seg_len = n
|
|
text = ''
|
|
for i in range(40):
|
|
seg = Y[i * seg_len:(i + 1) * seg_len]
|
|
index = decode_message(seg, codebook)
|
|
if index in index_to_char:
|
|
text += index_to_char[index]
|
|
else:
|
|
text += '?' # Unknown character
|
|
return text |