youngtsai commited on
Commit
6ef69da
·
1 Parent(s): 13da3b2

update_sheet_cell

Browse files
Files changed (1) hide show
  1. app.py +67 -54
app.py CHANGED
@@ -2270,12 +2270,30 @@ def refresh_video_LLM_all_content_by_sheet(sheet_url, sheet_qa_column, video_ids
2270
  video_id_col_index = header_row.index(target_id_column_name)
2271
  qa_col_index = header_row.index(target_qa_column_name)
2272
  # Google Sheet 的欄位字母 (A=0, B=1, ...)
2273
- qa_col_letter = chr(ord('A') + qa_col_index)
2274
  print(f"'{target_id_column_name}' 欄位索引: {video_id_col_index}")
2275
  print(f"'{target_qa_column_name}' 欄位索引: {qa_col_index} (欄位 {qa_col_letter})")
 
 
 
 
 
 
 
 
 
 
 
 
2276
  except ValueError as e:
2277
  print(f"錯誤:在標頭列 {header_row} 中找不到必要的欄位: {e}")
2278
  return {"success_video_ids": [], "failed_video_ids": []}
 
 
 
 
 
 
2279
 
2280
  video_id_to_row_map = {}
2281
  for i, row in enumerate(data_rows):
@@ -2314,26 +2332,29 @@ def refresh_video_LLM_all_content_by_sheet(sheet_url, sheet_qa_column, video_ids
2314
  ids_to_refresh.append(video_id) # 如果檢查出錯,也歸類為需要刷新
2315
 
2316
  # 5. 批次更新 "OO" (Phase 1: GCS 已存在)
2317
- if ids_to_set_oo_phase1:
2318
  print(f"\n準備批次更新 {len(ids_to_set_oo_phase1)} 個 Video ID 的 QA 為 '{sheet_qa_success_tag}' (GCS 已存在)...")
2319
  update_data_oo1 = []
2320
- sheet_name = SHEET_SERVICE.get_sheet_name_by_url(sheet_url) # 需要 SHEET_SERVICE 提供此方法
2321
- if not sheet_name:
2322
- print("錯誤:無法獲取工作表名稱,無法執行批次更新。")
2323
- # 或者可以嘗試從 sheet_data 推斷,但不夠通用
2324
- else:
2325
- for vid, row_num in ids_to_set_oo_phase1:
2326
- update_data_oo1.append({
2327
- 'range': f"{sheet_name}!{qa_col_letter}{row_num}",
2328
- 'value': sheet_qa_success_tag
2329
- })
2330
  try:
2331
  # *** 假設 SHEET_SERVICE.batch_update_cells 存在 ***
 
2332
  SHEET_SERVICE.batch_update_cells(sheet_url, update_data_oo1)
2333
  print(f"成功批次更新 {len(update_data_oo1)} 個儲存格為 '{sheet_qa_success_tag}'。")
2334
  except Exception as e:
2335
  print(f"批次更新 QA 為 '{sheet_qa_success_tag}' 時發生錯誤: {e}")
2336
  # 這裡可以考慮是否要將這些 ID 移到失敗列表
 
 
2337
 
2338
  # 6. 逐一處理需要刷新的 Video ID,並即時更新 Sheet 狀態
2339
  if ids_to_refresh:
@@ -2342,67 +2363,59 @@ def refresh_video_LLM_all_content_by_sheet(sheet_url, sheet_qa_column, video_ids
2342
  failed_refresh_ids = [] # 初始化失敗列表
2343
  # 這個迴圈負責執行刷新,並在每次完成後立即更新 Sheet
2344
  for video_id in ids_to_refresh:
2345
- row_number = video_id_to_row_map[video_id] # 必定存在,前面已檢查
2346
  print(f" 正在刷新 {video_id} (第 {row_number} 列)...")
2347
- update_request = None
2348
  try:
2349
  refresh_video_LLM_all_content_by_id(video_id)
2350
  print(f" - {video_id} 刷新成功。")
2351
  successfully_refreshed_ids.append((video_id, row_number)) # 仍然記錄成功,以備後續統計
2352
- # 準備單一成功更新請求
2353
- # *** 注意: 您需要確認 SHEET_NAME 和 STATUS_COL_LETTER ***
2354
- update_request = [{
2355
- 'range': f'{SHEET_NAME}!{STATUS_COL_LETTER}{row_number}', # 例如: '工作表1!G5'
2356
- 'values': [['OO']]
2357
- }]
2358
  time.sleep(1) # 避免過於頻繁觸發其他 API (例如 GCS 刪除/上傳)
2359
  except Exception as e:
2360
  print(f" - {video_id} 刷新失敗: {str(e)}")
2361
  failed_refresh_ids.append((video_id, row_number)) # 仍然記錄失敗,以備後續統計
2362
- # 準備單一失敗更新請求
2363
- # *** 注意: 您需要確認 SHEET_NAME 和 STATUS_COL_LETTER ***
2364
- update_request = [{
2365
- 'range': f'{SHEET_NAME}!{STATUS_COL_LETTER}{row_number}', # 例如: '工作表1!G5'
2366
- 'values': [['XX']]
2367
- }]
2368
  time.sleep(5) # 失敗時稍作停頓
2369
  finally:
2370
- # 無論成功或失敗,都嘗試更新該行的狀態
2371
- if update_request:
2372
  try:
2373
- print(f" - 更新 Sheet {row_number} 列狀態...")
2374
- # *** 假設 batch_update_cells 可以接受單一更新請求的列表 ***
2375
- # *** 注意: 您需要確認 batch_update_cells 函式存在且能處理此格式 ***
2376
- SHEET_SERVICE.batch_update_cells(sheet_url, update_request) # 假設使用 SHEET_SERVICE
2377
- print(f" - 第 {row_number} 列狀態更新成功。")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2378
  except Exception as update_e:
2379
- print(f" - !! 更新 Sheet 第 {row_number} 列狀態失敗: {str(update_e)}")
2380
- # 即使更新 Sheet 失敗,也要記錄下來,避免影響下一個影片的處理
2381
- # 可以在這裡加入更詳細的錯誤記錄機制
2382
-
2383
- # 7. 批次更新刷新結果 (OO for success, XX for failure) <-- 這段程式碼現在不需要了,因為已在迴圈內即時更新
2384
- # if successfully_refreshed_ids or failed_refresh_ids:
2385
- # print("\n開始批次更新 Google Sheet 刷新結果...")
2386
- # update_requests = []
2387
- # # ... (原本準備 update_requests 的程式碼) ...
2388
- #
2389
- # if update_requests:
2390
- # try:
2391
- # batch_update_cells(update_requests)
2392
- # print(f" 成功更新 {len(successfully_refreshed_ids)} 個成功,{len(failed_refresh_ids)} 個失敗的狀態。")
2393
- # except Exception as e:
2394
- # print(f" 批次更新 Google Sheet 失敗: {str(e)}")
2395
- # else:
2396
- # print(" 沒有需要更新的狀態。")
2397
-
2398
- # 8. 整理最終結果
2399
  final_success_ids = [item[0] for item in ids_to_set_oo_phase1] + [item[0] for item in successfully_refreshed_ids]
2400
  final_failed_ids = [item[0] for item in failed_refresh_ids]
2401
  # 將在工作表中找不到的 ID 也視為失敗
2402
  initial_not_found = [vid for vid in video_ids_list if vid not in video_id_to_row_map]
2403
  final_failed_ids.extend(initial_not_found)
2404
 
2405
- print("\n=== 批次處理完成 ===")
2406
  print(f"成功處理 (或 GCS 已存在): {len(final_success_ids)} 個")
2407
  print(f"處理失敗 (或未找到/刷新失敗): {len(final_failed_ids)} 個")
2408
 
 
2270
  video_id_col_index = header_row.index(target_id_column_name)
2271
  qa_col_index = header_row.index(target_qa_column_name)
2272
  # Google Sheet 的欄位字母 (A=0, B=1, ...)
2273
+ qa_col_letter = chr(ord('A') + qa_col_index) # <--- 使用這個變數
2274
  print(f"'{target_id_column_name}' 欄位索引: {video_id_col_index}")
2275
  print(f"'{target_qa_column_name}' 欄位索引: {qa_col_index} (欄位 {qa_col_letter})")
2276
+
2277
+ # *** 新增:嘗試取得工作表名稱 ***
2278
+ sheet_name = SHEET_SERVICE.get_sheet_name_by_url(sheet_url) # 假設 SHEET_SERVICE 有此方法
2279
+ if not sheet_name:
2280
+ print("錯誤:無法從 URL 獲取工作表名稱。將無法執行即時更新。")
2281
+ # 可以選擇在這裡 return 或設定一個標誌來跳過更新
2282
+ # return {"success_video_ids": [], "failed_video_ids": list(set(video_ids_list))} # 範例:直接返回失敗
2283
+ can_update_sheet = False
2284
+ else:
2285
+ print(f"取得工作表名稱: {sheet_name}")
2286
+ can_update_sheet = True
2287
+
2288
  except ValueError as e:
2289
  print(f"錯誤:在標頭列 {header_row} 中找不到必要的欄位: {e}")
2290
  return {"success_video_ids": [], "failed_video_ids": []}
2291
+ except AttributeError:
2292
+ print("錯誤:SHEET_SERVICE 可能沒有 get_sheet_name_by_url 方法。請確認或實作。")
2293
+ can_update_sheet = False
2294
+ except Exception as e: # 捕捉其他可能的錯誤
2295
+ print(f"取得工作表名稱時發生未預期錯誤: {e}")
2296
+ can_update_sheet = False
2297
 
2298
  video_id_to_row_map = {}
2299
  for i, row in enumerate(data_rows):
 
2332
  ids_to_refresh.append(video_id) # 如果檢查出錯,也歸類為需要刷新
2333
 
2334
  # 5. 批次更新 "OO" (Phase 1: GCS 已存在)
2335
+ if ids_to_set_oo_phase1 and can_update_sheet: # <--- 加上 can_update_sheet 檢查
2336
  print(f"\n準備批次更新 {len(ids_to_set_oo_phase1)} 個 Video ID 的 QA 為 '{sheet_qa_success_tag}' (GCS 已存在)...")
2337
  update_data_oo1 = []
2338
+ # sheet_name = SHEET_SERVICE.get_sheet_name_by_url(sheet_url) # 已在前面取得
2339
+ # if not sheet_name:
2340
+ # print("錯誤:無法獲取工作表名稱,無法執行批次更新。")
2341
+ # else:
2342
+ for vid, row_num in ids_to_set_oo_phase1:
2343
+ update_data_oo1.append({
2344
+ 'range': f"{sheet_name}!{qa_col_letter}{row_num}", # <--- 使用 sheet_name 和 qa_col_letter
2345
+ 'values': [[sheet_qa_success_tag]] # Google API batchUpdate 通常需要二維列表
2346
+ })
2347
+ if update_data_oo1: # 確保列表不是空的
2348
  try:
2349
  # *** 假設 SHEET_SERVICE.batch_update_cells 存在 ***
2350
+ # *** 注意:確認 batch_update_cells 的 value 格式是否需要 [[value]] ***
2351
  SHEET_SERVICE.batch_update_cells(sheet_url, update_data_oo1)
2352
  print(f"成功批次更新 {len(update_data_oo1)} 個儲存格為 '{sheet_qa_success_tag}'。")
2353
  except Exception as e:
2354
  print(f"批次更新 QA 為 '{sheet_qa_success_tag}' 時發生錯誤: {e}")
2355
  # 這裡可以考慮是否要將這些 ID 移到失敗列表
2356
+ elif ids_to_set_oo_phase1 and not can_update_sheet:
2357
+ print(f"\n警告:無法取得工作表名稱,跳過批次更新 {len(ids_to_set_oo_phase1)} 個 GCS 已存在的狀態。")
2358
 
2359
  # 6. 逐一處理需要刷新的 Video ID,並即時更新 Sheet 狀態
2360
  if ids_to_refresh:
 
2363
  failed_refresh_ids = [] # 初始化失敗列表
2364
  # 這個迴圈負責執行刷新,並在每次完成後立即更新 Sheet
2365
  for video_id in ids_to_refresh:
2366
+ row_number = video_id_to_row_map[video_id] # 必定存在,前面已檢查 (1-based sheet row number)
2367
  print(f" 正在刷新 {video_id} (第 {row_number} 列)...")
2368
+ current_status_tag = sheet_qa_failed_tag # 預設失敗
2369
  try:
2370
  refresh_video_LLM_all_content_by_id(video_id)
2371
  print(f" - {video_id} 刷新成功。")
2372
  successfully_refreshed_ids.append((video_id, row_number)) # 仍然記錄成功,以備後續統計
2373
+ current_status_tag = sheet_qa_success_tag # 設為成功
 
 
 
 
 
2374
  time.sleep(1) # 避免過於頻繁觸發其他 API (例如 GCS 刪除/上傳)
2375
  except Exception as e:
2376
  print(f" - {video_id} 刷新失敗: {str(e)}")
2377
  failed_refresh_ids.append((video_id, row_number)) # 仍然記錄失敗,以備後續統計
2378
+ current_status_tag = sheet_qa_failed_tag # 確認是失敗
 
 
 
 
 
2379
  time.sleep(5) # 失敗時稍作停頓
2380
  finally:
2381
+ # 無論成功或失敗,都嘗試更新該行的狀態 (如果可以更新 Sheet)
2382
+ if can_update_sheet: # <--- 加上 can_update_sheet 檢查
2383
  try:
2384
+ # *** 使用 update_sheet_cell 更新單一儲存格 ***
2385
+ # row_number 1-based 的實際列號
2386
+ # update_sheet_cell 需要 0-based 的索引,所以傳遞 row_number - 1
2387
+ target_row_index = row_number - 1
2388
+ print(f" - 更新 Sheet 第 {row_number} 列, 欄位索引 {qa_col_index} 狀態為 '{current_status_tag}'...")
2389
+
2390
+ # 呼叫 update_sheet_cell
2391
+ update_success = SHEET_SERVICE.update_sheet_cell(
2392
+ sheet_url=sheet_url,
2393
+ target_row_index_in_data=target_row_index, # 傳遞 0-based 索引
2394
+ qa_col_index=qa_col_index, # 傳遞 0-based 索引
2395
+ qa_result=current_status_tag # 傳遞要寫入的值
2396
+ )
2397
+
2398
+ if update_success:
2399
+ print(f" - 第 {row_number} 列狀態更新成功。")
2400
+ else:
2401
+ # update_sheet_cell 內部已經記錄了錯誤,這裡可以選擇性地再記錄一次
2402
+ print(f" - !! 更新 Sheet 第 {row_number} 列狀態失敗 (詳見先前日誌)。")
2403
+
2404
  except Exception as update_e:
2405
+ # 捕獲呼叫 update_sheet_cell 本身可能發生的意外錯誤
2406
+ print(f" - !! 呼叫 update_sheet_cell 時發生未預期錯誤: {str(update_e)}")
2407
+ # 即使更新 Sheet 失敗,也要記錄下來
2408
+ else:
2409
+ print(f" - 無法取得工作表名稱,跳過更新 Sheet {row_number} 列狀態。")
2410
+
2411
+ # 7. 整理最終結果 (移除舊的批次更新邏輯)
2412
+ print("\n=== 批次處理完成 ===")
 
 
 
 
 
 
 
 
 
 
 
 
2413
  final_success_ids = [item[0] for item in ids_to_set_oo_phase1] + [item[0] for item in successfully_refreshed_ids]
2414
  final_failed_ids = [item[0] for item in failed_refresh_ids]
2415
  # 將在工作表中找不到的 ID 也視為失敗
2416
  initial_not_found = [vid for vid in video_ids_list if vid not in video_id_to_row_map]
2417
  final_failed_ids.extend(initial_not_found)
2418
 
 
2419
  print(f"成功處理 (或 GCS 已存在): {len(final_success_ids)} 個")
2420
  print(f"處理失敗 (或未找到/刷新失敗): {len(final_failed_ids)} 個")
2421