llama_asr.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. import os
  2. import argparse
  3. from openai import OpenAI
  4. from dotenv import load_dotenv
  5. import jieba
  6. from datetime import datetime
  7. from pypinyin import pinyin, Style
  8. from langchain_community.chat_models import ChatOllama
  9. from langchain.schema import HumanMessage, SystemMessage
  10. load_dotenv('environment.env')
  11. client = OpenAI()
  12. local_llm = "llama3-groq-tool-use:latest"
  13. llm = ChatOllama(model=local_llm, temperature=0)
  14. system_prompt = """你是一位專業的轉錄校對助理,專門處理有關溫室氣體、碳排放和碳管理的對話轉錄。
  15. 你的任務是:
  16. 1. 確保以下專業術語的準確性:溫室氣體、碳排放、碳管理、碳盤查、碳權交易、碳足跡、淨零排放、碳權。
  17. 2. 在必要時添加適當的標點符號,如句號、逗號
  18. 3. 使用台灣的繁體中文,確保語言表達符合台灣的用語習慣。
  19. 4. 只更正明顯的錯誤或改善可讀性,不要改變原文的意思或結構。
  20. 5. 不要回答問題、解釋概念或添加任何不在原文中的信息。
  21. 6. 如果原文是一個問句,保持它的問句形式,不要提供答案。
  22. 請只根據提供的原文進行必要的更正,不要添加或刪除任何實質性內容。在修正時,請特別注意上下文,確保修正後的詞語符合整句話的語境。"""
  23. def transcribe(audio_file):
  24. try:
  25. transcript = client.audio.transcriptions.create(
  26. file=audio_file,
  27. model="whisper-1",
  28. response_format="text"
  29. )
  30. return transcript
  31. except Exception as e:
  32. print(f"轉錄時發生錯誤:{str(e)}")
  33. return None
  34. def save_output(file_name, raw_transcript, corrected_transcript):
  35. output_dir = "output"
  36. os.makedirs(output_dir, exist_ok=True)
  37. output_file = os.path.join(output_dir, "transcription_results.txt")
  38. with open(output_file, "a", encoding="utf-8") as f:
  39. f.write(f"\n{'='*50}\n")
  40. f.write(f"文件名: {file_name}\n")
  41. f.write(f"處理時間: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
  42. f.write("原始轉錄:\n")
  43. f.write(f"{raw_transcript}\n\n")
  44. f.write("修正後的轉錄:\n")
  45. f.write(f"{corrected_transcript}\n")
  46. def process_audio_file(file_path):
  47. try:
  48. with open(file_path, "rb") as audio_file:
  49. file_size = os.path.getsize(file_path) / (1024 * 1024) # 轉換為 MB
  50. if file_size > 25:
  51. print(f"警告:文件 {os.path.basename(file_path)} 大小為 {file_size:.2f} MB,超過了 25 MB 的限制。可能無法處理。")
  52. print(f"\n處理文件:{os.path.basename(file_path)}")
  53. raw_transcript = transcribe(audio_file)
  54. if raw_transcript is None:
  55. return
  56. print("\n原始轉錄:")
  57. print(raw_transcript)
  58. corrected_transcript = post_process_transcript(raw_transcript)
  59. print("\n修正後的轉錄:")
  60. print(corrected_transcript)
  61. save_output(os.path.basename(file_path), raw_transcript, corrected_transcript)
  62. except Exception as e:
  63. print(f"處理文件 {os.path.basename(file_path)} 時發生錯誤:{str(e)}")
  64. def process_folder(folder_path):
  65. processed_files = 0
  66. for filename in os.listdir(folder_path):
  67. if filename.lower().endswith((".mp3", ".wav", ".m4a")):
  68. file_path = os.path.join(folder_path, filename)
  69. process_audio_file(file_path)
  70. processed_files += 1
  71. print("\n=== 總結 ===")
  72. print(f"處理的文件數:{processed_files}")
  73. def chinese_soundex(pinyin_str):
  74. soundex_map = {
  75. 'b': '1', 'p': '1', 'm': '1', 'f': '1',
  76. 'd': '2', 't': '2', 'n': '2', 'l': '2',
  77. 'g': '3', 'k': '3', 'h': '3',
  78. 'j': '4', 'q': '4', 'x': '4',
  79. 'zh': '5', 'ch': '5', 'sh': '5', 'r': '5',
  80. 'z': '6', 'c': '6', 's': '6',
  81. 'an': '7', 'ang': '7', 'en': '8', 'eng': '8', 'in': '8', 'ing': '8',
  82. 'ong': '9', 'un': '9', 'uan': '9',
  83. 'i': 'A', 'u': 'A', 'v': 'A', # 'v' is used for 'ü' in some systems
  84. 'e': 'B', 'o': 'B',
  85. }
  86. code = ''
  87. tone = '0'
  88. i = 0
  89. while i < len(pinyin_str):
  90. if pinyin_str[i:i+2] in soundex_map:
  91. code += soundex_map[pinyin_str[i:i+2]]
  92. i += 2
  93. elif pinyin_str[i] in soundex_map:
  94. code += soundex_map[pinyin_str[i]]
  95. i += 1
  96. elif pinyin_str[i].isdigit():
  97. tone = pinyin_str[i]
  98. i += 1
  99. else:
  100. i += 1
  101. code = code[:1] + ''.join(sorted(set(code[1:])))
  102. return (code[:3] + tone).ljust(4, '0')
  103. def compare_chinese_words(word1, word2, tone_sensitive=True):
  104. pinyin1 = ''.join([p[0] for p in pinyin(word1, style=Style.TONE3, neutral_tone_with_five=True)])
  105. pinyin2 = ''.join([p[0] for p in pinyin(word2, style=Style.TONE3, neutral_tone_with_five=True)])
  106. soundex1 = chinese_soundex(pinyin1)
  107. soundex2 = chinese_soundex(pinyin2)
  108. if tone_sensitive:
  109. return soundex1 == soundex2
  110. else:
  111. return soundex1[:3] == soundex2[:3]
  112. error_correction = {
  113. "看拳": "碳權",
  114. "看盤插": "碳盤查",
  115. "盤插": "盤查",
  116. "看": "碳"
  117. }
  118. def fuzzy_correct_chinese(text, correct_terms):
  119. words = jieba.cut(text)
  120. corrected_words = []
  121. for word in words:
  122. if word in error_correction:
  123. corrected_words.append(error_correction[word])
  124. else:
  125. for term in correct_terms:
  126. if compare_chinese_words(word, term, tone_sensitive=True):
  127. print(f"corrected: {word} -> {term}")
  128. corrected_words.append(term)
  129. break
  130. else:
  131. corrected_words.append(word)
  132. return ''.join(corrected_words)
  133. def post_process_transcript(transcript):
  134. correct_terms = ["碳", "溫室氣體", "碳排放", "排放", "碳管理", "管理", "碳盤查", "盤查", "碳權交易", "碳費",
  135. "碳權", "碳足跡", "足跡", "淨零排放", "零排放", "排放", "淨零",
  136. "氣候變遷法", "氣候", "氣候變遷", "法",
  137. "是什麼", "請解釋", "為什麼", "什麼意思",
  138. "台灣"]
  139. corrected_transcript = fuzzy_correct_chinese(transcript, correct_terms)
  140. # 準備輸入
  141. messages = [
  142. SystemMessage(content=system_prompt),
  143. HumanMessage(content=f"請校對並修正以下轉錄文本,但不要改變其原意或回答問題:\n\n{corrected_transcript}")
  144. ]
  145. # 使用 ChatOllama 生成回應
  146. response = llm(messages)
  147. return response.content
  148. def main():
  149. parser = argparse.ArgumentParser(description="處理音頻文件使用 llama3-groq-tool-use:latest 模型")
  150. parser.add_argument("--file", help="要處理的單個音頻文件的路徑")
  151. parser.add_argument("--folder", default="data", help="包含音頻文件的文件夾路徑(默認:data)")
  152. args = parser.parse_args()
  153. if args.file:
  154. if os.path.isfile(args.file):
  155. process_audio_file(args.file)
  156. else:
  157. print(f"錯誤:文件 '{args.file}' 不存在。")
  158. elif args.folder:
  159. if os.path.isdir(args.folder):
  160. process_folder(args.folder)
  161. else:
  162. print(f"錯誤:文件夾 '{args.folder}' 不存在。")
  163. else:
  164. print("錯誤:請指定一個文件(--file)或文件夾(--folder)來處理。")
  165. if __name__ == "__main__":
  166. main()