AlanRex commited on
Commit
f6e1e1a
·
verified ·
1 Parent(s): dfa305f

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +133 -32
main.py CHANGED
@@ -60,28 +60,12 @@ def create_calendar_event(booking_data, booking_id):
60
 
61
  try:
62
  date_str = booking_data['date']
63
- time_str = booking_data['time']
64
 
65
- time_patterns = [
66
- r'(\d{1,2}):(\d{2})\s*[-~到至]\s*(\d{1,2}):(\d{2})',
67
- r'(\d{1,2})\s*點\s*[-~到至]\s*(\d{1,2})\s*點',
68
- ]
69
-
70
- start_time = "09:00"
71
- end_time = "10:00"
72
-
73
- for pattern in time_patterns:
74
- match = re.search(pattern, time_str)
75
- if match:
76
- groups = match.groups()
77
- if len(groups) == 4:
78
- start_time = f"{int(groups[0]):02d}:{int(groups[1]):02d}"
79
- end_time = f"{int(groups[2]):02d}:{int(groups[3]):02d}"
80
- elif len(groups) == 2:
81
- start_time = f"{int(groups[0]):02d}:00"
82
- end_time = f"{int(groups[1]):02d}:00"
83
- break
84
 
 
85
  start_datetime = f"{date_str}T{start_time}:00"
86
  end_datetime = f"{date_str}T{end_time}:00"
87
 
@@ -91,6 +75,7 @@ def create_calendar_event(booking_data, booking_id):
91
  f'預約編號:{booking_id}\n'
92
  f'琴房:{booking_data["room"]}\n'
93
  f'人數:{booking_data["people"]}人\n'
 
94
  f'狀態:待確認'
95
  ),
96
  'start': {
@@ -181,6 +166,8 @@ def init_user_booking(user_id):
181
  "state": BookingState.IDLE,
182
  "date": None,
183
  "time": None,
 
 
184
  "people": None,
185
  "room": None,
186
  "last_update": time.time()
@@ -229,13 +216,119 @@ def parse_date(date_str):
229
  except ValueError:
230
  pass
231
 
232
- return None, "❌ 日期格式不正確\n例如:明天、2025-12-26"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
 
234
  def validate_time(time_str):
235
- time_keywords = ["點", "時", ":", "-", "到", "至", "~"]
236
- if any(kw in time_str for kw in time_keywords):
237
- return True, None
238
- return False, "❌ 時段格式不正確\n例如:09:00-11:00"
 
239
 
240
  def parse_people(people_str):
241
  numbers = re.findall(r'\d+', people_str)
@@ -275,6 +368,8 @@ def save_booking_to_file(user_id, booking_data):
275
  "user_id": user_id,
276
  "date": booking_data["date"],
277
  "time": booking_data["time"],
 
 
278
  "people": booking_data["people"],
279
  "room": booking_data["room"],
280
  "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
@@ -312,7 +407,7 @@ def handle_booking_flow(user_id, user_message):
312
  if current_state == BookingState.IDLE:
313
  if is_booking_keyword(user_message):
314
  booking["state"] = BookingState.ASKING_DATE
315
- return "🎹 琴房預約系統\n\n📅 請問預約日期?\n例如:明天、2025-12-26"
316
  return None
317
 
318
  elif current_state == BookingState.ASKING_DATE:
@@ -324,12 +419,18 @@ def handle_booking_flow(user_id, user_message):
324
  return f"✅ 日期:{parsed_date}\n\n⏰ 請問時段?\n例如:09:00-11:00"
325
 
326
  elif current_state == BookingState.ASKING_TIME:
327
- is_valid, error = validate_time(user_message)
328
- if not is_valid:
329
- return error
330
- booking["time"] = user_message
 
 
 
 
 
331
  booking["state"] = BookingState.ASKING_PEOPLE
332
- return f"✅ 時段:{user_message}\n\n👥 請問人數?\n例如:2人"
 
333
 
334
  elif current_state == BookingState.ASKING_PEOPLE:
335
  people_count, error = parse_people(user_message)
@@ -576,7 +677,7 @@ def handle_message(event):
576
  try:
577
  prompt = f"參考資料:{pdf_content}\n\n問題:{user_message}\n\n簡潔回答。" if pdf_content else user_message
578
 
579
- model = genai.GenerativeModel('gemini-2.5-flash')
580
  response = model.generate_content(prompt)
581
 
582
  out = response.text if response and response.text else "無法回答"
 
60
 
61
  try:
62
  date_str = booking_data['date']
 
63
 
64
+ # 直接使用已解析的時間
65
+ start_time = booking_data.get('start_time', '09:00')
66
+ end_time = booking_data.get('end_time', '10:00')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
+ # 建立 ISO 格式的時間
69
  start_datetime = f"{date_str}T{start_time}:00"
70
  end_datetime = f"{date_str}T{end_time}:00"
71
 
 
75
  f'預約編號:{booking_id}\n'
76
  f'琴房:{booking_data["room"]}\n'
77
  f'人數:{booking_data["people"]}人\n'
78
+ f'時段:{booking_data["time"]}\n'
79
  f'狀態:待確認'
80
  ),
