Self-hosted project management for devs and their clients: tickets, time tracking, docs and meetings, with an AI assistant that cites its sources. AGPL-3.0.
Ruby agplai-assistantdockerdsgvogdprhotwireissue-trackerjira-alternativeknowledge-basellmmcp-servermeeting-notesopen-sourceproject-managementredmine-alternativeruby-on-railsself-hostedticketingtime-tracking
feat(meetings): count and replace a heard form by one rule
Guido Boyke34958f4f35be
diff --git a/app/services/meetings/speaker_markup.rb b/app/services/meetings/speaker_markup.rbindex 9f0cf05..ffa3f84 100644--- a/app/services/meetings/speaker_markup.rb+++ b/app/services/meetings/speaker_markup.rb@@ -34,6 +34,16 @@ module Meetings# rendered with its suffix intact, so nothing is lost on screen.DIARISATION_SUFFIX = /\s*\((?:(?:speaker|sprecher)\s*\d+|\?)\)\s*\z/i+ # The label as the tools sometimes emit it, already bolded: "**Samira:**"+ # or "**Samira**:". mark leaves such a line as it is; #label reads it,+ # because the page shows it as a label too.+ BOLD_SPEAKER_LINE = /\A(\s*)\*\*([^:*\n]{1,#{MAX_LABEL_LENGTH}}?)\s*(?::\*\*|\*\*\s*:)/++ # A speaker label at the start of a line: where it ends (the character+ # after its colon, and after the closing ** of a bolded one) and the name+ # it gives, without a diarisation suffix.+ Label = Data.define(:ends_at, :name)+def self.call(...)new(...).callend@@ -49,6 +59,17 @@ module Meetingstext.each_line.map { |line| mark(line) }.joinend+ # The speaker label at the start of one line, or nil: the rule mark bolds+ # by, against the same participant list, so nothing counts as a label that+ # the page does not show as one. Meetings::TermReplacement never replaces+ # inside it and reads the speaker of a line from it (K4b).+ def label(line)+ match = SPEAKER_LINE.match(line) || BOLD_SPEAKER_LINE.match(line)+ return if match.nil? || !speaker?(match[2])++ Label.new(ends_at: match.end(0), name: match[2].sub(DIARISATION_SUFFIX, '').strip)+ end+privateattr_reader :text, :participant_namesdiff --git a/app/services/meetings/term_replacement.rb b/app/services/meetings/term_replacement.rbnew file mode 100644index 0000000..d83e2eb--- /dev/null+++ b/app/services/meetings/term_replacement.rb@@ -0,0 +1,178 @@+# frozen_string_literal: true++# The ONE rule for counting and replacing a heard form in a meeting text (K4b,+# plan §5.2): the transcript, and on "replace everywhere" its AI summary too.+# Pure Ruby, no database: the caller hands in the text and the meeting's+# participants (anything with a display_name).+#+# * A match is a whole word: no letter (with its marks) and no digit of any+# script directly before or after it. Not \b: Ruby's \b takes "_" for a+# letter and wants a letter at both ends of the form, so "C++" or "2.0?"+# would never match where they stand alone. A hyphen is a boundary, so+# "Lalabeis-Konto" holds "Lalabeis".+# * Case as marked. A form of several words matches across horizontal+# whitespace (space, tab, no-break space) inside one line, never across a+# line break: a place has one line (term_corrections.line_index).+# * Never inside the speaker label at the start of a line+# (Meetings::SpeakerMarkup#label, the rule the page bolds by): the label+# belongs to the participant list. Never in the frontmatter+# (Meeting::FRONTMATTER_BLOCK): the page does not show it.+#+# #occurrences is the one list behind the count of the dialog and the+# replacement, so the two cannot disagree. Lines are counted from the first+# line stored (with the frontmatter), offsets in characters, not bytes.+#+# Entry point: scan, occurrences, count, replace, at, speaker_of, count_by_speaker+module Meetings+ class TermReplacement+ # A letter (with its combining marks) or a digit of any script.+ WORD_CHARACTER = '[\p{L}\p{M}\p{N}]'+ # Between the words of a form: horizontal whitespace only.+ WORD_GAP = '[[:blank:]]+'++ # One whole-word match: its line, where it starts in the line and how long+ # it is (characters), and whether it starts inside the speaker label.+ Match = Data.define(:line_index, :char_offset, :length, :in_label)+ Replaced = Data.define(:text, :count)++ def initialize(text:, heard:, participants: [])+ @text = text.to_s+ @words = heard.to_s.split(/[[:space:]]+/).reject(&:empty?)+ @participants = Array(participants)+ end++ # Every whole-word match outside the frontmatter, in text order, the ones+ # in a speaker label included (in_label). Meetings::TranscriptMark maps a+ # mark of the browser through it; counting and replacing use #occurrences.+ def scan+ @scan ||= @words.empty? ? [] : collect_matches+ end++ # The matches that count and are replaced: every one outside a label.+ def occurrences+ @occurrences ||= scan.reject(&:in_label)+ end++ def count+ occurrences.size+ end++ # The text with `with` in place of every occurrence, or only of the one+ # given (one of #occurrences), and how many it replaced.+ def replace(with:, only: nil)+ targets = only.nil? ? occurrences : [own!(only)]+ by_line = targets.group_by(&:line_index)+ result = lines.each_with_index.map do |line, index|+ hits = by_line[index]+ next line unless hits++ hits.sort_by(&:char_offset).reverse.each_with_object(line.dup) do |hit, changed|+ changed[hit.char_offset, hit.length] = with+ end+ end+ Replaced.new(text: result.join("\n"), count: targets.size)+ end++ # The occurrence that overlaps a marked span of one line, or nil.+ def at(line_index:, char_offset:, length:)+ finish = char_offset + length+ occurrences.find do |match|+ match.line_index == line_index && match.char_offset < finish && char_offset < match.char_offset + match.length+ end+ end++ # Who spoke a line: the participant its label names (full name, or a first+ # name only one participant has), else whoever spoke the last labelled+ # line before it. nil before the first label, after a label that names+ # nobody or two participants, and in the frontmatter.+ def speaker_of(line_index)+ speakers[line_index]+ end++ # How often the form stands in the turns of each speaker (nil: nobody known).+ def count_by_speaker+ occurrences.group_by { |match| speaker_of(match.line_index) }.transform_values(&:size)+ end++ private++ def lines+ @lines ||= @text.split("\n", -1)+ end++ def collect_matches+ regex = pattern+ lines.each_with_index.flat_map do |line, index|+ next [] if index < first_content_line++ label_end = labels[index]&.ends_at+ line.to_enum(:scan, regex).map do+ found = Regexp.last_match+ start = found.begin(0)+ Match.new(line_index: index, char_offset: start, length: found[0].length,+ in_label: !label_end.nil? && start < label_end)+ end+ end+ end++ def pattern+ body = @words.map { |word| Regexp.escape(word) }.join(WORD_GAP)+ Regexp.new("(?<!#{WORD_CHARACTER})#{body}(?!#{WORD_CHARACTER})")+ end++ # The frontmatter's lines are no content: nobody sees or marks them. A+ # block that ends the text without a line break ends on a line of its own.+ def first_content_line+ @first_content_line ||= begin+ block = @text[Meeting::FRONTMATTER_BLOCK]+ if block.nil? then 0+ elsif block.end_with?("\n") then block.count("\n")+ else block.count("\n") + 1+ end+ end+ end++ def labels+ @labels ||= begin+ reader = Meetings::SpeakerMarkup.new(text: '', participant_names: @participants.map(&:display_name))+ lines.each_with_index.map { |line, index| reader.label(line) if index >= first_content_line }+ end+ end++ def speakers+ @speakers ||= begin+ current = nil+ labels.each_with_index.map do |label, index|+ next if index < first_content_line++ current = participant_named(label.name) if label+ current+ end+ end+ end++ def participant_named(name)+ key = MeetingParticipant.normalize_name(name)+ full = @participants.select { |participant| normalized_names[participant].first == key }+ return full.first if full.size == 1+ return if full.size > 1++ first = @participants.select { |participant| normalized_names[participant].last == key }+ first.first if first.size == 1+ end++ # [full name, first name] of each participant, normalized once.+ def normalized_names+ @normalized_names ||= @participants.to_h do |participant|+ name = participant.display_name.to_s.strip+ [participant, [MeetingParticipant.normalize_name(name), MeetingParticipant.normalize_name(name.split(/\s+/).first)]]+ end+ end++ def own!(match)+ raise ArgumentError, 'not an occurrence of this text' unless occurrences.include?(match)++ match+ end+ end+enddiff --git a/spec/services/meetings/speaker_markup_spec.rb b/spec/services/meetings/speaker_markup_spec.rbindex fe2e2d0..eb2ac02 100644--- a/spec/services/meetings/speaker_markup_spec.rb+++ b/spec/services/meetings/speaker_markup_spec.rb@@ -120,4 +120,28 @@ RSpec.describe Meetings::SpeakerMarkup doexpect(mark(text, ['Bert Bauer', 'Karl Krause'])).to eq(text)endend+ # The label of one line (K4b): what Meetings::TermReplacement never replaces+ # and reads the speaker from. The same participant list decides, in the plain+ # and in the already bolded form.+ describe '#label' do+ def label(line, names = ['Samira Barati'])+ described_class.new(text: '', participant_names: names).label(line)+ end++ it 'gives where a plain label ends and the name it gives' do+ expect(label('Samira: Diese Tickets.').to_h).to eq(ends_at: 7, name: 'Samira')+ expect(label(' Samira Barati (Speaker 2): Ja.').to_h).to eq(ends_at: 28, name: 'Samira Barati')+ end++ it 'reads a bolded label in both forms' do+ expect(label('**Samira:** Ja.').to_h).to eq(ends_at: 11, name: 'Samira')+ expect(label('**Samira**: Ja.').to_h).to eq(ends_at: 11, name: 'Samira')+ end++ it 'is nothing for prose before a colon, a bolded lead-in or a line without a colon' do+ expect(label('Problem: Die Belege fehlen.')).to be_nil+ expect(label('**Fazit:** Getränke bestellt.')).to be_nil+ expect(label('Samira sagt ja.')).to be_nil+ end+ endenddiff --git a/spec/services/meetings/term_replacement_spec.rb b/spec/services/meetings/term_replacement_spec.rbnew file mode 100644index 0000000..dd5a33a--- /dev/null+++ b/spec/services/meetings/term_replacement_spec.rb@@ -0,0 +1,249 @@+# frozen_string_literal: true++require 'rails_helper'++# The one rule for counting and replacing a heard form in a meeting text+# (K4b, plan §5.2), without a database: whole words after Unicode (letters+# and digits of every script, not \b), case as marked, several words across+# horizontal whitespace inside a line, never inside the speaker label at the+# start of a line, never in the frontmatter. The count of the dialog and the+# count of the replacement come from the same list. Invented words and names+# only.+RSpec.describe Meetings::TermReplacement do+ # A participant as the class reads it: only the name. No database.+ def participant(name)+ Struct.new(:display_name).new(name)+ end++ let(:anna) { participant('Anna Ananas') }+ let(:ben) { participant('Ben Birne') }++ def replacement(text, heard, participants: [])+ described_class.new(text: text, heard: heard, participants: participants)+ end++ def count(text, heard, participants: [])+ replacement(text, heard, participants: participants).count+ end++ def replaced(text, heard, with:, participants: [])+ replacement(text, heard, participants: participants).replace(with: with).text+ end++ describe 'whole words' do+ it 'finds umlauts and ß at either end of a word' do+ expect(count('Ärger mit der Straße, viel Ärger.', 'Ärger')).to eq(2)+ expect(count('Die Straße ist frei', 'Straße')).to eq(1)+ expect(count('Grüße an alle, Grüße', 'Grüße')).to eq(2)+ end++ it 'finds no word inside a longer one, also where it touches an umlaut or ß' do+ expect(count('Die Maßnahme und das Fußballspiel', 'Maß')).to eq(0)+ expect(count('Ein Fußball im Fußraum', 'Fuß')).to eq(0)+ expect(count('Lalabeisen und XLalabeis und Lalabeisä', 'Lalabeis')).to eq(0)+ expect(count('Hauptstraße', 'Straße')).to eq(0)+ end++ # The hyphen is no letter: a compound with a hyphen is two words for the+ # rule, so a misheard name is fixed inside "Lalabeis-Konto" too.+ it 'takes a hyphen for a boundary, and a hyphen in the form literally' do+ expect(replaced('Das Lalabeis-Konto und -Lalabeis', 'Lalabeis', with: 'Lalabase'))+ .to eq('Das Lalabase-Konto und -Lalabase')+ expect(count('Lala-Beis, Lala Beis, Lala-Beisel', 'Lala-Beis')).to eq(1)+ end++ # Where the rule differs from Ruby's \b: an underscore and a sign at the+ # end of the form are no letters and no digits.+ it 'takes an underscore for a boundary' do+ expect(count('datei_Lalabeis_neu.txt', 'Lalabeis')).to eq(1)+ end++ it 'finds a form that ends in a sign, but not inside a longer word' do+ expect(replaced('Wir nehmen C++ und Cobol, nicht C++x', 'C++', with: 'Java'))+ .to eq('Wir nehmen Java und Cobol, nicht C++x')+ expect(count('Läuft das auf Version 2.0?', '2.0?')).to eq(1)+ end++ it 'counts digits of every script as part of a word' do+ expect(count('Raum 12 und Raum 123', 'Raum 12')).to eq(1)+ expect(count("Lalabeis\u0663 und Lalabeis", 'Lalabeis')).to eq(1)+ end+ end++ it 'keeps case as marked' do+ expect(count('Lalabeis, lalabeis, LALABEIS', 'Lalabeis')).to eq(1)+ expect(count('Lalabeis, lalabeis, LALABEIS', 'lalabeis')).to eq(1)+ end++ describe 'a form of several words' do+ it 'matches across horizontal whitespace inside a line' do+ text = "Lala Beis und Lala Beis\nLala\tBeis und Lala\u00A0Beis"++ expect(count(text, 'Lala Beis')).to eq(4)+ end++ it 'never matches across a line break' do+ expect(count("Wir sagen Lala\nBeis dazu.", 'Lala Beis')).to eq(0)+ expect(count("Wir sagen Lala\r\nBeis dazu.", 'Lala Beis')).to eq(0)+ end++ it 'takes the whitespace inside the form as one gap' do+ expect(count('Lala Beis', "Lala \t Beis")).to eq(1)+ end+ end++ describe 'the speaker label at the start of a line' do+ let(:participants) { [anna, ben] }++ it 'is never counted or replaced' do+ text = "Anna: Anna hat recht.\nBen: Danke, Anna."++ expect(count(text, 'Anna', participants: participants)).to eq(2)+ expect(replaced(text, 'Anna', with: 'Hanna', participants: participants))+ .to eq("Anna: Hanna hat recht.\nBen: Danke, Hanna.")+ end++ it 'is protected in its bolded form and with a diarisation suffix too' do+ text = "**Anna:** Anna hier.\n**Ben**: Ben da.\nAnna (Speaker 2): Anna wieder."++ expect(replaced(text, 'Anna', with: 'Hanna', participants: participants))+ .to eq("**Anna:** Hanna hier.\n**Ben**: Ben da.\nAnna (Speaker 2): Hanna wieder.")+ end++ it 'is a label only for a participant, so a word before a colon in prose counts' do+ text = 'Problem: Problem gelöst.'++ expect(count(text, 'Problem', participants: participants)).to eq(2)+ end++ it 'is listed by the scan, marked as a label, for the mapping of a mark' do+ scan = replacement('Anna: Anna hat recht.', 'Anna', participants: participants).scan++ expect(scan.map { |match| [match.char_offset, match.in_label] }).to eq([[0, true], [6, false]])+ end+ end++ it 'leaves the frontmatter alone, and counts lines from the first line stored' do+ text = "---\nid: Lalabeis\n---\nLalabeis sagt hallo."+ subject = replacement(text, 'Lalabeis')++ expect(subject.occurrences.map { |match| [match.line_index, match.char_offset] }).to eq([[3, 0]])+ expect(subject.replace(with: 'Lalabase').text).to eq("---\nid: Lalabeis\n---\nLalabase sagt hallo.")+ end++ describe 'counting and replacing' do+ it 'finds nothing and changes nothing where the form is not' do+ subject = replacement("Anna: Alles gut.\n", 'Lalabeis', participants: [anna])+ result = subject.replace(with: 'Lalabase')++ expect([subject.count, result.count, result.text]).to eq([0, 0, "Anna: Alles gut.\n"])+ end++ it 'replaces exactly what it counts' do+ texts = [+ "Anna: Lalabeis und Lalabeis.\nLalabeis-Konto, Lalabeisen\nBen: lalabeis Lalabeis",+ "---\nx: Lalabeis\n---\nLalabeis\r\nLalabeis!",+ 'Lalabeis_Lalabeis Lalabeis'+ ]++ texts.each do |text|+ subject = replacement(text, 'Lalabeis', participants: [anna, ben])+ result = subject.replace(with: 'Zirbel')++ expect(result.count).to eq(subject.count), text+ expect(result.text.scan('Zirbel').size).to eq(subject.count), text+ expect(replacement(result.text, 'Lalabeis', participants: [anna, ben]).count).to eq(0), text+ end+ end++ it 'replaces only the one occurrence it is given' do+ subject = replacement("Lalabeis eins\nLalabeis zwei, Lalabeis drei", 'Lalabeis')+ second = subject.occurrences[1]+ result = subject.replace(with: 'Lalabase', only: second)++ expect([result.text, result.count]).to eq(["Lalabeis eins\nLalabase zwei, Lalabeis drei", 1])+ end++ it 'refuses an occurrence that is not one of its own' do+ other = replacement('xx Lalabeis', 'Lalabeis').occurrences.first++ expect { replacement('Lalabeis', 'Lalabeis').replace(with: 'Lalabase', only: other) }.to raise_error(ArgumentError)+ end++ it 'keeps line endings and a last line break' do+ expect(replaced("Lalabeis\r\nLalabeis\n", 'Lalabeis', with: 'Lalabase')).to eq("Lalabase\r\nLalabase\n")+ end++ it 'counts in characters, not bytes' do+ occurrence = replacement('Grüße, Lalabeis', 'Lalabeis').occurrences.first++ expect([occurrence.line_index, occurrence.char_offset, occurrence.length]).to eq([0, 7, 8])+ end++ it 'finds nothing for a blank form or a blank text' do+ expect(count('Lalabeis', ' ')).to eq(0)+ expect(count(nil, 'Lalabeis')).to eq(0)+ expect(replacement(nil, 'Lalabeis').replace(with: 'x').text).to eq('')+ end+ end++ describe 'the speaker of a place' do+ let(:participants) { [anna, ben] }+ let(:text) do+ [+ 'Vorweg ohne Sprecher: Lalabeis.',+ 'Anna: Lalabeis ist gut.',+ 'Und Lalabeis kann mehr.',+ '',+ 'Ben: Lalabeis auch bei mir.',+ 'Anna Ananas: Lalabeis zum Schluss.'+ ].join("\n")+ end+ let(:subject) { replacement(text, 'Lalabeis', participants: participants) }++ it 'is the participant named at the start of the line, by first name or full name' do+ expect(subject.speaker_of(1)).to eq(anna)+ expect(subject.speaker_of(4)).to eq(ben)+ expect(subject.speaker_of(5)).to eq(anna)+ end++ it 'is the speaker of the last labelled line for a line without a label' do+ expect(subject.speaker_of(2)).to eq(anna)+ expect(subject.speaker_of(3)).to eq(anna)+ end++ it 'is nobody before the first label' do+ expect(subject.speaker_of(0)).to be_nil+ end++ it 'counts the occurrences per speaker' do+ expect(subject.count_by_speaker).to eq(nil => 1, anna => 3, ben => 1)+ end++ # Two participants share the first name: the line is a speaker turn (the+ # page bolds it), but whose is unknown, and the turn is nobody's.+ it 'is nobody for a first name two participants share, and that line ends the turn before' do+ other_anna = participant('Anna Apfel')+ shared = replacement("Ben: eins\nAnna: Lalabeis\nweiter", 'Lalabeis', participants: [anna, other_anna, ben])++ expect(shared.speaker_of(0)).to eq(ben)+ expect(shared.speaker_of(1)).to be_nil+ expect(shared.speaker_of(2)).to be_nil+ expect(shared.scan.first.in_label).to be(false)+ end+ end++ describe 'the occurrence at a marked place' do+ let(:subject) { replacement('Wir nutzen Lala Beis und Lalabeis.', 'Lala Beis') }++ it 'is the occurrence that overlaps the marked span' do+ expect(subject.at(line_index: 0, char_offset: 11, length: 4)&.char_offset).to eq(11)+ expect(subject.at(line_index: 0, char_offset: 16, length: 4)&.char_offset).to eq(11)+ end++ it 'is nothing where the form does not stand' do+ expect(subject.at(line_index: 0, char_offset: 25, length: 8)).to be_nil+ expect(subject.at(line_index: 1, char_offset: 11, length: 4)).to be_nil+ end+ end+end