pythonでfirestoreデータ保存
import sounddevice as sd
from module.module_whisper import FasterWhisperModel
from module.module_recorder import Recorder
import time
from line_notify import LineNotify
from ollama_text_correction import OllamaTextCorrector
from line_bot_sender import LineBotSender
import firebase_admin
from firebase_admin import credentials, firestore
# Firebase Admin SDKの初期化
if not firebase_admin._apps:
cred = credentials.Certificate("serviceAccountKey.json") # 認証ファイルのパスに置き換え
firebase_admin.initialize_app(cred)
# Firestoreのクライアントを取得
db = firestore.client()
def save_to_firestore(user_id, text):
# Firestoreにメッセージを保存する関数
message_data = {
"user_id": user_id,
"text": text,
"timestamp": firestore.SERVER_TIMESTAMP,
"read": False
}
db.collection("messages").add(message_data)
def main():
recorder = Recorder()
fasterWhispermodel = FasterWhisperModel()
recognized_texts = []
line_notify = LineNotify("config.json")
text_corrector = OllamaTextCorrector("config.json")
line_bot_sender = LineBotSender("config.json")
while True:
start_time = time.time()
audio_data = recorder.speech2audio()
if time.time() - start_time >= 10:
print("10秒間音声が入力されなかったため、ループを終了します。")
break
if audio_data is None:
print("無音状態が続いたため、ループを終了します。")
break
# 音声をテキストに変換
text = fasterWhispermodel.audio2text(audio_data)
# Ollamaでテキストを構成
corrected_text = text_corrector.correct_text(text)
if corrected_text:
recognized_texts.append(corrected_text)
print(corrected_text)
# Firestoreにメッセージを保存
save_to_firestore("user_id_example", corrected_text) # user_idを適切に設定
if recognized_texts:
message = "\n".join(recognized_texts)
print("\n入力された音声テキスト一覧:")
print(message)
# LINE Notifyでメッセージを送信
line_notify.send(f"入力された音声テキスト一覧:\n{message}")
# LINE botで修正されたテキストを送信
line_bot_sender.send_message(f"修正された音声テキスト:\n{message}")
else:
print("入力メッセージはありませんでした")
if __name__ == "__main__":
main()
として
Firestoreでデータ保存するようにしたけど
[2024-11-10 06:39:11.240] [ctranslate2] [thread 3843030] [warning] The compute type inferred from the saved model is float16, but the target device or backend do not support efficient float16 computation. The model weights have been automatically converted to use the float32 compute type instead. stand by ready OK recording... finished 動作していますか WARNING: All log messages before absl::InitializeLog() is called are written to STDERR I0000 00:00:1731188374.394713 3843030 config.cc:230] gRPC experiments enabled: call_status_override_on_cancellation, event_engine_dns, event_engine_listener, http2_stats_fix, monitoring_experiment, pick_first_new, trace_record_callops, work_serializer_clears_time_cache stand by ready OK recording... finished 10秒間音声が入力されなかったため、ループを終了します。 入力された音声テキスト一覧: 動作していますか
となるが保存されているかわからない
対応策をGPTで調べる
このメッセージは、音声テキストが「動作していますか」と認識され、表示されていることを示しています。
ただし、Firestoreに保存されたかどうかについての情報が表示されていません。
Firestoreに保存されない原因と確認すべきポイントについて以下に示します。### 確認ポイント
1. **Firestoreの保存関数の確認**
Firestoreへの保存処理が正常に機能しているか確認するため、
以下のようにFirestore保存関数に`try-except`ブロックを追加して、エラーメッセージが出力されるようにします。“`python
def save_to_firestore(user_id, text):
try:
message_data = {
“user_id”: user_id,
“text”: text,
“timestamp”: firestore.SERVER_TIMESTAMP,
“read”: False
}
db.collection(“messages”).add(message_data)
print(“Firestoreに保存されました:”, text)
except Exception as e:
print(f”Firestoreに保存中にエラーが発生しました: {e}”)
“``main2.py`の実行中にエラーメッセージが出力されるか確認してください。
2. **Firestoreへの接続確認**
– `firebase_admin.initialize_app()`の認証情報が正しいか確認します。
特に、`serviceAccountKey.json`のファイルパスが正しいかを再度確認してください。
– Firestore Consoleで「messages」コレクションが生成されているか確認し、
データが追加されていない場合は、アクセス権限やネットワーク接続を再確認します。3. **Firestoreルールの設定確認**
Firebase ConsoleのFirestoreルールで読み書きが許可されているかを確認します。ルールの設定はテスト目的で以下のように設定し、保存されるか確認してみてください。“`plaintext
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
“`4. **デバッグ出力の追加**
Firestoreにデータが保存される直前と保存後に、以下のようなデバッグメッセージを出力すると、保存処理のどの段階で問題が発生しているか確認しやすくなります。“`python
print(“Firestoreに保存を開始します:”, text)
save_to_firestore(“user_id_example”, corrected_text)
print(“Firestoreへの保存処理が完了しました”)
“`これらの手順を試してみて、Firestoreにデータが保存されるかどうかを確認してください。
とのこと
import sounddevice as sd
from module.module_whisper import FasterWhisperModel
from module.module_recorder import Recorder
import time
from line_notify import LineNotify # 作成したLineNotifyモジュールをインポート
from ollama_text_correction import OllamaTextCorrector # Ollamaによる修正モジュールをインポート
from line_bot_sender import LineBotSender # LINE bot送信用のモジュールをインポート
import firebase_admin
from firebase_admin import credentials, firestore
# Firebase Admin SDKの初期化
if not firebase_admin._apps:
cred = credentials.Certificate("serviceAccountKey.json") # 認証ファイルのパスに置き換え
firebase_admin.initialize_app(cred)
# Firestoreのクライアントを取得
db = firestore.client()
def save_to_firestore(user_id, text):
# Firestoreにメッセージを保存する関数
try:
message_data = {
"user_id": user_id,
"text": text,
"timestamp": firestore.SERVER_TIMESTAMP,
"read": False
}
db.collection("messages").add(message_data)
print("Firestoreに保存されました:", text)
except Exception as e:
print(f"Firestoreに保存中にエラーが発生しました: {e}")
def main():
recorder = Recorder()
fasterWhispermodel = FasterWhisperModel()
# 入力された音声テキストを格納するリスト
recognized_texts = []
# LINE Notifyのモジュールを初期化(config.jsonからトークンを読み込む)
line_notify = LineNotify("config.json")
# Ollamaのテキスト修正モジュールを初期化
text_corrector = OllamaTextCorrector("config.json")
# LINE bot送信用のモジュールを初期化
line_bot_sender = LineBotSender("config.json")
while True:
start_time = time.time() # 処理開始時刻を記録
audio_data = recorder.speech2audio()
# 処理が10秒間行われなかった場合はループを抜ける
if time.time() - start_time >= 10:
print("10秒間音声が入力されなかったため、ループを終了します。")
break
if audio_data is None:
print("無音状態が続いたため、ループを終了します。")
break # 無音でループを抜ける
# 音声をテキストに変換
text = fasterWhispermodel.audio2text(audio_data)
# Ollamaでテキストを構成
corrected_text = text_corrector.correct_text(text)
if corrected_text: # Noneが返された場合はスキップ
recognized_texts.append(corrected_text)
print("認識されたテキスト:", corrected_text)
# Firestoreに保存を開始
print("Firestoreに保存を開始します:", corrected_text)
save_to_firestore("user_id_example", corrected_text) # user_idを適切に設定
print("Firestoreへの保存処理が完了しました")
# ループ終了後に、入力した音声テキストを改行付きで一覧表示
if recognized_texts:
message = "\n".join(recognized_texts)
print("\n入力された音声テキスト一覧:")
print(message)
# LINE Notifyでメッセージを送信
line_notify.send(f"入力された音声テキスト一覧:\n{message}")
# LINE botで修正されたテキストを送信
line_bot_sender.send_message(f"修正された音声テキスト:\n{message}")
else:
print("入力メッセージはありませんでした")
if __name__ == "__main__":
main()
へ修正する
実行すると
[2024-11-10 06:45:16.017] [ctranslate2] [thread 3848107] [warning] The compute type inferred from the saved model is float16, but the target device or backend do not support efficient float16 computation. The model weights have been automatically converted to use the float32 compute type instead. stand by ready OK recording... finished 認識されたテキスト: 今度はiCloud Driveに保存しますか Firestoreに保存を開始します: 今度はiCloud Driveに保存しますか WARNING: All log messages before absl::InitializeLog() is called are written to STDERR I0000 00:00:1731188739.927080 3848107 config.cc:230] gRPC experiments enabled: call_status_override_on_cancellation, event_engine_dns, event_engine_listener, http2_stats_fix, monitoring_experiment, pick_first_new, trace_record_callops, work_serializer_clears_time_cache Firestoreに保存されました: 今度はiCloud Driveに保存しますか Firestoreへの保存処理が完了しました stand by ready OK recording... finished 10秒間音声が入力されなかったため、ループを終了します。 入力された音声テキスト一覧: 今度はiCloud Driveに保存しますか
となる
これで firestoreへの保存はOK
次はこのメッセージを取得する