m8chaa commited on
Commit
8faf8a0
ยท
verified ยท
1 Parent(s): 760b248

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -74
app.py CHANGED
@@ -743,93 +743,84 @@ async def create_shortcut(file_id, parent_folder_id, name):
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 and detailed logging
747
  """
748
  try:
749
- # Log input parameters
750
  logging.info(f"Searching business info for company: '{company_name}', address: '{address}'")
751
 
752
  # Clean and normalize input strings
753
- company_name = company_name.replace("'", "''").strip()
754
- address = address.replace("'", "''").strip()
755
- logging.info(f"Normalized company name: '{company_name}', address: '{address}'")
756
 
757
- # Create multiple queries to increase chances of finding matches
758
- queries = [
759
- # Exact match query
760
- f"""
761
- SELECT B, C, L, M, N, O
762
- WHERE
763
- LOWER(B) = LOWER('{company_name}')
764
- OR LOWER(M) = LOWER('{address}')
765
- LIMIT 1
766
- """,
767
 
768
- # Partial match query for company name
769
- f"""
770
- SELECT B, C, L, M, N, O
771
- WHERE
772
- LOWER(B) CONTAINS LOWER('{company_name.replace("(์ฃผ)", "").strip()}')
773
- LIMIT 3
774
- """,
775
-
776
- # Partial match query for address
777
- f"""
778
- SELECT B, C, L, M, N, O
779
- WHERE
780
- LOWER(M) CONTAINS LOWER('{" ".join(address.split()[:3])}')
781
- LIMIT 3
782
- """
783
- ]
784
-
785
- range_name = f"๊ฒฝ๊ธฐ๋„!A2:Z"
786
- results = []
787
 
788
- # Execute each query and collect results
789
- for i, query in enumerate(queries):
790
- logging.info(f"Executing query {i+1}: {query.strip()}")
791
- result = sheet_service.spreadsheets().values().get(
792
- spreadsheetId=spreadsheet_id,
793
- range=range_name,
794
- valueRenderOption='UNFORMATTED_VALUE'
795
- ).execute()
796
 
797
- if result.get('values'):
798
- logging.info(f"Query {i+1} returned {len(result.get('values'))} results")
799
- results.extend(result.get('values', []))
800
- else:
801
- logging.info(f"Query {i+1} returned no results")
802
-
803
- logging.info(f"Total results before deduplication: {len(results)}")
804
-
805
- # Remove duplicates based on business number
806
- seen = set()
807
- unique_results = []
808
- for row in results:
809
- if len(row) >= 15:
810
- business_number = row[2] if len(row) > 2 else None
811
- if business_number and business_number not in seen:
812
- seen.add(business_number)
813
- unique_results.append(row)
814
- logging.info(f"Found unique business: Number={business_number}, Name={row[1] if len(row) > 1 else 'N/A'}")
815
-
816
- logging.info(f"Unique results after deduplication: {len(unique_results)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
817
 
818
- if not unique_results:
819
- logging.info("No matching business found")
820
  return None
821
 
822
- # Return the first match (highest priority query result)
823
- row = unique_results[0]
824
- result = {
825
- "์‚ฌ์—…์ž๋ฒˆํ˜ธ": str(row[2]) if len(row) > 2 else "",
826
- "๋Œ€ํ‘œ์ž๋ช…": str(row[11]) if len(row) > 11 else "",
827
- "์ „ํ™”๋ฒˆํ˜ธ": str(row[13]) if len(row) > 13 else "",
828
- "์šฐํŽธ๋ฒˆํ˜ธ": str(row[14]) if len(row) > 14 else "",
829
- }
830
 
831
- logging.info(f"Returning business info: {result}")
832
- return result
833
 
834
  except Exception as e:
835
  logging.error(f"Error searching business info: {str(e)}", exc_info=True)
 
743
 
744
  async def search_business_info(company_name: str, address: str, spreadsheet_id: str = '1YhbIaFFcz6mrMpA9yCSri8zaPL49V6v7l1YYt0AiKss') -> dict:
745
  """
