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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import io
|
| 4 |
+
from scipy.io import wavfile
|
| 5 |
+
import speech_recognition as sr
|
| 6 |
+
import soundfile as sf
|
| 7 |
+
|
| 8 |
+
# Morse code dictionary (ITU standard)
|
| 9 |
+
MORSE_CODE_DICT = {
|
| 10 |
+
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.',
|
| 11 |
+
'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..',
|
| 12 |
+
'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.',
|
| 13 |
+
'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-',
|
| 14 |
+
'Y': '-.--', 'Z': '--..', '1': '.----', '2': '..---', '3': '...--',
|
| 15 |
+
'4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..',
|
| 16 |
+
'9': '----.', '0': '-----', ' ': '/'
|
| 17 |
+
}
|
| 18 |
+
MORSE_TO_CHAR = {v: k for k, v in MORSE_CODE_DICT.items()}
|
| 19 |
+
|
| 20 |
+
# Morse code timing (in seconds)
|
| 21 |
+
DIT_DURATION = 0.1 # 100ms for dit
|
| 22 |
+
DAH_DURATION = 3 * DIT_DURATION # 300ms for dah
|
| 23 |
+
SPACE_DURATION = 7 * DIT_DURATION # 700ms for word space
|
| 24 |
+
CHAR_SPACE = DIT_DURATION # Space between characters
|
| 25 |
+
SAMPLE_RATE = 44100 # Standard audio sample rate
|
| 26 |
+
|
| 27 |
+
# Decode Morse from audio (simplified)
|
| 28 |
+
def decode_morse_from_audio(audio_data):
|
| 29 |
+
if audio_data is None:
|
| 30 |
+
return "", ""
|
| 31 |
+
sample_rate, data = audio_data
|
| 32 |
+
if len(data.shape) > 1:
|
| 33 |
+
data = data.mean(axis=1)
|
| 34 |
+
data = data / np.max(np.abs(data))
|
| 35 |
+
|
| 36 |
+
threshold = 0.1
|
| 37 |
+
signal = data > threshold
|
| 38 |
+
morse_code, decoded_text = "", ""
|
| 39 |
+
i = 0
|
| 40 |
+
|
| 41 |
+
while i < len(signal) - int(SAMPLE_RATE * DIT_DURATION):
|
| 42 |
+
if signal[i]:
|
| 43 |
+
start = i
|
| 44 |
+
while i < len(signal) and signal[i]:
|
| 45 |
+
i += 1
|
| 46 |
+
duration = (i - start) / sample_rate
|
| 47 |
+
morse_code += "-" if duration >= DAH_DURATION else "."
|
| 48 |
+
else:
|
| 49 |
+
start = i
|
| 50 |
+
while i < len(signal) and not signal[i]:
|
| 51 |
+
i += 1
|
| 52 |
+
pause = (i - start) / sample_rate
|
| 53 |
+
if pause >= SPACE_DURATION and morse_code:
|
| 54 |
+
decoded_text += " "
|
| 55 |
+
morse_code = ""
|
| 56 |
+
elif pause >= DIT_DURATION and morse_code:
|
| 57 |
+
decoded_text += MORSE_TO_CHAR.get(morse_code, "?")
|
| 58 |
+
morse_code = ""
|
| 59 |
+
i += 1
|
| 60 |
+
|
| 61 |
+
if morse_code:
|
| 62 |
+
decoded_text += MORSE_TO_CHAR.get(morse_code, "?")
|
| 63 |
+
return morse_code, decoded_text.strip()
|
| 64 |
+
|
| 65 |
+
# Convert text to Morse code
|
| 66 |
+
def text_to_morse(text):
|
| 67 |
+
text = text.upper()
|
| 68 |
+
morse = " ".join(MORSE_CODE_DICT.get(char, "?") for char in text if char in MORSE_CODE_DICT)
|
| 69 |
+
return morse
|
| 70 |
+
|
| 71 |
+
# Generate Morse code audio from text
|
| 72 |
+
def generate_morse_audio(morse):
|
| 73 |
+
audio = []
|
| 74 |
+
frequency = 750 # Hz for Morse tone
|
| 75 |
+
|
| 76 |
+
for symbol in morse.split():
|
| 77 |
+
if symbol == "/":
|
| 78 |
+
audio.extend([0] * int(SAMPLE_RATE * SPACE_DURATION))
|
| 79 |
+
else:
|
| 80 |
+
for char in symbol:
|
| 81 |
+
duration = DAH_DURATION if char == "-" else DIT_DURATION
|
| 82 |
+
t = np.linspace(0, duration, int(SAMPLE_RATE * duration), False)
|
| 83 |
+
tone = 0.5 * np.sin(2 * np.pi * frequency * t)
|
| 84 |
+
audio.extend(tone)
|
| 85 |
+
audio.extend([0] * int(SAMPLE_RATE * DIT_DURATION)) # Space between dits/dahs
|
| 86 |
+
audio.extend([0] * int(SAMPLE_RATE * CHAR_SPACE)) # Space between characters
|
| 87 |
+
|
| 88 |
+
audio = np.array(audio, dtype=np.float32)
|
| 89 |
+
buffer = io.BytesIO()
|
| 90 |
+
sf.write(buffer, audio, SAMPLE_RATE, format="wav")
|
| 91 |
+
buffer.seek(0)
|
| 92 |
+
return buffer
|
| 93 |
+
|
| 94 |
+
# Speech to text
|
| 95 |
+
def speech_to_text(audio):
|
| 96 |
+
recognizer = sr.Recognizer()
|
| 97 |
+
with sr.AudioFile(audio) as source:
|
| 98 |
+
audio_data = recognizer.record(source)
|
| 99 |
+
try:
|
| 100 |
+
return recognizer.recognize_google(audio_data)
|
| 101 |
+
except sr.UnknownValueError:
|
| 102 |
+
return "Could not understand audio"
|
| 103 |
+
except sr.RequestError:
|
| 104 |
+
return "Speech recognition service unavailable"
|
| 105 |
+
|
| 106 |
+
# Highlight alphabet in UI
|
| 107 |
+
def generate_alphabet_html(decoded_text):
|
| 108 |
+
html = "<div style='font-family: monospace; font-size: 16px;'>"
|
| 109 |
+
for char in MORSE_CODE_DICT.keys():
|
| 110 |
+
color = "red" if char in decoded_text.upper() else "black"
|
| 111 |
+
html += f"<span style='color: {color}; margin: 5px;'>{char}: {MORSE_CODE_DICT[char]}</span>"
|
| 112 |
+
if char in "AEIMQUZ":
|
| 113 |
+
html += "<br>"
|
| 114 |
+
html += "</div>"
|
| 115 |
+
return html
|
| 116 |
+
|
| 117 |
+
# Combined processing function
|
| 118 |
+
def process_input(text=None, speech=None, audio=None):
|
| 119 |
+
morse, decoded_text, audio_output = "", "", None
|
| 120 |
+
|
| 121 |
+
if text: # Text input
|
| 122 |
+
morse = text_to_morse(text)
|
| 123 |
+
decoded_text = text
|
| 124 |
+
audio_output = generate_morse_audio(morse)
|
| 125 |
+
|
| 126 |
+
elif speech: # Speech input
|
| 127 |
+
text = speech_to_text(speech)
|
| 128 |
+
morse = text_to_morse(text)
|
| 129 |
+
decoded_text = text
|
| 130 |
+
audio_output = generate_morse_audio(morse)
|
| 131 |
+
|
| 132 |
+
elif audio: # Live audio input
|
| 133 |
+
morse, decoded_text = decode_morse_from_audio(audio)
|
| 134 |
+
|
| 135 |
+
alphabet_html = generate_alphabet_html(decoded_text)
|
| 136 |
+
return morse, decoded_text, alphabet_html, audio_output
|
| 137 |
+
|
| 138 |
+
# Gradio UI with Blocks
|
| 139 |
+
with gr.Blocks(title="Morse Code Decoder & Generator") as demo:
|
| 140 |
+
gr.Markdown("# Morse Code Decoder & Generator")
|
| 141 |
+
gr.Markdown("Decode live Morse audio, or generate Morse from text/speech!")
|
| 142 |
+
|
| 143 |
+
with gr.Tab("Decode Live Audio"):
|
| 144 |
+
audio_input = gr.Audio(source="microphone", type="numpy", streaming=True, label="Live Audio Input")
|
| 145 |
+
with gr.Row():
|
| 146 |
+
with gr.Column():
|
| 147 |
+
morse_output = gr.Textbox(label="Detected Morse Code", interactive=False)
|
| 148 |
+
text_output = gr.Textbox(label="Decoded Text", interactive=False)
|
| 149 |
+
alphabet_display = gr.HTML(label="Morse Alphabet (Highlighted)")
|
| 150 |
+
|
| 151 |
+
audio_input.stream(
|
| 152 |
+
fn=process_input,
|
| 153 |
+
inputs=[audio_input],
|
| 154 |
+
outputs=[morse_output, text_output, alphabet_display, gr.Audio(visible=False)],
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
with gr.Tab("Generate from Text"):
|
| 158 |
+
text_input = gr.Textbox(label="Enter Text", placeholder="Type here...")
|
| 159 |
+
generate_btn = gr.Button("Generate Morse")
|
| 160 |
+
with gr.Row():
|
| 161 |
+
with gr.Column():
|
| 162 |
+
morse_gen_output = gr.Textbox(label="Morse Code", interactive=False)
|
| 163 |
+
text_gen_output = gr.Textbox(label="Original Text", interactive=False)
|
| 164 |
+
gen_alphabet_display = gr.HTML(label="Morse Alphabet (Highlighted)")
|
| 165 |
+
audio_playback = gr.Audio(label="Morse Audio Playback", interactive=False)
|
| 166 |
+
|
| 167 |
+
generate_btn.click(
|
| 168 |
+
fn=process_input,
|
| 169 |
+
inputs=[text_input],
|
| 170 |
+
outputs=[morse_gen_output, text_gen_output, gen_alphabet_display, audio_playback]
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
with gr.Tab("Generate from Speech"):
|
| 174 |
+
speech_input = gr.Audio(source="microphone", type="filepath", label="Speak Your Text")
|
| 175 |
+
speech_btn = gr.Button("Convert Speech to Morse")
|
| 176 |
+
with gr.Row():
|
| 177 |
+
with gr.Column():
|
| 178 |
+
morse_speech_output = gr.Textbox(label="Morse Code", interactive=False)
|
| 179 |
+
text_speech_output = gr.Textbox(label="Transcribed Text", interactive=False)
|
| 180 |
+
speech_alphabet_display = gr.HTML(label="Morse Alphabet (Highlighted)")
|
| 181 |
+
speech_audio_playback = gr.Audio(label="Morse Audio Playback", interactive=False)
|
| 182 |
+
|
| 183 |
+
speech_btn.click(
|
| 184 |
+
fn=process_input,
|
| 185 |
+
inputs=[speech_input],
|
| 186 |
+
outputs=[morse_speech_output, text_speech_output, speech_alphabet_display, speech_audio_playback]
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
# Launch the app
|
| 190 |
+
demo.launch()
|