File size: 4,005 Bytes
17470b6
5086233
17470b6
d6a8411
5086233
 
 
 
 
 
 
d6a8411
 
 
 
 
 
 
 
17470b6
 
d6a8411
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5086233
d6a8411
 
 
 
 
eb19481
 
11a316a
eb19481
d6a8411
 
 
 
 
 
 
 
 
 
 
 
17470b6
 
 
d6a8411
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import gradio as gr
import os 
import numpy as np
import scipy.io.wavfile as wavfile
# Base directory setup
BASE_DIR = os.getcwd()

DEFAULT_FONT_PATH = f"{BASE_DIR}/fonts/Vipnagorgialla Bd.otf"




# Morse code dictionary
MORSE_CODE_DICT = {
    'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....',
    'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.',
    'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-',
    'Y': '-.--', 'Z': '--..', '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-',
    '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', ' ': ' '
}

def text_to_morse(text):
    """Convert text to Morse code."""
    text = text.upper()
    morse = []
    for char in text:
        if char in MORSE_CODE_DICT:
            morse.append(MORSE_CODE_DICT[char])
        else:
            morse.append('?')
    return ' '.join(morse)

def generate_morse_audio(morse_text, frequency=800, wpm=20, sample_rate=44100):
    """Generate audio for Morse code."""
    # Timing calculations based on WPM (words per minute)
    dit_duration = 1.2 / wpm  # Duration of a dit in seconds
    dah_duration = 3 * dit_duration  # Duration of a dah
    space_duration = dit_duration  # Space between symbols
    word_space_duration = 7 * dit_duration  # Space between words

    # Generate audio samples
    t = np.linspace(0, 1, int(sample_rate * 1), endpoint=False)
    tone = np.sin(2 * np.pi * frequency * t)

    audio = []
    for symbol in morse_text:
        if symbol == '.':
            # Dit: short beep
            audio.extend(tone[:int(sample_rate * dit_duration)])
        elif symbol == '-':
            # Dah: long beep
            audio.extend(tone[:int(sample_rate * dah_duration)])
        elif symbol == ' ':
            # Space between words
            audio.extend(np.zeros(int(sample_rate * word_space_duration)))
        # Space between symbols
        if symbol != ' ':
            audio.extend(np.zeros(int(sample_rate * space_duration)))

    audio = np.array(audio)
    # Normalize audio to prevent clipping
    audio = audio / np.max(np.abs(audio)) * 0.8
    # Save to WAV file
    output_file = "morse_audio.wav"
    wavfile.write(output_file, sample_rate, audio.astype(np.float32))
    return output_file

def convert_to_morse_and_audio(input_text, frequency, wpm):
    """Convert text to Morse code and generate audio."""
    if not input_text:
        return "Please enter some text.", None
    
    # Convert text to Morse code
    morse_text = text_to_morse(input_text)
    # Generate audio
    audio_file = generate_morse_audio(morse_text, frequency, wpm)
    return morse_text, audio_file

# Gradio Blocks UI
with gr.Blocks(title="Text to Morse Code Audio Converter", css="footer{display:none !important}", theme=gr.themes.Soft(primary_hue="sky", secondary_hue="blue", spacing_size="sm", radius_size="lg", font=DEFAULT_FONT_PATH)) as demo:
    gr.Markdown("# Text to Morse Code Audio Converter")
    gr.Markdown("Enter text to convert it to Morse code and generate an audio file.")
    
    with gr.Row():
        with gr.Column():
            text_input = gr.Textbox(
                label="Input Text",
                placeholder="Enter text (e.g., SOS)"
            )
            frequency = gr.Slider(400, 1200, value=800, step=10, label="Audio Frequency (Hz)")
            wpm = gr.Slider(5, 40, value=20, step=1, label="Speed (Words Per Minute)")
            convert_button = gr.Button("Convert")
        
        with gr.Column():
            morse_output = gr.Textbox(label="Morse Code", interactive=False)
            audio_output = gr.Audio(label="Morse Code Audio", interactive=False)
    
    convert_button.click(
        fn=convert_to_morse_and_audio,
        inputs=[text_input, frequency, wpm],
        outputs=[morse_output, audio_output]
    )

if __name__ == "__main__":
    demo.launch()