### 零件規格 ### # WEMOS LOLIN D32 ESP32 物聯網開發板的規格 https://www.wemos.cc/en/latest/d32/d32.html # WEMOS LOLIN D32 ESP32 的購買連結 https://reurl.cc/lQNZX6 # 購買電子零件的網站 https://shopee.tw/mirotek https://www.taiwansensor.com.tw/ https://www.taiwaniot.com.tw/ ### ex-01 ### # Thonny 下載 https://thonny.org ### ex-02 ### # 執行單行程式 >>> print('Hello World') # 使用內建函式 print(),在電腦上顯示 'Hello World' 字串物件 ### ex-03 ### # CH341SER 驅動程式 http://www.wch.cn/downloads/CH341SER_EXE.html ### ex-04 (LAB01.py) ### from machine import Pin # 從 machine 模組匯入 Pin 類別 import time # 匯入時間相關的 time 模組 led = Pin(5, Pin.OUT) # 建立 5 號腳位的 Pin 物件,設定為腳位輸出,命名為 led while True: led.value(1) # 熄滅 LED 燈 time.sleep(1) # 暫停 0.5 秒 led.value(0) # 點亮 LED 燈 time.sleep(1) # 暫停 0.5 秒 ### ex-05 ### # FM637A 範例程式下載 https://www.flag.com.tw/bk/t/FM637A ### ex-06 (LAB02.py) ### from machine import Pin import time led_pin = Pin(5, Pin.OUT) record_switch = Pin(18, Pin.IN, Pin.PULL_UP) # Pin.PULL_UP: 腳位設定上拉電阻 while True: print(record_switch.value()) # 在螢幕上印出按鈕狀態 if record_switch.value() == 0: # 若按下按鈕,點亮 LED led_pin.value(0) else: # 否則放開按鈕,熄滅 LED led_pin.value(1) time.sleep(0.1) ### ex-07 (LAB03.py) ### from machine import Pin, I2S # 增加 I2S 類別 import time led_pin = Pin(5, Pin.OUT) record_switch = Pin(18, Pin.IN, Pin.PULL_UP) mic_sample_rate = 4000 # 麥克風音訊採樣率 chunk_size = mic_sample_rate * 2 # 緩衝區大小為採樣率的兩倍 audio_in = I2S(0, # I2S 的編號 sck = Pin(25), # I2S 的硬體腳位 ws = Pin(27), # 同上 sd = Pin(26), # 同上 mode = I2S.RX, # 設定 I2S 為接收模式 bits = 16, # 音訊數據的位元數 format = I2S.MONO, # 設定為單聲道 (MONO) rate = mic_sample_rate, ibuf = chunk_size ) while True: if record_switch.value() == 0: # 若按下按鈕,準備啟動錄音 recording_time = 0 # 初始錄音時間 ibuf = bytearray(chunk_size) # 使用 btyearray() 建立空的二進制物件用以儲存音訊數據 pcm = open('/input.pcm', 'wb') # 使用 open() 建立新的空白錄音檔。'/input.pcm': 檔名; 'wb': 用二進制寫入檔案 led_pin.value(0) # 亮燈表示開始錄音 print('---請說話---') # 螢幕提示 '---請說話---' print('\r🎤:', recording_time, 's', end='') # 顯示已錄音的秒數 while record_switch.value() == 0 and recording_time < 11: # 當持續按下按鈕,且秒數 < 11 秒,繼續錄音 t_start = time.time() # t_start: 取得當前的系統時間 audio_in.readinto(ibuf, chunk_size) # 使用 audio_in.readinto() 錄音。ibuf: pcm.write(ibuf) # 將音訊數據存入錄音檔中 t_close = time.time() # t_close: 再次取得當前的系統時間 recording_time += (t_close - t_start) # 累計的錄音時間 print('\r🎤:', recording_time, 's', end = '') # 螢幕提示錄音時間 print('\n---說完了---') # 離開次要 while ,代表錄完了 led_pin.value(1) # 熄燈 pcm.close() # 關閉檔案 break # 離開主要 while time.sleep(0.1) ### ex-08 (LAB03-SERVER.py) ### from PCM2WAV import * pcm_file = 'input.pcm' # 已錄製好的檔名 wav_file = 'output.wav' # 欲輸出的檔名 pcm2wav(pcm_file, wav_file, channels = 1, bits = 16, sample_rate = 4000) # 將 pcm 檔轉成 wav 檔。pcm2wav(): PCM2WAV 模組內的函式 ### ex-09 ### # FFmpeg for Windows 下載網址 https://reurl.cc/nrD2G6 # FFmpeg for MAC 下載網址 https://reurl.cc/bD9gj3 ### ex-10 (LAB04.py) ### from machine import I2S, Pin from chat_tools import * # 匯入旗標寫的 chat_tool 模組 import time import gc # 匯入記憶體垃圾處理模組 led_pin = Pin(5, Pin.OUT) record_switch = Pin(18, Pin.IN, Pin.PULL_UP) spk_sample_rate = 8000 # 設定音訊放大器採樣率為 8000 Hz mic_sample_rate = 8000 # 設定麥克風音訊採樣率為 8000 Hz config(ssr=spk_sample_rate, msr=mic_sample_rate) # 設定音訊放大器採樣率為 8000 Hz audio_out = I2S(1, # 建立音訊放大器 I2S 物件 sck=Pin(12), ws=Pin(14), sd=Pin(13), mode=I2S.TX, bits=16, format=I2S.MONO, rate=spk_sample_rate, ibuf=8000) while True: if record_switch.value() == 0: # 若按下按鈕,則開始錄音 11 秒,然後播放 record(11) # 使用 chat_tool 模組裡的錄音函式 with open("input.pcm", "rb") as f: # 開啟 input.pcm 檔案 print('\n---播放---') while True: data = f.read(1024) # 每次讀取 1024 位元組大小的資料 if not data: # 若沒有資料則不再讀取 data = None break audio_out.write(data) # 將每次的資料寫入到音訊放大器中 gc.collect() # 回收 ESP32 的記憶體 time.sleep(0.1) ### ex-11 (LAB05.py) ### from machine import Pin, I2S import gc spk_sample_rate = 8000 audio_out = I2S(1, sck = Pin(12), ws = Pin(14), sd = Pin(13), mode = I2S.TX, bits = 16, format = I2S.MONO, rate = spk_sample_rate, ibuf = 8000) gc.collect() wav_file = open('music.wav', 'rb') # 開啟 music.wav 檔 chunk_size = 2048 header_size = 44 wav_file.seek(header_size) # 跳過音訊檔案的前 44 個位元組 (略過附帶格式的訊息) while True: wav_data = wav_file.read(chunk_size) if not wav_data: break audio_out.write(wav_data) wav_file.close() audio_out.deinit() gc.collect() ### ex-12 ### # 安裝 flask 後,測試模組 >>> import flask # 匯入 flask 模組 ### ex-13 (LAB06-SERVER.py) ### from flask import Flask # 匯入 flask 模組的 Flask 類別 app = Flask(__name__) # 建立 app @app.route("/") # 設定當收到針對 '/' 路徑 (網站根目錄) 的請求時,自動執行下方的 hello 函式 def hello(): return "Welcome to the audio server!" # 回傳字串 if __name__ == '__main__': # 當此程式為主程式執行時 app.run(host = '0.0.0.0', port = 5000) # 啟動 flask 程式,要公開給外部使用的伺服器程式,必須指定 IP 為 0.0.0.0 ### ex-14 (LAB06.py) ### from chat_tools import * import urequests wifi_connect("無線網路名稱", "無線網路密碼") # 設定 wifi url = "伺服器網址" # 欲連結的網址 (需含 http:// 或 https://) response = urequests.get(url) # 瀏覽網頁 print(response.text) # 顯示網頁內容的程式碼 ### ex-15 (LAB07-SERVER.py) ### from flask import Flask, request, send_file, abort import os app = Flask(__name__) # 建立 app # 根目錄 @app.route("/") def hello(): return "Welcome to the audio server!" # 下載音檔的路徑 @app.route('/download/', methods = ['GET']) def download_file(filename): if os.path.exists(filename): # 確認有回覆的音檔 return send_file(filename, as_attachment = True) else: return abort(404) # 沒有檔案則回覆 404 if __name__ == '__main__': app.run(host = '0.0.0.0', port = 5000) ### ex-16 (LAB07.py) ### from machine import Pin, I2S from chat_tools import * record_switch = Pin(18, Pin.IN, Pin.PULL_UP) wifi_connect("無線網路名稱", "無線網路密碼") url = "伺服器網址" # 伺服器的網址 config(n_url = url, rb = 2048, ssr = 20000) # 將常用參數傳入模組中 while True: if record_switch.value() == 0: audio_player(True, 'temp.wav') # 下載並播放伺服器上的 temp.wav 音檔 ### ex-17 (LAB08-SERVER.py) ### from flask import Flask, request, send_file, abort import os app = Flask(__name__) # 建立 app # 根目錄 @app.route("/") def hello(): return "Welcome to the audio server!" # 上傳 PCM 音檔 @app.route("/upload_audio", methods = ["POST"]) # 路徑設為 /upload_audio,代表使用者向網址 + /upload_audio 發送 POST 請求 def upload_audio(): audio_data = request.data with open("input.pcm", "wb") as audio_file: # 把音訊檔寫進 input.pcm 檔中,'w': 代表寫入文件,且會建立或覆蓋原有文件。'b': 代表以二進制形式寫入。 audio_file.write(audio_data) return "上傳成功" # 下載音檔的路徑 @app.route('/download/', methods = ['GET']) def download_file(filename): if os.path.exists(filename): # 確認有回覆的音檔 return send_file(filename, as_attachment = True) else: return abort(404) # 沒有檔案則回覆 404 if __name__ == '__main__': app.run(host = '0.0.0.0', port = 5000) ### ex-18 (LAB08.py) ### from machine import Pin, I2S from chat_tools import * import time led_pin = Pin(5, Pin.OUT) record_switch = Pin(18, Pin.IN, Pin.PULL_UP) wifi_connect("無線網路名稱", "無線網路密碼") url = "伺服器網址" config(n_url = url, rb = 2048, ssr = 8000, msr = 8000) while True: if record_switch.value() == 0: record(3) server_text = upload_pcm() # 上傳錄音檔至 Server print(f'server_text: {server_text}') audio_player(True, 'input.pcm') # 下載並播放 Server 上的錄音檔 ### ex-19 ### # OpenAI 官網 https://platform.openai.com/login ### ex-20 ### # OpenAI API key 測試用 sk-proj-0VyccJ1G4Apt8orzzxukT3BlbkFJ0k5ethV8xTR8ah7hoxZY ### ex-21 (LAB09-SERVER.py) ### from Chat_Module import * from flask import Flask, request # 建立 uploads 資料夾 make_upload_folder('uploads') app = Flask(__name__) # 建立 app # 根目錄-測試用 @app.route("/") def hello(): return "Welcome to the audio server!" # 上傳PCM音檔 @app.route("/upload_audio", methods=["POST"]) def upload_audio(): audio_data = request.data with open("uploads/input.pcm", "wb") as audio_file: audio_file.write(audio_data) user_text,error_info = speech_to_text() print(user_text) print('Error_info:',error_info) return user_text if __name__ == '__main__': app.run(host='0.0.0.0', port=80) ### ex-22 (LAB09.py) ### from machine import Pin, I2S from chat_tools import * import urequests import time led_pin = Pin(5, Pin.OUT) record_switch = Pin(18, Pin.IN, Pin.PULL_UP) wifi_connect("Deco", "pllai0207") url = "http://192.168.68.108" config(n_url=url, msr=4000) while True: if record_switch.value() == 0: record(7) server_reply = upload_pcm() print(f'語音辨識: {server_reply}') time.sleep(0.1) ### ex-23 (LAB10.py) ### from machine import Pin from chat_tools import * import time set_color(902,609,722) # 桃花色 time.sleep(5) close_light() time.sleep(1) start_rainbow() ### ex-24 (LAB11-SERVER.py) ### from Chat_Module import * from flask import Flask, request, jsonify app = Flask(__name__) uploads_dir = make_upload_folder('uploads') # 根目錄 @app.route("/") def hello(): return "Welcome to the audio server!" # 歡迎信息 # 上傳 PCM 音檔 input.pcm @app.route("/upload_audio", methods = ["POST"]) def upload_audio(): audio_data = request.data # 從請求中獲取音頻數據 with open(f'{uploads_dir}/input.pcm', "wb") as audio_file: audio_file.write(audio_data) # 將音頻數據寫入文件 return "上傳成功" # 返回上傳成功信息 # 處理聊天請求 @app.route("/chat", methods = ["GET"]) # 定義 chat 路徑為 get 請求 def chat(): cmd = '' # 參數初始值 user_text, error = speech_to_text() # 語音檔轉文字 light_list = ['開燈', '白色', '紅色', '綠色', '藍色', '黃色', '紫色', '藍綠色', '循環燈', '關燈'] # 關鍵字的串列 max_light_list = sorted(light_list, key = len, reverse = True) # 將串列中的字串長度由大排到小 match_cmd = [keyword for keyword in max_light_list if keyword in user_text] # 查找符合的關鍵字 if match_cmd: # 當語句中出現關鍵字 cmd = match_cmd[0] reply_dict = {"user": user_text, "cmd": cmd} # 返回用戶文字和匹配的指令 print(reply_dict) return jsonify(reply_dict) # 回傳使用者說的話,Server 回傳文字,與指令 if __name__ == '__main__': app.run(host = '0.0.0.0', port = 5000) # 運行伺服器,監聽所有主機地址和5000端口 ### ex-25 (LAB11.py) ### from machine import I2S, Pin from chat_tools import * record_switch = Pin(18, Pin.IN, Pin.PULL_UP) wifi_connect("無線網路名稱", "無線網路密碼") url = "伺服器網址" config(n_url = url, rb = 2048, ssr = 30000, msr = 4000) # 定義功能對應的字典,關鍵字對應相應的功能函式 function_mapping = { "開燈": lambda: set_color(1023, 1023, 1023), "白色": lambda: set_color(1023, 1023, 1023), "紅色": lambda: set_color(1023, 0, 0), "綠色": lambda: set_color(0, 1023, 0), "藍色": lambda: set_color(0, 0, 1023), "黃色": lambda: set_color(1023, 1023, 0), "紫色": lambda: set_color(1023, 0, 1023), "藍綠色": lambda: set_color(0, 1023, 1023), "循環燈": lambda: start_ranbow(), "關燈": lambda: close_light(), } # 主循環,持續監測錄音按鈕 while True: if record_switch.value() == 0: # 如果錄音按鈕被按下 record(7, LED=True) # 開始錄音,持續 7 秒,並啟用 LED 指示 response = upload_pcm() # 上傳錄音資料 if response == "error": # 如果上傳失敗,重新開始循環 continue server_reply = chat(url) # 與伺服器進行對話 cmd = server_reply["cmd"] # 獲取伺服器回覆的指令 print(f'你: {server_reply["user"]}') # 輸出使用者語音轉換的文字 print(f'關鍵字:{cmd}') # 輸出獲取的指令關鍵字 gc.collect() # 進行垃圾回收,釋放記憶體 if cmd in function_mapping: # 如果指令存在於功能對應字典中 function = function_mapping[cmd] # 獲取相應的功能函式 function() # 執行相應的功能 ### ex-26 (LAB12.py) ### from Chat_Module import * # 設置聊天配置 config(backtrace = 3, # 設置回溯訊息數量為3 system = "請使用繁體中文簡答,並只講重點。", # 設置系統提示訊息,要求使用繁體中文簡答,並只講重點 model="gpt-3.5-turbo", # 設置使用的模型為 gpt-3.5-turbo (或 gpt-4o) max_tokens = 500) # 設置最大回應字數為500 # 無限迴圈以持續與用戶進行對話 while True: user_text = input("USER: ") # 從用戶輸入取得文字 if user_text == '': # 若用戶輸入為空字串,則跳出迴圈 break reply, error_info, _ = chat_function(user_text) # 使用 chat_function 生成回應 print(f'ChatGPT: {reply}') # 輸出 ChatGPT 的回應 if error_info: # 若有錯誤訊息則輸出錯誤訊息 print(f'error: {error_info}') save_chat(user_text, reply) # 保存對話紀錄 ### ex-27 (LAB13.py) ### from Chat_Module import * make_upload_folder('uploads') # 創建名為 'uploads' 的上傳資料夾 sample_rate(30000) # 設定聲音輸出採樣率為 30000 Hz config(voice = "echo", db = 10) # 設定初始參數,聲音為 "echo",音量為 10 分貝 # 無窮迴圈,持續接收輸入 while True: text = input('輸入文字: ') # 提示使用者輸入文字 output_file = text_to_speech(text) # 將輸入的文字轉換為語音檔 print(f'已轉成語音檔: {output_file}') # 輸出生成的語音檔案名稱 ### ex-28 (LAB14-SERVER.py) ### import os from Chat_Module import * from flask import Flask, request, jsonify, send_file, abort app = Flask(__name__) uploads_dir = make_upload_folder('uploads') # 建立上傳目錄 # 根目錄路由 @app.route("/") def hello(): return "Welcome to the audio server!" # 上傳PCM音檔的路由 @app.route("/upload_audio", methods=["POST"]) def upload_audio(): audio_data = request.data # 獲取上傳的音訊數據 with open(f'{uploads_dir}/input.pcm', 'wb') as audio_file: # 打開目標檔案 audio_file.write(audio_data) # 寫入音訊數據 return "上傳成功" # 返回成功訊息 # 處理聊天請求的路由 @app.route("/chat", methods=["GET"]) def chat(): reply_text, error_info = '', '' # 初始化回覆文字和錯誤資訊 # =====處理錄音檔並轉成文字===== user_text, error = speech_to_text() # 語音轉文字 # =====判斷是否成功識別語音===== if user_text == "無法識別語音": # 如果語音識別失敗 reply_text = user_text # 回覆無法識別 else: # =====成功識別語音===== reply_text, error_info, _ = chat_function(user_text) # 呼叫聊天功能取得回覆 save_chat(user_text, reply_text) # 保存聊天記錄 print(f"USER:{user_text}") # 輸出用戶語音轉文字結果 print(f"Chatgpt:{reply_text}\nerror_info:{error_info}") # 輸出回覆和錯誤資訊 text_to_speech(reply_text) # 將回覆轉成語音 reply_dict = {"user": user_text, "reply": reply_text} # 構建回覆字典 return jsonify(reply_dict) # 返回回覆字典 # 下載音檔的路由 @app.route('/download/', methods=['GET']) def download_file(filename): file_path = f'{uploads_dir}/{filename}' # 構建文件路徑 if os.path.exists(file_path): # 確認文件是否存在 return send_file(file_path, as_attachment=True) # 傳送文件 else: return abort(404) # 文件不存在返回404錯誤 if __name__ == '__main__': sample_rate(30000) # 設定取樣率 config(voice="echo", db=10, backtrace=3, system="請使用繁體中文簡答,並只講重點。", model="gpt-3.5-turbo", max_tokens=500) # 設定系統配置 app.run(host='0.0.0.0', port=5000) # 啟動 Flask 服務 ### ex-29 (LAB14.py) ### from machine import I2S, Pin # 引入 I2S 和 Pin 類 from chat_tools import * # 引入自定義的聊天工具函式庫 # 定義錄音開關的引腳 (GPIO 18) record_switch = Pin(18, Pin.IN, Pin.PULL_UP) # 連接 Wi-Fi wifi_connect("無線網路名稱", "無線網路密碼") # 設定伺服器的 URL url = "伺服器網址" # 配置錄音參數,設置伺服器 URL,錄音緩衝區大小為 2048,錄音長度為 30 秒,最大取樣率為 4000 config(n_url=url, rb=2048, ssr=30000, msr=4000) while True: # 檢查錄音開關是否被按下 if record_switch.value() == 0: # 開始錄音,錄音時間為 7 秒,錄音期間 LED 燈亮 record(7, LED=True) # 上傳 PCM 錄音文件 response = upload_pcm() # 如果上傳過程中出現錯誤,則重新開始循環 if response == "error": continue # 從伺服器獲取聊天回應 server_reply = chat(url) # 打印使用者輸入和語音助理回應 print(f'你: {server_reply["user"]}') print(f'語音助理: {server_reply["reply"]}') # 進行垃圾回收以釋放記憶體 gc.collect() # 播放伺服器回應的語音文件 'temp.wav' audio_player(True, 'temp.wav') ### ex-30 (LAB15-SERVER.py) ### import os from Chat_Module import * from flask import Flask, request, jsonify, send_file, abort app = Flask(__name__) uploads_dir = make_upload_folder('uploads') # 根目錄 @app.route("/") def hello(): return "Welcome to the audio server!" # 上傳PCM音檔 @app.route("/upload_audio", methods=["POST"]) def upload_audio(): audio_data = request.data with open(f'{uploads_dir}/input.pcm', 'wb') as audio_file: audio_file.write(audio_data) return "上傳成功" # 處理聊天請求 @app.route("/chat", methods=["GET"]) def chat(): reply_text, error_info = '','' # =====處理錄音檔並轉成文字===== user_text,error = speech_to_text() # =====判斷是否成功識別語音===== if user_text == "無法識別語音": reply_text = user_text else:# =====成功識別語音===== functions = [ {"type": "function", "function": { "name": "translate", "description": "翻譯使用者要求的句子: 例如:我要去一趟" "超市義大利語->Al mio cane piace molto" " fare il bagno", "parameters": { "type": "object", "properties": { "target_result": { "type": "string", "description": "翻譯的結果, 如 " "Al mio cane piace molto fare il bagno" } }, "required": ["target_result"]} }} ] reply_text, error_info, _ = chat_function(user_text, functions) save_chat(user_text, reply_text) print(f"USER:{user_text}") print(f"Chatgpt:{reply_text}\nerror_info:{error_info}") text_to_speech(reply_text) reply_dict = {"user":user_text,"reply":reply_text} return jsonify(reply_dict) # 下載音檔的路徑 @app.route('/download/', methods=['GET']) def download_file(filename): file_path = f'{uploads_dir}/{filename}' if os.path.exists(file_path): # 確認有回覆的音檔 return send_file(file_path, as_attachment=True) else: return abort(404) if __name__ == '__main__': sample_rate(30000) config(voice="echo", db=10, backtrace=3, system="請使用繁體中文簡答,並只講重點。", model="gpt-3.5-turbo", max_tokens = 500) app.run(host='0.0.0.0', port=5000) ### ex-31 ### # google-search-API http://bit.ly/search_api ### ex-32 (LAB16.py) ### from Chat_Module import * chat_model = "gpt-3.5-turbo" # 定義聊天模型為 "gpt-3.5-turbo" user_text = "2024年有哪些電影" # 使用者輸入的文字 args = {"user_text":user_text} # 將使用者輸入的文字存入參數字典 search_config(API_KEY=False) # False 為使用搜尋套件 reply_text, cmd, error_info = google_search(args) # 使用 google_search 函數進行搜尋,傳入參數字典 print(reply_text) # 打印出回覆文字 ### ex-33 (LAB17-SERVER.py) ### import os from Chat_Module import * from flask import Flask, request, jsonify, send_file, abort app = Flask(__name__) uploads_dir = make_upload_folder('uploads') # 創建上傳文件夾 @app.route("/") # 根目錄 def hello(): return "Welcome to the audio server!" @app.route("/upload_audio", methods=["POST"]) # 上傳PCM音檔 def upload_audio(): audio_data = request.data with open(f'{uploads_dir}/input.pcm', 'wb') as audio_file: audio_file.write(audio_data) # 將上傳的音檔保存到指定位置 return "上傳成功" @app.route("/chat", methods=["GET"]) # 處理聊天請求 def chat(): reply_text, error_info = '', '' user_text, error = speech_to_text() # =====處理錄音檔並轉成文字===== if user_text == "無法識別語音": # =====判斷是否成功識別語音===== reply_text = user_text else: # =====成功識別語音===== functions = [ {"type": "function", "function": { "name": "translate", "description": "翻譯使用者要求的句子: 例如 我要去一趟超市" "義大利語->Al mio cane piace molto fare il bagno", "parameters": { "type": "object", "properties": { "target_result": { "type": "string", "description": "翻譯的結果, 如 Al mio cane piace molto fare il bagno" } }, "required": ["target_result"]} }}, {"type": "function", "function": { "name": "google_search", "description": "網路查詢,可以取得最新即時資訊,根據" "未知問題可使用此 function", "parameters": { "type": "object", "properties": { "user_text": { "type": "string", "description": "要搜尋的關鍵字, 必須是繁體中文" } }, "required": ["user_text"]} }} ] # 呼叫 chat_function 處理用戶語音轉文字的結果 reply_text, error_info, _ = chat_function(user_text, functions) save_chat(user_text, reply_text) # 保存聊天記錄 print(f"USER:{user_text}") print(f"Chatgpt:{reply_text}\nerror_info:{error_info}") text_to_speech(reply_text) # 將回覆文字轉成語音 reply_dict = {"user": user_text, "reply": reply_text} return jsonify(reply_dict) @app.route('/download/', methods=['GET']) # 下載音檔的路徑 def download_file(filename): file_path = f'{uploads_dir}/{filename}' if os.path.exists(file_path): # 確認有回覆的音檔 return send_file(file_path, as_attachment=True) else: return abort(404) if __name__ == '__main__': sample_rate(30000) # 設定樣本率 search_config(API_KEY=False) # 設定搜尋配置 config(voice="echo", db=10, backtrace=3, # 設定聊天模組配置 system="請使用繁體中文簡答,並只講重點。", model="gpt-3.5-turbo", max_tokens=500) app.run(host='0.0.0.0', port=5000) # 啟動 Flask 伺服器 ### ex-34 ### # TDX 官網 https://tdx.transportdata.tw # TDX Client Id (老師的,測試用) allwow5168-ad5a96cf-0ccf-41d5 # TDX Client Secret (老師的,測試用) 8a1703e8-773b-4886-bdfa-1f3c28453dee # OpenAI API key (老師的,測試用) sk-proj-0VyccJ1G4Apt8orzzxukT3BlbkFJ0k5ethV8xTR8ah7hoxZY # google-search-API key (老師的,測試用) AIzaSyCN35BTnhWgQeIUdMbM5aHqjnwPIQugVGU # google-search ID (老師的,測試用) 67460ddf4268e4eca ### ex-35 ### # ngrok 官網 https://ngrok.com ### ex-36 ### # 建立對外通道 ngrok http --scheme=http 5000