nightfury commited on
Commit
5de1276
·
verified ·
1 Parent(s): 9e8347c

Create app2.py

Browse files
Files changed (1) hide show
  1. app2.py +217 -0
app2.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import tempfile
4
+ from scipy.io import wavfile
5
+ import speech_recognition as sr
6
+ import soundfile as sf
7
+
8
+ # Morse code dictionary
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
+ # Timing constants
21
+ DIT_DURATION = 0.1
22
+ DAH_DURATION = 3 * DIT_DURATION
23
+ SPACE_DURATION = 7 * DIT_DURATION
24
+ CHAR_SPACE = DIT_DURATION
25
+ SAMPLE_RATE = 44100
26
+
27
+ # Decode Morse from audio beeps
28
+ def decode_morse_from_audio(audio_data, is_file=False):
29
+ if audio_data is None:
30
+ return "", ""
31
+ if is_file:
32
+ sample_rate, data = wavfile.read(audio_data)
33
+ else:
34
+ sample_rate, data = audio_data
35
+ if len(data.shape) > 1:
36
+ data = data.mean(axis=1)
37
+ data = data / np.max(np.abs(data))
38
+
39
+ threshold = 0.1
40
+ signal = data > threshold
41
+ morse_code, decoded_text = "", ""
42
+ i = 0
43
+
44
+ while i < len(signal) - int(SAMPLE_RATE * DIT_DURATION):
45
+ if signal[i]:
46
+ start = i
47
+ while i < len(signal) and signal[i]:
48
+ i += 1
49
+ duration = (i - start) / sample_rate
50
+ morse_code += "-" if duration >= DAH_DURATION else "."
51
+ else:
52
+ start = i
53
+ while i < len(signal) and not signal[i]:
54
+ i += 1
55
+ pause = (i - start) / sample_rate
56
+ if pause >= SPACE_DURATION and morse_code:
57
+ decoded_text += " "
58
+ morse_code = ""
59
+ elif pause >= DIT_DURATION and morse_code:
60
+ decoded_text += MORSE_TO_CHAR.get(morse_code, "?")
61
+ morse_code = ""
62
+ i += 1
63
+
64
+ if morse_code:
65
+ decoded_text += MORSE_TO_CHAR.get(morse_code, "?")
66
+ return morse_code, decoded_text.strip()
67
+
68
+ # Decode Morse from text
69
+ def decode_morse_from_text(morse_text):
70
+ if not morse_text:
71
+ return ""
72
+ words = morse_text.split("/")
73
+ decoded_text = ""
74
+ for word in words:
75
+ chars = word.strip().split()
76
+ for char in chars:
77
+ decoded_text += MORSE_TO_CHAR.get(char, "?")
78
+ decoded_text += " "
79
+ return decoded_text.strip()
80
+
81
+ # Encode text to Morse
82
+ def text_to_morse(text):
83
+ text = text.upper()
84
+ return " ".join(MORSE_CODE_DICT.get(char, "?") for char in text if char in MORSE_CODE_DICT)
85
+
86
+ # Generate Morse audio
87
+ def generate_morse_audio(morse):
88
+ audio = []
89
+ frequency = 750
90
+
91
+ for symbol in morse.split():
92
+ if symbol == "/":
93
+ audio.extend([0] * int(SAMPLE_RATE * SPACE_DURATION))
94
+ else:
95
+ for char in symbol:
96
+ duration = DAH_DURATION if char == "-" else DIT_DURATION
97
+ t = np.linspace(0, duration, int(SAMPLE_RATE * duration), False)
98
+ tone = 0.5 * np.sin(2 * np.pi * frequency * t)
99
+ audio.extend(tone)
100
+ audio.extend([0] * int(SAMPLE_RATE * DIT_DURATION))
101
+ audio.extend([0] * int(SAMPLE_RATE * CHAR_SPACE))
102
+
103
+ audio = np.array(audio, dtype=np.float32)
104
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_file:
105
+ sf.write(temp_file.name, audio, SAMPLE_RATE, format="wav")
106
+ return temp_file.name
107
+
108
+ # Speech to text
109
+ def speech_to_text(audio_path):
110
+ recognizer = sr.Recognizer()
111
+ with sr.AudioFile(audio_path) as source:
112
+ audio_data = recognizer.record(source)
113
+ try:
114
+ return recognizer.recognize_google(audio_data)
115
+ except:
116
+ return "Speech recognition failed"
117
+
118
+ # Highlight alphabet
119
+ def generate_alphabet_html(text):
120
+ html = "<div style='font-family: monospace; font-size: 16px;'>"
121
+ for char in MORSE_CODE_DICT.keys():
122
+ color = "red" if char in text.upper() else "black"
123
+ html += f"<span style='color: {color}; margin: 5px;'>{char}: {MORSE_CODE_DICT[char]}</span>"
124
+ if char in "AEIMQUZ":
125
+ html += "<br>"
126
+ html += "</div>"
127
+ return html
128
+
129
+ # Encoding functions
130
+ def encode_text_to_morse(text):
131
+ morse = text_to_morse(text)
132
+ audio = generate_morse_audio(morse)
133
+ return morse, text, generate_alphabet_html(text), audio
134
+
135
+ def encode_speech_to_morse(audio_path):
136
+ text = speech_to_text(audio_path)
137
+ morse = text_to_morse(text)
138
+ audio = generate_morse_audio(morse)
139
+ return morse, text, generate_alphabet_html(text), audio
140
+
141
+ # Decoding functions
142
+ def decode_morse_text(morse_text):
143
+ text = decode_morse_from_text(morse_text)
144
+ audio = generate_morse_audio(morse_text)
145
+ return morse_text, text, generate_alphabet_html(text), audio
146
+
147
+ def decode_morse_speech(audio_path):
148
+ transcribed = speech_to_text(audio_path).replace("dit", ".").replace("dah", "-").replace("slash", "/")
149
+ text = decode_morse_from_text(transcribed)
150
+ audio = generate_morse_audio(transcribed)
151
+ return transcribed, text, generate_alphabet_html(text), audio
152
+
153
+ def decode_morse_audio(audio_path):
154
+ morse, text = decode_morse_from_audio(audio_path, is_file=True)
155
+ return morse, text, generate_alphabet_html(text), None
156
+
157
+ def decode_live_morse(audio_data):
158
+ morse, text = decode_morse_from_audio(audio_data, is_file=False)
159
+ return morse, text, generate_alphabet_html(text), None
160
+
161
+ # Gradio UI
162
+ with gr.Blocks(title="Morse Code Converter") as demo:
163
+ gr.Markdown("# Morse Code Converter")
164
+ gr.Markdown("Encode to Morse or decode Morse from text, speech, or audio!")
165
+
166
+ with gr.Tab("Encode Text to Morse"):
167
+ text_input = gr.Textbox(label="Enter Text", placeholder="e.g., HELLO")
168
+ text_btn = gr.Button("Convert to Morse")
169
+ text_morse_out = gr.Textbox(label="Morse Code", interactive=False)
170
+ text_text_out = gr.Textbox(label="Original Text", interactive=False)
171
+ text_alphabet = gr.HTML(label="Alphabet (Highlighted)")
172
+ text_audio = gr.Audio(label="Morse Audio", interactive=False)
173
+ text_btn.click(fn=encode_text_to_morse, inputs=[text_input], outputs=[text_morse_out, text_text_out, text_alphabet, text_audio])
174
+
175
+ with gr.Tab("Encode Speech to Morse"):
176
+ speech_input = gr.Audio(type="filepath", label="Record Speech (e.g., say 'HELLO')")
177
+ speech_btn = gr.Button("Convert to Morse")
178
+ speech_morse_out = gr.Textbox(label="Morse Code", interactive=False)
179
+ speech_text_out = gr.Textbox(label="Transcribed Text", interactive=False)
180
+ speech_alphabet = gr.HTML(label="Alphabet (Highlighted)")
181
+ speech_audio = gr.Audio(label="Morse Audio", interactive=False)
182
+ speech_btn.click(fn=encode_speech_to_morse, inputs=[speech_input], outputs=[speech_morse_out, speech_text_out, speech_alphabet, speech_audio])
183
+
184
+ with gr.Tab("Decode Morse Text"):
185
+ morse_text_input = gr.Textbox(label="Enter Morse Text", placeholder="e.g., .... . .-.. .-.. ---")
186
+ morse_text_btn = gr.Button("Decode Morse")
187
+ morse_text_morse_out = gr.Textbox(label="Morse Code", interactive=False)
188
+ morse_text_text_out = gr.Textbox(label="Decoded Text", interactive=False)
189
+ morse_text_alphabet = gr.HTML(label="Alphabet (Highlighted)")
190
+ morse_text_audio = gr.Audio(label="Morse Audio", interactive=False)
191
+ morse_text_btn.click(fn=decode_morse_text, inputs=[morse_text_input], outputs=[morse_text_morse_out, morse_text_text_out, morse_text_alphabet, morse_text_audio])
192
+
193
+ with gr.Tab("Decode Morse Speech"):
194
+ morse_speech_input = gr.Audio(type="filepath", label="Record Morse Speech (e.g., say 'dit dit dit dit dit')")
195
+ morse_speech_btn = gr.Button("Decode Morse")
196
+ morse_speech_morse_out = gr.Textbox(label="Transcribed Morse", interactive=False)
197
+ morse_speech_text_out = gr.Textbox(label="Decoded Text", interactive=False)
198
+ morse_speech_alphabet = gr.HTML(label="Alphabet (Highlighted)")
199
+ morse_speech_audio = gr.Audio(label="Morse Audio", interactive=False)
200
+ morse_speech_btn.click(fn=decode_morse_speech, inputs=[morse_speech_input], outputs=[morse_speech_morse_out, morse_speech_text_out, morse_speech_alphabet, morse_speech_audio])
201
+
202
+ with gr.Tab("Decode Morse Audio"):
203
+ morse_audio_input = gr.Audio(type="filepath", label="Upload Morse Audio (WAV of beeps)")
204
+ morse_audio_btn = gr.Button("Decode Morse")
205
+ morse_audio_morse_out = gr.Textbox(label="Detected Morse", interactive=False)
206
+ morse_audio_text_out = gr.Textbox(label="Decoded Text", interactive=False)
207
+ morse_audio_alphabet = gr.HTML(label="Alphabet (Highlighted)")
208
+ morse_audio_btn.click(fn=decode_morse_audio, inputs=[morse_audio_input], outputs=[morse_audio_morse_out, morse_audio_text_out, morse_audio_alphabet])
209
+
210
+ with gr.Tab("Decode Live Morse"):
211
+ live_audio_input = gr.Audio(type="numpy", label="Live Morse Input (Use Microphone)", streaming=True)
212
+ live_morse_out = gr.Textbox(label="Detected Morse", interactive=False)
213
+ live_text_out = gr.Textbox(label="Decoded Text", interactive=False)
214
+ live_alphabet = gr.HTML(label="Alphabet (Highlighted)")
215
+ live_audio_input.stream(fn=decode_live_morse, inputs=[live_audio_input], outputs=[live_morse_out, live_text_out, live_alphabet])
216
+
217
+ demo.launch()