Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integrate OpenAI Whisper API for Enhanced Transcription Support #145

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions bot_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,15 @@
logger = logging.getLogger(__name__)

# Initialize services
aws_services = AWSServices()
audio_transcriber = AudioTranscriber(aws_services)
text_summarizer = TextSummarizer(os.environ.get('MARKETROUTER_API_KEY'))
from config import Config

aws_services = AWSServices() if Config.TRANSCRIPTION_SERVICE == 'aws' else None
audio_transcriber = AudioTranscriber(
aws_services=aws_services,
openai_api_key=Config.OPENAI_API_KEY,
service=Config.TRANSCRIPTION_SERVICE
)
text_summarizer = TextSummarizer(Config.MARKETROUTER_API_KEY)

def handle_update(update: Dict[str, Any]) -> None:
if 'message' in update:
Expand Down
2 changes: 2 additions & 0 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ class Config:
MARKETROUTER_API_KEY = os.environ.get('MARKETROUTER_API_KEY')
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')
TRANSCRIPTION_SERVICE = os.environ.get('TRANSCRIPTION_SERVICE', 'aws') # 'aws' or 'openai'
70 changes: 54 additions & 16 deletions services.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,33 +50,71 @@ def start_transcription_job(self, job_name, media_uri, media_format='ogg', langu
def get_transcription_job_status(self, job_name):
return self.transcribe_client.get_transcription_job(TranscriptionJobName=job_name)

class OpenAITranscriber:
def __init__(self, api_key: str):
self.api_key = api_key
self.api_url = "https://api.openai.com/v1/audio/transcriptions"

def transcribe_audio(self, audio_content: bytes) -> str:
try:
headers = {
"Authorization": f"Bearer {self.api_key}"
}

files = {
'file': ('audio.ogg', audio_content, 'audio/ogg'),
'model': (None, 'whisper-1'),
}

response = requests.post(self.api_url, headers=headers, files=files)
response.raise_for_status()

return response.json()['text']
except Exception as e:
logger.error(f"OpenAI transcription error: {e}")
raise

class AudioTranscriber:
def __init__(self, aws_services: AWSServices):
def __init__(self, aws_services: Optional[AWSServices] = None, openai_api_key: Optional[str] = None, service: str = 'aws'):
self.service = service
self.aws_services = aws_services
self.openai_transcriber = OpenAITranscriber(openai_api_key) if openai_api_key else None
self.bucket_name = 'audio-transcribe-temp'

if service == 'aws' and not aws_services:
raise ValueError("AWS services required for AWS transcription")
if service == 'openai' and not openai_api_key:
raise ValueError("OpenAI API key required for OpenAI transcription")

def transcribe_audio(self, file_url: str) -> str:
try:
self.aws_services.create_s3_bucket_if_not_exists(self.bucket_name)
logger.info(f"S3 Bucket created/confirmed: {self.bucket_name}")

audio_content = self._download_audio(file_url)
object_key = f'audio_{uuid.uuid4()}.ogg'
s3_uri = self.aws_services.upload_file_to_s3(audio_content, self.bucket_name, object_key)
logger.info(f"S3 URI: {s3_uri}")

job_name = f"whisper_job_{int(time.time())}"
self.aws_services.start_transcription_job(job_name, s3_uri)
logger.info(f"Transcription job started: {job_name}")

transcription = self._wait_for_transcription(job_name)
self.aws_services.delete_file_from_s3(self.bucket_name, object_key)

return transcription

if self.service == 'openai':
return self.openai_transcriber.transcribe_audio(audio_content)
else: # aws
return self._transcribe_with_aws(audio_content)
except Exception as e:
logger.error(f"An error occurred: {e}")
raise

def _transcribe_with_aws(self, audio_content: bytes) -> str:
self.aws_services.create_s3_bucket_if_not_exists(self.bucket_name)
logger.info(f"S3 Bucket created/confirmed: {self.bucket_name}")

object_key = f'audio_{uuid.uuid4()}.ogg'
s3_uri = self.aws_services.upload_file_to_s3(audio_content, self.bucket_name, object_key)
logger.info(f"S3 URI: {s3_uri}")

job_name = f"whisper_job_{int(time.time())}"
self.aws_services.start_transcription_job(job_name, s3_uri)
logger.info(f"Transcription job started: {job_name}")

transcription = self._wait_for_transcription(job_name)
self.aws_services.delete_file_from_s3(self.bucket_name, object_key)

return transcription

def _download_audio(self, file_url: str) -> bytes:
response = requests.get(file_url)
response.raise_for_status()
Expand Down