Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Enable diarization for chunked files using known speaker references
Murtaza Nasir1d4acf1b34fd
diff --git a/docs/faq.md b/docs/faq.mdindex 086159ec..406fb42c 100644--- a/docs/faq.md+++ b/docs/faq.md@@ -88,6 +88,8 @@ Transcription accuracy depends on several factors - audio quality, speaker clariWhisper API provides basic transcription - converting speech to text without speaker identification. The [recommended ASR container](getting-started.md#option-b-custom-asr-endpoint-configuration) (`onerahmet/openai-whisper-asr-webservice`) offers advanced features like [speaker diarization](features.md#speaker-diarization), which identifies and labels different speakers in the conversation. Learn to [manage speakers](user-guide/transcripts.md#speaker-identification) after transcription. Diarization is essential for meetings with multiple participants, while Whisper API works fine for single-speaker recordings like dictations or podcasts.+OpenAI's `gpt-4o-transcribe-diarize` model also offers cloud-based diarization. For longer files (over ~23 minutes), speaker tracking supports up to 4 speakers - recordings with more speakers may have inconsistent labels across sections.+**Note on ASR engines**: For speaker diarization to work properly with the ASR webservice, you must use `ASR_ENGINE=whisperx`, not `faster_whisper`. While faster_whisper provides transcription, it doesn't support speaker identification.### Can Speakr transcribe languages other than English?diff --git a/docs/features.md b/docs/features.mdindex 961d21c1..90be122f 100644--- a/docs/features.md+++ b/docs/features.md@@ -12,6 +12,8 @@ Speakr supports multiple transcription engines to match your needs and budget. UWhen using the [ASR endpoint](getting-started.md#option-b-custom-asr-endpoint-configuration), Speakr automatically identifies different speakers in your recordings. If you encounter issues, check the [troubleshooting guide](troubleshooting.md#speaker-identification-not-working). Each speaker gets a unique label that you can later customize with actual names. The system remembers these speaker profiles, building a library that improves identification accuracy over time. Manage your speaker library in [account settings](user-guide/settings.md). This feature transforms multi-person meetings from walls of text into organized conversations.+**Cloud Diarization with OpenAI**: When using OpenAI's `gpt-4o-transcribe-diarize` model, speaker diarization is also available with speakers labeled as A, B, C, etc. For longer files (over ~23 minutes) that require chunking, the system maintains speaker identity across chunks using audio reference samples. This technique supports **up to 4 speakers** - recordings with more speakers may have inconsistent labels across different sections of the transcript.+### Interactive Audio SynchronizationSpeakr provides seamless bidirectional synchronization between audio playback and transcript text for recordings with speaker diarization. Click any part of the transcript to jump directly to that moment in the audio, making it easy to review specific sections. As the audio plays, the system automatically highlights the currently spoken text in real-time with smooth visual feedback. Enable auto-scroll follow mode to keep the active segment centered in view, allowing you to follow along effortlessly during playback.diff --git a/docs/getting-started.md b/docs/getting-started.mdindex a26af5f5..b09466c7 100644--- a/docs/getting-started.md+++ b/docs/getting-started.md@@ -70,7 +70,7 @@ Choose ONE of the following options:TRANSCRIPTION_API_KEY=sk-your_openai_api_keyTRANSCRIPTION_MODEL=gpt-4o-transcribe-diarize```-This provides high-quality transcription with automatic speaker identification - no GPU or self-hosted service required.+This provides high-quality transcription with automatic speaker identification - no GPU or self-hosted service required. Note: For longer files (over ~23 minutes), speaker tracking across chunks supports up to 4 speakers.**Option B: Self-hosted ASR/WhisperX (Best for privacy)**```bashdiff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.mdindex 2e94acc3..f0c28334 100644--- a/docs/getting-started/installation.md+++ b/docs/getting-started/installation.md@@ -88,6 +88,8 @@ The connector automatically detects that you want the OpenAI Transcribe connecto- `gpt-4o-mini-transcribe` - Cost-effective option- `whisper-1` - Legacy model (uses Whisper connector)+> **Note:** For longer files (over ~23 minutes) using `gpt-4o-transcribe-diarize`, speaker tracking across chunks supports up to 4 speakers. Recordings with more speakers may have inconsistent labels across sections.+Now configure the text generation model that powers summaries, titles, and chat features. OpenRouter is recommended here because it provides access to multiple AI models at competitive prices, but you can use any OpenAI-compatible service:```bashdiff --git a/src/audio_chunking.py b/src/audio_chunking.pyindex 7e0f4dd4..c91356fe 100644--- a/src/audio_chunking.py+++ b/src/audio_chunking.py@@ -978,6 +978,214 @@ class AudioChunkingService:except Exception as e:logger.warning(f"Error cleaning up temporary MP3 file: {e}")+def get_audio_duration_ffprobe(file_path: str) -> Optional[float]:+ """Get actual audio duration using ffprobe."""+ try:+ result = subprocess.run([+ 'ffprobe', '-v', 'error', '-show_entries', 'format=duration',+ '-of', 'default=noprint_wrappers=1:nokey=1', file_path+ ], capture_output=True, text=True, check=True)+ return float(result.stdout.strip())+ except Exception:+ return None+++def extract_speaker_samples(+ audio_path: str,+ segments: List[Dict[str, Any]],+ output_dir: str,+ min_duration: float = 1.5, # OpenAI minimum is 1.2s, use 1.5s for safety+ max_duration: float = 9.0, # OpenAI maximum is 10.0s, use 9.0s for safety+ max_speakers: int = 4+) -> Dict[str, str]:+ """+ Extract audio samples for each unique speaker from diarized segments.++ This is used to maintain speaker identity across chunks when processing+ long audio files with the gpt-4o-transcribe-diarize model.++ Args:+ audio_path: Path to the source audio file (should be the converted chunk MP3)+ segments: List of diarized segments with speaker, start_time, end_time+ output_dir: Directory to store extracted speaker samples+ min_duration: Minimum duration for a speaker sample (OpenAI requires 1.2-10s)+ max_duration: Maximum duration for a speaker sample+ max_speakers: Maximum number of speakers to extract (OpenAI supports up to 4)++ Returns:+ Dict mapping speaker label (e.g., "A", "B") to path of extracted audio sample+ """+ # OpenAI's actual limits+ OPENAI_MIN_DURATION = 1.2+ OPENAI_MAX_DURATION = 10.0++ # Group segments by speaker+ speaker_segments: Dict[str, List[Dict]] = {}+ for seg in segments:+ # Handle both dict and object segments+ if isinstance(seg, dict):+ speaker = seg.get('speaker', 'Unknown')+ start = seg.get('start_time') or seg.get('start')+ end = seg.get('end_time') or seg.get('end')+ else:+ speaker = getattr(seg, 'speaker', 'Unknown')+ start = getattr(seg, 'start_time', None) or getattr(seg, 'start', None)+ end = getattr(seg, 'end_time', None) or getattr(seg, 'end', None)++ if speaker == 'Unknown' or start is None or end is None:+ continue++ if speaker not in speaker_segments:+ speaker_segments[speaker] = []+ speaker_segments[speaker].append({'start': start, 'end': end})++ if not speaker_segments:+ logger.warning("No valid speaker segments found for sample extraction")+ return {}++ # Sort speakers to get consistent ordering (A, B, C, D...)+ sorted_speakers = sorted(speaker_segments.keys())[:max_speakers]+ logger.info(f"Extracting samples for {len(sorted_speakers)} speakers: {sorted_speakers}")++ speaker_samples = {}++ for speaker in sorted_speakers:+ segs = speaker_segments[speaker]++ # Find the best segment for this speaker (ideally 1.5-9 seconds)+ best_segment = None+ best_duration = 0++ for seg in segs:+ duration = seg['end'] - seg['start']++ # Prefer segments in the ideal range+ if min_duration <= duration <= max_duration:+ if duration > best_duration:+ best_segment = seg+ best_duration = duration++ # If no segment in ideal range, try to find one we can trim+ if not best_segment:+ for seg in segs:+ duration = seg['end'] - seg['start']+ if duration >= min_duration:+ # Trim to max_duration if needed+ best_segment = {+ 'start': seg['start'],+ 'end': min(seg['end'], seg['start'] + max_duration)+ }+ best_duration = best_segment['end'] - best_segment['start']+ break++ # Still no segment? Try combining multiple short segments+ if not best_segment and len(segs) > 1:+ # Sort by start time and try to find consecutive segments+ sorted_segs = sorted(segs, key=lambda x: x['start'])+ combined_start = sorted_segs[0]['start']+ combined_end = sorted_segs[0]['end']++ for i in range(1, len(sorted_segs)):+ # If segments are close (within 1 second), combine them+ if sorted_segs[i]['start'] - combined_end < 1.0:+ combined_end = sorted_segs[i]['end']+ if combined_end - combined_start >= min_duration:+ break++ combined_duration = combined_end - combined_start+ if combined_duration >= min_duration:+ best_segment = {+ 'start': combined_start,+ 'end': min(combined_end, combined_start + max_duration)+ }+ best_duration = best_segment['end'] - best_segment['start']++ if not best_segment:+ logger.warning(f"Could not find suitable segment for speaker {speaker}")+ continue++ # Extract the audio sample using ffmpeg+ sample_filename = f"speaker_{speaker}_sample.mp3"+ sample_path = os.path.join(output_dir, sample_filename)++ try:+ cmd = [+ 'ffmpeg', '-i', audio_path,+ '-ss', str(best_segment['start']),+ '-t', str(best_duration),+ '-acodec', 'libmp3lame',+ '-b:a', '128k',+ '-y',+ sample_path+ ]++ result = subprocess.run(cmd, capture_output=True, text=True)+ if result.returncode != 0:+ logger.error(f"Failed to extract sample for speaker {speaker}: {result.stderr}")+ continue++ if os.path.exists(sample_path) and os.path.getsize(sample_path) > 0:+ # Verify actual duration meets OpenAI requirements+ actual_duration = get_audio_duration_ffprobe(sample_path)+ if actual_duration:+ logger.info(f"Speaker {speaker} sample: expected {best_duration:.2f}s, actual {actual_duration:.2f}s")++ if actual_duration < OPENAI_MIN_DURATION:+ logger.warning(f"Sample for speaker {speaker} too short ({actual_duration:.2f}s < {OPENAI_MIN_DURATION}s), skipping")+ os.remove(sample_path)+ continue+ elif actual_duration > OPENAI_MAX_DURATION:+ logger.warning(f"Sample for speaker {speaker} too long ({actual_duration:.2f}s > {OPENAI_MAX_DURATION}s), skipping")+ os.remove(sample_path)+ continue++ speaker_samples[speaker] = sample_path+ logger.info(f"Extracted {actual_duration:.1f}s sample for speaker {speaker} "+ f"(from {best_segment['start']:.1f}s to {best_segment['end']:.1f}s)")+ else:+ logger.warning(f"Sample file not created for speaker {speaker}")++ except Exception as e:+ logger.error(f"Error extracting sample for speaker {speaker}: {e}")++ return speaker_samples+++def samples_to_data_urls(speaker_samples: Dict[str, str]) -> Dict[str, str]:+ """+ Convert speaker sample file paths to base64-encoded data URLs.++ OpenAI's known_speaker_references requires audio samples as data URLs+ when using multipart form data.++ Args:+ speaker_samples: Dict mapping speaker label to file path++ Returns:+ Dict mapping speaker label to data URL+ """+ import base64++ data_urls = {}++ for speaker, path in speaker_samples.items():+ try:+ with open(path, 'rb') as f:+ audio_data = f.read()++ # Encode as base64 data URL+ b64_data = base64.b64encode(audio_data).decode('utf-8')+ data_url = f"data:audio/mpeg;base64,{b64_data}"+ data_urls[speaker] = data_url++ logger.debug(f"Converted speaker {speaker} sample to data URL ({len(b64_data)} bytes)")++ except Exception as e:+ logger.error(f"Error converting speaker {speaker} sample to data URL: {e}")++ return data_urls++class ChunkProcessingError(Exception):"""Exception raised when chunk processing fails."""passdiff --git a/src/services/transcription/base.py b/src/services/transcription/base.pyindex a515c293..02426cb7 100644--- a/src/services/transcription/base.py+++ b/src/services/transcription/base.py@@ -67,7 +67,8 @@ class TranscriptionRequest:min_speakers: Optional[int] = Nonemax_speakers: Optional[int] = Noneknown_speaker_names: Optional[List[str]] = None- known_speaker_references: Optional[Dict[str, BinaryIO]] = None+ # known_speaker_references: Dict mapping speaker label to either BinaryIO or data URL string+ known_speaker_references: Optional[Dict[str, Any]] = None# Advanced optionsprompt: Optional[str] = Nonediff --git a/src/services/transcription/connectors/openai_transcribe.py b/src/services/transcription/connectors/openai_transcribe.pyindex 8ce3409f..37d6d059 100644--- a/src/services/transcription/connectors/openai_transcribe.py+++ b/src/services/transcription/connectors/openai_transcribe.py@@ -180,9 +180,26 @@ class OpenAITranscribeConnector(BaseTranscriptionConnector):params["response_format"] = "diarized_json"logger.info("Using diarized_json response format for speaker diarization")- # Optional: known speaker support (for future implementation)- # if request.known_speaker_names:- # params["known_speaker_names"] = request.known_speaker_names+ # Known speaker support for maintaining speaker identity across chunks+ # known_speaker_names is a list of speaker labels (e.g., ["A", "B"])+ # known_speaker_references is a dict mapping label to data URL+ if request.known_speaker_names and request.known_speaker_references:+ # OpenAI expects lists for both parameters+ speaker_names = []+ speaker_refs = []++ for name in request.known_speaker_names:+ if name in request.known_speaker_references:+ speaker_names.append(name)+ speaker_refs.append(request.known_speaker_references[name])++ if speaker_names:+ # Use extra_body to pass the known speaker parameters+ params["extra_body"] = {+ "known_speaker_names": speaker_names,+ "known_speaker_references": speaker_refs+ }+ logger.info(f"Using known speaker references for {len(speaker_names)} speakers: {speaker_names}")else:# Non-diarization modelsif request.prompt:@@ -248,6 +265,10 @@ class OpenAITranscribeConnector(BaseTranscriptionConnector):start = getattr(seg, 'start', None)end = getattr(seg, 'end', None)+ # Skip empty segments+ if not text or not text.strip():+ continue+speakers.add(speaker)full_text_parts.append(f"[{speaker}]: {text}")@@ -258,13 +279,9 @@ class OpenAITranscribeConnector(BaseTranscriptionConnector):end_time=end))- # Get the full text if available- if hasattr(response, 'text'):- full_text = response.text- elif isinstance(response, dict) and 'text' in response:- full_text = response['text']- else:- full_text = '\n'.join(full_text_parts)+ # Always use our formatted text with speaker labels for diarized responses+ # OpenAI's response.text is plain text WITHOUT speaker labels+ full_text = '\n'.join(full_text_parts)logger.info(f"Parsed {len(segments)} segments with {len(speakers)} unique speakers: {sorted(speakers)}")diff --git a/src/tasks/processing.py b/src/tasks/processing.pyindex 32954a8e..b1328cb1 100644--- a/src/tasks/processing.py+++ b/src/tasks/processing.py@@ -998,29 +998,121 @@ def compress_lossless_audio(filepath, codec='mp3', bitrate='128k', codec_info=Noraise-def transcribe_chunks_with_connector(connector, filepath, filename, mime_type, language):+def merge_diarized_chunks(chunk_results):+ """+ Merge diarized transcription chunks while preserving speaker labels AND segments.++ 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++ Args:+ chunk_results: List of chunk results with 'transcription', 'segments', 'start_time'++ Returns:+ Tuple of (merged_text, merged_segments, all_speakers)+ """+ from src.services.transcription import TranscriptionSegment++ if not chunk_results:+ return "", [], []++ # Sort chunks by start time to ensure correct order+ sorted_chunks = sorted(chunk_results, key=lambda x: x.get('start_time', 0))++ merged_parts = []+ merged_segments = []+ all_speakers = set()++ for chunk in sorted_chunks:+ chunk_text = chunk.get('transcription', '').strip()+ if chunk_text:+ merged_parts.append(chunk_text)++ # Merge segments with adjusted timestamps+ 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+ if hasattr(seg, 'speaker'):+ speaker = seg.speaker+ text = seg.text+ start_time = seg.start_time+ end_time = seg.end_time+ else:+ speaker = seg.get('speaker', 'Unknown')+ text = seg.get('text', '')+ start_time = seg.get('start_time') or seg.get('start')+ end_time = seg.get('end_time') or seg.get('end')++ # Skip empty segments+ if not text or not text.strip():+ continue++ all_speakers.add(speaker)++ # Adjust timestamps by chunk offset+ adjusted_start = (start_time or 0) + chunk_start_offset+ adjusted_end = (end_time or 0) + chunk_start_offset++ merged_segments.append(TranscriptionSegment(+ text=text,+ speaker=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))+++def transcribe_chunks_with_connector(connector, filepath, filename, mime_type, language, diarize=False):"""Transcribe a large audio file using chunking with the connector architecture.This is used when the connector doesn't handle chunking internally (e.g., OpenAI Whisper)and the file exceeds the configured chunk limit.+ For diarization-enabled connectors (gpt-4o-transcribe-diarize), this function:+ 1. Processes the first chunk with diarization enabled+ 2. Extracts speaker audio samples from the diarized response+ 3. Passes those samples as known_speaker_references to subsequent chunks+ This maintains consistent speaker labels (A, B, C, D) across all chunks.+Args:connector: The transcription connector to usefilepath: Path to the audio filefilename: Original filename for loggingmime_type: MIME type of the audio filelanguage: Optional language code+ diarize: Whether diarization was requested (for connectors that support it)Returns:- Merged transcription text+ Merged transcription text (with speaker labels if diarization enabled)"""import tempfilefrom src.services.transcription import TranscriptionRequest+ from src.audio_chunking import extract_speaker_samples, samples_to_data_urls# Get connector specs for proper chunking (respects hard limits like max_duration_seconds)connector_specs = connector.specifications+ # Check if connector supports diarization (property, not method - no parentheses)+ supports_diarization = connector.supports_diarization+ use_diarization = diarize and supports_diarization++ if use_diarization:+ current_app.logger.info("Diarization enabled - will use known_speaker_references for consistent speaker labels across chunks")+ elif diarize and not supports_diarization:+ current_app.logger.warning("Diarization requested but connector doesn't support it - transcribing without diarization")+with tempfile.TemporaryDirectory() as temp_dir:try:# Create chunks (passes connector_specs for duration-based chunking if needed)@@ -1034,6 +1126,8 @@ def transcribe_chunks_with_connector(connector, filepath, filename, mime_type, l# Process each chunkchunk_results = []+ known_speaker_names = None+ known_speaker_refs = None # Dict of speaker label -> data URLfor i, chunk in enumerate(chunks):max_retries = 3@@ -1047,16 +1141,55 @@ def transcribe_chunks_with_connector(connector, filepath, filename, mime_type, l# Transcribe chunk using connectorwith open(chunk['path'], 'rb') as chunk_file:- request = TranscriptionRequest(- audio_file=chunk_file,- filename=chunk['filename'],- mime_type='audio/mpeg', # Chunks are always MP3- language=language,- diarize=False # Chunking doesn't support diarization- )+ # For diarization: first chunk gets diarize=True, subsequent chunks+ # get diarize=True + known_speaker_references+ if use_diarization:+ request = TranscriptionRequest(+ audio_file=chunk_file,+ filename=chunk['filename'],+ mime_type='audio/mpeg', # Chunks are always MP3+ language=language,+ diarize=True,+ known_speaker_names=known_speaker_names,+ known_speaker_references=known_speaker_refs+ )+ else:+ request = TranscriptionRequest(+ audio_file=chunk_file,+ filename=chunk['filename'],+ mime_type='audio/mpeg',+ language=language,+ diarize=False+ )response = connector.transcribe(request)+ # For the first diarized chunk, extract speaker samples for subsequent chunks+ if use_diarization and i == 0 and response.segments:+ current_app.logger.info(f"First chunk diarized with {len(response.speakers or [])} speakers, extracting samples...")++ # Extract speaker samples from the first chunk+ speaker_samples = extract_speaker_samples(+ audio_path=chunk['path'],+ segments=[{+ 'speaker': seg.speaker,+ 'start_time': seg.start_time,+ 'end_time': seg.end_time+ } for seg in response.segments],+ output_dir=temp_dir,+ min_duration=2.0,+ max_duration=10.0,+ max_speakers=4+ )++ if speaker_samples:+ # Convert to data URLs for the API+ known_speaker_refs = samples_to_data_urls(speaker_samples)+ known_speaker_names = list(known_speaker_refs.keys())+ current_app.logger.info(f"Extracted speaker references for {len(known_speaker_names)} speakers: {known_speaker_names}")+ else:+ current_app.logger.warning("Could not extract speaker samples from first chunk")+# Store chunk resultchunk_result = {'index': chunk['index'],@@ -1065,7 +1198,9 @@ def transcribe_chunks_with_connector(connector, filepath, filename, mime_type, l'duration': chunk['duration'],'size_mb': chunk['size_mb'],'transcription': response.text,- 'filename': chunk['filename']+ 'filename': chunk['filename'],+ 'segments': response.segments if use_diarization else None,+ 'speakers': response.speakers if use_diarization else None}chunk_results.append(chunk_result)current_app.logger.info(f"Chunk {i+1} transcribed successfully: {len(response.text)} characters")@@ -1096,15 +1231,38 @@ def transcribe_chunks_with_connector(connector, filepath, filename, mime_type, l# Merge transcriptionscurrent_app.logger.info(f"Merging {len(chunk_results)} chunk transcriptions...")- merged_transcription = chunking_service.merge_transcriptions(chunk_results)- if not merged_transcription.strip():- raise ChunkProcessingError("Merged transcription is empty")+ if use_diarization:+ # For diarized chunks, merge text AND segments with adjusted timestamps+ merged_text, merged_segments, all_speakers = merge_diarized_chunks(chunk_results)- # Log statistics- chunking_service.log_processing_statistics(chunk_results)+ if not merged_text.strip():+ raise ChunkProcessingError("Merged transcription is empty")- return merged_transcription+ # Log statistics+ chunking_service.log_processing_statistics(chunk_results)++ current_app.logger.info(f"Merged diarization: {len(merged_segments)} segments, {len(all_speakers)} speakers: {all_speakers}")++ # Return a TranscriptionResponse so segments are preserved+ from src.services.transcription import TranscriptionResponse+ return TranscriptionResponse(+ text=merged_text,+ segments=merged_segments,+ speakers=all_speakers,+ provider=connector.PROVIDER_NAME,+ model=getattr(connector, 'model', 'unknown')+ )+ else:+ merged_transcription = chunking_service.merge_transcriptions(chunk_results)++ if not merged_transcription.strip():+ raise ChunkProcessingError("Merged transcription is empty")++ # Log statistics+ chunking_service.log_processing_statistics(chunk_results)++ return merged_transcriptionexcept Exception as e:current_app.logger.error(f"Chunking transcription failed for {filepath}: {e}")@@ -1276,12 +1434,21 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file# Use chunking for large filesfile_size_mb = os.path.getsize(actual_filepath) / (1024 * 1024)current_app.logger.info(f"File {actual_filepath} is large ({file_size_mb:.1f}MB), using chunking for transcription")- transcription_text = transcribe_chunks_with_connector(- connector, actual_filepath, actual_filename, actual_content_type, language+ chunk_result = transcribe_chunks_with_connector(+ connector, actual_filepath, actual_filename, actual_content_type, language,+ diarize=should_diarize # Pass diarization setting for speaker reference tracking)- # Store as plain text (chunked transcription doesn't preserve diarization)- recording.transcription = transcription_text- current_app.logger.info(f"Chunked transcription completed: {len(transcription_text)} characters")++ # Handle result based on type (TranscriptionResponse for diarized, string for plain)+ if hasattr(chunk_result, 'segments') and chunk_result.segments and chunk_result.has_diarization():+ # Diarized response - store with segments for click-to-seek and speaker identification+ recording.transcription = chunk_result.to_storage_format()+ current_app.logger.info(f"Chunked diarized transcription completed: {len(chunk_result.text)} characters, {len(chunk_result.segments)} segments")+ else:+ # Plain text response+ transcription_text = chunk_result.text if hasattr(chunk_result, 'text') else chunk_result+ recording.transcription = transcription_text+ current_app.logger.info(f"Chunked transcription completed: {len(transcription_text)} characters")else:# Build the transcription request for single filewith open(actual_filepath, 'rb') as audio_file: