Spaces:
Runtime error
Runtime error
Update app.py
Browse files208 unmodified lines20921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731877 unmodified lines3963973983994004014028 unmodified lines41141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362484 unmodified lines709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821208 unmodified lineslogging.error(f"Failed to move file {file_id} to new folders: {e}")async def update_user_sheet(spreadsheet_id:str, sheet_id:int, sheet_name, data: List[List[str]], is_reset: Optional[bool] = False):print(f"Spreadsheet ID: {spreadsheet_id}, Sheet ID: {sheet_id}, sheet name: {sheet_name}, Data: {data}")# first identify the area to insert the datano_of_rows = len(data)no_of_cols = len(data[0])if is_reset:# sheet_name = f"{sheet_name} {datetime.now(kst).strftime("%Y-%m-%d %H:%M:%S")}"sheet_name = f"{sheet_name} {datetime.now(kst).strftime('%Y-%m-%d %H:%M')}"duplicate_requests = [{"duplicateSheet": {"sourceSheetId": contacts_ss,"newSheetName": sheet_name}}]duplicate_response = sheet_service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id,body={'requests': duplicate_requests}).execute()sheet_id = duplicate_response['replies'][0]['duplicateSheet']['properties']['sheetId']# Insert new rowsrequests = [{"updateSheetProperties": {"properties": {"sheetId": sheet_id,"hidden": False},"fields": "hidden"}},{"insertDimension": {"range": {"sheetId": sheet_id,"dimension": "ROWS","startIndex": 1,"endIndex": no_of_rows + 1},"inheritFromBefore": False,}}]response = sheet_service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id,body={'requests': requests}).execute()update_body = {'values': data}start_column = 'A'end_column = chr(ord(start_column) + no_of_cols - 1)range_to_update = f'{sheet_name}!{start_column}2:{end_column}{no_of_rows + 1}'result = sheet_service.spreadsheets().values().update(spreadsheetId=spreadsheet_id,range=range_to_update,valueInputOption='USER_ENTERED',body=update_body).execute()# Format the cellsfor row_index, row in enumerate(data):for col_index, cell_value in enumerate(row):if cell_value.startswith('=HYPERLINK'):color = {"red": 0, "green": 0, "blue": 1} # Blue for hyperlinkselse:color = {"red": 0, "green": 0, "blue": 0} # Black for other textrequests = [{"repeatCell": {"range": {"sheetId": sheet_id,"startRowIndex": row_index + 1,"endRowIndex": row_index + 2,"startColumnIndex": col_index,"endColumnIndex": col_index + 1},"cell": {"userEnteredFormat": {"textFormat": {"foregroundColor": color}}},"fields": "userEnteredFormat.textFormat.foregroundColor"}}]response = sheet_service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id,body={'requests': requests}).execute()async def copy_sms_sheet(phone_no: str, spreadsheet_id: str):requests = [77 unmodified linesasync def edit_spreadsheet(target_sheet_id: str = Form(...)):try:# Retrieve the target spreadsheet's metadatatarget_spreadsheet = sheet_service.spreadsheets().get(spreadsheetId=target_sheet_id).execute()# Collect all sheet IDs in the target spreadsheettarget_sheet_ids = [sheet['properties']['sheetId'] for sheet in target_spreadsheet.get('sheets', [])]8 unmodified lines})# Retrieve the template spreadsheet's metadatatemplate_spreadsheet = sheet_service.spreadsheets().get(spreadsheetId=template_sheet_id).execute()# Iterate through each sheet in the template spreadsheetfor sheet in template_spreadsheet.get('sheets', []):sheet_id = sheet['properties']['sheetId']# Use the copyTo method to copy the sheet to the target spreadsheetcopy_request = sheet_service.spreadsheets().sheets().copyTo(spreadsheetId=template_sheet_id,sheetId=sheet_id,body={"destinationSpreadsheetId": target_sheet_id})copy_response = copy_request.execute()# Get the copied sheet IDcopied_sheet_id = copy_response['sheetId']# Rename the copied sheet to remove "Copy of"copied_sheet_title = sheet['properties']['title'].replace("Copy of ", "")rename_request = {"updateSheetProperties": {"properties": {"sheetId": copied_sheet_id,"title": copied_sheet_title},"fields": "title"}}# Execute rename requestsheet_service.spreadsheets().batchUpdate(spreadsheetId=target_sheet_id,body={"requests": [rename_request]}).execute()logging.info(f"Sheet {sheet['properties']['title']} copied and renamed to {copied_sheet_title} in {target_sheet_id}.")if requests:# Execute batch update to delete sheetsbatch_update_request = {"requests": requests}sheet_service.spreadsheets().batchUpdate(spreadsheetId=target_sheet_id,body=batch_update_request).execute()logging.info(f"Deleted existing sheets in target spreadsheet {target_sheet_id}.")logging.info(f"All sheets from template {template_sheet_id} copied to {target_sheet_id}.")return {"message": "Spreadsheet copied successfully"}except Exception as e:logging.error(f"Failed to copy sheets: {e}")return {"error": str(e)}# image upload# receive image id and user_id# check if they have enough credits# post to gpt4o with the user credit info# identify the sheet_id to update by checking in user_id# update user sheet# update firebase transaction# privatize the image and move the image to appropriate folder(s)# @app.post("/process-image")# async def process_photo(image_id: str = Form(...), user_id: str = Form(...)):# transaction_ref = transactions_collection_ref.document(user_id)# transaction = transaction_ref.get()# # If transaction does not exist, create a new one# if not transaction.exists:# transaction_ref.set({# "no_sms": 0,# "no_contacts": 0,# "no_receipts": 0,# "no_business_cards": 0,# "purchased_credit": {# "image_detection": 100,# "sync_data": 500,# }# })# transaction = transaction_ref.get()# transaction_data = transaction.to_dict()# # check if any of the limits have been reached# if transaction_data['no_receipts'] + transaction_data['no_business_cards'] >= transaction_data['purchased_credit']['image_detection']:# return {"error": "You have reached the limit of the number of items you can process. Please upgrade your plan."}# user_ref = users_collection_ref.document(user_id)# user = user_ref.get()# user_data = user.to_dict()# try:# parent_folders = [user_data['gDrive_metadata']['yungsoogi'], user_data['gDrive_metadata']['uploaded']]# dataJson = await request_gpt4o_completion(image_id, transaction_data['purchased_credit']['image_detection'])# if dataJson is None:# return {"error": "An error occurred while processing the image"}# data = json.loads(dataJson)# # Check if 'receipts' key exists and the length# found_receipt_no = len(data['receipts']) if 'receipts' in data else 0# found_business_cards_no = len(data['busi_cards']) if 'busi_cards' in data else 0# new_folders = []# timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")# # https://drive.google.com/file/d/1cFIA09PBqFjM8YvIz1D60p7HMGk1uBvo/view?usp=sharing# download_image_url = f"https://drive.google.com/uc?id={image_id}&export=download"# image_url = f"https://drive.google.com/file/d/{image_id}/view?usp=sharing"# # 이미지를 보여주어야 할때 =image({image_url})를 사용하고 갈 수 있는 경로를 만들때는 =HYPERLINK({image_url}, '바로가기')를 사용하세요.# if found_receipt_no > 0:# new_folders.append(user_data['gDrive_metadata']['receipts'])# receipts_data = convert_dicts_to_list(# data['receipts'],# add_link=True,# image_id=image_id,# link_text="바로가기",# link_position=1 # Link third# )# print(receipts_data)# await update_user_sheet(user_data['gDrive_metadata']['spreadsheet'], receipts_ss, "영수증", receipts_data)# if found_business_cards_no > 0:# new_folders.append(user_data['gDrive_metadata']['business_cards'])# business_cards_data = convert_dicts_to_list(# data['busi_cards'],# add_link=True,# image_id=image_id,# link_text="명함보기",# link_position=-1 # Link at the end# )# await update_user_sheet(user_data['gDrive_metadata']['spreadsheet'], business_cards_ss, "명함", business_cards_data)# print(f"{found_receipt_no}, {found_business_cards_no}")# status = await update_fb_transaction(# transaction_ref,# no_receipts=found_receipt_no,# no_business_cards=found_business_cards_no# )# if status['status'] == "Success":# await move_file_to_folder(image_id, parent_folders, new_folders)# return {"success": True}# else:# logging.error(f"Transaction update failed with status: {status['status']}")# return {"error": "An error has occurred while updating the transaction"}# except Exception as e:# logging.error(f"An error occurred: {e}")# # Move the image file to the error folder# await move_file_to_folder(image_id, parent_folders, user_data['gDrive_metadata']['error'])# return {"error": str(e)}# async def update_user_sheets_and_folders(user_data, transaction_ref, transaction_data, image_id):# try:# parent_folders = [user_data['gDrive_metadata']['yungsoogi'], user_data['gDrive_metadata']['uploaded']]# dataJson = await request_gpt4o_completion(image_id, transaction_data['purchased_credit']['image_detection'])# if dataJson is None:# return {"error": "An error occurred while processing the image"}# data = json.loads(dataJson)# # Check if 'receipts' key exists and the length# found_receipt_no = len(data['receipts']) if 'receipts' in data else 0# found_business_cards_no = len(data['busi_cards']) if 'busi_cards' in data else 0# new_folders = []# timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")# # https://drive.google.com/file/d/1cFIA09PBqFjM8YvIz1D60p7HMGk1uBvo/view?usp=sharing# download_image_url = f"https://drive.google.com/uc?id={image_id}&export=download"# image_url = f"https://drive.google.com/file/d/{image_id}/view?usp=sharing"# # 이미지를 보여주어야 할때 =image({image_url})를 사용하고 갈 수 있는 경로를 만들때는 =HYPERLINK({image_url}, '바로가기')를 사용하세요.# if found_receipt_no > 0:# new_folders.append(user_data['gDrive_metadata']['receipts'])# receipts_data = convert_dicts_to_list(# data['receipts'],# add_link=True,# image_id=image_id,# link_text="바로가기",# link_position=1 # Link third# )# print(receipts_data)# await update_user_sheet(user_data['gDrive_metadata']['spreadsheet'], receipts_ss, "영수증", receipts_data)# if found_business_cards_no > 0:# new_folders.append(user_data['gDrive_metadata']['business_cards'])# business_cards_data = convert_dicts_to_list(# data['busi_cards'],# add_link=True,# image_id=image_id,# link_text="명함보기",# link_position=-1 # Link at the end# )# await update_user_sheet(user_data['gDrive_metadata']['spreadsheet'], business_cards_ss, "명함", business_cards_data)# print(f"{found_receipt_no}, {found_business_cards_no}")# status = await update_fb_transaction(# transaction_ref,# no_receipts=found_receipt_no,# no_business_cards=found_business_cards_no# )# if status['status'] == "Success":# await move_file_to_folder(image_id, parent_folders, new_folders)# return {"success": True}# else:# logging.error(f"Transaction update failed with status: {status['status']}")# return {"error": "An error has occurred while updating the transaction"}# except Exception as e:# logging.error(f"An error occurred: {e}")# # Move the image file to the error folder# await move_file_to_folder(image_id, parent_folders, user_data['gDrive_metadata']['error'])# return {"error": str(e)}async def create_shortcut(file_id, parent_folder_id, name):try:file_metadata = {84 unmodified lines@app.post("/process-image")async def process_photo(background_tasks: BackgroundTasks, image_id: str = Form(...), user_id: str = Form(...)):transaction_ref = transactions_collection_ref.document(user_id)transaction = transaction_ref.get()if not transaction.exists:transaction_ref.set({"no_sms": 0,"no_contacts": 0,"no_receipts": 0,"no_business_cards": 0,"purchased_credit": {"image_detection": 100,"sync_data": 500,}})transaction = transaction_ref.get()transaction_data = transaction.to_dict()if transaction_data['no_receipts'] + transaction_data['no_business_cards'] >= transaction_data['purchased_credit']['image_detection']:return {"error": "You have reached the limit of the number of items you can process. Please upgrade your plan."}user_ref = users_collection_ref.document(user_id)user = user_ref.get()user_data = user.to_dict()background_tasks.add_task(update_user_sheets_and_folders, user_data, transaction_ref, transaction_data, image_id)return {"success": True}@app.post("/sync-data")async def process_photo(data_json: str = Form(...), user_id: str = Form(...)):# print(data_json)data: Dict[str, Any] = json.loads(data_json)transaction_ref = transactions_collection_ref.document(user_id)transaction = transaction_ref.get()if not transaction.exists:transaction_ref.set({"no_sms": 0,"no_contacts": 0,"no_receipts": 0,"no_business_cards": 0,"purchased_credit": {"image_detection": 100,"sync_data": 500,}})transaction = transaction_ref.get()transaction_data = transaction.to_dict()if transaction_data['no_contacts'] + transaction_data['no_sms'] >= transaction_data['purchased_credit']['sync_data']:return {"error": "You have reached the limit of the number of items you can process. Please upgrade your plan."}user_ref = users_collection_ref.document(user_id)user = user_ref.get()user_data = user.to_dict()try:if data['isContacts']:await update_user_sheet(user_data['gDrive_metadata']['spreadsheet'], contacts_ss, "연락처", data['data'], True)transaction_data['no_contacts'] += len(data['data'])transaction_ref.update({'no_contacts': transaction_data['no_contacts']})else:if 'sms_ids' not in user_data:print('No sms_ids')user_data['sms_ids'] = {}existing_phones = set(user_data.get('sms_ids', {}).keys())new_phones = [phone['address'] for phone in data['data'] if phone['address'] not in existing_phones]print(f"Existing phones: {existing_phones}")for phone_address in new_phones:new_sheet_id = await copy_sms_sheet(phone_address, user_data['gDrive_metadata']['spreadsheet'])print(f"New sheet id: {new_sheet_id}")user_data['sms_ids'][phone_address] = {'sheet_id': new_sheet_id, 'last_updated': "1970-01-01T00:00:00.000"}print(user_data['sms_ids'])updated_sms_count = 0for phone in data['data']:last_updated = user_data['sms_ids'][phone['address']]['last_updated']print(f"Last updated: {last_updated}")# Convert last_updated to datetime for comparisonlast_updated_dt = datetime.fromisoformat(last_updated)update_message = [sms for sms in phone['sms'] if datetime.fromisoformat(sms[0]) > last_updated_dt]print(f"Update message: {update_message}")if not update_message:continuesheet_id = user_data['sms_ids'][phone['address']]['sheet_id']print(f"Sheet ID: {sheet_id}")await update_user_sheet(user_data['gDrive_metadata']['spreadsheet'], sheet_id, 'SMS ' + phone['address'], update_message, False)user_data['sms_ids'][phone['address']]['last_updated'] = phone['sms'][0][0]updated_sms_count += len(update_message)user_ref.update({'sms_ids': user_data['sms_ids']})transaction_data['no_sms'] += updated_sms_counttransaction_ref.update({'no_sms': transaction_data['no_sms']})return {"success": True}except Exception as e:logging.error(f"An error occurred: {e}")return {"error": str(e)}208 unmodified lines20921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430577 unmodified lines3833843853863873883893903913923933943958 unmodified lines40440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847984 unmodified lines564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745208 unmodified lineslogging.error(f"Failed to move file {file_id} to new folders: {e}")# Update the update_user_sheets_and_folders function for better error handlingasync def update_user_sheets_and_folders(user_data, transaction_ref, transaction_data, image_id):try:parent_folders = [user_data['gDrive_metadata']['yungsoogi'], user_data['gDrive_metadata']['uploaded']]# Request GPT-4 completiondataJson = await request_gpt4o_completion(image_id, transaction_data['purchased_credit']['image_detection'])if dataJson is None:raise Exception("Failed to process the image with GPT-4")data = json.loads(dataJson)# Process receipts and business cardsfound_receipt_no = len(data.get('receipts', []))found_business_cards_no = len(data.get('busi_cards', []))new_folder = Nonesecondary_folder = Nonetimestamp = datetime.now(kst).strftime("%Y-%m-%d %H:%M:%S")# Process receiptsif found_receipt_no > 0:new_folder = user_data['gDrive_metadata']['receipts']receipts_data = convert_dicts_to_list(data['receipts'],receipt_sheet_headers,add_link=True,image_id=image_id,link_text="바로가기",link_position=1)try:await update_user_sheet(user_data['gDrive_metadata']['spreadsheet'], receipts_ss, "영수증", receipts_data)except HttpError as e:logging.error(f"Failed to update receipt sheet: {str(e)}")raise Exception("Failed to update receipt data in spreadsheet")# Process business cardsif found_business_cards_no > 0:if new_folder is None:new_folder = user_data['gDrive_metadata']['business_cards']else:secondary_folder = user_data['gDrive_metadata']['business_cards']business_cards_data = convert_dicts_to_list(data['busi_cards'],business_card_sheet_headers,add_link=True,image_id=image_id,link_text="명함보기",link_position=-1)try:await update_user_sheet(user_data['gDrive_metadata']['spreadsheet'], business_cards_ss, "명함", business_cards_data)except HttpError as e:logging.error(f"Failed to update business card sheet: {str(e)}")raise Exception("Failed to update business card data in spreadsheet")# Update Firebase transactionstatus = await update_fb_transaction(transaction_ref,no_receipts=found_receipt_no,no_business_cards=found_business_cards_no)if status['status'] != "Success":logging.error(f"Transaction update failed with status: {status['status']}")raise Exception("Failed to update transaction in Firebase")# Move file to appropriate folderif new_folder:try:await move_file_to_folder(image_id, parent_folders, [new_folder])if secondary_folder:await create_shortcut(image_id, secondary_folder, f"Shortcut to {image_id}")except HttpError as e:logging.error(f"Failed to move file or create shortcut: {str(e)}")raise Exception("Failed to organize processed image in Google Drive")logging.info(f"Successfully processed image {image_id} for user {user_data['uid']}")except Exception as e:logging.error(f"Error processing image {image_id} for user {user_data['uid']}: {str(e)}")try:# Move the image file to the error folderawait move_file_to_folder(image_id, parent_folders, [user_data['gDrive_metadata']['error']])logging.info(f"Moved image {image_id} to error folder for user {user_data['uid']}")except Exception as move_error:logging.error(f"Failed to move image {image_id} to error folder: {str(move_error)}")# You might want to update the transaction or user document to indicate the error# This depends on your error handling strategyasync def copy_sms_sheet(phone_no: str, spreadsheet_id: str):requests = [77 unmodified linesasync def edit_spreadsheet(target_sheet_id: str = Form(...)):try:# Retrieve the target spreadsheet's metadatatry:target_spreadsheet = sheet_service.spreadsheets().get(spreadsheetId=target_sheet_id).execute()except HttpError as e:if e.resp.status == 404:raise HTTPException(status_code=404, detail="Target spreadsheet not found")else:raise HTTPException(status_code=e.resp.status, detail=f"Error accessing target spreadsheet: {e.error_details}")# Collect all sheet IDs in the target spreadsheettarget_sheet_ids = [sheet['properties']['sheetId'] for sheet in target_spreadsheet.get('sheets', [])]8 unmodified lines})# Retrieve the template spreadsheet's metadatatry:template_spreadsheet = sheet_service.spreadsheets().get(spreadsheetId=template_sheet_id).execute()except HttpError as e:if e.resp.status == 404:raise HTTPException(status_code=404, detail="Template spreadsheet not found")else:raise HTTPException(status_code=e.resp.status, detail=f"Error accessing template spreadsheet: {e.error_details}")# Iterate through each sheet in the template spreadsheetfor sheet in template_spreadsheet.get('sheets', []):sheet_id = sheet['properties']['sheetId']try:# Use the copyTo method to copy the sheet to the target spreadsheetcopy_request = sheet_service.spreadsheets().sheets().copyTo(spreadsheetId=template_sheet_id,sheetId=sheet_id,body={"destinationSpreadsheetId": target_sheet_id})copy_response = copy_request.execute()# Get the copied sheet IDcopied_sheet_id = copy_response['sheetId']# Rename the copied sheet to remove "Copy of"copied_sheet_title = sheet['properties']['title'].replace("Copy of ", "")rename_request = {"updateSheetProperties": {"properties": {"sheetId": copied_sheet_id,"title": copied_sheet_title},"fields": "title"}}# Execute rename requestsheet_service.spreadsheets().batchUpdate(spreadsheetId=target_sheet_id,body={"requests": [rename_request]}).execute()logging.info(f"Sheet {sheet['properties']['title']} copied and renamed to {copied_sheet_title} in {target_sheet_id}.")except HttpError as e:logging.error(f"Error copying or renaming sheet {sheet['properties']['title']}: {e}")raise HTTPException(status_code=e.resp.status, detail=f"Error copying or renaming sheet: {e.error_details}")if requests:try:# Execute batch update to delete sheetsbatch_update_request = {"requests": requests}sheet_service.spreadsheets().batchUpdate(spreadsheetId=target_sheet_id,body=batch_update_request).execute()logging.info(f"Deleted existing sheets in target spreadsheet {target_sheet_id}.")except HttpError as e:logging.error(f"Error deleting existing sheets: {e}")raise HTTPException(status_code=e.resp.status, detail=f"Error deleting existing sheets: {e.error_details}")logging.info(f"All sheets from template {template_sheet_id} copied to {target_sheet_id}.")return {"message": "Spreadsheet copied successfully"}except HTTPException as he:# Re-raise HTTP exceptionsraise heexcept Exception as e:logging.error(f"Unexpected error in edit_spreadsheet: {e}")raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")async def create_shortcut(file_id, parent_folder_id, name):try:file_metadata = {84 unmodified lines@app.post("/process-image")async def process_photo(background_tasks: BackgroundTasks, image_id: str = Form(...), user_id: str = Form(...)):try:# Validate inputif not image_id or not user_id:raise HTTPException(status_code=400, detail="Both image_id and user_id are required")# Get transaction datatransaction_ref = transactions_collection_ref.document(user_id)transaction = transaction_ref.get()if not transaction.exists:# Initialize new transaction if it doesn't existtry:transaction_ref.set({"no_sms": 0,"no_contacts": 0,"no_receipts": 0,"no_business_cards": 0,"purchased_credit": {"image_detection": 100,"sync_data": 500,}})transaction = transaction_ref.get()except Exception as e:logging.error(f"Failed to initialize new transaction for user {user_id}: {str(e)}")raise HTTPException(status_code=500, detail="Failed to initialize user transaction")transaction_data = transaction.to_dict()# Check credit limitif transaction_data['no_receipts'] + transaction_data['no_business_cards'] >= transaction_data['purchased_credit']['image_detection']:raise HTTPException(status_code=403, detail="You have reached the limit of the number of items you can process. Please upgrade your plan.")# Get user datauser_ref = users_collection_ref.document(user_id)user = user_ref.get()if not user.exists:raise HTTPException(status_code=404, detail="User not found")user_data = user.to_dict()# Validate user dataif 'gDrive_metadata' not in user_data:raise HTTPException(status_code=400, detail="User Google Drive metadata not found")# Add task to backgroundtry:background_tasks.add_task(update_user_sheets_and_folders, user_data, transaction_ref, transaction_data, image_id)except Exception as e:logging.error(f"Failed to add background task for user {user_id}, image {image_id}: {str(e)}")raise HTTPException(status_code=500, detail="Failed to start image processing")return {"success": True, "message": "Image processing started"}except HTTPException as he:# Re-raise HTTP exceptionsraise heexcept Exception as e:logging.error(f"Unexpected error in process_photo for user {user_id}, image {image_id}: {str(e)}")raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")@app.post("/sync-data")async def sync_data(data_json: str = Form(...), user_id: str = Form(...)):try:# Validate inputif not data_json or not user_id:raise HTTPException(status_code=400, detail="Both data_json and user_id are required")# Parse JSON datatry:data: Dict[str, Any] = json.loads(data_json)except json.JSONDecodeError as e:logging.error(f"Invalid JSON data for user {user_id}: {str(e)}")raise HTTPException(status_code=400, detail="Invalid JSON data")# Get transaction datatransaction_ref = transactions_collection_ref.document(user_id)try:transaction = transaction_ref.get()if not transaction.exists:transaction_ref.set({"no_sms": 0,"no_contacts": 0,"no_receipts": 0,"no_business_cards": 0,"purchased_credit": {"image_detection": 100,"sync_data": 500,}})transaction = transaction_ref.get()except GoogleAPICallError as e:logging.error(f"Firebase error for user {user_id}: {str(e)}")raise HTTPException(status_code=500, detail="Error accessing user transaction data")transaction_data = transaction.to_dict()# Check credit limitif transaction_data['no_contacts'] + transaction_data['no_sms'] >= transaction_data['purchased_credit']['sync_data']:raise HTTPException(status_code=403, detail="You have reached the limit of the number of items you can process. Please upgrade your plan.")# Get user datauser_ref = users_collection_ref.document(user_id)try:user = user_ref.get()if not user.exists:raise HTTPException(status_code=404, detail="User not found")user_data = user.to_dict()except GoogleAPICallError as e:logging.error(f"Firebase error fetching user data for user {user_id}: {str(e)}")raise HTTPException(status_code=500, detail="Error accessing user data")# Process contactsif data.get('isContacts', False):try:await update_user_sheet(user_data['gDrive_metadata']['spreadsheet'], contacts_ss, "연락처", data['data'], True)new_contacts_count = len(data['data'])transaction_data['no_contacts'] += new_contacts_counttransaction_ref.update({'no_contacts': transaction_data['no_contacts']})logging.info(f"Updated {new_contacts_count} contacts for user {user_id}")except HttpError as e:logging.error(f"Google Sheets API error updating contacts for user {user_id}: {str(e)}")raise HTTPException(status_code=500, detail="Error updating contact data")except KeyError as e:logging.error(f"Missing key in user data for user {user_id}: {str(e)}")raise HTTPException(status_code=500, detail="Error accessing user Google Drive data")# Process SMSelse:if 'sms_ids' not in user_data:user_data['sms_ids'] = {}existing_phones = set(user_data.get('sms_ids', {}).keys())new_phones = [phone['address'] for phone in data['data'] if phone['address'] not in existing_phones]for phone_address in new_phones:try:new_sheet_id = await copy_sms_sheet(phone_address, user_data['gDrive_metadata']['spreadsheet'])user_data['sms_ids'][phone_address] = {'sheet_id': new_sheet_id, 'last_updated': "1970-01-01T00:00:00.000"}except HttpError as e:logging.error(f"Google Sheets API error creating new SMS sheet for user {user_id}, phone {phone_address}: {str(e)}")raise HTTPException(status_code=500, detail=f"Error creating new SMS sheet for phone {phone_address}")updated_sms_count = 0for phone in data['data']:try:last_updated = user_data['sms_ids'][phone['address']]['last_updated']last_updated_dt = datetime.fromisoformat(last_updated)update_message = [sms for sms in phone['sms'] if datetime.fromisoformat(sms[0]) > last_updated_dt]if update_message:sheet_id = user_data['sms_ids'][phone['address']]['sheet_id']await update_user_sheet(user_data['gDrive_metadata']['spreadsheet'], sheet_id, 'SMS ' + phone['address'], update_message, False)user_data['sms_ids'][phone['address']]['last_updated'] = phone['sms'][0][0]updated_sms_count += len(update_message)except KeyError as e:logging.error(f"Missing key in SMS data for user {user_id}, phone {phone['address']}: {str(e)}")continueexcept HttpError as e:logging.error(f"Google Sheets API error updating SMS for user {user_id}, phone {phone['address']}: {str(e)}")continuetry:user_ref.update({'sms_ids': user_data['sms_ids']})transaction_data['no_sms'] += updated_sms_counttransaction_ref.update({'no_sms': transaction_data['no_sms']})logging.info(f"Updated {updated_sms_count} SMS messages for user {user_id}")except GoogleAPICallError as e:logging.error(f"Firebase error updating user data for user {user_id}: {str(e)}")raise HTTPException(status_code=500, detail="Error updating user data")return {"success": True, "updated_count": new_contacts_count if data.get('isContacts', False) else updated_sms_count}except HTTPException as he:# Re-raise HTTP exceptionsraise heexcept Exception as e:logging.error(f"Unexpected error in sync_data for user {user_id}: {str(e)}")raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")
app.py+310-386