81
  'start': {
 
166
  "state": BookingState.IDLE,
167
  "date": None,
168
  "time": None,
169
+ "start_time": None,
170
+ "end_time": None,
171
  "people": None,
172
  "room": None,
173
  "last_update": time.time()
 
216
  except ValueError:
217
  pass
218
 
219
+ return None, "❌ 日期格式不正確\n例如:明天、12/26"
220
+
221
+ def parse_time_range(time_str):
222
+ """解析並驗證時間範圍,返回標準格式"""
223
+
224
+ # 移除空格
225
+ time_str = time_str.replace(" ", "")
226
+
227
+ # 定義多種時間格式的正則表達式
228
+ patterns = [
229
+ # 標準格式:09:00-11:00, 9:00-11:00
230
+ (r'(\d{1,2}):(\d{2})[-~到至](\d{1,2}):(\d{2})', 'hh:mm-hh:mm'),
231
+ # 4位數格式:0900-1100
232
+ (r'(\d{4})[-~到至](\d{4})', 'hhmm-hhmm'),
233
+ # 中文格式:9點到11點, 下午2點到4點
234
+ (r'(?:上午|下午)?(\d{1,2})點(?:半)?[-~到至](?:上午|下午)?(\d{1,2})點(?:半)?', '中文'),
235
+ # 混合格式:9:00到11:00
236
+ (r'(\d{1,2}):(\d{2})[-~到至](\d{1,2})', 'h:mm-h'),
237
+ ]
238
+
239
+ start_hour = None
240
+ start_minute = None
241
+ end_hour = None
242
+ end_minute = None
243
+
244
+ for pattern, format_type in patterns:
245
+ match = re.search(pattern, time_str)
246
+ if match:
247
+ groups = match.groups()
248
+
249
+ if format_type == 'hh:mm-hh:mm':
250
+ # 09:00-11:00
251
+ start_hour = int(groups[0])
252
+ start_minute = int(groups[1])
253
+ end_hour = int(groups[2])
254
+ end_minute = int(groups[3])
255
+
256
+ elif format_type == 'hhmm-hhmm':
257
+ # 0900-1100
258
+ start_str = groups[0]
259
+ end_str = groups[1]
260
+
261
+ if len(start_str) == 4 and len(end_str) == 4:
262
+ start_hour = int(start_str[:2])
263
+ start_minute = int(start_str[2:])
264
+ end_hour = int(end_str[:2])
265
+ end_minute = int(end_str[2:])
266
+ else:
267
+ continue
268
+
269
+ elif format_type == '中文':
270
+ # 9點到11點
271
+ start_hour = int(groups[0])
272
+ start_minute = 0
273
+ end_hour = int(groups[1])
274
+ end_minute = 0
275
+
276
+ # 處理下午時間(如果有)
277
+ if '下午' in time_str and start_hour < 12:
278
+ start_hour += 12
279
+ if '下午' in time_str and end_hour < 12:
280
+ end_hour += 12
281
+
282
+ # 處理半點
283
+ if '半' in time_str.split('到')[0]:
284
+ start_minute = 30
285
+ if '半' in time_str.split('到')[1]:
286
+ end_minute = 30
287
+
288
+ elif format_type == 'h:mm-h':
289
+ # 9:00到11
290
+ start_hour = int(groups[0])
291
+ start_minute = int(groups[1])
292
+ end_hour = int(groups[2])
293
+ end_minute = 0
294
+
295
+ break
296
+
297
+ # 驗證解析結果
298
+ if start_hour is None or end_hour is None:
299
+ return None, None, None, None, "��� 時段格式不正確\n請使用以下格式:\n• 09:00-11:00\n• 0900-1100\n• 9點到11點\n• 下午2點到4點"
300
+
301
+ # 驗證時間有效性
302
+ if not (0 <= start_hour <= 23 and 0 <= end_hour <= 23):
303
+ return None, None, None, None, "❌ 小時必須在 0-23 之間"
304
+
305
+ if not (0 <= start_minute <= 59 and 0 <= end_minute <= 59):
306
+ return None, None, None, None, "❌ 分鐘必須在 0-59 之間"
307
+
308
+ # 計算時間(轉換為分鐘便於比較)
309
+ start_total = start_hour * 60 + start_minute
310
+ end_total = end_hour * 60 + end_minute
311
+
312
+ if start_total >= end_total:
313
+ return None, None, None, None, "❌ 結束時間必須晚於開始時間"
314
+
315
+ duration = (end_total - start_total) / 60
316
+ if duration > 8:
317
+ return None, None, None, None, "❌ 預約時段不能超過 8 小時"
318
+
319
+ # 返回標準格式
320
+ start_time = f"{start_hour:02d}:{start_minute:02d}"
321
+ end_time = f"{end_hour:02d}:{end_minute:02d}"
322
+ display_time = f"{start_time}-{end_time}"
323
+
324
+ return start_time, end_time, display_time, None, None
325
 
326
  def validate_time(time_str):
327
+ """驗證時間格式(保留向後兼容)"""
328
+ start_time, end_time, display_time, error, _ = parse_time_range(time_str)
329
+ if error:
330
+ return False, error
331
+ return True, None
332
 
333
  def parse_people(people_str):
334
  numbers = re.findall(r'\d+', people_str)
 
368
  "user_id": user_id,
369
  "date": booking_data["date"],
370
  "time": booking_data["time"],
371
+ "start_time": booking_data.get("start_time"),
372
+ "end_time": booking_data.get("end_time"),
373
  "people": booking_data["people"],
374
  "room": booking_data["room"],
375
  "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
 
407
  if current_state == BookingState.IDLE:
408
  if is_booking_keyword(user_message):
409
  booking["state"] = BookingState.ASKING_DATE
410
+ return "🎹 琴房預約系統\n\n📅 請問預約日期?\n例如:明天、12/26"
411
  return None
412
 
413
  elif current_state == BookingState.ASKING_DATE:
 
419
  return f"✅ 日期:{parsed_date}\n\n⏰ 請問時段?\n例如:09:00-11:00"
420
 
421
  elif current_state == BookingState.ASKING_TIME:
422
+ # 解析並驗證時間
423
+ start_time, end_time, display_time, error, err_msg = parse_time_range(user_message)
424
+ if error:
425
+ return err_msg
426
+
427
+ # 儲存標準格式
428
+ booking["time"] = display_time
429
+ booking["start_time"] = start_time
430
+ booking["end_time"] = end_time
431
  booking["state"] = BookingState.ASKING_PEOPLE
432
+
433
+ return f"✅ 時段:{display_time}\n\n👥 請問人數?\n例如:2人"
434
 
435
  elif current_state == BookingState.ASKING_PEOPLE:
436
  people_count, error = parse_people(user_message)
 
677
  try:
678
  prompt = f"參考資料:{pdf_content}\n\n問題:{user_message}\n\n簡潔回答。" if pdf_content else user_message
679
 
680
+ model = genai.GenerativeModel('gemini-1.5-flash')
681
  response = model.generate_content(prompt)
682
 
683
  out = response.text if response and response.text else "無法回答"