Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Preserve merge metadata: let the user pick which source's notes to keep (or none) in the modal, and union participants and tags across all sources instead of losing them
Murtaza Nasir098e7103dc9e
diff --git a/src/api/recordings.py b/src/api/recordings.pyindex 2da7a88f..b9a635d5 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -773,7 +773,7 @@ def merge_recordings_endpoint():recording is created immediately in PROCESSING and queued for the normaltranscription + summarization pipeline. See src/services/recording_merge.py."""- from src.services.recording_merge import create_merge_recording, MergeError+ from src.services.recording_merge import create_merge_recording, MergeError, _UNSETdata = request.get_json(silent=True) or {}raw_ids = data.get('recording_ids')@@ -789,12 +789,29 @@ def merge_recordings_endpoint():title = data.get('title')delete_originals = bool(data.get('delete_originals', False))+ # notes_source_id: which source's notes to keep on the merged recording.+ # key absent -> default to the first source+ # null -> keep no notes+ # <id> -> that source's notes+ if 'notes_source_id' in data:+ raw_notes_src = data.get('notes_source_id')+ if raw_notes_src is None:+ notes_source_id = None+ else:+ try:+ notes_source_id = int(raw_notes_src)+ except (ValueError, TypeError):+ notes_source_id = _UNSET+ else:+ notes_source_id = _UNSET+try:recording = create_merge_recording(current_user,recording_ids,title=title,delete_originals=delete_originals,+ notes_source_id=notes_source_id,)except MergeError as e:return jsonify({'error': str(e)}), 400diff --git a/src/services/recording_merge.py b/src/services/recording_merge.pyindex 8ab5e463..9940fd01 100644--- a/src/services/recording_merge.py+++ b/src/services/recording_merge.py@@ -54,11 +54,32 @@ _MERGED_BITRATE = '192k'# video is extracted to audio, so PENDING/PROCESSING sources are rejected._STABLE_STATUSES = {'COMPLETED', 'SUMMARIZING', 'FAILED'}+# Distinguishes "caller did not choose a notes source" (default to the first+# source, for API back-compat) from "explicitly keep no notes" (None).+_UNSET = object()+class MergeError(Exception):"""Raised when a merge cannot be performed. The message is user-safe."""+def _union_participants(recordings):+ """Union the comma-separated participants of all sources, de-duplicated+ case-insensitively and order-preserving. Participants are additive across a+ merge, so none should be lost. Returns a comma-separated string or None."""+ seen = set()+ out = []+ for rec in recordings:+ if not rec.participants:+ continue+ for name in (p.strip() for p in rec.participants.split(',')):+ key = name.lower()+ if name and key not in seen:+ seen.add(key)+ out.append(name)+ return ', '.join(out) if out else None++def _build_concat_filter(num_inputs: int) -> str:"""Build an ffmpeg -filter_complex string that normalizes then concatenatesthe first audio stream of each input."""@@ -138,7 +159,7 @@ def _validate_sources(user, recording_ids, storage, require_settled=True):def create_merge_recording(user, recording_ids, title=None, delete_originals=False,- require_settled=True):+ require_settled=True, notes_source_id=_UNSET):"""Validate sources and create a placeholder recording queued for merging.Runs in the request (or, with ``require_settled=False``, from the stitch@@ -157,8 +178,24 @@ def create_merge_recording(user, recording_ids, title=None, delete_originals=Falnow = datetime.utcnow()- # Inherit folder from the first source; leave meeting_date at the earliest- # source's date so the merged session sorts where the conversation began.+ # Notes cannot be meaningfully concatenated, so keep exactly one source's:+ # - notes_source_id unset -> the first source (API back-compat default)+ # - notes_source_id is None -> keep no notes+ # - notes_source_id == <id> -> that source's notes (the user's pick)+ if notes_source_id is _UNSET:+ merged_notes = first.notes+ elif notes_source_id is None:+ merged_notes = None+ else:+ chosen = next((r for r in recordings if r.id == notes_source_id), None)+ merged_notes = chosen.notes if chosen else first.notes++ # Participants are additive across a merge — union them so none are lost.+ merged_participants = _union_participants(recordings)++ # Folder: a recording lives in exactly one folder; keep the first source's.+ # meeting_date: earliest source date so the merged session sorts where the+ # conversation began.meeting_dates = [r.meeting_date for r in recordings if r.meeting_date]merged_meeting_date = min(meeting_dates) if meeting_dates else now@@ -172,21 +209,31 @@ def create_merge_recording(user, recording_ids, title=None, delete_originals=Falmeeting_date=merged_meeting_date,user_id=user.id,mime_type='audio/mp4',- notes=first.notes,+ notes=merged_notes,+ participants=merged_participants,folder_id=first.folder_id,processing_source='merge',)db.session.add(recording)db.session.flush() # assign recording.id- # Inherit the first source's tags (preserving order).- for order, tag in enumerate(first.tags, 1):- db.session.add(RecordingTag(- recording_id=recording.id,- tag_id=tag.id,- order=order,- added_at=datetime.utcnow(),- ))+ # Tags are additive too: union across all sources so none are lost. The first+ # source's tags come first (in order) so the transcription-param resolver+ # still keys off the first source's primary tag; other sources' tags follow.+ order = 1+ seen_tag_ids = set()+ for rec in recordings:+ for tag in rec.tags:+ if tag.id in seen_tag_ids:+ continue+ seen_tag_ids.add(tag.id)+ db.session.add(RecordingTag(+ recording_id=recording.id,+ tag_id=tag.id,+ order=order,+ added_at=datetime.utcnow(),+ ))+ order += 1db.session.commit()diff --git a/src/services/recording_stitch.py b/src/services/recording_stitch.pyindex 086a0083..7a69a5af 100644--- a/src/services/recording_stitch.py+++ b/src/services/recording_stitch.py@@ -436,7 +436,7 @@ def _try_kickoff_merge(recording, user_id, metadata) -> bool:from flask import current_appfrom src.database import dbfrom src.models import User- from src.services.recording_merge import create_merge_recording, MergeError+ from src.services.recording_merge import create_merge_recording, MergeError, _UNSETtry:# Substitute this clip's real id for the "__self__" placeholder, coercing@@ -458,6 +458,22 @@ def _try_kickoff_merge(recording, user_id, metadata) -> bool:if not user:return False+ # Resolve which source's notes to keep. '__self__' -> the clip; an id ->+ # that source; null -> none; absent -> first source (default).+ if 'notes_source' in intent:+ ns = intent.get('notes_source')+ if ns == '__self__':+ notes_source_id = recording.id+ elif ns is None:+ notes_source_id = None+ else:+ try:+ notes_source_id = int(ns)+ except (TypeError, ValueError):+ notes_source_id = _UNSET+ else:+ notes_source_id = _UNSET+# Trusted path: the clip's audio was just produced by the stitch, so it# is final even though the recording is not COMPLETED (require_settled# off). Ownership + audio-existence are still enforced.@@ -467,6 +483,7 @@ def _try_kickoff_merge(recording, user_id, metadata) -> bool:title=(intent.get('title') or None),delete_originals=bool(intent.get('delete_originals', False)),require_settled=False,+ notes_source_id=notes_source_id,)return Trueexcept MergeError as e:diff --git a/static/js/modules/composables/audio.js b/static/js/modules/composables/audio.jsindex 520c3c89..9a56764e 100644--- a/static/js/modules/composables/audio.js+++ b/static/js/modules/composables/audio.js@@ -1081,21 +1081,27 @@ export function useAudio(state, utils) {return;}if (utils.openMergeForRecording) {- utils.openMergeForRecording();+ // Pass the clip's recording-view notes so it can be offered as a+ // notes source in the merge modal.+ utils.openMergeForRecording({ clipNotes: recordingNotes.value || '' });}};// Called by the merge modal (recording mode) on confirm: finalize the// recording session with the merge intent. `orderedSpec` is the ordered// source list with the string '__self__' marking this clip's position.- const finalizeRecordingMerge = async (orderedSpec, { deleteOriginals = true, title = undefined } = {}) => {- return uploadRecordedAudio({- mergeIntent: {- order: orderedSpec,- delete_originals: !!deleteOriginals,- title: title || undefined,- },- });+ const finalizeRecordingMerge = async (orderedSpec, { deleteOriginals = true, title = undefined, notesSource = undefined } = {}) => {+ const mergeIntent = {+ order: orderedSpec,+ delete_originals: !!deleteOriginals,+ title: title || undefined,+ };+ // notesSource: '__self__' | <id> | null. Only include the key when the+ // caller specified one, so its absence means "use the backend default".+ if (notesSource !== undefined) {+ mergeIntent.notes_source = notesSource;+ }+ return uploadRecordedAudio({ mergeIntent });};// Upload recorded audio in incognito modediff --git a/static/js/modules/composables/bulk-operations.js b/static/js/modules/composables/bulk-operations.jsindex 9e619c4f..80b0fce5 100644--- a/static/js/modules/composables/bulk-operations.js+++ b/static/js/modules/composables/bulk-operations.js@@ -42,6 +42,24 @@ export function useBulkOperations({// holds a virtual { __self__: true } entry for the not-yet-uploaded clip and// confirm finalizes the recording session with the merge intent instead.const mergeMode = ref('bulk');+ // Which source's notes to keep on the merged recording. Notes cannot be+ // concatenated, so only one source's are kept. Value is a recording id,+ // '__self__' (the recorded clip), or null (keep no notes).+ const mergeNotesSourceId = ref(null);+ // Sources in the merge that actually have notes — drives the selector.+ const mergeNotesCandidates = computed(() =>+ mergeOrderedList.value.filter(r => r && r.notes && String(r.notes).trim())+ );+ // Keep the notes selection valid as the list changes: default to the first+ // source with notes; respect an explicit "keep none" ('none'); and if the+ // chosen source leaves the list, fall back to the first remaining one.+ watch(mergeNotesCandidates, (cands) => {+ const ids = cands.map(r => r.id);+ if (mergeNotesSourceId.value === 'none') return; // explicit opt-out+ if (mergeNotesSourceId.value === null || !ids.includes(mergeNotesSourceId.value)) {+ mergeNotesSourceId.value = ids.length ? ids[0] : null;+ }+ }, { deep: false });// In-modal "add recording" picker (lets the user append existing recordings// to the merge from within the modal — used by the normal merge and by the// merge-from-recording flow that seeds the modal with a just-recorded clip).@@ -354,6 +372,7 @@ export function useBulkOperations({mergeOrderedList.value = selectedRecordings.value.slice();mergeTitle.value = '';mergeDeleteOriginals.value = false;+ mergeNotesSourceId.value = null;mergeAddPickerOpen.value = false;mergeAddSearch.value = '';showBulkMergeModal.value = true;@@ -362,12 +381,18 @@ export function useBulkOperations({// Open the merge modal for a just-recorded clip that has NOT been uploaded// yet. The list starts with a virtual placeholder for the clip; the user// adds existing recordings to merge it into. Defaults to replacing the- // sources (the chosen behavior for this flow).- const openMergeForRecording = () => {+ // sources (the chosen behavior for this flow). ``clipNotes`` carries the+ // notes typed in the recording view so the clip can be a notes source.+ const openMergeForRecording = ({ clipNotes = '' } = {}) => {mergeMode.value = 'recording';- mergeOrderedList.value = [{ id: '__self__', __self__: true, title: _t('mergeRecordings.thisRecording', 'This recording') }];+ mergeOrderedList.value = [{+ id: '__self__', __self__: true,+ title: _t('mergeRecordings.thisRecording', 'This recording'),+ notes: clipNotes || '',+ }];mergeTitle.value = '';mergeDeleteOriginals.value = true;+ mergeNotesSourceId.value = null;mergeAddPickerOpen.value = false;mergeAddSearch.value = '';showBulkMergeModal.value = true;@@ -387,6 +412,7 @@ export function useBulkOperations({mergeOrderedList.value = (seedRecordings || []).slice();mergeTitle.value = title || '';mergeDeleteOriginals.value = !!deleteOriginals;+ mergeNotesSourceId.value = null;mergeAddPickerOpen.value = false;mergeAddSearch.value = '';showBulkMergeModal.value = true;@@ -443,9 +469,11 @@ export function useBulkOperations({if (!hasExisting || typeof finalizeRecordingMerge !== 'function') return;const title = mergeTitle.value.trim() || undefined;const deleteOriginals = mergeDeleteOriginals.value;+ // notes source: 'none' -> keep none (null); else the id or '__self__'.+ const notesSource = mergeNotesSourceId.value === 'none' ? null : mergeNotesSourceId.value;closeBulkMergeModal();try {- await finalizeRecordingMerge(orderedSpec, { deleteOriginals, title });+ await finalizeRecordingMerge(orderedSpec, { deleteOriginals, title, notesSource });} catch (error) {console.error('Recording merge finalize error:', error);setGlobalError(`Failed to start merge: ${error.message}`);@@ -469,7 +497,9 @@ export function useBulkOperations({body: JSON.stringify({recording_ids: orderedIds,title: mergeTitle.value.trim() || undefined,- delete_originals: mergeDeleteOriginals.value+ delete_originals: mergeDeleteOriginals.value,+ // 'none' -> keep no notes (null); otherwise the chosen source id.+ notes_source_id: mergeNotesSourceId.value === 'none' ? null : mergeNotesSourceId.value})});@@ -706,6 +736,8 @@ export function useBulkOperations({mergePickerHasMore,loadMoreMergeCandidates,mergeMode,+ mergeNotesSourceId,+ mergeNotesCandidates,// Bulk DeleteopenBulkDeleteModal,diff --git a/static/locales/de.json b/static/locales/de.jsonindex 3accb8c2..fd9017b3 100644--- a/static/locales/de.json+++ b/static/locales/de.json@@ -1888,6 +1888,10 @@"preparingClip": "Ihr Clip wird vorbereitet — die Optionen zum Zusammenführen öffnen sich, sobald er bereit ist.","clipNotReady": "Der Clip konnte nicht zum Zusammenführen vorbereitet werden.","thisRecording": "Diese Aufnahme",- "searching": "Suche…"+ "searching": "Suche…",+ "notesLabel": "Notizen übernehmen von",+ "notesNone": "Keine Notizen übernehmen",+ "notesWarning": "Es können nur die Notizen einer Aufnahme übernommen werden. Teilnehmer und Tags aller Aufnahmen werden zusammengeführt.",+ "notesHint": "Teilnehmer und Tags aller Aufnahmen werden zusammengeführt."}}\ No newline at end of filediff --git a/static/locales/en.json b/static/locales/en.jsonindex a008361d..542b0e11 100644--- a/static/locales/en.json+++ b/static/locales/en.json@@ -1888,6 +1888,10 @@"preparingClip": "Preparing your clip — the merge options will open when it's ready.","clipNotReady": "The clip could not be prepared for merging.","thisRecording": "This recording",- "searching": "Searching…"+ "searching": "Searching…",+ "notesLabel": "Keep notes from",+ "notesNone": "Don't keep notes",+ "notesWarning": "Only one recording's notes can be kept. Participants and tags from all recordings are combined.",+ "notesHint": "Participants and tags from all recordings are combined."}}\ No newline at end of filediff --git a/static/locales/es.json b/static/locales/es.jsonindex 61842bb6..3fef390a 100644--- a/static/locales/es.json+++ b/static/locales/es.json@@ -1888,6 +1888,10 @@"preparingClip": "Preparando tu clip: las opciones de combinación se abrirán cuando esté listo.","clipNotReady": "No se pudo preparar el clip para la combinación.","thisRecording": "Esta grabación",- "searching": "Buscando…"+ "searching": "Buscando…",+ "notesLabel": "Conservar notas de",+ "notesNone": "No conservar notas",+ "notesWarning": "Solo se pueden conservar las notas de una grabación. Los participantes y las etiquetas de todas las grabaciones se combinan.",+ "notesHint": "Los participantes y las etiquetas de todas las grabaciones se combinan."}}\ No newline at end of filediff --git a/static/locales/fr.json b/static/locales/fr.jsonindex 98dccbf7..02ef4174 100644--- a/static/locales/fr.json+++ b/static/locales/fr.json@@ -1888,6 +1888,10 @@"preparingClip": "Préparation de votre extrait — les options de fusion s'ouvriront dès qu'il sera prêt.","clipNotReady": "Impossible de préparer l'extrait pour la fusion.","thisRecording": "Cet enregistrement",- "searching": "Recherche…"+ "searching": "Recherche…",+ "notesLabel": "Conserver les notes de",+ "notesNone": "Ne pas conserver de notes",+ "notesWarning": "Les notes d'un seul enregistrement peuvent être conservées. Les participants et les étiquettes de tous les enregistrements sont regroupés.",+ "notesHint": "Les participants et les étiquettes de tous les enregistrements sont regroupés."}}\ No newline at end of filediff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.jsonindex 1e7bec93..41f5f70a 100644--- a/static/locales/pt-BR.json+++ b/static/locales/pt-BR.json@@ -1888,6 +1888,10 @@"preparingClip": "Preparando seu clipe — as opções de mesclagem abrirão quando estiver pronto.","clipNotReady": "Não foi possível preparar o clipe para a mesclagem.","thisRecording": "Esta gravação",- "searching": "Pesquisando…"+ "searching": "Pesquisando…",+ "notesLabel": "Manter notas de",+ "notesNone": "Não manter notas",+ "notesWarning": "Somente as notas de uma gravação podem ser mantidas. Os participantes e as tags de todas as gravações são combinados.",+ "notesHint": "Os participantes e as tags de todas as gravações são combinados."}}\ No newline at end of filediff --git a/static/locales/ru.json b/static/locales/ru.jsonindex aaa4f4f0..b64d7fd9 100644--- a/static/locales/ru.json+++ b/static/locales/ru.json@@ -1888,6 +1888,10 @@"preparingClip": "Подготовка фрагмента — параметры объединения откроются, когда он будет готов.","clipNotReady": "Не удалось подготовить фрагмент к объединению.","thisRecording": "Эта запись",- "searching": "Поиск…"+ "searching": "Поиск…",+ "notesLabel": "Сохранить заметки из",+ "notesNone": "Не сохранять заметки",+ "notesWarning": "Можно сохранить заметки только одной записи. Участники и теги всех записей объединяются.",+ "notesHint": "Участники и теги всех записей объединяются."}}\ No newline at end of filediff --git a/static/locales/zh.json b/static/locales/zh.jsonindex e618d526..d9120e50 100644--- a/static/locales/zh.json+++ b/static/locales/zh.json@@ -1888,6 +1888,10 @@"preparingClip": "正在准备您的片段——准备就绪后将打开合并选项。","clipNotReady": "无法准备该片段以进行合并。","thisRecording": "此录音",- "searching": "搜索中…"+ "searching": "搜索中…",+ "notesLabel": "保留备注来自",+ "notesNone": "不保留备注",+ "notesWarning": "只能保留一条录音的备注。所有录音的参与者和标签将被合并。",+ "notesHint": "所有录音的参与者和标签将被合并。"}}\ No newline at end of filediff --git a/templates/modals/bulk-merge-modal.html b/templates/modals/bulk-merge-modal.htmlindex f51ddaba..6e91a453 100644--- a/templates/modals/bulk-merge-modal.html+++ b/templates/modals/bulk-merge-modal.html@@ -70,6 +70,22 @@</div></div>+ <!-- Notes source — shown only when a source has notes. Notes can't be+ concatenated, so exactly one source's notes are kept. -->+ <div v-if="mergeNotesCandidates.length >= 1" class="mb-4">+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1" v-text="t('mergeRecordings.notesLabel')"></label>+ <select v-model="mergeNotesSourceId"+ class="w-full px-3 py-2 bg-[var(--bg-input)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">+ <option v-for="cand in mergeNotesCandidates" :key="cand.id" :value="cand.id">${ cand.title || t('mergeRecordings.untitled') }</option>+ <option value="none" v-text="t('mergeRecordings.notesNone')"></option>+ </select>+ <p v-if="mergeNotesCandidates.length >= 2" class="t-meta mt-1 flex items-start gap-1.5">+ <i class="fas fa-exclamation-triangle text-amber-500" style="margin-top: 2px;"></i>+ <span v-text="t('mergeRecordings.notesWarning')"></span>+ </p>+ <p v-else class="t-meta mt-1" v-text="t('mergeRecordings.notesHint')"></p>+ </div>+<!-- Title --><div class="mb-4"><label class="block text-sm font-medium text-[var(--text-secondary)] mb-1" v-text="t('mergeRecordings.titleLabel')"></label>diff --git a/tests/test_merge_export_features.py b/tests/test_merge_export_features.pyindex 4a9fa867..85c70070 100644--- a/tests/test_merge_export_features.py+++ b/tests/test_merge_export_features.py@@ -446,3 +446,86 @@ def test_try_kickoff_merge_other_users_source_falls_through():with _endpoint_mocks():# create_merge_recording raises MergeError (not owned) -> falls throughassert _try_kickoff_merge(clip, me.id, metadata) is False+++# --------------------------------------------------------------------------- #+# #323 — Merge metadata preservation (notes pick, participants/tags union)+# --------------------------------------------------------------------------- #++def test_merge_notes_default_is_first_source():+ from src.services.recording_merge import create_merge_recording+ with app.app_context():+ user = _mk_user()+ a = _mk_recording(user, title="A", notes="alpha notes")+ b = _mk_recording(user, title="B", notes="beta notes")+ with _endpoint_mocks():+ merged = create_merge_recording(user, [a.id, b.id])+ assert merged.notes == "alpha notes"+++def test_merge_notes_explicit_source():+ from src.services.recording_merge import create_merge_recording+ with app.app_context():+ user = _mk_user()+ a = _mk_recording(user, title="A", notes="alpha notes")+ b = _mk_recording(user, title="B", notes="beta notes")+ with _endpoint_mocks():+ merged = create_merge_recording(user, [a.id, b.id], notes_source_id=b.id)+ assert merged.notes == "beta notes"+++def test_merge_notes_none_keeps_no_notes():+ from src.services.recording_merge import create_merge_recording+ with app.app_context():+ user = _mk_user()+ a = _mk_recording(user, title="A", notes="alpha notes")+ b = _mk_recording(user, title="B", notes="beta notes")+ with _endpoint_mocks():+ merged = create_merge_recording(user, [a.id, b.id], notes_source_id=None)+ assert merged.notes is None+++def test_merge_participants_unioned_dedup_case_insensitive():+ from src.services.recording_merge import create_merge_recording+ with app.app_context():+ user = _mk_user()+ a = _mk_recording(user, title="A", participants="Alice, Bob")+ b = _mk_recording(user, title="B", participants="bob, Carol")+ with _endpoint_mocks():+ merged = create_merge_recording(user, [a.id, b.id])+ parts = [p.strip() for p in (merged.participants or "").split(",") if p.strip()]+ assert parts == ["Alice", "Bob", "Carol"]+++def test_merge_tags_unioned_first_source_first():+ from src.services.recording_merge import create_merge_recording+ with app.app_context():+ user = _mk_user()+ t1 = Tag(name=f"t1_{uuid.uuid4().hex[:6]}", user_id=user.id)+ t2 = Tag(name=f"t2_{uuid.uuid4().hex[:6]}", user_id=user.id)+ db.session.add_all([t1, t2])+ db.session.commit()+ a = _mk_recording(user, title="A")+ db.session.add(RecordingTag(recording_id=a.id, tag_id=t1.id, order=1))+ b = _mk_recording(user, title="B")+ db.session.add(RecordingTag(recording_id=b.id, tag_id=t2.id, order=1))+ db.session.add(RecordingTag(recording_id=b.id, tag_id=t1.id, order=2)) # dup of a's tag+ db.session.commit()+ with _endpoint_mocks():+ merged = create_merge_recording(user, [a.id, b.id])+ assert [t.id for t in merged.tags] == [t1.id, t2.id]+++def test_merge_endpoint_passes_notes_source_id():+ with app.app_context():+ user = _mk_user()+ a = _mk_recording(user, title="A", notes="alpha")+ b = _mk_recording(user, title="B", notes="beta")+ client = app.test_client()+ _login(client, user)+ with _endpoint_mocks():+ resp = client.post("/api/recordings/merge",+ json={"recording_ids": [a.id, b.id], "notes_source_id": b.id})+ assert resp.status_code == 200+ merged = db.session.get(Recording, resp.get_json()["recording_id"])+ assert merged.notes == "beta"