-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.py
More file actions
168 lines (145 loc) · 6.89 KB
/
chat.py
File metadata and controls
168 lines (145 loc) · 6.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import os
import google.generativeai as genai
from response import parse_date, get_events
import speech_recognition as sr
from log import add
from read import read as read
import json
import datetime
rec=True
class GeminiAPIChatbot:
# 初期化メソッド
def __init__(self, api_key: str, model_name: str = 'gemini-2.0-flash', log_file: str = 'data/chat_log.json'):
genai.configure(api_key=api_key)
self.model = genai.GenerativeModel(model_name)
self.log_file = log_file
self.chat_history = self.load_chat_history()
# カレンダー質問判定メソッド
def is_calendar_query(self, user_input: str) -> bool:
calendar_keywords = ["予定", "スケジュール", "会議", "イベント"]
return any(keyword in user_input for keyword in calendar_keywords)
# カレンダー処理メソッド
def handle_calendar_query(self, user_input: str) -> str:
try:
start_time, end_time = parse_date(user_input)
if not start_time or not end_time:
return "指定された日時の予定が見つかりませんでした。"
events = get_events('primary', start_time, end_time)
if not events:
return "{}の予定はありません。".format(datetime.datetime.fromisoformat(start_time).strftime('%Y年%m月%d日'))
event_list = []
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
end = event['end'].get('dateTime', event['end'].get('date'))
summary = event.get('summary', '予定なし')
# 開始時刻と終了時刻を抽出
start_time_obj = datetime.datetime.fromisoformat(start)
end_time_obj = datetime.datetime.fromisoformat(end)
start_time_str = start_time_obj.strftime('%H:%M')
end_time_str = end_time_obj.strftime('%H:%M')
event_list.append(f"{start_time_str}から{end_time_str}に{summary}が")
return "{}の予定は{}あります。".format(datetime.datetime.fromisoformat(start_time).strftime('%Y年%m月%d日'), "、".join(event_list))
except Exception as e:
return f"予定確認中にエラーが発生しました: {e}"
# 雑談応答メソッド
def generate_response(self, user_input: str) -> str:
try:
# 感情分析(簡易版)
emotional_keywords = {
"嬉しい": "positive",
"楽しい": "positive",
"悲しい": "negative",
"困った": "negative",
"すごい": "positive",
"難しい": "negative"
}
user_emotion = "neutral"
for word, emotion in emotional_keywords.items():
if word in user_input:
user_emotion = emotion
break
# 過去の対話履歴を作成
context = "\n".join([
f"ユーザー: {log['user']}(感情: {emotional_keywords.get(log['user'], 'neutral')})\nBot: {log['bot']}"
for log in self.chat_history[-10:]
])
with open(f'data/config.json', 'r', encoding='utf-8') as f:
loadconfigs = json.load(f)
# プロンプト作成
prompt = (
"あなたの名前は晒屋時計です。\n"
f"ここは{loadconfigs['areaname']}です。\n"
"ユーザーの感情に寄り添い、フレンドリーかつ思いやりのある口調で答えてください。\n"
"また、返答は100文字程度で簡潔に回答してください。\n"
"ユーザーには音声ベースで伝えられます。絵文字は絶対に使わないでください。\n"
"以下は過去の対話です。ユーザーはできるだけ自然な会話を求めています。\n"
f"{context}\n\n"
f"ユーザー: {user_input}(感情: {user_emotion})\n"
"Bot:"
)
# Geminiモデルによる応答生成
response = self.model.generate_content(prompt)
return response.text.strip() if response.text else "すみません、よくわかりませんでした。"
except Exception as e:
return f"エラーが発生しました: {e}"
# チャットログの読み込み
def load_chat_history(self):
if os.path.exists(self.log_file):
with open(self.log_file, 'r', encoding='utf-8') as file:
try:
data = file.read().strip() # 空白行を除外
return json.loads(data) if data else []
except json.JSONDecodeError:
return [] # JSONエラーが出たら初期化
return []
# チャットログの保存
def save_chat_history(self):
with open(self.log_file, 'w', encoding='utf-8') as file:
json.dump(self.chat_history, file, ensure_ascii=False, indent=4)
# チャットログを追加
def add_chat_log(self, user_input: str, bot_response: str):
self.chat_history.append({"user": user_input, "bot": bot_response})
self.save_chat_history()
# 入力処理メソッド
def process_input(self, user_input: str) -> str:
if self.is_calendar_query(user_input):
return self.handle_calendar_query(user_input)
else:
return self.generate_response(user_input)
# APIキーの取得
api_key = "A"
# GeminiAPIChatbotのインスタンス作成
chatbot = GeminiAPIChatbot(api_key)
# Recognizerオブジェクトを作成
recognizer = sr.Recognizer()
while rec:
# マイクから音声を取得
try:
with sr.Microphone() as source:
print("話してください...")
recognizer.adjust_for_ambient_noise(source) # 周囲のノイズを調整
audio = recognizer.listen(source) # 音声を取得
except:
pass
# 音声をテキストに変換
try:
text = recognizer.recognize_google(audio, language="ja-JP") # 日本語対応
print(f"認識結果,{text}" )
if text.startswith("さらしや") or text.startswith("晒"):
text = text[len("さらしや"):]
text = text[len("晒"):]
else:
continue
add(f"認識結果,{text}" )
rec=False
response = chatbot.process_input(text).replace("😊","").replace("*","")
add(response)
read(response)
rec=True
# ログ追加
chatbot.save_chat_history()
chatbot.add_chat_log(text, response)
except sr.UnknownValueError:
add("recエラー,音声を認識できませんでした。")
except sr.RequestError:
add("recエラー,Google APIに接続できませんでした。")