m8chaa commited on
Commit
63bad78
ยท
verified ยท
1 Parent(s): 4018018

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -68
app.py CHANGED
@@ -741,80 +741,103 @@ async def create_shortcut(file_id, parent_folder_id, name):
741
  # logging.error(f"Error searching business info: {e}")
742
  # return None
743
 
744
- async def search_business_info(company_name: str, address: str, spreadsheet_id: str = '1YhbIaFFcz6mrMpA9yCSri8zaPL49V6v7l1YYt0AiKss') -> dict:
745
- """
746
- Enhanced search for business information with improved matching logic
747
- """
748
  try:
749
- # Clean and normalize input strings
750
- company_name = company_name.replace("'", "''").strip()
751
- address = address.replace("'", "''").strip()
752
-
753
- # Create multiple queries to increase chances of finding matches
754
- queries = [
755
- # Exact match query
756
- f"""
757
- SELECT B, C, L, M, N, O
758
- WHERE
759
- LOWER(B) = LOWER('{company_name}')
760
- OR LOWER(M) = LOWER('{address}')
761
- LIMIT 1
762
- """,
763
-
764
- # Partial match query for company name
765
- f"""
766
- SELECT B, C, L, M, N, O
767
- WHERE
768
- LOWER(B) CONTAINS LOWER('{company_name.replace("(์ฃผ)", "").strip()}')
769
- LIMIT 3
770
- """,
771
-
772
- # Partial match query for address
773
- f"""
774
- SELECT B, C, L, M, N, O
775
- WHERE
776
- LOWER(M) CONTAINS LOWER('{" ".join(address.split()[:3])}')
777
- LIMIT 3
778
- """
779
- ]
780
-
781
- range_name = f"๊ฒฝ๊ธฐ๋„!A2:Z"
782
- results = []
783
 
784
- # Execute each query and collect results
785
- for query in queries:
786
- result = sheet_service.spreadsheets().values().get(
787
- spreadsheetId=spreadsheet_id,
788
- range=range_name,
789
- valueRenderOption='UNFORMATTED_VALUE'
790
- ).execute()
791
 
792
- if result.get('values'):
793
- results.extend(result.get('values', []))
794
-
795
- # Remove duplicates based on business number
796
- seen = set()
797
- unique_results = []
798
- for row in results:
799
- if len(row) >= 15 and row[2] not in seen:
800
- seen.add(row[2])
801
- unique_results.append(row)
802
 
803
- if not unique_results:
804
- return None
805
-
806
- # Return the first match (highest priority query result)
807
- row = unique_results[0]
808
- return {
809
- "์‚ฌ์—…์ž๋ฒˆํ˜ธ": str(row[2]) if len(row) > 2 else "",
810
- "๋Œ€ํ‘œ์ž๋ช…": str(row[11]) if len(row) > 11 else "",
811
- "์ „ํ™”๋ฒˆํ˜ธ": str(row[13]) if len(row) > 13 else "",
812
- "์šฐํŽธ๋ฒˆํ˜ธ": str(row[14]) if len(row) > 14 else "",
813
- }
814
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
815
  except Exception as e:
816
- logging.error(f"Error searching business info: {e}")
817
- return None
 
 
818
 
819
  async def update_user_sheets_and_folders(user_data, transaction_ref, transaction_data, image_id):
820
  try:
 
741
  # logging.error(f"Error searching business info: {e}")
742
  # return None
743
 
744
+ async def update_user_sheets_and_folders(user_data, transaction_ref, transaction_data, image_id):
 
 
 
745
  try:
