Read the stations that never say a word
Most of what identifies itself on the air identifies itself in Morse. A repeater, a beacon, an unattended transmitter: four to six characters, over in a second or two, and no speech anywhere in the capture. Every one of those was being thrown away, in three separate places. The callsign book and the map were built inside the transcription branch, on the reasoning that callsigns come out of transcripts. They also come out of Morse and out of APRS headers, neither of which involves a speech recogniser -- so a receiver with none installed found none of them, and a CW ident reached the sidecar and stopped there. Both are now built whenever classification is on, and all three sources go through one place. The CW decoder only ran where the classifier had already said cw, ook or carrier. A two-second ident is a fraction of a capture named after whatever filled the rest of it. Every capture is offered to it now, once it has finished; a decode does not relabel a capture that plainly holds speech. And the decoder's own gates were written for a paragraph. Three characters, eight elements, and any repeated character refused -- which read VVV, DE, AR and K correctly and then discarded them. Short is the normal case now, on a second bar: perfect timing, nothing undecoded, and the keyed tone at least 20 dB over its band. That last is not decoration. With four elements the dot length is fitted to those very elements, so noise lands on the grid as neatly as keying does; a third of a second of white noise decodes as a perfectly timed V. Over 200 noise blocks the loudest bin never rose 13 dB above the median while keying at 3 dB SNR sits above 40. One keyed element is still refused: a single pulse is an E or a T whether a person sent it or the squelch opened on a click. 288 non-Morse cases, no false positives. Feeding that text to a callsign lookup made truncation matter. A capture opens when the squelch does, halfway through an element as often as not, and half a character is not a smaller reading -- a K missing its first dash is an A. So the sliced character is dropped, and so is the rest of its word, because what is left can read as a whole one: K1AA caught halfway through is K1A, which is somebody else. Across 1805 truncated captures that is 107 invented callsigns down to none, with 550 correct ones still found. Phonetics, which is the other half of the ask. A recogniser has never heard of the alphabet -- it writes what the words sounded like: Whiskey-One-Alpha-Whiskey hyphenated WhiskeyOneAlphaWhiskey run together Whiskey1AlphaWhiskey and half in digits wiskey one alfa whisky spelled the way it sounded whiskey one alpha, uh, whiskey with the hesitation written down All read back to W1AW now. A word is only taken apart when it is phonetic all the way through, which is what keeps it off "kilometre" and "victorious". Two bugs found on the way, both of which invented a callsign: - Nothing is joined across a slash any more. The beacon W1AW/B came back as W1AWB, which belongs to nobody, and W1AW-4 came back as nothing at all. - Nor across a gap the sender chose. A transcript's spacing is the recogniser's guess and may be closed up; a word gap in Morse is seven dot units, so "KU0W K" is a station signing off, not a longer callsign. Also here: - saunterbrowse gives Morse a panel of its own, with the licence under it, searchable with / and readable with t. - --simulate no longer looks anything up or writes a map. The demo band is invented but W1AW is the ARRL's own station, and it would have been pinned to the same map a real scan writes. - classify._psk_order took the logarithm of zero on a silent block. - The demo band has a repeater ident in it, and its Morse no longer runs one repeat into the next. - conftest refuses a real licence lookup from any test. 1161 tests, up from 1014. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016PsWPTweCT6pwxKngvVxcg
This commit is contained in:
parent
f9f0d94000
commit
b4718aa425
21 changed files with 1434 additions and 129 deletions
|
|
@ -1,6 +1,7 @@
|
|||
"""Fixtures every test gets.
|
||||
|
||||
Both of them are about not touching the machine the tests run on.
|
||||
All three are about not touching the machine the tests run on, or anyone
|
||||
else's.
|
||||
|
||||
The cache: a lookup writes to ``~/.cache`` by default, and a test run that
|
||||
touches the real one leaves entries behind and reads back entries an earlier
|
||||
|
|
@ -10,10 +11,14 @@ The settings: locking a frequency out writes it into ``config.yaml``, and a
|
|||
test that reached the real one would silently change what the next real scan
|
||||
does. The constant is replaced in every module that holds a copy, so that
|
||||
forgetting to pass a directory somewhere cannot end in someone's own settings.
|
||||
|
||||
The network: a licence lookup goes to a public database and returns a real
|
||||
person's name and address. No test has any business doing that.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
import bandsaunter.browse
|
||||
import bandsaunter.callsign
|
||||
import bandsaunter.cli
|
||||
import bandsaunter.config
|
||||
import bandsaunter.tui
|
||||
|
|
@ -25,6 +30,21 @@ def isolated_cache(tmp_path_factory, monkeypatch):
|
|||
str(tmp_path_factory.mktemp("cache")))
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_licence_lookups(monkeypatch):
|
||||
"""No test may contact the licence database.
|
||||
|
||||
One did, silently, and passed -- it was only visible because the
|
||||
assertion it failed printed a real operator's address. A test that wants
|
||||
answers stubs this itself; anything else fails loudly rather than going
|
||||
to the network and being slow, flaky and rude about it.
|
||||
"""
|
||||
def refuse(self, call):
|
||||
raise AssertionError(f"a test tried to look up {call} for real")
|
||||
|
||||
monkeypatch.setattr(bandsaunter.callsign.CallsignBook, "_request", refuse)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def isolated_settings(tmp_path_factory, monkeypatch):
|
||||
where = tmp_path_factory.mktemp("config")
|
||||
|
|
|
|||
|
|
@ -14,8 +14,9 @@ import time
|
|||
|
||||
import pytest
|
||||
|
||||
from bandsaunter.callsign import (Callsign, CallsignBook, HEADING,
|
||||
NOT_CALLSIGNS, SHAPE, describe_prefix,
|
||||
from bandsaunter.callsign import (Callsign, CallsignBook, FILLERS, HEADING,
|
||||
NOT_CALLSIGNS, PHONETIC, SHAPE,
|
||||
_phonetic_parts, describe_prefix,
|
||||
find_callsigns, person_case, report,
|
||||
split_postcode)
|
||||
|
||||
|
|
@ -124,6 +125,103 @@ def test_every_excluded_word_could_actually_have_matched():
|
|||
assert SHAPE.match(word), f"{word} never matched in the first place"
|
||||
|
||||
|
||||
# -- the phonetic alphabet, as a recogniser writes it down --------------------
|
||||
#
|
||||
# It is never written the way the ITU prints it. A recogniser hears the
|
||||
# words and writes what they sounded like, joins them up, hyphenates them, or
|
||||
# drops a hesitation in the middle of the run.
|
||||
|
||||
@pytest.mark.parametrize("text,want", [
|
||||
# Hyphenated, which is how a recogniser writes anything spelled out.
|
||||
("Whiskey-One-Alpha-Whiskey", ["W1AW"]),
|
||||
("this is whiskey-one-alpha-whiskey clear", ["W1AW"]),
|
||||
# Run together, when it was said quickly.
|
||||
("WhiskeyOneAlphaWhiskey", ["W1AW"]),
|
||||
("The station is Whiskey1AlphaWhiskey", ["W1AW"]),
|
||||
("kilouniformzerowhiskey", ["KU0W"]),
|
||||
# Said with a hesitation in the middle of it.
|
||||
("whiskey one alpha, uh, whiskey", ["W1AW"]),
|
||||
("kilo uniform um zero whiskey", ["KU0W"]),
|
||||
# The spellings that are not the official ones.
|
||||
("wiskey one alfa whisky", ["W1AW"]),
|
||||
("juliette alpha one november golf", ["JA1NG"]),
|
||||
("oskar viktor two charley romeo", ["OV2CR"]),
|
||||
])
|
||||
def test_a_phonetic_spelling_is_read_however_it_was_written(text, want):
|
||||
assert find_callsigns(text) == want
|
||||
|
||||
|
||||
@pytest.mark.parametrize("word", [
|
||||
"kilometre", "kilometer", "victorious", "november", "onetime", "papaya",
|
||||
"hotelier", "echoes", "deltas", "golfing", "oneself", "foxtrotting",
|
||||
"sierras", "alphabet", "zeroed", "information", "uniformity", "tangos",
|
||||
"twofold", "fivefold", "sixty", "seventeen", "nineteen", "charlies",
|
||||
"oscars", "limas", "romeos", "echoing", "novembers", "onto", "golfer",
|
||||
])
|
||||
def test_an_ordinary_word_is_not_taken_apart(word):
|
||||
"""Splitting only fires on a word that is phonetic all the way through.
|
||||
|
||||
A partial match is no match, which is the whole of what keeps this away
|
||||
from English: "kilometre" begins with a phonetic word and "victorious"
|
||||
contains one, and neither can be consumed to the end.
|
||||
"""
|
||||
assert _phonetic_parts(word) is None
|
||||
|
||||
|
||||
def test_x_ray_is_one_letter_not_two_words():
|
||||
"""The one phonetic word with a hyphen in it of its own."""
|
||||
assert find_callsigns("x-ray echo two delta") == ["XE2D"]
|
||||
assert find_callsigns("xray echo two delta") == ["XE2D"]
|
||||
|
||||
|
||||
def test_every_filler_is_something_a_recogniser_writes():
|
||||
"""Each of these has to be a word, not a letter it would swallow."""
|
||||
for word in FILLERS:
|
||||
assert word.lower() not in PHONETIC, word
|
||||
assert not SHAPE.match(word), word
|
||||
|
||||
|
||||
# -- suffixes, which are not part of the callsign ----------------------------
|
||||
|
||||
@pytest.mark.parametrize("text,want", [
|
||||
("W1AW/4", ["W1AW"]),
|
||||
("DL/W1AW", ["W1AW"]),
|
||||
("This is W1AW-4", ["W1AW"]),
|
||||
("VVV DE W1AW/B FN31", ["W1AW"]),
|
||||
("VE3XYZ/M mobile", ["VE3XYZ"]),
|
||||
])
|
||||
def test_a_suffix_is_not_glued_onto_the_callsign(text, want):
|
||||
"""A slash means "somewhere else", not another letter.
|
||||
|
||||
The beacon W1AW/B used to come back as W1AWB, which belongs to nobody
|
||||
and would have been looked up and pinned to a map.
|
||||
"""
|
||||
assert find_callsigns(text) == want
|
||||
|
||||
|
||||
# -- where the spacing is real ----------------------------------------------
|
||||
|
||||
def test_words_are_joined_where_a_recogniser_put_the_gaps_in():
|
||||
"""A transcript's spacing is a guess, so it is allowed to be wrong."""
|
||||
assert find_callsigns("KU 0W") == ["KU0W"]
|
||||
assert find_callsigns("K7 RA") == ["K7RA"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text,want", [
|
||||
("KU0W K", ["KU0W"]), # a station signing off, not KU0WK
|
||||
("CQ CQ DE KU0W K", ["KU0W"]),
|
||||
("DE W1AW K", ["W1AW"]),
|
||||
("VVV DE W1AW/B FN31", ["W1AW"]),
|
||||
])
|
||||
def test_nothing_is_joined_where_the_sender_put_the_gaps_in(text, want):
|
||||
"""A word gap in Morse is seven dot units the sender chose to send.
|
||||
|
||||
Joining across one turns a station signing off with K -- "over" -- into a
|
||||
callsign one letter longer that belongs to somebody else entirely.
|
||||
"""
|
||||
assert find_callsigns(text, join_words=False) == want
|
||||
|
||||
|
||||
# -- what the callsign says about itself -------------------------------------
|
||||
|
||||
@pytest.mark.parametrize("call,country", [
|
||||
|
|
|
|||
340
tests/test_ident.py
Normal file
340
tests/test_ident.py
Normal file
|
|
@ -0,0 +1,340 @@
|
|||
"""A station that identifies itself, and what happens to it after that.
|
||||
|
||||
Most stations on the air never say a word. A repeater, a beacon or an
|
||||
unattended transmitter sends its callsign in Morse and stops, and until this
|
||||
existed the text was decoded, written into the sidecar, and read by nobody:
|
||||
the callsign book and the map were built where the transcripts were, and a
|
||||
CW ident produces no transcript.
|
||||
|
||||
So these are about the whole path -- decode, find the callsign, look it up,
|
||||
say so, put it on the map -- and about the two places it is allowed to say
|
||||
nothing rather than say the wrong thing.
|
||||
"""
|
||||
import json
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from rich.console import Console
|
||||
|
||||
from bandsaunter.browse import Browser, Player
|
||||
from bandsaunter.callsign import CallsignBook
|
||||
from bandsaunter.config import ScanConfig
|
||||
from bandsaunter.morse import decode_morse
|
||||
from bandsaunter.quality import assess
|
||||
from bandsaunter.ranges import parse_range_list
|
||||
from bandsaunter.scanner import Scanner
|
||||
from bandsaunter.simulator import SimulatedDevice, default_transmitters
|
||||
|
||||
from morse_gen import morse_audio
|
||||
|
||||
FS = 16000
|
||||
|
||||
|
||||
class StubBook(CallsignBook):
|
||||
"""Answers every lookup from itself, so no test goes to the network."""
|
||||
|
||||
def __init__(self, tmp, **kw):
|
||||
self.asked: list[str] = []
|
||||
super().__init__(cache=Path(tmp) / "calls.json", **kw)
|
||||
|
||||
def _request(self, call):
|
||||
self.asked.append(call)
|
||||
return {"status": "VALID", "current": {"callsign": call},
|
||||
"name": "Newington Radio Club",
|
||||
"address": {"line2": "Newington, CT"},
|
||||
"location": {"latitude": "41.71", "longitude": "-72.72",
|
||||
"gridsquare": "FN31pr"}}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The scan
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _scanner(tmp_path, mhz: str, **over) -> Scanner:
|
||||
cfg = ScanConfig(ranges=parse_range_list(mhz),
|
||||
output_dir=str(tmp_path), transcribe=False,
|
||||
record_seconds=10, hang_seconds=1.5,
|
||||
max_runtime_seconds=over.pop("seconds", 45),
|
||||
**over)
|
||||
scanner = Scanner(cfg, device=SimulatedDevice(realtime=False).open())
|
||||
scanner.prepare()
|
||||
scanner.callsigns = StubBook(tmp_path)
|
||||
return scanner
|
||||
|
||||
|
||||
def test_the_book_and_the_map_exist_without_a_speech_recogniser(tmp_path):
|
||||
"""They used to be built inside the transcription branch.
|
||||
|
||||
Callsigns arrive in Morse and in packets as well as in speech, neither of
|
||||
which involves a recogniser, so a machine with none installed found none
|
||||
of them -- which is most of the machines this runs on.
|
||||
"""
|
||||
scanner = _scanner(tmp_path, "147.0M-147.1M")
|
||||
assert scanner.transcriber is None
|
||||
assert scanner.callsigns is not None
|
||||
assert scanner.kml is not None
|
||||
|
||||
|
||||
def test_a_repeater_identifying_in_morse_reaches_the_map(tmp_path):
|
||||
scanner = _scanner(tmp_path, "147.0M-147.1M", seconds=45)
|
||||
scanner.run()
|
||||
assert scanner.hits, "the ident was not recorded at all"
|
||||
assert any(h.morse_text for h in scanner.hits), \
|
||||
"recorded it and read nothing out of it"
|
||||
assert "K1AA" in scanner.heard
|
||||
assert "K1AA" in scanner.kml.contacts
|
||||
contact = scanner.kml.contacts["K1AA"]
|
||||
assert contact.name == "Newington Radio Club"
|
||||
assert contact.located
|
||||
|
||||
|
||||
def test_the_map_is_written_out(tmp_path):
|
||||
scanner = _scanner(tmp_path, "147.0M-147.1M", seconds=45)
|
||||
scanner.run()
|
||||
written = (tmp_path / scanner.cfg.kml_file).read_text()
|
||||
assert "K1AA" in written and "<Point>" in written
|
||||
|
||||
|
||||
def test_a_beacon_is_identified_from_the_words_that_survived(tmp_path):
|
||||
"""A continuous beacon is always caught partway through.
|
||||
|
||||
Every capture of one begins and ends in the middle of the message, so
|
||||
what can be said about it is whatever lies between two word gaps.
|
||||
"""
|
||||
scanner = _scanner(tmp_path, "144.05M-144.15M", seconds=30)
|
||||
scanner.run()
|
||||
assert "W1AW" in scanner.heard
|
||||
assert set(scanner.heard) == {"W1AW"}, \
|
||||
f"invented a station: {sorted(scanner.heard)}"
|
||||
|
||||
|
||||
def test_the_hit_keeps_both_the_text_and_the_part_it_can_be_identified_from(
|
||||
tmp_path):
|
||||
scanner = _scanner(tmp_path, "144.05M-144.15M", seconds=30)
|
||||
scanner.run()
|
||||
cw = [h for h in scanner.hits if h.morse_text]
|
||||
assert cw
|
||||
for hit in cw:
|
||||
assert hit.morse_complete in hit.morse_text or not hit.morse_complete
|
||||
|
||||
|
||||
def test_the_sidecar_carries_them(tmp_path):
|
||||
scanner = _scanner(tmp_path, "147.0M-147.1M", seconds=45)
|
||||
scanner.run()
|
||||
sidecars = [json.loads(p.read_text()) for p in tmp_path.glob("*.json")]
|
||||
hits = [doc.get("hit", doc) for doc in sidecars]
|
||||
assert any(h.get("morse_text") for h in hits)
|
||||
assert any(h.get("morse_complete") for h in hits)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Every capture is offered to the decoder, not only the ones that looked keyed
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_morse_under_a_label_that_is_not_cw_is_still_decoded(tmp_path):
|
||||
"""A burst of CW is a second or two of a capture the classifier named
|
||||
after whatever filled the rest of it, or after nothing at all."""
|
||||
seen = {}
|
||||
scanner = _scanner(tmp_path, "147.0M-147.1M", seconds=45)
|
||||
real = scanner._decode_cw
|
||||
|
||||
def watch(iq, demod):
|
||||
got = real(iq, demod)
|
||||
seen.setdefault("calls", 0)
|
||||
seen["calls"] += 1
|
||||
return got
|
||||
|
||||
scanner._decode_cw = watch
|
||||
scanner.run()
|
||||
assert seen.get("calls"), "nothing was offered to the CW decoder"
|
||||
|
||||
|
||||
def _on_the_air(mode: str, seconds: float = 3.0, freq: float = 147.06e6):
|
||||
"""A real signal, classified and demodulated the way the scanner does.
|
||||
|
||||
Not a stand-in feature object: what `assess` does with a Morse decode
|
||||
depends on measurements taken off the signal, and a hand-written set of
|
||||
them would only ever prove that the test agreed with itself.
|
||||
"""
|
||||
from bandsaunter.classify import classify
|
||||
from bandsaunter.demod import make_demodulator
|
||||
from bandsaunter.simulator import VirtualTransmitter
|
||||
|
||||
fs = 240_000
|
||||
voice = mode == "nfm"
|
||||
tx = VirtualTransmitter(freq, mode, 0.5, 12_500 if voice else 500,
|
||||
f"test {mode}", message="DE W1AW", wpm=20)
|
||||
iq = tx.generate(0.0, int(fs * seconds), fs)
|
||||
# A receiver always has some. Without it the key-up stretches of a CW
|
||||
# signal are exactly zero, which is not a thing any aerial produces.
|
||||
rng = np.random.default_rng(3)
|
||||
iq = iq + (0.004 * (rng.standard_normal(iq.size)
|
||||
+ 1j * rng.standard_normal(iq.size))).astype("complex64")
|
||||
cls = classify(iq, fs, freq_hz=freq)
|
||||
demod = make_demodulator("nfm" if voice else "cw", fs,
|
||||
12_500.0 if voice else 800.0, FS)
|
||||
return cls, demod.process(iq), demod.audio_rate
|
||||
|
||||
|
||||
def test_speech_is_not_relabelled_by_a_morse_decode():
|
||||
"""Both can be true at once, and the conversation is what was recorded.
|
||||
|
||||
Every capture is offered to the CW decoder now, not only the ones that
|
||||
looked keyed, so a decode can land on a capture full of speech. The text
|
||||
is recorded either way; the label follows the speech.
|
||||
"""
|
||||
cls, audio, rate = _on_the_air("nfm")
|
||||
spoken = assess(cls, audio, rate, morse=None)
|
||||
if spoken.category != "voice":
|
||||
pytest.skip("the speech detector did not hear the synthetic talker")
|
||||
|
||||
_, keyed, keyed_rate = _on_the_air("cw")
|
||||
morse = decode_morse(keyed, keyed_rate)
|
||||
assert morse.is_morse, "the fixture did not produce a Morse decode"
|
||||
assert assess(cls, audio, rate, morse=morse).category == "voice"
|
||||
|
||||
|
||||
def test_a_keyed_carrier_is_still_labelled_cw():
|
||||
"""The families that were always decoded keep their behaviour exactly."""
|
||||
cls, audio, rate = _on_the_air("cw")
|
||||
morse = decode_morse(audio, rate)
|
||||
assert morse.is_morse
|
||||
assert assess(cls, audio, rate, morse=morse).category == "cw"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reading it back
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _capture(directory: Path, meta: dict) -> Path:
|
||||
stem = "0147.060000MHz--2026-08-29_10_00_00-cw"
|
||||
with wave.open(str(directory / f"{stem}.wav"), "wb") as w:
|
||||
w.setnchannels(1)
|
||||
w.setsampwidth(2)
|
||||
w.setframerate(FS)
|
||||
w.writeframes(b"\0\0" * FS)
|
||||
(directory / f"{stem}.json").write_text(json.dumps({"hit": meta}))
|
||||
return directory / f"{stem}.wav"
|
||||
|
||||
|
||||
def _browser(directory) -> Browser:
|
||||
console = Console(width=100, height=30, force_terminal=True)
|
||||
return Browser(directory, console=console, player=Player([]),
|
||||
book=StubBook(directory))
|
||||
|
||||
|
||||
def frame(browser) -> str:
|
||||
with browser.console.capture() as cap:
|
||||
browser.console.print(browser.render())
|
||||
return cap.get()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def keyed(tmp_path):
|
||||
_capture(tmp_path, {"frequency": 147.06e6, "category": "cw",
|
||||
"classification": "CW / Morse at 20 WPM",
|
||||
"morse_text": "E DE K1AA",
|
||||
"morse_complete": "DE K1AA",
|
||||
"morse_wpm": 20.0, "confidence": 0.9})
|
||||
return tmp_path
|
||||
|
||||
|
||||
def test_the_morse_gets_the_top_of_the_screen(keyed):
|
||||
shown = frame(_browser(keyed))
|
||||
assert "Morse" in shown and "DE K1AA" in shown
|
||||
|
||||
|
||||
def test_the_callsign_is_listed_under_it(keyed):
|
||||
browser = _browser(keyed)
|
||||
browser.book.get_all(browser.current.callsigns)
|
||||
browser.book.wait(5.0)
|
||||
shown = frame(browser)
|
||||
assert "K1AA" in shown and "Newington Radio Club" in shown
|
||||
|
||||
|
||||
def test_a_cw_capture_can_be_searched_for_by_what_it_keyed(keyed):
|
||||
browser = _browser(keyed)
|
||||
browser.query = "k1aa"
|
||||
browser.apply()
|
||||
assert len(browser.view) == 1
|
||||
|
||||
|
||||
def test_the_reader_opens_on_it(keyed):
|
||||
browser = _browser(keyed)
|
||||
assert browser.handle("t")
|
||||
assert browser.reading
|
||||
assert "DE K1AA" in frame(browser)
|
||||
|
||||
|
||||
def test_only_the_part_it_can_be_identified_from_is_searched(tmp_path):
|
||||
"""The sidecar keeps both, and the callsign comes out of the safe one."""
|
||||
_capture(tmp_path, {"frequency": 147.06e6, "category": "cw",
|
||||
"morse_text": "K1A", "morse_complete": "",
|
||||
"classification": "CW / Morse at 20 WPM"})
|
||||
browser = _browser(tmp_path)
|
||||
assert browser.current.morse == "K1A"
|
||||
assert browser.current.callsigns == []
|
||||
|
||||
|
||||
def test_an_older_recording_falls_back_to_the_whole_text(tmp_path):
|
||||
"""Sidecars written before this distinction existed carry only the text."""
|
||||
_capture(tmp_path, {"frequency": 147.06e6, "category": "cw",
|
||||
"morse_text": "VVV DE W1AW",
|
||||
"classification": "CW / Morse at 20 WPM"})
|
||||
assert _browser(tmp_path).current.callsigns == ["W1AW"]
|
||||
|
||||
|
||||
def test_a_hex_dump_is_not_searched_for_callsigns(tmp_path):
|
||||
"""Enough two-character groups in a row join into something shaped like
|
||||
a callsign that nobody transmitted."""
|
||||
_capture(tmp_path, {"frequency": 147.06e6, "category": "digital",
|
||||
"data_messages": ["4A 3F 1B 22 9C 04"],
|
||||
"classification": "OOK data"})
|
||||
assert _browser(tmp_path).current.callsigns == []
|
||||
|
||||
|
||||
def test_a_packet_header_is(tmp_path):
|
||||
_capture(tmp_path, {"frequency": 144.39e6, "category": "digital",
|
||||
"data_messages": ["W1AW-1>APRS,TCPIP*:=4123.45N/"
|
||||
"07234.56W-"],
|
||||
"classification": "AX.25 / APRS"})
|
||||
assert _browser(tmp_path).current.callsigns == ["W1AW"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The demo band is invented; the callsigns in it are not
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_the_simulator_identifies_itself_the_way_a_repeater_does():
|
||||
idents = [t for t in default_transmitters()
|
||||
if t.mode == "cw" and t.period_seconds]
|
||||
assert idents, "nothing in the demo band sends a short CW ident"
|
||||
assert idents[0].on_seconds < 8.0
|
||||
|
||||
|
||||
def test_a_simulated_run_neither_looks_up_nor_maps_anything(monkeypatch,
|
||||
tmp_path):
|
||||
"""W1AW is the ARRL's own station, and the demo band is made up.
|
||||
|
||||
Looking it up would put a licence nobody heard on the same map a real
|
||||
scan writes.
|
||||
"""
|
||||
from bandsaunter import cli
|
||||
seen = {}
|
||||
|
||||
class Stop(Exception):
|
||||
pass
|
||||
|
||||
def fake_scanner(cfg, **kw):
|
||||
seen["cfg"] = cfg
|
||||
raise Stop
|
||||
|
||||
monkeypatch.setattr(cli, "Scanner", fake_scanner)
|
||||
monkeypatch.setattr(cli, "console", Console(file=open("/dev/null", "w")))
|
||||
with pytest.raises(Stop):
|
||||
cli.main(["scan", "--simulate", "--no-config", "-r", "144M-148M",
|
||||
"-o", str(tmp_path)])
|
||||
assert seen["cfg"].callsign_lookup is False
|
||||
assert seen["cfg"].kml_file == ""
|
||||
|
|
@ -48,3 +48,152 @@ def test_silence_is_rejected():
|
|||
def test_encode_round_trip():
|
||||
assert encode_morse("SOS") == "... --- ..."
|
||||
assert encode_morse("A B") == ".- / -..."
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Short bursts
|
||||
#
|
||||
# Most of the CW on the air is not a conversation. It is a repeater, a
|
||||
# beacon or an unattended transmitter saying who it is and stopping, which is
|
||||
# four to six characters and over in a second or two. Those used to be read
|
||||
# correctly and then thrown away by gates written for a paragraph of text.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
SHORT = ["W1AW", "K1AA", "KU0W", "N0CALL", "VVV", "DE", "AR", "K", "73", "QRZ"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("msg", SHORT)
|
||||
@pytest.mark.parametrize("wpm", [12, 20, 30, 45])
|
||||
def test_a_short_burst_is_read_and_believed(msg, wpm):
|
||||
r = decode_morse(morse_audio(msg, wpm, FS, 18), FS)
|
||||
assert r.text.strip() == msg
|
||||
assert r.is_morse, f"read {msg} correctly and then refused it: {r.notes}"
|
||||
|
||||
|
||||
def test_a_callsign_on_its_own_is_under_two_seconds_at_thirty_words():
|
||||
"""The length this is all about, stated so a regression is obvious."""
|
||||
from morse_gen import morse_keying
|
||||
keyed = np.flatnonzero(morse_keying("W1AW", 30, FS) > 0)
|
||||
assert (keyed[-1] - keyed[0]) / FS < 2.0
|
||||
assert decode_morse(morse_audio("W1AW", 30, FS, 18), FS).is_morse
|
||||
|
||||
|
||||
@pytest.mark.parametrize("msg", ["E", "T"])
|
||||
def test_one_keyed_element_is_not_an_identification(msg):
|
||||
"""A single pulse is an E or a T whether a person sent it or not.
|
||||
|
||||
This is where "no matter how short" stops, and it stops here because
|
||||
below it there is nothing left to be right about.
|
||||
"""
|
||||
assert not decode_morse(morse_audio(msg, 20, FS, 20), FS).is_morse
|
||||
|
||||
|
||||
def test_a_repeated_character_with_structure_is_still_text():
|
||||
"""VVV is the oldest thing anyone sends, and it is not a pulse train.
|
||||
|
||||
A uniform train of identical pulses decodes to EEEE or TTTT, which is
|
||||
what the check against one repeated character is for -- but V has dots
|
||||
and a dash of its own, which no train of identical pulses can produce.
|
||||
"""
|
||||
r = decode_morse(morse_audio("VVV", 20, FS, 20), FS)
|
||||
assert r.text.strip() == "VVV" and r.is_morse
|
||||
|
||||
|
||||
def test_a_uniform_pulse_train_is_still_refused():
|
||||
dot = 1.2 / 20.0
|
||||
env, fs = [], FS
|
||||
for _ in range(14):
|
||||
env += [1.0] * int(dot * fs) + [0.0] * int(3 * dot * fs)
|
||||
env = np.array(env)
|
||||
t = np.arange(env.size) / fs
|
||||
audio = env * np.sin(2 * np.pi * 700 * t)
|
||||
assert not decode_morse(audio, fs).is_morse
|
||||
|
||||
|
||||
# -- what the capture window cut off ----------------------------------------
|
||||
|
||||
def _clipped(msg, wpm, head, tail):
|
||||
audio = morse_audio(msg, wpm, FS, 20)
|
||||
return audio[int(head * FS):audio.size - int(tail * FS)]
|
||||
|
||||
|
||||
def test_a_character_sliced_by_the_window_is_dropped_not_guessed():
|
||||
"""A K with its first dash missing is an A, not a worse K."""
|
||||
r = decode_morse(_clipped("K1AA", 20, 0.55, 0.55), FS)
|
||||
assert "A1AA" not in r.text, "half a character was reported as a whole one"
|
||||
assert any("cut off" in note for note in r.notes)
|
||||
|
||||
|
||||
def test_what_is_left_of_a_cut_word_is_not_reported_as_a_whole_one():
|
||||
"""K1AA caught halfway through reads as K1A, which is somebody else."""
|
||||
r = decode_morse(_clipped("K1AA", 20, 0.05, 0.9), FS)
|
||||
assert r.tail_cut
|
||||
assert "K1A" not in r.complete_text.split()
|
||||
|
||||
|
||||
def test_the_words_that_survived_are_still_reported():
|
||||
r = decode_morse(_clipped("VVV DE W1AW", 20, 0.6, 0.1), FS)
|
||||
assert r.head_cut and not r.tail_cut
|
||||
assert "W1AW" in r.complete_text.split()
|
||||
|
||||
|
||||
def test_a_complete_transmission_keeps_every_word():
|
||||
r = decode_morse(morse_audio("VVV DE W1AW", 20, FS, 20), FS)
|
||||
assert not r.head_cut and not r.tail_cut
|
||||
assert r.complete_text == r.text == "VVV DE W1AW"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("head,tail", [(0.05, 0.4), (0.4, 0.05), (0.7, 0.7),
|
||||
(1.1, 0.3), (0.3, 1.1)])
|
||||
def test_a_truncated_capture_never_invents_a_callsign(head, tail):
|
||||
"""The point of all of the above: this text is looked at for callsigns.
|
||||
|
||||
A station heard through half its ident is better reported as half an
|
||||
ident than as a different station, because the different station gets
|
||||
looked up and pinned to a map.
|
||||
"""
|
||||
from bandsaunter.callsign import find_callsigns
|
||||
r = decode_morse(_clipped("VVV DE W1AW/B FN31", 20, head, tail), FS)
|
||||
if not r.is_morse:
|
||||
return
|
||||
found = find_callsigns(r.complete_text, join_words=False)
|
||||
assert set(found) <= {"W1AW"}, f"invented {found} from {r.text!r}"
|
||||
|
||||
|
||||
# -- and nothing that was not sent ------------------------------------------
|
||||
|
||||
@pytest.mark.parametrize("seed", range(10))
|
||||
def test_a_blip_of_noise_is_not_a_short_transmission(seed):
|
||||
"""The gates that let a two-character ident in must not let this in.
|
||||
|
||||
With three or four elements the dot length is fitted to those very
|
||||
elements, so they land on the grid whatever produced them: a third of a
|
||||
second of noise decodes as a perfectly timed V. What separates them is
|
||||
that keying is a tone and noise is not.
|
||||
"""
|
||||
rng = np.random.default_rng(seed)
|
||||
for size in (1200, int(FS * 0.3), FS * 2):
|
||||
assert not decode_morse(rng.standard_normal(size), FS).is_morse
|
||||
|
||||
|
||||
@pytest.mark.parametrize("seed", range(6))
|
||||
def test_a_squelch_click_is_not_a_transmission(seed):
|
||||
rng = np.random.default_rng(seed)
|
||||
t = np.arange(int(FS * 0.5)) / FS
|
||||
for edges in ([(0.20, 0.25)], [(0.10, 0.14), (0.30, 0.34)]):
|
||||
env = np.zeros_like(t)
|
||||
for a, b in edges:
|
||||
env[int(a * FS):int(b * FS)] = 1.0
|
||||
audio = env * np.sin(2 * np.pi * 700 * t) + 0.02 * rng.standard_normal(t.size)
|
||||
assert not decode_morse(audio, FS).is_morse
|
||||
|
||||
|
||||
def test_a_tone_that_never_keys_is_not_morse():
|
||||
t = np.arange(FS * 2) / FS
|
||||
assert not decode_morse(np.sin(2 * np.pi * 700 * t), FS).is_morse
|
||||
|
||||
|
||||
@pytest.mark.parametrize("seed", range(4))
|
||||
def test_speech_is_not_morse(seed):
|
||||
from speech import synth_speech
|
||||
assert not decode_morse(synth_speech(2.5, FS, seed=seed), FS).is_morse
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue