Detect callsigns in transcripts, and say whose they are

Under the transcript, headed DETECTED CALLSIGNS:, every callsign heard in
it with the name and location on its licence.

Finding them is not one regular expression over the text as written.  A
speech recogniser is poor at callsigns -- they are not words, they are
said one character at a time -- so it breaks them wherever the speaker
paused and writes the phonetic alphabet down verbatim.  The recording that
prompted this has "Alright, KU 0W" in it, with a space; spelled out it
would have been "kilo uniform zero whiskey".  All three forms read back to
KU0W.

Not inventing them matters more.  A run of words is accepted only when
none of its parts is an ordinary English word: "or 3. Can you open 4" and
"CC1 boy", both from real transcripts here, fit the shape once the
punctuation is gone and are not callsigns.  A single token said in one
breath is still trusted, because W1BOY is a perfectly good callsign, and a
lone "a" or "i" cannot start a join or "a B4U player" becomes AB4U.
Across the 126 transcripts in the recordings directory that turns three
candidates into the one that was actually said.

Lookups use the FCC's own licence data at callook.info -- no account, no
key, the callsign the only thing sent.  They never delay the display: the
entry reads "looking up" and fills itself in, and results are cached under
~/.cache so a net recorded night after night is looked up once.
--no-lookup contacts nothing and still describes a callsign from its own
structure, the ITU prefix giving the country and the digit the US
district, which is also all there is to say for callsigns outside the US.
--callsigns prints everyone who identified themselves and where they were
heard.

Also asked: are transcripts appended to, or overwritten, when another
transmission arrives on the same frequency?  Neither could be shown from
reading the code alone, so there are now three tests that run real scans
and look at the files.  By default each transmission has a transcript of
its own -- the timestamp is in the name, so two overs cannot land on one
file.  With --combine there is one recording per frequency and therefore
one transcript, opened for append with the time of each over; a second
scan into the same directory adds to it rather than starting it over,
which is the case the last of the three tests covers.

The browser and callsign tests refuse to reach the network at all.  One
test did, quietly, and passed -- visible only because the assertion it
failed printed a real operator's address.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016PsWPTweCT6pwxKngvVxcg
This commit is contained in:
The Dust Council 2026-08-22 15:41:02 -07:00
parent cc317914e1
commit 739a2faaf4
11 changed files with 1502 additions and 16 deletions

View file

@ -19,6 +19,7 @@ from rich.console import Console
from bandsaunter.browse import (Browser, Player, PLAYERS, Keyboard, main,
scan_directory)
from bandsaunter.callsign import CallsignBook
# -- fixtures ----------------------------------------------------------------
@ -51,6 +52,7 @@ def make_capture(directory: Path, mhz: float, when: str, mode: str,
@pytest.fixture
def library(tmp_path):
"""A small recordings directory covering the cases that render differently."""
# The transcript names a callsign, as a real one from a net would.
make_capture(tmp_path, 146.52, "2026-08-22_10_00_00", "nfm", 4.0,
transcript="Net control, this is W1AW, standing by.",
meta={"category": "voice", "snr_db": 21.5,
@ -68,6 +70,20 @@ def library(tmp_path):
return tmp_path
@pytest.fixture(autouse=True)
def no_network(monkeypatch):
"""No test in this file 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 stub that is forgotten
should fail loudly rather than work.
"""
def refuse(self, call):
raise AssertionError(f"a test tried to look up {call} for real")
monkeypatch.setattr(CallsignBook, "_request", refuse)
def browser(directory, width=100, height=30, player=None) -> Browser:
console = Console(width=width, height=height, force_terminal=True)
return Browser(directory, console=console,
@ -655,3 +671,172 @@ def test_the_output_directory_is_found_without_being_told(monkeypatch,
monkeypatch.setenv("BANDSAUNTER_OUTPUT", str(tmp_path))
from bandsaunter.browse import default_directory
assert default_directory() == tmp_path
# -- detected callsigns ------------------------------------------------------
class StubBook(CallsignBook):
"""Answers lookups from a dict, so no test touches the network."""
def __init__(self, answers=None, tmp=None, **kw):
self.answers = answers or {}
self.requested = []
super().__init__(cache=(tmp or Path("/nonexistent")) / "c.json", **kw)
def _request(self, call):
self.requested.append(call)
if call not in self.answers:
raise OSError("offline")
return self.answers[call]
KU0W = {
"status": "VALID", "type": "PERSON", "name": "ROD R GOWDY",
"current": {"callsign": "KU0W", "operClass": "EXTRA"},
"previous": {"callsign": ""}, "trustee": {"callsign": ""},
"address": {"line2": "TUCSON, AZ 85742"},
"location": {"gridsquare": "DM42lj"},
"otherInfo": {"expiryDate": "08/09/2034"},
}
@pytest.fixture
def net(tmp_path):
"""A directory whose transcript names a callsign, and a stubbed lookup."""
make_capture(tmp_path, 146.52, "2026-08-22_10_00_00", "nfm", 4.0,
transcript="Net control, this is KU 0W, standing by.",
meta={"category": "voice", "classification": "NFM voice"})
return tmp_path
def net_browser(directory, tmp, answers=None, **kw):
b = browser(directory, **kw)
b.book = StubBook(answers if answers is not None else {"KU0W": KU0W},
tmp=tmp)
return b
def test_callsigns_are_listed_under_the_transcript(net, tmp_path):
b = net_browser(net, tmp_path)
b.book.get("KU0W")
b.book.wait(5)
out = frame(b)
head, _, rest = out.partition("recordings in")
assert "DETECTED CALLSIGNS:" in head
assert "KU0W" in head
assert "Rod R Gowdy" in head and "Tucson, AZ" in head
# Under the words, not above them.
assert head.index("standing by") < head.index("DETECTED CALLSIGNS:")
def test_a_callsign_broken_by_the_recogniser_is_still_found(net, tmp_path):
"""The transcript says "KU 0W"; the licence is under KU0W."""
cap = scan_directory(net)[0]
assert cap.callsigns == ["KU0W"]
def test_the_lookup_is_shown_as_pending_before_it_lands(net, tmp_path):
class Slow(StubBook):
def _request(self, call):
time.sleep(1.0)
return super()._request(call)
b = browser(net)
b.book = Slow({"KU0W": KU0W}, tmp=tmp_path)
assert "looking up" in frame(b)
def test_a_transcript_with_no_callsign_has_no_block(tmp_path):
make_capture(tmp_path, 146.52, "2026-08-22_10_00_00", "nfm",
transcript="the meeting is at seven on the fourth Saturday",
meta={"category": "voice"})
assert "DETECTED CALLSIGNS" not in frame(browser(tmp_path))
def test_a_callsign_that_cannot_be_looked_up_still_appears(net, tmp_path):
"""Offline, the prefix still says which country and district it is."""
b = net_browser(net, tmp_path, answers={})
b.book.get("KU0W")
b.book.wait(5)
out = frame(b)
assert "KU0W" in out and "United States" in out
def test_the_callsigns_survive_a_transcript_too_long_for_the_panel(tmp_path):
"""Whatever else is squeezed, the callsigns stay: they are the part of the
panel that cannot be recovered by listening to the recording."""
make_capture(tmp_path, 146.52, "2026-08-22_10_00_00", "nfm",
transcript="KU0W " + " ".join(f"word{i}" for i in range(400)),
meta={"category": "voice"})
b = net_browser(tmp_path, tmp_path, height=22)
b.book.get("KU0W")
b.book.wait(5)
out = frame(b)
assert "DETECTED CALLSIGNS:" in out and "Rod R Gowdy" in out
assert "more line(s)" in out
def test_the_reader_shows_them_at_the_end_of_the_words(tmp_path):
make_capture(tmp_path, 146.52, "2026-08-22_10_00_00", "nfm",
transcript="KU0W " + " ".join(f"word{i}" for i in range(400)),
meta={"category": "voice"})
b = net_browser(tmp_path, tmp_path, height=22)
b.book.get("KU0W")
b.book.wait(5)
b.handle("t")
assert "DETECTED CALLSIGNS" not in frame(b), "shown beside the middle"
b.handle("end")
assert "DETECTED CALLSIGNS:" in frame(b)
def test_the_frame_still_fits_with_callsigns(net, tmp_path):
for height in (16, 20, 24, 40):
b = net_browser(net, tmp_path, height=height)
b.book.get("KU0W")
b.book.wait(5)
lines = frame(b).rstrip("\n").split("\n")
assert len(lines) <= height, f"{len(lines)} lines in {height}"
def test_callsigns_are_found_once_per_recording(net):
cap = scan_directory(net)[0]
assert cap._calls is None
first = cap.callsigns
assert cap._calls is not None
assert cap.callsigns is first
# -- the callsign command line -----------------------------------------------
def test_callsigns_flag_reports_where_each_was_heard(net, capsys, monkeypatch):
monkeypatch.setattr("bandsaunter.browse.CallsignBook",
lambda **kw: StubBook({"KU0W": KU0W}, tmp=net, **kw))
assert main(["--callsigns", str(net)]) == 0
out = capsys.readouterr().out
assert "KU0W" in out and "Rod R Gowdy" in out
assert "heard on" in out and "146.52 MHz" in out
def test_callsigns_flag_says_so_when_there_are_none(tmp_path, capsys):
make_capture(tmp_path, 856.5625, "2026-08-22_11_00_00", "fsk", 2.0,
meta={"category": "trunk"})
assert main(["--callsigns", str(tmp_path)]) == 1
assert "no callsigns" in capsys.readouterr().out
def test_no_lookup_contacts_nothing(net, capsys, monkeypatch):
"""The flag has to mean it: nothing leaves the machine."""
made = []
class Watching(StubBook):
def _request(self, call):
made.append(call)
return super()._request(call)
monkeypatch.setattr("bandsaunter.browse.CallsignBook",
lambda **kw: Watching({"KU0W": KU0W}, tmp=net, **kw))
assert main(["--callsigns", "--no-lookup", str(net)]) == 0
out = capsys.readouterr().out
assert made == [], "a request was made with --no-lookup"
assert "KU0W" in out
assert "United States" in out, "the prefix should still be described"

358
tests/test_callsign.py Normal file
View file

@ -0,0 +1,358 @@
"""Finding callsigns in a transcript, and saying who they belong to.
The hard part is not the regular expression, it is everything the speech
recogniser does to a callsign on the way: it breaks it wherever the speaker
paused, and it writes the phonetic alphabet down as words. So most of these
are about text that came out of a real recogniser rather than text anyone
would type.
Nothing here touches the network. The lookup is tested against a stub, and
one test asserts that no request is made when it is switched off.
"""
import json
import time
import pytest
from bandsaunter.callsign import (Callsign, CallsignBook, HEADING,
NOT_CALLSIGNS, SHAPE, describe_prefix,
find_callsigns, person_case, report,
split_postcode)
@pytest.fixture(autouse=True)
def no_network(monkeypatch):
"""Nothing here may contact the licence database for real.
Every lookup test uses a stub; this makes forgetting one fail loudly
rather than quietly pass with somebody's real address in the output.
"""
def refuse(self, call):
raise AssertionError(f"a test tried to look up {call} for real")
monkeypatch.setattr(CallsignBook, "_request", refuse)
# -- finding them ------------------------------------------------------------
@pytest.mark.parametrize("text,want", [
("This is W1AW calling CQ", ["W1AW"]),
("K7RA this is N7XYZ over", ["K7RA", "N7XYZ"]),
("VE3ABC and G0ABC and 2E0XYZ", ["VE3ABC", "G0ABC", "2E0XYZ"]),
("net control, W1AW, W1AW again", ["W1AW"]),
])
def test_a_callsign_written_properly_is_found(text, want):
assert find_callsigns(text) == want
@pytest.mark.parametrize("text,want", [
("Alright, KU 0W. And the HF net will be a couple minutes.", ["KU0W"]),
("N7 XYZ this is K7 RA", ["N7XYZ", "K7RA"]),
("W 1 A W standing by", ["W1AW"]),
])
def test_a_callsign_broken_across_words_is_still_one_callsign(text, want):
"""A recogniser breaks it wherever the speaker paused. "KU 0W" is what
came out of a real recording of somebody saying KU0W."""
assert find_callsigns(text) == want
@pytest.mark.parametrize("text,want", [
("kilo uniform zero whiskey, are you there", ["KU0W"]),
("whiskey one alpha whiskey this is kilo seven romeo alpha",
["W1AW", "K7RA"]),
("november seven x-ray yankee zulu", ["N7XYZ"]),
("kilo uniform zero whisky", ["KU0W"]), # both spellings
("niner", []),
])
def test_the_phonetic_alphabet_is_read_back(text, want):
"""Spelled out, a callsign arrives as one token per character."""
assert find_callsigns(text) == want
@pytest.mark.parametrize("text", [
"7 on alleviate or 3. Can you open 4 and close the rest.",
"CC1 boy",
"I bought 3 of them for $5 and a B4U model MP3 player",
"the 4th Saturday at 1.30pm on 7.242 megahertz",
"Check out communication of group activities and training.",
"we need 2 of them and 4 spare",
"it was on channel 3 for a while",
])
def test_ordinary_speech_produces_no_callsigns(text):
"""Every one of these came out of a real transcript or is one word away
from something that did. A browser that invents callsigns is worse than
one that finds none."""
assert find_callsigns(text) == []
def test_a_join_is_refused_when_a_part_is_an_english_word():
""""or 3. Can you" fits the shape once the punctuation is gone. Nobody
spells a callsign with English words."""
assert find_callsigns("or 3 can") == []
assert find_callsigns("CC1 boy") == []
# ... but a single token said in one breath is trusted.
assert find_callsigns("W1BOY is on frequency") == ["W1BOY"]
def test_a_lone_article_is_not_a_prefix():
assert find_callsigns("a B4U player") == []
assert find_callsigns("alpha bravo four uniform") == ["AB4U"]
def test_the_same_callsign_is_reported_once():
assert find_callsigns("W1AW W1AW W1AW") == ["W1AW"]
def test_they_come_back_in_the_order_they_were_said():
assert find_callsigns("N7XYZ this is W1AW") == ["N7XYZ", "W1AW"]
def test_the_count_is_capped():
text = " ".join(f"W{i}AB" for i in range(0, 9)) + " K7RA N7XYZ VE3ABC"
assert len(find_callsigns(text, max_found=4)) == 4
def test_empty_text_is_not_an_error():
assert find_callsigns("") == []
assert find_callsigns(" \n ") == []
def test_every_excluded_word_could_actually_have_matched():
"""A list of words that could not match anyway would only suggest the
filter was doing more work than it is."""
for word in NOT_CALLSIGNS:
assert SHAPE.match(word), f"{word} never matched in the first place"
# -- what the callsign says about itself -------------------------------------
@pytest.mark.parametrize("call,country", [
("W1AW", "United States"), ("KU0W", "United States"),
("N7XYZ", "United States"), ("AA1AB", "United States"),
("VE3ABC", "Canada"), ("XE1ABC", "Mexico"),
("G0ABC", "United Kingdom"), ("2E0XYZ", "United Kingdom"),
("JA1ABC", "Japan"), ("VK2DEF", "Australia"),
("IK4ABC", "Italy"), ("DL1ABC", "Germany"),
("4X4ABC", "Israel"), ("ZZ9ZZZ", ""),
])
def test_the_prefix_names_the_country_without_a_database(call, country):
"""This works offline and for callsigns no database holds."""
assert describe_prefix(call)[0] == country
def test_a_one_letter_prefix_does_not_claim_everything():
""""I" is Italy, but only when what follows is the rest of a prefix."""
assert describe_prefix("IK4ABC")[0] == "Italy"
assert describe_prefix("KU0W")[0] == "United States" # not Italy-shaped
def test_the_digit_gives_the_us_district():
assert "New England" in describe_prefix("W1AW")[1]
assert "California" in describe_prefix("K6ABC")[1]
assert describe_prefix("VE3ABC")[1] == "", "districts are a US idea"
# -- tidying the licence record ----------------------------------------------
@pytest.mark.parametrize("raw,want", [
("ROD R GOWDY", "Rod R Gowdy"),
("PAUL PAKES COOK, III.", "Paul Pakes Cook, III."),
("ARRL HQ OPERATORS CLUB", "ARRL HQ Operators Club"),
("JOHN SMITH JR", "John Smith JR"),
("de Vries, Anna", "de Vries, Anna"), # already mixed: left alone
])
def test_licence_names_are_made_readable_without_being_corrupted(raw, want):
assert person_case(raw) == want
@pytest.mark.parametrize("raw,town,code", [
("TUCSON, AZ 85742", "Tucson, AZ", "85742"),
("SEATTLE, WA 98105-3505", "Seattle, WA", "98105-3505"),
("NEWINGTON, CT 06111", "Newington, CT", "06111"),
("SOMEWHERE ABROAD", "Somewhere Abroad", ""),
])
def test_the_postcode_is_separated_from_the_place(raw, town, code):
"""The town and state say where somebody is; the postcode is detail."""
assert split_postcode(raw) == (town, code)
# -- looking them up ---------------------------------------------------------
VALID = {
"status": "VALID", "type": "PERSON", "name": "ROD R GOWDY",
"current": {"callsign": "KU0W", "operClass": "EXTRA"},
"previous": {"callsign": "KK7QPA"},
"trustee": {"callsign": ""},
"address": {"line1": "5455 W OASIS RD", "line2": "TUCSON, AZ 85742"},
"location": {"gridsquare": "DM42lj"},
"otherInfo": {"expiryDate": "08/09/2034"},
}
class StubBook(CallsignBook):
"""A book whose lookups are answered from a dict, not the network."""
def __init__(self, answers, **kw):
self.answers = answers
self.requested = []
super().__init__(**kw)
def _request(self, call):
self.requested.append(call)
if call not in self.answers:
raise OSError("no route to host")
return self.answers[call]
def book(tmp_path, answers=None, **kw):
return StubBook(answers if answers is not None else {"KU0W": VALID},
cache=tmp_path / "cache.json", **kw)
def test_a_lookup_fills_in_the_name_and_the_place(tmp_path):
b = book(tmp_path)
b.get("KU0W")
b.wait(5)
entry = b.get("KU0W")
assert entry.known
assert entry.name == "Rod R Gowdy"
assert entry.location == "Tucson, AZ"
assert entry.grid == "DM42lj"
assert entry.oper_class == "EXTRA"
assert entry.previous == "KK7QPA"
def test_rendering_never_waits_for_the_network(tmp_path):
"""A lookup returns at once with what is known, and fills itself in.
The stub is deliberately slow: a fast one would finish before the
assertion and the test would pass whether or not the call blocked.
"""
class Slow(StubBook):
def _request(self, call):
time.sleep(1.0)
return super()._request(call)
b = Slow({"KU0W": VALID}, cache=tmp_path / "cache.json")
started = time.time()
entry = b.get("KU0W")
assert time.time() - started < 0.3, "the lookup blocked the caller"
assert entry.status == "pending"
assert entry.summary() == "looking up…"
b.wait(10)
assert b.get("KU0W").known
def test_an_unknown_callsign_says_what_the_prefix_says(tmp_path):
"""Not in the database is not nothing: the prefix is still information."""
b = book(tmp_path, {"G0ABC": {"status": "INVALID"}})
b.get("G0ABC")
b.wait(5)
summary = b.get("G0ABC").summary()
assert "unlisted" in summary and "United Kingdom" in summary
def test_a_lookup_that_fails_is_not_an_error(tmp_path):
"""Offline, blocked or rate-limited, the transcript still has to show."""
b = book(tmp_path, {})
b.get("W1AW")
b.wait(5)
entry = b.get("W1AW")
assert entry.status == "offline"
assert "United States" in entry.summary()
def test_nothing_is_requested_when_lookup_is_switched_off(tmp_path):
b = book(tmp_path, online=False)
entry = b.get("KU0W")
b.wait(2)
assert b.requested == [], "a request was made with lookup off"
assert entry.status == "offline"
assert "United States" in entry.summary()
def test_a_callsign_is_looked_up_once(tmp_path):
b = book(tmp_path)
for _ in range(5):
b.get("KU0W")
b.wait(5)
assert b.requested == ["KU0W"]
def test_results_are_cached_between_runs(tmp_path):
"""The same net, logged night after night, is looked up once."""
first = book(tmp_path)
first.get("KU0W")
first.wait(5)
first.save()
assert (tmp_path / "cache.json").exists()
second = book(tmp_path)
entry = second.get("KU0W")
assert entry.known, "the cache was not read"
assert second.requested == [], "a cached callsign was looked up again"
def test_a_stale_cache_entry_is_looked_up_again(tmp_path):
first = book(tmp_path)
first.get("KU0W")
first.wait(5)
first.save()
body = json.loads((tmp_path / "cache.json").read_text())
body["KU0W"]["fetched_at"] = time.time() - 400 * 86_400
(tmp_path / "cache.json").write_text(json.dumps(body))
second = book(tmp_path)
second.get("KU0W")
second.wait(5)
assert second.requested == ["KU0W"]
def test_a_cache_from_another_version_is_ignored_not_fatal(tmp_path):
(tmp_path / "cache.json").write_text(
json.dumps({"KU0W": {"call": "KU0W", "somethingelse": 1}}))
b = book(tmp_path)
b.get("KU0W")
b.wait(5)
assert b.requested == ["KU0W"], "an unusable cache entry was trusted"
assert b.get("KU0W").known
def test_an_unreadable_cache_is_ignored_not_fatal(tmp_path):
(tmp_path / "cache.json").write_text("{not json")
b = book(tmp_path)
b.get("KU0W")
b.wait(5)
assert b.get("KU0W").known
def test_only_resolved_entries_are_cached(tmp_path):
"""Caching a failure would make one flaky lookup permanent."""
b = book(tmp_path, {})
b.get("W1AW")
b.wait(5)
b.save()
body = json.loads((tmp_path / "cache.json").read_text()) \
if (tmp_path / "cache.json").exists() else {}
assert "W1AW" not in body
# -- the block that goes under the transcript --------------------------------
def test_the_report_is_headed_the_way_it_was_asked_for():
entry = Callsign(call="W1AW", name="ARRL", location="Newington, CT",
status="found")
lines = report([entry])
assert lines[0] == HEADING == "DETECTED CALLSIGNS:"
assert "W1AW" in lines[1] and "Newington" in lines[1]
def test_nothing_found_means_no_block_at_all():
assert report([]) == []
def test_the_report_carries_the_extra_detail():
entry = Callsign(call="KU0W", name="Rod R Gowdy", location="Tucson, AZ",
oper_class="EXTRA", grid="DM42lj", status="found")
line = report([entry], width=0)[1]
assert "Extra" in line and "DM42lj" in line

View file

@ -5,6 +5,7 @@ from datetime import datetime
from pathlib import Path
import numpy as np
import re
import pytest
from bandsaunter import transcribe as tr
@ -424,3 +425,69 @@ def test_a_missing_vendor_directory_is_not_added(tmp_path, monkeypatch):
monkeypatch.setattr(tr, "VENDOR_DIR", tmp_path / "absent")
tr._add_vendor_path()
assert str(tmp_path / "absent") not in sys.path
# ---------------------------------------------------------------------------
# Two transmissions on one frequency
# ---------------------------------------------------------------------------
def test_each_transmission_gets_a_transcript_of_its_own(tmp_path, fake_engine,
monkeypatch):
"""The default is one file per transmission, named after it. Nothing is
overwritten because nothing is shared: the timestamp is in the name, so
two overs on one frequency cannot land on one file."""
monkeypatch.setattr("bandsaunter.scanner.available_engine", lambda: "fake")
scanner, hits = _scan(tmp_path, [V(146_520_000, "nfm", 0.4, 12_500, "v")],
record_seconds=2.0, max_cycles=3,
revisit_seconds=0.05)
assert len(hits) >= 2, "only one transmission was captured"
texts = sorted(tmp_path.glob("*_transcription.txt"))
assert len(texts) == len(hits), [p.name for p in texts]
for path in texts:
assert "transcribed text" in path.read_text()
# One transmission, one line. More than one would mean two captures
# had collided on a single name.
assert len(path.read_text().strip().split("\n")) == 1, path.name
def test_combining_appends_every_over_to_one_file(tmp_path, fake_engine,
monkeypatch):
"""With --combine there is one recording per frequency, so there is one
transcript per frequency, and each over is added to the end of it with the
time it was heard."""
monkeypatch.setattr("bandsaunter.scanner.available_engine", lambda: "fake")
scanner, hits = _scan(tmp_path, [V(146_520_000, "nfm", 0.4, 12_500, "v")],
combine_by_frequency=True,
announce_timestamps=False, record_seconds=2.0,
max_cycles=3, revisit_seconds=0.05)
assert len(hits) >= 2
texts = list(tmp_path.glob("*_transcription.txt"))
assert len(texts) == 1, [p.name for p in texts]
lines = [ln for ln in texts[0].read_text().strip().split("\n") if ln]
assert len(lines) == len(hits)
for line in lines:
assert re.match(r"^\[\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\] ", line), line
def test_a_later_run_never_truncates_an_earlier_transcript(tmp_path,
fake_engine,
monkeypatch):
"""The question this answers: can a later transmission on the same
frequency wipe out an earlier one's words? The combined file is opened
for append, and it is the only transcript two captures ever share, so an
unattended receiver adds to it night after night rather than starting it
over."""
monkeypatch.setattr("bandsaunter.scanner.available_engine", lambda: "fake")
args = dict(combine_by_frequency=True, announce_timestamps=False,
record_seconds=2.0, max_cycles=2, revisit_seconds=0.05)
tx = [V(146_520_000, "nfm", 0.4, 12_500, "v")]
_scan(tmp_path, tx, **args)
combined = next(iter(tmp_path.glob("*_transcription.txt")))
before = combined.read_text()
assert before.strip()
_scan(tmp_path, tx, **args) # a second run into the same directory
after = combined.read_text()
assert after.startswith(before), "the earlier transcript was overwritten"
assert len(after) > len(before), "the later over was not added"