Views
No views yet
This Model cannot translate ',' to morse code because it is not included in the RAW Dataset.
Pull me a request If you find to solve this instead of a csv file as a dataset.1# Load the model weights if available
2try:
3 model.load_state_dict(torch.load('morse_model_weights.pth', weights_only=True))
4except FileNotFoundError:
5 print("Pre-trained weights not found, start training from scratch.")
6
7# INFERENCE FUNCTIONS
8def predict(character_index):
9 """Predict the Morse code sequence for a given character index."""
10 with torch.no_grad():
11 output = model(torch.tensor([character_index]))
12 _, prediction = torch.max(output, 2)
13 return prediction[0]
14
15def decode(prediction):
16 """Decode a prediction from numerical values to Morse code symbols."""
17 prediction = [p for p in prediction if p != 2]
18 return ''.join('.' if c == 0 else '-' for c in prediction)
19
20def encode(word):
21 """Encode a word into character indices."""
22 return [label_encoder.transform([char])[0] for char in word.upper()]
23
24def get_morse_word(word):
25 """Convert a word into Morse code using the model predictions."""
26 char_indices = encode(word)
27 morse_sequence = []
28 for index in char_indices:
29 pred = predict(index)
30 morse_sequence.append(decode(pred))
31 morse_sequence.append(' ')
32 return ''.join(morse_sequence)
33
34# USER INPUT INFERENCE
35user_input = input("Type your message: ")
36response = [get_morse_word(word) + ' ' for word in user_input.split()]
37response = ''.join(response)
38
39print("Response: ", response)
40