audio_processing.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from openai import OpenAI
  2. from api.openai_scripts_tai_gi.config import SYSTEM_PROMPT, OPENAI_API_KEY, SUPABASE_KEY, SUPABASE_URL, ERROR_CORRECTION
  3. from supabase import create_client, Client
  4. from api.openai_scripts_tai_gi.text_processing import fuzzy_correct_chinese
  5. client = OpenAI(api_key=OPENAI_API_KEY)
  6. supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
  7. def transcribe(audio_file):
  8. try:
  9. table_name = "word_database"
  10. response = supabase.table(table_name).select("term").execute()
  11. custom_vocab = []
  12. if response.data:
  13. for item in response.data:
  14. custom_vocab.append({item['term']})
  15. else:
  16. print(f"No data found or an error occurred: {response.error}")
  17. print("Using default dictionary as Supabase data couldn't be fetched.")
  18. transcript = client.audio.transcriptions.create(
  19. file=audio_file,
  20. model="whisper-1",
  21. response_format="text",
  22. prompt=f"""你是一位專業的閩南語轉錄為中文校對助理,專門處理有關長照/日照中心的台語對話轉錄.
  23. 轉錄時對於「早餐、午餐、晚餐、幼兒園、國小、國中、高中、大學」等詞需特別注意。也需注意以下詞彙:{custom_vocab}"""
  24. )
  25. return transcript
  26. except Exception as e:
  27. print(f"轉錄時發生錯誤:{str(e)}")
  28. return None
  29. def post_process_transcript(transcript, temperature=0):
  30. corrected_transcript = fuzzy_correct_chinese(transcript)
  31. messages = [
  32. {"role": "system", "content": SYSTEM_PROMPT},
  33. {"role": "user", "content": f"請校對並修正下面引號內的轉錄文本且只需回傳修正後的文本內容:「{corrected_transcript}」,重點是要查看上述文本是否還有台語的部分,若有則需要修正為繁體中文意思,沒有的話只需要順一下句子。文本裡面若出現「{ERROR_CORRECTION}」這個字典中的字,就直接以此字典內的規則修正文本。最後強調,只需要回傳順過之後的文本,不用加其他不相干的字或是說明。"}
  34. ]
  35. response = client.chat.completions.create(
  36. model="gpt-4",
  37. temperature=temperature,
  38. messages=messages
  39. )
  40. return response.choices[0].message.content
  41. def process_audio(audio_data):
  42. raw_transcript = transcribe(audio_data)
  43. print(raw_transcript)
  44. if raw_transcript is None:
  45. return None, None
  46. corrected_transcript = post_process_transcript(raw_transcript)
  47. return raw_transcript, corrected_transcript