746
+ Enhanced search for business information using fuzzy string matching and weighted scoring
747
  """
748
  try:
 
749
  logging.info(f"Searching business info for company: '{company_name}', address: '{address}'")
750
 
751
  # Clean and normalize input strings
752
+ company_name = company_name.strip().lower()
753
+ address = address.strip().lower()
 
754
 
755
+ # Remove common company suffixes for better matching
756
+ company_suffixes = ['(์ฃผ)', '(์œ )', '์ฃผ์‹ํšŒ์‚ฌ', '์œ ํ•œํšŒ์‚ฌ']
757
+ normalized_company = company_name
758
+ for suffix in company_suffixes:
759
+ normalized_company = normalized_company.replace(suffix.lower(), '').strip()
 
 
 
 
 
760
 
761
+ # Get all rows from the spreadsheet
762
+ range_name = "๊ฒฝ๊ธฐ๋„!A2:P" # Extending range to include all relevant columns
763
+ result = sheet_service.spreadsheets().values().get(
764
+ spreadsheetId=spreadsheet_id,
765
+ range=range_name,
766
+ valueRenderOption='UNFORMATTED_VALUE'
767
+ ).execute()
 
 
 
 
 
 
 
 
 
 
 
 
768
 
769
+ if not result.get('values'):
770
+ logging.info("No data found in spreadsheet")
771
+ return None
 
 
 
 
 
772
 
773
+ # Process each row and calculate match scores
774
+ matches = []
775
+ for row in result.get('values', []):
776
+ if len(row) < 15: # Skip incomplete rows
777
+ continue
778
+
779
+ db_company = str(row[1]).strip().lower() # Company name is in column B
780
+ db_address = str(row[12]).strip().lower() # Address is in column M
781
+
782
+ # Normalize database company name
783
+ normalized_db_company = db_company
784
+ for suffix in company_suffixes:
785
+ normalized_db_company = normalized_db_company.replace(suffix.lower(), '').strip()
786
+
787
+ # Calculate match scores
788
+ company_score = fuzz.token_sort_ratio(normalized_company, normalized_db_company)
789
+ address_score = fuzz.token_sort_ratio(address, db_address)
790
+
791
+ # Weight the scores (giving more weight to company name match)
792
+ total_score = (company_score * 0.7) + (address_score * 0.3)
793
+
794
+ # Only consider matches above certain thresholds
795
+ if company_score > 60 or address_score > 80:
796
+ matches.append({
797
+ 'score': total_score,
798
+ 'data': {
799
+ "์‚ฌ์—…์ž๋ฒˆํ˜ธ": str(row[2]) if len(row) > 2 else "",
800
+ "๋Œ€ํ‘œ์ž๋ช…": str(row[11]) if len(row) > 11 else "",
801
+ "์ „ํ™”๋ฒˆํ˜ธ": str(row[13]) if len(row) > 13 else "",
802
+ "์šฐํŽธ๋ฒˆํ˜ธ": str(row[14]) if len(row) > 14 else "",
803
+ },
804
+ 'company_score': company_score,
805
+ 'address_score': address_score
806
+ })
807
+
808
+ logging.info(f"Found potential match: {db_company}")
809
+ logging.info(f"Scores - Company: {company_score}, Address: {address_score}, Total: {total_score}")
810
 
811
+ if not matches:
812
+ logging.info("No matches found meeting the threshold criteria")
813
  return None
814
 
815
+ # Sort matches by total score and return the best match
816
+ matches.sort(key=lambda x: x['score'], reverse=True)
817
+ best_match = matches[0]
818
+
819
+ logging.info(f"Best match found with score {best_match['score']}")
820
+ logging.info(f"Company match score: {best_match['company_score']}")
821
+ logging.info(f"Address match score: {best_match['address_score']}")
 
822
 
823
+ return best_match['data']
 
824
 
825
  except Exception as e:
826
  logging.error(f"Error searching business info: {str(e)}", exc_info=True)