def transcribe_audio(audio_path, show_progress=True):
    """Transcribe audio file using the model with detailed progress reporting."""
    start_time = time.time()
    converted_path = None
    
    try:
        model = load_model()
        if model is None:
            return None
        
        processed_path, duration_sec = process_audio(audio_path)
        if processed_path is None:
            return None
        
        # Store converted path for cleanup
        if processed_path != audio_path:
            converted_path = processed_path

        # Handle long audio
        long_audio_settings_applied = False
        if duration_sec > LONG_AUDIO_THRESHOLD:
            try:
                custom_info(f"Audio longer than {LONG_AUDIO_THRESHOLD/60:.1f} minutes. Applying optimized settings...")
                model.change_attention_model("rel_pos_local_attn", [256, 256])
                model.change_subsampling_conv_chunking_factor(1)
                long_audio_settings_applied = True
            except Exception as e:
                custom_warning(f"Could not apply long audio settings: {str(e)}")
        
        try:
            if show_progress:
                with st.spinner("Transcribing audio..."):
                    progress_bar = st.progress(0)
                    estimated_total_time = duration_sec * 0.5
                    
                    def update_progress():
                        for i in range(1, 101):
                            elapsed = time.time() - start_time
                            if elapsed >= estimated_total_time:
                                break
                            progress = min(elapsed / estimated_total_time, 0.95)
                            progress_bar.progress(progress)
                            time.sleep(estimated_total_time / 100)
                    
                    import threading
                    progress_thread = threading.Thread(target=update_progress)
                    progress_thread.daemon = True
                    progress_thread.start()
                    
                    output = model.transcribe([processed_path], timestamps=True)
                    progress_bar.progress(1.0)
            else:
                output = model.transcribe([processed_path], timestamps=True)
            
            if not output or not isinstance(output, list) or not output[0] or not hasattr(output[0], 'timestamp'):
                custom_error("Transcription failed or produced unexpected output.")
                return None
            
            segment_timestamps = output[0].timestamp['segment']
            csv_data = [["From (s)", "To (s)", "From (time)", "To (time)", "Duration", "Transcription"]]
            
            for ts in segment_timestamps:
                start_s = ts['start']
                end_s = ts['end']
                start_formatted = format_time(start_s)
                end_formatted = format_time(end_s)
                duration = end_s - start_s
                
                csv_data.append([
                    f"{start_s:.2f}", 
                    f"{end_s:.2f}", 
                    start_formatted,
                    end_formatted,
                    f"{duration:.2f}",
                    ts['segment']
                ])
            
            processing_time = time.time() - start_time
            custom_success(f"Transcription completed in {processing_time:.1f} seconds!")
            
            filename = os.path.basename(audio_path)
            st.session_state.transcription_history.append({
                'filename': filename,
                'duration': duration_sec,
                'timestamp': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'csv_data': csv_data
            })
            
            return csv_data
            
        finally:
            if long_audio_settings_applied:
                try:
                    model.change_attention_model("rel_pos")
                    model.change_subsampling_conv_chunking_factor(-1)
                except Exception as e:
                    custom_warning(f"Issue reverting model settings: {str(e)}")
            
            # Cleanup all processed files
            if converted_path and os.path.exists(converted_path):
                os.remove(converted_path)
            
            torch.cuda.empty_cache()
            gc.collect()
            
    except Exception as e:
        custom_error(f"Error during transcription: {str(e)}")
        if "CUDA out of memory" in str(e):
            custom_info("GPU ran out of memory. Try a shorter audio file.")
        return None

def export_to_formats(csv_data):
    """Create exportable data in multiple formats"""
    # CSV
    csv_string = "\n".join([",".join([f'"{cell}"' if ',' in cell else cell for cell in row]) for row in csv_data])
    
    # Plain text
    text_string = "\n\n".join([row[5] for row in csv_data[1:]])
    
    # SRT format
    srt_string = ""
    for i, row in enumerate(csv_data[1:], 1):
        start_s = float(row[0])
        end_s = float(row[1])
        start_srt = f"{int(start_s//3600):02d}:{int((start_s%3600)//60):02d}:{int(start_s%60):02d},{int((start_s%1)*1000):03d}"
        end_srt = f"{int(end_s//3600):02d}:{int((end_s%3600)//60):02d}:{int(end_s%60):02d},{int((end_s%1)*1000):03d}"
        srt_string += f"{i}\n{start_srt} --> {end_srt}\n{row[5]}\n\n"
    
    return csv_string, text_string, srt_string