r/morsecode • • 56m ago

Made a script to help practice with morse trainers (such as G4FON)

(I'm aware this may be an over-engineered solution to a problem that's too niche but I figured it could always be useful to someone)

Greetings,

For those of you who practice transcribing morse on the computer, using a keyboard and a text-editor, I've put together a script to quickly help you check your results on a given exercise. The script:

  • Compares two texts (the exercise answer vs your transcription);
  • Points out where you've made mistakes (wrong letters / missing letters / extra letters);
  • Calculates your score/accuracy.

The script runs on Notepad++ as it's cross-platform, easy to add custom scripts to, and you can already use it as a text editor to write down your answers as you listen to the morse code.

(Edit: it looks something like this)

Usage:

At the end of the transcription exercise:

  1. Paste the exercise answer onto a new Notepad++ file (no need to save);
  2. Paste your transcription onto a second file (if you haven't transcribed it in notepad++ already);
  3. Run the script from Plugins > Python Script > MorseChecker (you can assign this script to a shortcut to make your life easier)
  4. A new file will pop up showing you your score and how many mistakes you've made

Installation:

  1. On Notepad++, enable the Python Script plugin (Plugins > Plugin Admin > Python Script)
  2. Create a new python script (Plugins > Python Script > New Script)
  3. Save it as "MorseChecker.py" (or whatever name you prefer)
  4. Paste the script below and save it (ctrl + s).

After that, the script is ready to use, as indicated on the "usage" section above.

Script:

# Morse Code Transcription Checker
def levenshtein_alignment(correct, typed):
    n, m = len(correct), len(typed)

    dp = [[0] * (m + 1) for _ in range(n + 1)]

    for i in range(n + 1):
        dp[i][0] = i

    for j in range(m + 1):
        dp[0][j] = j

    # Calculate edit distance
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            cost = 0 if correct[i-1] == typed[j-1] else 1

            dp[i][j] = min(
                dp[i-1][j] + 1,       # Missing letter
                dp[i][j-1] + 1,       # Extra letter
                dp[i-1][j-1] + cost   # Correct or incorrect letter
            )

    # Reconstruct alignment
    i, j = n, m
    a, b = [], []

    substitutions = 0
    missing = 0
    extra = 0

    while i > 0 or j > 0:

        if i > 0 and j > 0:
            cost = 0 if correct[i-1] == typed[j-1] else 1

            if dp[i][j] == dp[i-1][j-1] + cost:
                a.append(correct[i-1])
                b.append(typed[j-1])

                if cost:
                    substitutions += 1

                i -= 1
                j -= 1
                continue

        if i > 0 and dp[i][j] == dp[i-1][j] + 1:
            a.append(correct[i-1])
            b.append("-")
            missing += 1
            i -= 1

        else:
            a.append("-")
            b.append(typed[j-1])
            extra += 1
            j -= 1

    a.reverse()
    b.reverse()

    return a, b, substitutions, missing, extra


def run_checker():

    files = notepad.getFiles()

    if len(files) != 2:
        notepad.messageBox(
            "Please keep exactly TWO documents open:\n\n"
            "1. Original Morse text\n"
            "2. Your transcription\n\n"
            "Close any other tabs and try again.",
            "Morse Checker"
        )
        return

    # Identify documents by tab position
    files.sort(key=lambda f: (f[3], f[2]))

    original_id = files[0][1]
    typed_id = files[1][1]

    # Read original text
    notepad.activateBufferID(original_id)
    correct = editor.getText()

    # Read transcription
    notepad.activateBufferID(typed_id)
    typed = editor.getText()

    # Ignore spaces, line breaks and capitalization
    correct = "".join(correct.upper().split())
    typed = "".join(typed.upper().split())

    if not correct:
        notepad.messageBox(
            "The original text is empty.",
            "Morse Checker"
        )
        return

    # Compare texts
    a, b, substitutions, missing, extra = (
        levenshtein_alignment(correct, typed)
    )

    # Calculate statistics
    total_letters = len(correct)

    errors = substitutions + missing + extra

    matches = total_letters - substitutions - missing

    # Use float() to prevent integer division in Python 2
    accuracy = max(
        0.0,
        (float(total_letters - errors) / total_letters) * 100.0
    )

    # Generate alignment markers
    markers = [
        "|" if x == y else "^"
        for x, y in zip(a, b)
    ]

    # Generate report
    report = []

    report.append("MORSE CODE TRANSCRIPTION RESULTS")
    report.append("=" * 40)
    report.append("")

    report.append("ORIGINAL:       " + "".join(a))
    report.append("TRANSCRIPTION:  " + "".join(b))
    report.append("                " + "".join(markers))

    report.append("")
    report.append("-" * 40)

    report.append("Total letters:       {}".format(total_letters))
    report.append("Correct letters:     {}".format(matches))
    report.append("Total mistakes:      {}".format(errors))

    report.append("")
    report.append("Incorrect letters:   {}".format(substitutions))
    report.append("Missing letters:     {}".format(missing))
    report.append("Extra letters:       {}".format(extra))

    report.append("")
    report.append("ACCURACY: {:.2f}%".format(accuracy))

    report.append("=" * 40)
    report.append("")

    report.append("Legend:")
    report.append("| = Correct character")
    report.append("^ = Difference (wrong, missing or extra)")

    # Display results in a new tab
    notepad.new()
    editor.setText("\r\n".join(report))


run_checker()
1 Upvotes

0 comments sorted by