746
+ parent_folders = [user_data['gDrive_metadata']['yungsoogi'], user_data['gDrive_metadata']['uploaded']]
747
+ logging.info(f"Starting GPT-4V processing for image: {image_id}")
748
+ dataJson = await request_gpt4o_completion(image_id, transaction_data['purchased_credit']['image_detection'], use_gpt4=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
749
 
750
+ if dataJson is None:
751
+ logging.error("GPT-4V returned None response")
752
+ return {"error": "An error occurred while processing the image"}
 
 
 
 
753
 
754
+ logging.info(f"GPT-4V response received: {dataJson}")
755
+ data = json.loads(dataJson)
 
 
 
 
 
 
 
 
756
 
757
+ # Log parsed data structure
758
+ found_receipt_no = len(data.get('receipts', []))
759
+ found_business_cards_no = len(data.get('busi_cards', []))
760
+ logging.info(f"Found {found_receipt_no} receipts and {found_business_cards_no} business cards")
 
 
 
 
 
 
 
761
 
762
+ new_folder = None
763
+ secondary_folder = None
764
+ timestamp = datetime.now(kst).strftime("%Y-%m-%d %H:%M:%S")
765
+
766
+ if found_receipt_no > 0:
767
+ new_folder = user_data['gDrive_metadata']['receipts']
768
+ receipts_data = convert_dicts_to_list(
769
+ data['receipts'],
770
+ receipt_sheet_headers,
771
+ add_link=True,
772
+ image_id=image_id,
773
+ link_text="๋ฐ”๋กœ๊ฐ€๊ธฐ",
774
+ link_position=1
775
+ )
776
+ logging.info(f"Preparing to update receipts sheet with data: {receipts_data}")
777
+ await update_user_sheet(user_data['gDrive_metadata']['spreadsheet'], "์˜์ˆ˜์ฆ", receipts_data)
778
+ logging.info("Receipt sheet updated successfully")
779
+
780
+ if found_business_cards_no > 0:
781
+ for card in data['busi_cards']:
782
+ if card.get('ํšŒ์‚ฌ๋ช…') and card.get('์ฃผ์†Œ'):
783
+ logging.info(f"Searching additional info for company: {card['ํšŒ์‚ฌ๋ช…']}")
784
+ additional_info = await search_business_info(card['ํšŒ์‚ฌ๋ช…'], card['์ฃผ์†Œ'])
785
+ logging.info(f"Additional info found: {additional_info}")
786
+
787
+ if additional_info:
788
+ if not card.get('์‚ฌ์—…์ž๋ฒˆํ˜ธ') and additional_info.get('์‚ฌ์—…์ž๋ฒˆํ˜ธ'):
789
+ card['์‚ฌ์—…์ž๋ฒˆํ˜ธ'] = additional_info['์‚ฌ์—…์ž๋ฒˆํ˜ธ']
790
+
791
+ extra_info = []
792
+ if additional_info.get('๋Œ€ํ‘œ์ž๋ช…'):
793
+ extra_info.append(f"๋Œ€ํ‘œ์ž: {additional_info['๋Œ€ํ‘œ์ž๋ช…']}")
794
+ if additional_info.get('์šฐํŽธ๋ฒˆํ˜ธ'):
795
+ extra_info.append(f"์šฐํŽธ๋ฒˆํ˜ธ: {additional_info['์šฐํŽธ๋ฒˆํ˜ธ']}")
796
+
797
+ if extra_info:
798
+ if '๊ธฐํƒ€' in card:
799
+ card['๊ธฐํƒ€'] += ", " + ", ".join(extra_info)
800
+ else:
801
+ card['๊ธฐํƒ€'] = ", ".join(extra_info)
802
+
803
+ if new_folder is None:
804
+ new_folder = user_data['gDrive_metadata']['business_cards']
805
+ else:
806
+ secondary_folder = user_data['gDrive_metadata']['business_cards']
807
+
808
+ business_cards_data = convert_dicts_to_list(
809
+ data['busi_cards'],
810
+ business_card_sheet_headers,
811
+ add_link=True,
812
+ image_id=image_id,
813
+ link_text="๋ช…ํ•จ๋ณด๊ธฐ",
814
+ link_position=10
815
+ )
816
+ logging.info(f"Preparing to update business cards sheet with data: {business_cards_data}")
817
+ await update_user_sheet(user_data['gDrive_metadata']['spreadsheet'], "๋ช…ํ•จ", business_cards_data)
818
+ logging.info("Business cards sheet updated successfully")
819
+
820
+ status = await update_fb_transaction(
821
+ transaction_ref,
822
+ no_receipts=found_receipt_no,
823
+ no_business_cards=found_business_cards_no
824
+ )
825
+ logging.info(f"Firebase transaction update status: {status}")
826
+
827
+ if status['status'] == "Success":
828
+ if new_folder:
829
+ await move_file_to_folder(image_id, parent_folders, [new_folder])
830
+ if secondary_folder:
831
+ await create_shortcut(image_id, secondary_folder, f"Shortcut to {image_id}")
832
+ return {"success": True}
833
+ else:
834
+ logging.error(f"Transaction update failed with status: {status['status']}")
835
+ return {"error": "An error has occurred while updating the transaction"}
836
  except Exception as e:
837
+ logging.error(f"An error occurred in update_user_sheets_and_folders: {str(e)}", exc_info=True)
838
+ # Move the image file to the error folder
839
+ await move_file_to_folder(image_id, parent_folders, [user_data['gDrive_metadata']['error']])
840
+ return {"error": str(e)}
841
 
842
  async def update_user_sheets_and_folders(user_data, transaction_ref, transaction_data, image_id):
843
  try: