audio_parser.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import base64
  2. import logging
  3. import os
  4. import tempfile
  5. from typing import AsyncGenerator
  6. from core.base.parsers.base_parser import AsyncParser
  7. from core.base.providers import (
  8. CompletionProvider,
  9. DatabaseProvider,
  10. IngestionConfig,
  11. )
  12. logger = logging.getLogger()
  13. class AudioParser(AsyncParser[bytes]):
  14. """A parser for audio data using Whisper transcription."""
  15. def __init__(
  16. self,
  17. config: IngestionConfig,
  18. database_provider: DatabaseProvider,
  19. llm_provider: CompletionProvider,
  20. ):
  21. self.database_provider = database_provider
  22. self.llm_provider = llm_provider
  23. self.config = config
  24. try:
  25. from litellm import atranscription
  26. self.atranscription = atranscription
  27. except ImportError:
  28. logger.error("Failed to import LiteLLM transcription")
  29. raise ImportError(
  30. "Please install the `litellm` package to use the AudioParser."
  31. )
  32. async def ingest( # type: ignore
  33. self, data: bytes, **kwargs
  34. ) -> AsyncGenerator[str, None]:
  35. """
  36. Ingest audio data and yield a transcription using Whisper via LiteLLM.
  37. Args:
  38. data: Raw audio bytes
  39. *args, **kwargs: Additional arguments passed to the transcription call
  40. Yields:
  41. Chunks of transcribed text
  42. """
  43. try:
  44. # Create a temporary file to store the audio data
  45. with tempfile.NamedTemporaryFile(
  46. suffix=".wav", delete=False
  47. ) as temp_file:
  48. temp_file.write(data)
  49. temp_file_path = temp_file.name
  50. # Call Whisper transcription
  51. response = await self.atranscription(
  52. model=self.config.audio_transcription_model,
  53. file=open(temp_file_path, "rb"),
  54. **kwargs,
  55. )
  56. # The response should contain the transcribed text directly
  57. yield response.text
  58. except Exception as e:
  59. logger.error(f"Error processing audio with Whisper: {str(e)}")
  60. raise
  61. finally:
  62. # Clean up the temporary file
  63. try:
  64. os.unlink(temp_file_path)
  65. except Exception as e:
  66. logger.warning(f"Failed to delete temporary file: {str(e)}")