#!/usr/bin/env python3 """International Morse code: encode, decode, timing and WAV audio. Standard library only. Part of the morse-code Agent Skill from https://morsekeyboard.com/skills/ . The table follows ITU-R M.1677-1, plus a few widely used signs that are not in it (marked below). It is the same table as the translator on morsekeyboard.com. Command line: python3 morse.py encode "CQ CQ DE N0CALL" python3 morse.py decode "... --- ..." python3 morse.py timing --wpm 20 --farnsworth 10 python3 morse.py wav "PARIS PARIS" out.wav --wpm 20 --farnsworth 10 --pitch 650 As a module: from morse import encode, decode, timing, schedule, write_wav Conventions: letters are separated by one space, words by " / ", lines by a newline. A prosign is written in angle brackets (, ) and sent as one run-together signal. Anything with no Morse form becomes "#". """ from __future__ import annotations import argparse import math import re import struct import sys import unicodedata import wave # (character, code, ITU-R M.1677-1?) TABLE = [ # Letters ("A", ".-", True), ("B", "-...", True), ("C", "-.-.", True), ("D", "-..", True), ("E", ".", True), ("F", "..-.", True), ("G", "--.", True), ("H", "....", True), ("I", "..", True), ("J", ".---", True), ("K", "-.-", True), ("L", ".-..", True), ("M", "--", True), ("N", "-.", True), ("O", "---", True), ("P", ".--.", True), ("Q", "--.-", True), ("R", ".-.", True), ("S", "...", True), ("T", "-", True), ("U", "..-", True), ("V", "...-", True), ("W", ".--", True), ("X", "-..-", True), ("Y", "-.--", True), ("Z", "--..", True), ("É", "..-..", True), # Figures ("1", ".----", True), ("2", "..---", True), ("3", "...--", True), ("4", "....-", True), ("5", ".....", True), ("6", "-....", True), ("7", "--...", True), ("8", "---..", True), ("9", "----.", True), ("0", "-----", True), # Punctuation and signs (".", ".-.-.-", True), (",", "--..--", True), (":", "---...", True), ("?", "..--..", True), ("'", ".----.", True), ("-", "-....-", True), ("/", "-..-.", True), ("(", "-.--.", True), (")", "-.--.-", True), ('"', ".-..-.", True), ("=", "-...-", True), ("+", ".-.-.", True), ("@", ".--.-.", True), # Widely used, not in ITU-R M.1677-1 ("!", "-.-.--", False), ("&", ".-...", False), (";", "-.-.-.", False), ("_", "..--.-", False), ("$", "...-..-", False), # Prosigns, sent as one signal with no letter gaps ("", ".-.-.", True), ("", ".-...", True), ("", "-...-", True), ("", "-.-.-", True), ("", "-.--.", False), ("", "...-.-", True), ("", "...-.", True), ("", "........", True), ("", "...---...", False), ] CHAR_TO_CODE = {c: code for c, code, _ in TABLE} # Where a prosign shares a pattern with a character (AR and +, BT and =, KN and (, AS and &), # decoding gives the character. CODE_TO_CHAR: dict[str, str] = {} for _c, _code, _ in TABLE: if not _c.startswith("<"): CODE_TO_CHAR.setdefault(_code, _c) for _c, _code, _ in TABLE: CODE_TO_CHAR.setdefault(_code, _c) PROSIGN_ALIASES = {"": "", "": "", "": ""} TEXT_ALIASES = { "‘": "'", "’": "'", "ʼ": "'", "“": '"', "”": '"', "„": '"', "×": "X", # ITU: the multiplication sign is sent as X "‐": "-", "‑": "-", "‒": "-", "–": "-", "—": "-", "−": "-", "⁄": "/", } DOT_LOOKALIKES = re.compile("[·•∙⋅‧・●․]") DASH_LOOKALIKES = re.compile("[‒–—―−‐‑⁃﹘﹣-_‾]") UNKNOWN = "#" PARIS_UNITS = 50 def _tokens(word: str) -> list[str]: out, i = [], 0 while i < len(word): m = re.match(r"<[A-Z]{2,3}>", word[i:]) if m: key = PROSIGN_ALIASES.get(m.group(0), m.group(0)) if key in CHAR_TO_CODE: out.append(key) i += len(m.group(0)) continue out.append(word[i]) i += 1 return out def encode(text: str, unknown: str = UNKNOWN) -> str: """Text to Morse: letters split by " ", words by " / ", lines by newlines.""" src = unicodedata.normalize("NFC", text).upper() lines = [] for line in re.split(r"\r\n|\r|\n", src): words = [] for word in line.split(): codes = [CHAR_TO_CODE.get(TEXT_ALIASES.get(ch, ch), unknown) for ch in _tokens(word)] words.append(" ".join(codes)) lines.append(" / ".join(words)) return "\n".join(lines) def normalize_morse(morse: str) -> str: """Folds lookalike marks (middle dots, en and em dashes, underscores) to "." and "-".""" s = unicodedata.normalize("NFC", morse) return DASH_LOOKALIKES.sub("-", DOT_LOOKALIKES.sub(".", s)).replace("|", "/") def decode(morse: str, unknown: str = UNKNOWN) -> str: """Morse to upper-case text. Word gaps: "/", "|" or three or more spaces.""" out_lines = [] for line in re.split(r"\r\n|\r|\n", normalize_morse(morse)): words = [w.strip() for w in re.split(r"\s*/\s*|[ \t]{3,}", line) if w.strip()] out_lines.append(" ".join( "".join(CODE_TO_CHAR.get(tok, unknown) if re.fullmatch(r"[.-]+", tok) else unknown for tok in w.split()) for w in words)) return "\n".join(out_lines) def farnsworth_gaps(char_wpm: float, effective_wpm: float) -> tuple[float, float]: """ARRL Farnsworth spacing, in seconds: (gap between characters, gap between words). ta = (60c - 37.2s) / (c * s) seconds of spacing per PARIS word; tc = 3ta/19; tw = 7ta/19. """ c, s = float(char_wpm), float(effective_wpm) if c <= 0 or s <= 0: raise ValueError("speeds must be positive") if s > c: raise ValueError("effective speed cannot exceed character speed") ta = (60 * c - 37.2 * s) / (c * s) return 3 * ta / 19, 7 * ta / 19 def timing(wpm: float = 20, farnsworth: float | None = None) -> dict: """Durations in milliseconds for a character speed and an optional slower overall speed.""" if wpm <= 0: raise ValueError("wpm must be positive") unit = 60000 / (PARIS_UNITS * wpm) # = 1200 / wpm letter_gap, word_gap = 3 * unit, 7 * unit fw = farnsworth is not None and 0 < farnsworth < wpm if fw: tc, tw = farnsworth_gaps(wpm, farnsworth) letter_gap, word_gap = tc * 1000, tw * 1000 return { "wpm": wpm, "effective_wpm": farnsworth if fw else wpm, "unit": unit, "dot": unit, "dash": 3 * unit, "intra_gap": unit, "letter_gap": letter_gap, "word_gap": word_gap, } def schedule(text_or_morse: str, wpm: float = 20, farnsworth: float | None = None) -> list[tuple[bool, float]]: """A list of (tone_on, milliseconds) segments for text (encoded first) or Morse.""" s = text_or_morse if not re.fullmatch(r"[\s./|#\-·•–—_]*", s) or not re.search(r"[.\-·•–—_]", s): s = encode(s) t = timing(wpm, farnsworth) segs: list[tuple[bool, float]] = [] for li, line in enumerate(re.split(r"\r\n|\r|\n", normalize_morse(s))): words = [w.split() for w in re.split(r"\s*/\s*|[ \t]{3,}", line) if w.strip()] for wi, letters in enumerate(words): if segs and (wi > 0 or li > 0): segs.append((False, t["word_gap"])) for ci, tok in enumerate(letters): if ci > 0: segs.append((False, t["letter_gap"])) for mi, mark in enumerate(m for m in tok if m in ".-"): if mi > 0: segs.append((False, t["intra_gap"])) segs.append((True, t["dot"] if mark == "." else t["dash"])) return segs def units(morse: str) -> int: """Length in units at standard timing, with a trailing word gap (PARIS = 50).""" t = timing(1) return round(sum(ms for _, ms in schedule(morse, 1)) / t["unit"]) + 7 def write_wav(text_or_morse: str, path: str, wpm: float = 20, farnsworth: float | None = None, pitch: float = 600, sample_rate: int = 8000, volume: float = 0.5, ramp_ms: float = 5) -> float: """Writes a mono 16-bit WAV of the signal and returns its length in seconds. Each tone gets a raised-cosine ramp (ramp_ms) at both ends so it does not click. """ if not 0 < volume <= 1: raise ValueError("volume must be in (0, 1]") if sample_rate <= 0: raise ValueError("sample rate must be positive") if not 0 < pitch < sample_rate / 2: raise ValueError(f"pitch must be above 0 and below half the sample rate ({sample_rate / 2:g} Hz)") segs = schedule(text_or_morse, wpm, farnsworth) if not any(on for on, _ in segs): raise ValueError("nothing to send: the text has no characters with a Morse code") frames = bytearray() lead = int(sample_rate * 0.1) # 100 ms of silence at each end frames += b"\x00\x00" * lead for on, ms in segs: n = int(round(sample_rate * ms / 1000)) if not on: frames += b"\x00\x00" * n continue ramp = min(int(sample_rate * ramp_ms / 1000), n // 2) for i in range(n): env = 1.0 if ramp and i < ramp: env = 0.5 - 0.5 * math.cos(math.pi * i / ramp) elif ramp and i >= n - ramp: env = 0.5 - 0.5 * math.cos(math.pi * (n - 1 - i) / ramp) v = volume * env * math.sin(2 * math.pi * pitch * i / sample_rate) frames += struct.pack(" int: p = argparse.ArgumentParser(description="International Morse code tools (stdlib only).") sub = p.add_subparsers(dest="cmd", required=True) sub.add_parser("encode", help="text to Morse").add_argument("text") sub.add_parser("decode", help="Morse to text").add_argument("morse") tp = sub.add_parser("timing", help="durations at a speed") tp.add_argument("--wpm", type=float, default=20) tp.add_argument("--farnsworth", type=float, default=None, help="overall (effective) WPM") wp = sub.add_parser("wav", help="write a WAV file") wp.add_argument("text") wp.add_argument("path") wp.add_argument("--wpm", type=float, default=20, help="character speed") wp.add_argument("--farnsworth", type=float, default=None, help="overall (effective) WPM") wp.add_argument("--pitch", type=float, default=600, help="tone in Hz") wp.add_argument("--rate", type=int, default=8000, help="sample rate") wp.add_argument("--volume", type=float, default=0.5) a = p.parse_args(argv) try: return _run(a) except ValueError as e: p.error(str(e)) # exits with status 2 and a usage line, not a traceback def _run(a: argparse.Namespace) -> int: fw = getattr(a, "farnsworth", None) if fw is not None and a.wpm > 0 and not 0 < fw < a.wpm: print(f"note: --farnsworth {fw:g} ignored: it must be above 0 and below --wpm {a.wpm:g}", file=sys.stderr) if a.cmd == "encode": print(encode(a.text)) elif a.cmd == "decode": print(decode(a.morse)) elif a.cmd == "timing": for k, v in timing(a.wpm, a.farnsworth).items(): print(f"{k}: {round(v, 1) if isinstance(v, float) else v}") else: secs = write_wav(a.text, a.path, a.wpm, a.farnsworth, a.pitch, a.rate, a.volume) print(f"wrote {a.path} ({secs:.2f} s)") return 0 if __name__ == "__main__": sys.exit(main())