Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Optimize chunking conversion and remap speakers to unique IDs across chunks

Murtaza Nasir386bfc1b7dee
diff --git a/src/audio_chunking.py b/src/audio_chunking.py
index c91356fe..4992816a 100644
--- a/src/audio_chunking.py
+++ b/src/audio_chunking.py
@@ -359,40 +359,48 @@ class AudioChunkingService:
def convert_to_mp3_and_get_info(self, file_path: str, temp_dir: str) -> Tuple[str, float, float]:
"""
Convert the input file to MP3 format for consistency and get its size and duration info.
-
+
+ If the input is already MP3, skips conversion and just copies it.
+
Args:
file_path: Path to the source audio file
temp_dir: Directory to store the temporary MP3 file
-
+
Returns:
Tuple of (mp3_file_path, duration_seconds, size_bytes)
"""
try:
+ import shutil
+
# Generate MP3 filename
base_name = os.path.splitext(os.path.basename(file_path))[0]
mp3_filename = f"{base_name}_converted.mp3"
mp3_path = os.path.join(temp_dir, mp3_filename)
-
- logger.info(f"Converting {file_path} to 128kbps MP3 format for accurate chunking...")
-
- # Use centralized FFmpeg utility for conversion
- convert_to_mp3(file_path, mp3_path)
-
+
+ # Check if input is already MP3 - skip conversion
+ file_ext = os.path.splitext(file_path)[1].lower()
+ if file_ext == '.mp3':
+ logger.info(f"Input {file_path} is already MP3, skipping conversion")
+ shutil.copy2(file_path, mp3_path)
+ else:
+ logger.info(f"Converting {file_path} to 128kbps MP3 format for chunking...")
+ # Use centralized FFmpeg utility for conversion
+ convert_to_mp3(file_path, mp3_path)
+
if not os.path.exists(mp3_path):
raise ValueError("MP3 file was not created")
-
- # Get the size and duration of the converted MP3 file
+
+ # Get the size and duration of the MP3 file
mp3_size = os.path.getsize(mp3_path)
mp3_duration = self.get_audio_duration(mp3_path)
-
+
if not mp3_duration:
raise ValueError("Could not determine MP3 file duration")
-
- logger.info(f"Converted MP3: {mp3_size/1024/1024:.1f}MB, {mp3_duration:.1f}s")
-
+
+ logger.info(f"MP3 ready for chunking: {mp3_size/1024/1024:.1f}MB, {mp3_duration:.1f}s")
+
# Optionally preserve converted file for debugging (set PRESERVE_CHUNK_DEBUG=true in env)
if os.getenv('PRESERVE_CHUNK_DEBUG', 'false').lower() == 'true':
- import shutil
# Save debug files in /data/uploads/debug/ directory
debug_dir = '/data/uploads/debug'
os.makedirs(debug_dir, exist_ok=True)
@@ -400,9 +408,9 @@ class AudioChunkingService:
debug_path = os.path.join(debug_dir, debug_filename)
shutil.copy2(mp3_path, debug_path)
logger.info(f"Debug: Preserved converted file as {debug_path}")
-
+
return mp3_path, mp3_duration, mp3_size
-
+
except (FFmpegError, FFmpegNotFoundError) as e:
logger.error(f"Error converting file to MP3: {e}")
raise
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index c44d43e5..45bb528d 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -1072,12 +1072,18 @@ def compress_lossless_audio(filepath, codec='mp3', bitrate='128k', codec_info=No
def merge_diarized_chunks(chunk_results):
"""
- Merge diarized transcription chunks while preserving speaker labels AND segments.
+ Merge diarized transcription chunks while remapping speaker labels to be unique.
- Since we use known_speaker_references, speaker labels (A, B, C, D) should be
- consistent across chunks. This function:
- 1. Concatenates the diarized text from each chunk
- 2. Merges all segments with adjusted timestamps based on chunk start_time
+ Since ASR services can't maintain speaker identity across chunks, each chunk's
+ speakers are remapped to unique IDs:
+ - Chunk 1: SPEAKER_00, SPEAKER_01 → SPEAKER_00, SPEAKER_01
+ - Chunk 2: SPEAKER_00, SPEAKER_01 → SPEAKER_02, SPEAKER_03
+ - etc.
+
+ This function:
+ 1. Remaps speaker labels to be unique across all chunks
+ 2. Updates both segments and transcription text with new labels
+ 3. Adjusts timestamps based on chunk start_time
Args:
chunk_results: List of chunk results with 'transcription', 'segments', 'start_time'
@@ -1086,6 +1092,7 @@ def merge_diarized_chunks(chunk_results):
Tuple of (merged_text, merged_segments, all_speakers)
"""
from src.services.transcription import TranscriptionSegment
+ import re
if not chunk_results:
return "", [], []
@@ -1096,15 +1103,69 @@ def merge_diarized_chunks(chunk_results):
merged_parts = []
merged_segments = []
all_speakers = set()
+ next_speaker_number = 0 # Track the next available speaker number
+
+ for chunk_idx, chunk in enumerate(sorted_chunks):
+ chunk_segments = chunk.get('segments') or []
+
+ # Build speaker remapping for this chunk
+ # Maps original speaker label -> new unique speaker label
+ chunk_speakers = set()
+ for seg in chunk_segments:
+ if hasattr(seg, 'speaker'):
+ speaker = seg.speaker
+ else:
+ speaker = seg.get('speaker', 'Unknown')
+ if speaker:
+ chunk_speakers.add(speaker)
+
+ # Also check chunk metadata for speakers
+ if chunk.get('speakers'):
+ for s in chunk['speakers']:
+ chunk_speakers.add(s)
+
+ # Create remapping: sort speakers to ensure deterministic ordering
+ speaker_remap = {}
+ for original_speaker in sorted(chunk_speakers):
+ if original_speaker and original_speaker != 'Unknown':
+ # Extract number from speaker label (e.g., SPEAKER_00 -> 0)
+ # For first chunk, keep original numbering; for subsequent chunks, remap
+ if chunk_idx == 0:
+ # First chunk: keep original labels but track highest number
+ speaker_remap[original_speaker] = original_speaker
+ match = re.search(r'(\d+)$', original_speaker)
+ if match:
+ num = int(match.group(1))
+ next_speaker_number = max(next_speaker_number, num + 1)
+ else:
+ # Subsequent chunks: remap to new unique numbers
+ new_speaker = f"SPEAKER_{next_speaker_number:02d}"
+ speaker_remap[original_speaker] = new_speaker
+ next_speaker_number += 1
- for chunk in sorted_chunks:
+ # Update transcription text with remapped speakers
chunk_text = chunk.get('transcription', '').strip()
+ if chunk_text and chunk_idx > 0:
+ # Replace speaker labels in text (e.g., [SPEAKER_00]: -> [SPEAKER_02]:)
+ for original, remapped in speaker_remap.items():
+ if original != remapped:
+ # Handle various formats: [SPEAKER_00]:, SPEAKER_00:, (SPEAKER_00)
+ chunk_text = re.sub(
+ rf'\[{re.escape(original)}\]',
+ f'[{remapped}]',
+ chunk_text
+ )
+ chunk_text = re.sub(
+ rf'(?<!\[){re.escape(original)}(?![\d])',
+ remapped,
+ chunk_text
+ )
+
if chunk_text:
merged_parts.append(chunk_text)
- # Merge segments with adjusted timestamps
+ # Merge segments with adjusted timestamps and remapped speakers
chunk_start_offset = chunk.get('start_time', 0)
- chunk_segments = chunk.get('segments') or []
for seg in chunk_segments:
# Handle both TranscriptionSegment objects and dicts
@@ -1123,7 +1184,9 @@ def merge_diarized_chunks(chunk_results):
if not text or not text.strip():
continue
- all_speakers.add(speaker)
+ # Remap speaker label
+ remapped_speaker = speaker_remap.get(speaker, speaker)
+ all_speakers.add(remapped_speaker)
# Adjust timestamps by chunk offset
adjusted_start = (start_time or 0) + chunk_start_offset
@@ -1131,16 +1194,11 @@ def merge_diarized_chunks(chunk_results):
merged_segments.append(TranscriptionSegment(
text=text,
- speaker=speaker,
+ speaker=remapped_speaker,
start_time=adjusted_start,
end_time=adjusted_end
))
- # Track speakers from chunk metadata too
- if chunk.get('speakers'):
- for s in chunk['speakers']:
- all_speakers.add(s)
-
merged_text = '\n'.join(merged_parts)
return merged_text, merged_segments, sorted(list(all_speakers))
diff --git a/src/utils/audio_conversion.py b/src/utils/audio_conversion.py
index 947c7df8..331e449b 100644
--- a/src/utils/audio_conversion.py
+++ b/src/utils/audio_conversion.py
@@ -258,15 +258,22 @@ def convert_if_needed(
logger.info(f"Converting {original_filename} (codec: {audio_codec}) - unsupported for processing")
if needs_conversion:
- # Determine target codec - fall back to mp3 if AUDIO_CODEC is unsupported by connector
- target_codec = AUDIO_CODEC
- if connector_specs and connector_specs.unsupported_codecs:
- if AUDIO_CODEC in connector_specs.unsupported_codecs:
- target_codec = 'mp3'
- logger.warning(
- f"AUDIO_CODEC '{AUDIO_CODEC}' is not supported by connector, "
- f"falling back to mp3 for {original_filename}"
- )
+ # Determine target codec
+ # If chunking is needed, always convert to MP3 (chunking requires MP3 anyway)
+ # This avoids double conversion: original → configured codec → mp3
+ if needs_chunking:
+ target_codec = 'mp3'
+ logger.info(f"Using MP3 for {original_filename} since chunking is needed")
+ else:
+ # Fall back to mp3 if AUDIO_CODEC is unsupported by connector
+ target_codec = AUDIO_CODEC
+ if connector_specs and connector_specs.unsupported_codecs:
+ if AUDIO_CODEC in connector_specs.unsupported_codecs:
+ target_codec = 'mp3'
+ logger.warning(
+ f"AUDIO_CODEC '{AUDIO_CODEC}' is not supported by connector, "
+ f"falling back to mp3 for {original_filename}"
+ )
logger.info(f"Converting {original_filename} to {target_codec.upper()}")