Business Matching: Reference Script
A ready-to-run Python version of the Business Matching Guidance. It reads a CSV of your records, runs the three tries with the checks from the guidance, and writes the matches, a rejections file, and a review file. It uses only the public Fusion endpoints and your own API key, read from the YELP_API_KEY environment variable.
Use it to get started, then make it yours. The script shows the approach working on your data in a few minutes. It isn't tuned for any particular list: expect to adjust the thresholds and options for your business types, and test on a sample before you rely on the results. Most teams port the logic into their own stack once they've settled their rules.
pip install requests rapidfuzz
export YELP_API_KEY="<your key>"
python3 yelp_business_matcher.py locations.csv
# Try one brand first
python3 yelp_business_matcher.py locations.csv --test-name "Example Hardware"
# A storefront list (restaurants, shops): reject Yelp listings that show no street address
python3 yelp_business_matcher.py restaurants.csv --no-street-listings reject
# A slower pace and smaller batch files
python3 yelp_business_matcher.py locations.csv --qps 2 --batch-size 10000
Input: a CSV with a header row. Required: name, city, state. Optional: address, address2, zip, phone, country, and location_count. Common header spellings ("Business Name", "Street Address", "postal_code") are detected, and every other column passes through to the output, so your own store IDs stay next to the Yelp IDs.
location_count (optional): how many locations the business has, from your own data. With 1 or 2, a same-name listing in the same zip can match even at another address, which catches small businesses that moved. Leave it blank to keep the address check strict.
Output, next to your input file:
matched_<input>.csv: every input row plus the match columns described in the guidance, includingbest_match_address_checkandbest_match_is_closed.matched_<input>_rejections.csv: every candidate that was turned down, and why. Start here when tuning.matched_<input>_manual_review.csv: Yelp IDs that 2 or more of your distinct records matched (distinct name and address, so exact duplicate rows don't count).
Errors: a row where a call still failed after retries gets input_error starting with "API error". Treat it as unknown, not as "no match": save those rows to a new CSV and run it again. If Yelp refuses your key (401 or 403), the script stops right away instead of writing empty results.
Things to tune for your list:
- The thresholds at the top of the script match the guidance's thresholds table.
GENERIC_TERMS: for a one-industry list, add its filler words (lowercase) so "Bella Hair Salon" vs "Luna Hair Salon" doesn't score high on "hair salon". Leave it empty for mixed lists.AFFILIATE_COMPANY_WORDS: company words plus a starter list of large networks (RE/MAX, Keller Williams, State Farm, Allstate and others). Add the brands common in your list so "Jane Doe - Brand Name" reads as a person.--no-street-listings:rejectfor storefronts,keep(default) for service-area businesses.
Optional first_names.txt: with a first-names list next to the script, it also detects people written as "First Last - Company" with no credential, and avoids treating opposite-gender names (Dan and Danielle) as nicknames. Each line is name,boy_share (share of babies with that name who were boys, 0 to 1, blank if unknown). You can build it from the U.S. Social Security Administration's public baby names data. Without it, people with credentials (MD, NP, Realtor and so on) are still detected.
The script
Copy the block below (the copy button keeps the indentation intact) and save it as yelp_business_matcher.py. The version date is at the top of the file; mention it if you contact us about the script.
#!/usr/bin/env python3
# Version 2026-12-01
"""
Yelp business matcher: map your business records to Yelp business IDs.
For each row of a CSV it calls three Yelp Fusion endpoints (Business Match, Phone Search and
Business Search), scores every candidate on name and location, and keeps a result only when it
passes the checks described in Yelp's Business Matching Guidance. People (doctors, agents, loan
officers) are matched to their own pages, and departments are linked to their parent listing.
Usage:
pip install requests rapidfuzz
export YELP_API_KEY="<your key>"
python3 yelp_business_matcher.py locations.csv
python3 yelp_business_matcher.py locations.csv --test-name "Example Hardware" # one brand only
python3 yelp_business_matcher.py locations.csv --qps 5 --batch-size 10000
python3 yelp_business_matcher.py restaurants.csv --no-street-listings reject # storefront list
Input: a CSV with a header row. Required columns: name, city, state. Optional: address, address2,
zip, phone, country, location_count (how many locations the business has, from your own data; 1 or 2
lets a same-name listing in the same zip match after a move). Common header spellings are detected.
Output (next to the input file):
matched_<input>.csv every input row plus the match columns
matched_<input>_rejections.csv candidates that were turned down, and why
matched_<input>_manual_review.csv business IDs that 2 or more different records matched
This is a starting point, not a finished integration. Results vary by business type and by how far
your records are from Yelp's; test it on a sample of your own records and tune it for your list.
Optional: put first_names.txt (lines of "name,boy_share") next to this script to detect people
written as "First Last - Company" without a credential. See the guide for how to build it.
"""
import argparse
import csv
import os
import re
import sys
import threading
import time
import unicodedata
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from functools import lru_cache
from math import asin, cos, radians, sin, sqrt
import requests
from rapidfuzz import fuzz
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
API_KEY = os.environ.get('YELP_API_KEY', '')
YELP_MATCH_URL = 'https://api.yelp.com/v3/businesses/matches'
YELP_PHONE_SEARCH_URL = 'https://api.yelp.com/v3/businesses/search/phone'
YELP_SEARCH_URL = 'https://api.yelp.com/v3/businesses/search'
SEARCH_LIMIT = 50
DEFAULT_QPS = 5 # per endpoint; keep it well within your key's limit
DEFAULT_WORKERS = 8
DEFAULT_BATCH_SIZE = 50_000
MAX_RETRIES = 3
RETRY_BASE_DELAY = 1 # seconds, doubles each retry
# Name and location thresholds (scores are 0-100)
MINIMUM_NAME_SCORE = 70 # Phone Search
CONFIDENCE_THRESHOLD = 75 # weak-fallback guard
CITY_STATE_ZIP_VERIFIED_THRESHOLD = 75 # Business Search result in the input's zip
CITY_STATE_UNVERIFIED_THRESHOLD = 85 # Business Search result without zip confirmation
CITY_STATE_MAX_MISMATCH_MILES = 25 # unverified result this far from known coordinates is rejected
CITY_STATE_MULTI_MATCH_ADDRESS_THRESHOLD = 60 # address score needed when 2+ candidates compete
BIZ_MULTI_RESULT_MIN_SCORE = 50
BIZ_SINGLE_RESULT_CONFIDENT_SCORE = 70 # a lone Business Match result below this needs the lead word
BIZ_CONFIDENT_SCORE = 85 # best matches below this get the lead-word check
BIZ_VERY_LOW_SCORE = 50 # below this the lead word itself must appear
SHARED_ID_REVIEW_THRESHOLD = 2 # distinct records (name + address) sharing one business ID -> review
NAME_AGREES_SCORE = 90 # name score at which two names "agree" (closed listings, same address)
NAME_CONTAINED_MIN_CHARS = 5 # one name inside the other counts only at this length ("Hot" vs "Hotline")
SMALL_BUSINESS_MAX_LOCATIONS = 2 # with a location_count column: businesses this small may match nearby
NO_STREET_LISTINGS = 'keep' # 'keep' or 'reject' Yelp listings with no street (--no-street-listings)
# People (doctors, clinicians, agents, loan officers)
PROVIDER_MIN_NAME_SCORE = 80
PROVIDER_SURNAME_CUTOFF = 90 # fuzz ratio for the surname to count as present
PROVIDER_FIRST_NAME_CUTOFF = 85 # fuzz ratio for the first name to count as present
PROVIDER_FULL_NAME_FLOOR = 90 # surname + first name
PROVIDER_INITIAL_FLOOR = 80 # surname + first initial
PROVIDER_NICKNAME_FLOOR = 80 # surname + nickname or short form (Phil / Phillip)
PROVIDER_SURNAME_ONLY_CAP = 65 # surname only
PROVIDER_FIRST_NAME_CONFLICT_CAP = 50 # surname + a different first name
INDIVIDUAL_LISTING_MAX_SCORE = 45 # business record vs one person's listing
PERSON_MIN_ADDRESS_SCORE = 60 # a person match must share the zip or score this on address
COMPANY_MIN_ADDRESS_SCORE = 60 # a person's company listing must be at their address
COMPANY_MIN_ORG_SCORE = 80 # record's company text vs listing name (token_set_ratio)
# Words common to your whole list's industry. They are removed before one of the name comparisons
# so "Bella Hair Salon" vs "Luna Hair Salon" doesn't score high for sharing "hair salon".
# Lowercase, no punctuation. Leave empty for a mixed list. Examples:
# beauty: ['hair', 'salon', 'spa', 'beauty', 'studio', 'nails', 'nail', 'lash', 'barber']
# fitness: ['fitness', 'gym', 'studio', 'yoga', 'pilates', 'training', 'crossfit']
# restaurants: ['restaurant', 'cafe', 'kitchen', 'bar', 'grill', 'bistro', 'diner', 'eatery']
GENERIC_TERMS = []
STATE_ABBREVIATIONS = {
'alabama': 'AL', 'alaska': 'AK', 'arizona': 'AZ', 'arkansas': 'AR',
'california': 'CA', 'colorado': 'CO', 'connecticut': 'CT', 'delaware': 'DE',
'florida': 'FL', 'georgia': 'GA', 'hawaii': 'HI', 'idaho': 'ID',
'illinois': 'IL', 'indiana': 'IN', 'iowa': 'IA', 'kansas': 'KS',
'kentucky': 'KY', 'louisiana': 'LA', 'maine': 'ME', 'maryland': 'MD',
'massachusetts': 'MA', 'michigan': 'MI', 'minnesota': 'MN', 'mississippi': 'MS',
'missouri': 'MO', 'montana': 'MT', 'nebraska': 'NE', 'nevada': 'NV',
'new hampshire': 'NH', 'new jersey': 'NJ', 'new mexico': 'NM', 'new york': 'NY',
'north carolina': 'NC', 'north dakota': 'ND', 'ohio': 'OH', 'oklahoma': 'OK',
'oregon': 'OR', 'pennsylvania': 'PA', 'rhode island': 'RI', 'south carolina': 'SC',
'south dakota': 'SD', 'tennessee': 'TN', 'texas': 'TX', 'utah': 'UT',
'vermont': 'VT', 'virginia': 'VA', 'washington': 'WA', 'west virginia': 'WV',
'wisconsin': 'WI', 'wyoming': 'WY', 'district of columbia': 'DC',
'alberta': 'AB', 'british columbia': 'BC', 'manitoba': 'MB', 'new brunswick': 'NB',
'newfoundland and labrador': 'NL', 'northwest territories': 'NT', 'nova scotia': 'NS',
'nunavut': 'NU', 'ontario': 'ON', 'prince edward island': 'PE', 'quebec': 'QC',
'saskatchewan': 'SK', 'yukon': 'YT',
'new south wales': 'NSW', 'victoria': 'VIC', 'queensland': 'QLD', 'south australia': 'SA',
'western australia': 'WA', 'tasmania': 'TAS', 'australian capital territory': 'ACT',
'northern territory': 'NT',
}
CANADIAN_PROVINCES = {'AB', 'BC', 'MB', 'NB', 'NL', 'NT', 'NS', 'NU', 'ON', 'PE', 'QC', 'SK', 'YT'}
AUSTRALIAN_STATES = {'NSW', 'VIC', 'QLD', 'TAS', 'ACT'}
AUSTRALIAN_AMBIGUOUS = {'SA', 'WA', 'NT'} # also US / Canadian codes; Australian only with a 4-digit postcode
# ---------------------------------------------------------------------------
# Person detection vocabulary
# ---------------------------------------------------------------------------
# Credential / degree tokens, compared uppercase with punctuation removed ("PA-C" -> "PAC")
PROVIDER_CREDENTIALS = {
'MD', 'DO', 'MBBS', 'DDS', 'DMD', 'DPM', 'OD', 'DC', 'ND', 'PHD', 'PSYD', 'EDD', 'PHARMD',
'NP', 'FNP', 'FNPC', 'FNPBC', 'ANP', 'AGNP', 'AGPCNP', 'ACNP', 'PMHNP', 'PMHNPBC', 'CNP',
'CPNP', 'CPNPPC', 'CRNP', 'APRN', 'APN', 'DNP', 'CNM', 'CRNA', 'RN', 'BSN', 'MSN',
'PA', 'PAC', 'LCSW', 'LICSW', 'LMSW', 'MSW', 'LPC', 'LPCC', 'LMFT', 'LMHC', 'LAC', 'LCPC',
'DPT', 'PT', 'OT', 'OTR', 'AUD', 'CCCSLP', 'RD', 'LD', 'RDN', 'DACM', 'MPH', 'MBA',
'FACC', 'FAAP', 'FACS', 'FACP', 'FACOG', 'FAAFP', 'FSCAI', 'FACE', 'FAAOS',
'NPC', 'AGNPC', 'AGACNP', 'AGACNPBC', 'ANPBC', 'PTA', 'COTA', 'CNS', 'LMT', 'ABPM', 'FRCPC', 'MSC',
'ARNP', 'APNP', 'LCMHC', 'LAT', 'ATC',
}
# Non-medical professional designations ("Jane Doe, Realtor", "John Smith CPA")
PROFESSIONAL_CREDENTIALS = {
'REALTOR', 'BROKER', 'CPA', 'ESQ', 'CFP', 'CHFC', 'CLU', 'JD', 'NMLS', 'CRPC', 'RICP',
'ABR', 'GRI', 'CRS', 'SRES',
}
PERSON_CREDENTIALS = PROVIDER_CREDENTIALS | PROFESSIONAL_CREDENTIALS
# Degrees that don't make a person on their own ("Pine Creek MPH" is a mobile home park)
SECONDARY_CREDENTIALS = {'MPH', 'MBA'}
# Credentials that are also US state codes ("Summit Chevrolet Bethlehem PA")
STATE_CODE_CREDENTIALS = {'MD', 'PA', 'DC', 'ND'}
# Credentials that are also street abbreviations: only count right after a comma ("Jane Doe, RD")
COMMA_ONLY_CREDENTIALS = {'RD'}
# Credential tokens are letters with optional periods/hyphens, so "3rd" can't read as RD
CREDENTIAL_TOKEN = re.compile(r'^[A-Za-z][A-Za-z.\-]*$')
DOCTOR_TITLE = re.compile(r'(?i)^\s*(?:the\s+office\s+of\s+)?dr\.?\s+(.+)$')
NAME_SUFFIXES = {'jr', 'sr', 'ii', 'iii', 'iv', 'v'}
NAME_NOISE = {'dr', 'doctor', 'the'}
# Words that mean the text before a "credential" is a business or place, not a person.
# Limited to words that aren't plausible surnames (Church, Bar, Law and Bank are real surnames).
NON_PERSON_WORDS = {
'of', 'and', 'for', 'at', 'center', 'centre', 'clinic', 'health', 'healthcare', 'medical',
'group', 'services', 'service', 'hospital', 'institute', 'specialty', 'surgical', 'associates',
'inc', 'llc', 'auto', 'tire', 'station', 'office', 'offices', 'care', 'family', 'pediatrics',
'rehabilitation', 'imaging', 'lab', 'labs', 'therapy', 'physical', 'location', 'township',
'tours', 'bus', 'hauling', 'motors', 'sales', 'parts', 'dealership', 'apartments', 'veterinary',
'chevrolet', 'chevy', 'nissan', 'toyota', 'honda', 'hyundai', 'subaru', 'buick', 'gmc', 'cadillac',
'chrysler', 'dodge', 'jeep', 'mazda', 'volkswagen', 'vw', 'bmw', 'audi', 'lexus', 'acura',
'infiniti', 'kia', 'mitsubishi', 'volvo', 'porsche', 'ave', 'blvd', 'hwy', 'floor', 'suite',
'orthopedics', 'dermatology', 'cardiology', 'urology', 'dental', 'dentistry', 'pediatric',
'mortgage', 'realty', 'financial', 'insurance', 'agency', 'lending', 'loans', 'credit', 'union',
'properties', 'estate', 'team', 'capital', 'partners', 'heights', 'vista', 'manor', 'village',
'gardens', 'commons', 'terrace', 'pointe', 'landing', 'estates', 'townhomes', 'lofts',
'residences', 'tower', 'towers', 'collision', 'emergency', 'physicians', 'childrens', 'military',
'housing', 'community', 'resort', 'cottage', 'apartment', 'living', 'wealth', 'advisors',
'investments', 'solutions', 'consultants', 'specialists', 'dispensary', 'pulmonology', 'medicine',
'orthodontics', 'orthodontist', 'endodontics', 'periodontics', 'eyecare',
}
# "First Last - Company" without a credential ("John Smith - Example Bank Mortgage").
# The person side must start with a known first name and the company side must contain a company word.
AFFILIATION_SPLIT = re.compile(r'\s*\|\s*|\s+[-–—]\s*|\s*[-–—]\s+|\s*:\s+')
# Unspaced hyphen between a surname and a company ("Smith-Example Financial"), only used when the
# right side has a company word
AFFILIATION_TIGHT_HYPHEN = re.compile(r'(?<=[a-z])-(?=[A-Z][a-z]+\s)')
# Company words, then a starter list of large brokerage, insurance and advisor networks whose
# individual agents commonly have their own Yelp pages. Brand names often carry no company word
# ("Jane Doe - RE/MAX"), so list them. Add the brands common in your own list.
AFFILIATE_COMPANY_WORDS = re.compile(
r'\b(?:financial|mortgage|bank|lending|loans?|realty|real estate|realtors?|insurance|properties|'
r'homes|brokerage|credit union|company|partnership|capital|wealth|advisors|keller williams|'
r're/?max|coldwell banker|century 21|compass|sotheby|berkshire hathaway|exp realty|redfin|'
r'state farm|allstate|farmers|nmls)\b', re.IGNORECASE)
# Place words that rule out a "Name - Company" person ("Lake City - Example Insurance")
AFFILIATION_PLACE_WORDS = {
'city', 'county', 'downtown', 'midtown', 'uptown', 'beach', 'valley', 'springs', 'hills',
'falls', 'lake', 'park', 'north', 'south', 'east', 'west',
}
AFFILIATION_MAX_PARTNERS = 2 # a "person" side seen with more distinct companies than this is a brand
AFFILIATION_MIN_PEOPLE = 3 # a company seen with this many known-first-name people is an employer
# Splits "Person, MD | Org", "Org: Person MD", "Person MD/Org", "Person MD - Org" into segments
NAME_SEGMENT_SPLIT = re.compile(r'\s*\|\s*|\s+[-–—]\s*|\s*[-–—]\s+|\s*:\s+|\s*/\s*')
# Filled once per run by register_name_overrides(), before any matching
BRAND_PREFIXES = set() # "Acme Boots" (Acme Boots - Springfield, Acme Boots - Dayton, ...)
EMPLOYERS = set() # companies seen with 3+ people in the file
NOT_PROVIDER_NAMES = set() # names whose "person" is really the city ("Acme Boots - Glen Burnie, MD")
# Filled from first_names.txt by load_first_names()
FIRST_NAMES = set()
FIRST_NAME_BOY_SHARE = {}
OPPOSITE_GENDER_MARGIN = 0.9 # boy share >= 0.9 vs <= 0.1: clearly different names (Dan / Danielle)
# Common nicknames. Short forms (Phil / Phillip, Chris / Christopher) are covered by a prefix rule.
NICKNAME_GROUPS = [
('robert', 'bob', 'bobby', 'rob', 'robbie', 'bert'), ('william', 'bill', 'billy', 'will', 'willie', 'liam'),
('richard', 'rick', 'ricky', 'rich', 'dick'), ('james', 'jim', 'jimmy', 'jamie'),
('john', 'jack', 'johnny', 'jon'), ('jonathan', 'jon', 'jonny'), ('joseph', 'joe', 'joey'),
('michael', 'mike', 'mikey', 'mick'), ('thomas', 'tom', 'tommy'), ('charles', 'chuck', 'charlie', 'chas'),
('edward', 'ed', 'eddie', 'ted', 'ned'), ('theodore', 'ted', 'teddy'),
('elizabeth', 'liz', 'beth', 'betsy', 'betty', 'eliza', 'libby', 'lisa'),
('margaret', 'maggie', 'meg', 'peggy', 'marge'), ('katherine', 'kate', 'kathy', 'katie', 'kat'),
('catherine', 'cathy', 'kate', 'katie', 'cat'), ('kathryn', 'kate', 'kathy', 'katie'),
('patricia', 'pat', 'patty', 'trish', 'tricia'), ('susan', 'sue', 'susie'),
('deborah', 'deb', 'debbie', 'debi'), ('debra', 'deb', 'debbie', 'debi'), ('rebecca', 'becky', 'becca'),
('anthony', 'tony'), ('steven', 'steve'), ('stephen', 'steve'), ('andrew', 'andy', 'drew'),
('nicholas', 'nick', 'nicky'), ('lawrence', 'larry'), ('gerald', 'jerry'), ('harold', 'hal', 'harry'),
('henry', 'hank', 'harry'), ('francis', 'frank'), ('frederick', 'fred'), ('albert', 'al', 'bert'),
('alexander', 'al', 'alex'), ('eugene', 'gene'), ('leonard', 'len', 'lenny'), ('walter', 'walt'),
('vincent', 'vince'), ('zachary', 'zach', 'zack', 'zac'), ('nathaniel', 'nate', 'nat'),
('raymond', 'ray'), ('ronald', 'ron', 'ronnie'), ('donald', 'don', 'donnie'), ('timothy', 'tim'),
('cynthia', 'cindy'), ('kimberly', 'kim'), ('pamela', 'pam'), ('amanda', 'mandy'), ('abigail', 'abby'),
('jacqueline', 'jackie'), ('judith', 'judy'), ('sandra', 'sandy'), ('teresa', 'terry', 'tess'),
('theresa', 'terry', 'tess'), ('victoria', 'vicky', 'tori'), ('virginia', 'ginny'), ('barbara', 'barb'),
('dorothy', 'dot', 'dottie'), ('melissa', 'missy'), ('valerie', 'val'), ('christina', 'tina'),
('christine', 'tina'),
]
NICKNAMES = defaultdict(set)
for _group in NICKNAME_GROUPS:
for _name in _group:
NICKNAMES[_name].update(n for n in _group if n != _name)
# Words in a listing's person segment that mean a business named after the person, not their own
# page ("Jane Doe Photography", "Smith John H Esquire")
OTHER_BUSINESS_WORDS = {
'esquire', 'esq', 'atty', 'attorney', 'attorneys', 'lawyer', 'lawyers', 'properties', 'property',
'realty', 'photography', 'photo', 'painting', 'wallpaper', 'tailor', 'shop', 'pet', 'pets',
'framing', 'preservation', 'insurance', 'mortgage', 'auto', 'salon', 'restaurant', 'cafe', 'store',
'construction', 'plumbing', 'roofing', 'cleaning', 'landscaping', 'church', 'ministries', 'rev',
'reverend', 'pastor', 'bakery', 'boutique', 'consulting', 'accounting', 'tax', 'travel', 'music',
'fitness', 'gym', 'catering', 'trucking', 'towing', 'repair', 'hvac', 'electric', 'electrical',
'barber', 'nails', 'tattoo', 'jewelry', 'florist', 'counseling',
}
# Credential hyphenated straight onto an org ("Jane Doe, MD-Lakeside ENT")
CREDENTIAL_HYPHEN = re.compile(r'(?<=[A-Za-z.])\s*-\s*(?=[A-Z])')
# Medical practice detection (listing name only), for doctors whose record has no company text
PRACTICE_KEYWORDS = [
'medical', 'medicine', 'medcenters', 'health', 'clinic', 'hospital', 'physician', 'doctor',
'familydr', 'internalmed', 'pediatric', 'urgent care', 'primary care', 'surgery', 'surgeon',
'orthop', 'cardio', 'dermatolog', 'dentist', 'dental', 'oncolog', 'neurolog', 'obgyn', 'gynec',
'radiolog', 'psychiatr', 'psycholog', 'chiropract', 'podiatr', 'optometr', 'ophthalm', 'allerg',
'gastro', 'urolog', 'endocrin', 'pulmon', 'nephro', 'rheumat', 'sportsmed',
]
# Matched at word starts so 'orthop' doesn't hit 'Orthodox' and 'health' doesn't hit 'Stealth'
PRACTICE_PATTERN = re.compile(r'\b(?:' + '|'.join(re.escape(k) for k in PRACTICE_KEYWORDS) + r')')
PRACTICE_EXCLUDE_KEYWORDS = ['pharmacy', 'drugstore']
# ---------------------------------------------------------------------------
# Brand, department and parent vocabulary
# ---------------------------------------------------------------------------
BRAND_HEAD_SKIP = {'the', 'and', 'dr', 'st', 'saint', 'mt', 'mount', 'at', 'of', 'in', 'north', 'south',
'east', 'west'}
# Category / department words and car makes: sharing one doesn't show it's the same business
BRAND_GENERIC_WORDS = {
'medical', 'health', 'healthcare', 'clinic', 'care', 'center', 'centre', 'services', 'service', 'group',
'hospital', 'pediatrics', 'pediatric', 'family', 'medicine', 'primary', 'urgent', 'specialty',
'specialists', 'physicians', 'associates', 'inc', 'llc', 'company', 'parts', 'department', 'dept',
'sales', 'auto', 'automotive', 'motor', 'lab', 'laboratory', 'pharmacy', 'imaging', 'surgery',
'surgical', 'plastic', 'reconstructive', 'home', 'quick', 'lane', 'ford', 'chevrolet', 'chevy', 'gmc',
'buick', 'cadillac', 'lincoln', 'dodge', 'jeep', 'chrysler', 'ram', 'nissan', 'toyota', 'honda',
'hyundai', 'kia', 'subaru', 'mazda', 'bmw', 'audi', 'lexus', 'acura', 'infiniti', 'volvo', 'volkswagen',
'mitsubishi',
}
NAME_ABBREVIATIONS = {'mtn': 'mountain', 'ft': 'fort', 'mt': 'mount', 'st': 'saint', 'ctr': 'center'}
# A listing naming one of these that the record doesn't is a different department of the same system
# ("Lakeside Physical Therapy" for "Lakeside Internal Medicine") or another business at the address
DEPARTMENT_WORDS = {
'rehabilitation', 'rehab', 'therapy', 'physical', 'pharmacy', 'lab', 'laboratory', 'imaging',
'radiology', 'urgent', 'emergency', 'mammography', 'dispensary', 'spine', 'hospice', 'dental',
'vision', 'eye', 'sleep', 'wellness', 'behavioral', 'oncology', 'cancer', 'surgery', 'orthopedics',
'orthopaedics', 'neurology', 'cardiology', 'dermatology', 'pediatrics', 'pulmonology', 'urology',
'gastroenterology', 'endocrinology', 'rheumatology', 'podiatry', 'audiology', 'ophthalmology',
'otolaryngology', 'obgyn', 'gynecology', 'obstetrics', 'psychiatry', 'psychology', 'chiropractic',
'infusion', 'dialysis', 'nutrition', 'vaccine', 'neurosurgery', 'allergy', 'nephrology',
'heart', 'transplant', 'colon', 'rectal', 'bariatric', 'weight', 'fertility', 'hematology',
'vascular', 'pulmonary', 'geriatrics', 'genetics', 'midwifery', 'hearing', 'electrophysiology',
# other kinds of business entirely
'insurance', 'agency', 'agent', 'collision', 'attorney', 'law', 'photography', 'salon', 'restaurant',
'cafe', 'coffee', 'bank', 'blood', 'donation', 'church',
}
CAR_MAKES = {
'ford', 'chevrolet', 'gmc', 'buick', 'cadillac', 'lincoln', 'dodge', 'jeep', 'chrysler', 'ram',
'nissan', 'toyota', 'honda', 'hyundai', 'kia', 'subaru', 'mazda', 'bmw', 'audi', 'lexus', 'acura',
'infiniti', 'volvo', 'volkswagen', 'mitsubishi', 'mercedes', 'porsche', 'jaguar', 'genesis', 'fiat',
}
MAKE_ALIASES = {'chevy': 'chevrolet', 'vw': 'volkswagen', 'benz': 'mercedes'}
# Words marking a part of a larger business: departments, dealer departments, store-in-store services
SUBUNIT_WORDS = (DEPARTMENT_WORDS - {'insurance', 'agency', 'agent', 'attorney', 'law', 'photography', 'salon',
'restaurant', 'cafe', 'coffee', 'bank', 'blood', 'donation', 'church'}) | {
'parts', 'service', 'collision', 'body', 'grooming', 'training', 'veterinary', 'doggie', 'camp',
'outpatient', 'inpatient', 'primary', 'internal', 'medicine', 'pediatric', 'birthing', 'women',
'womens', 'childrens', 'wound', 'pain', 'education',
}
LEGAL_SUFFIXES = {'inc', 'llc', 'ltd', 'corp', 'co', 'pc', 'pllc', 'lp', 'company'}
ADDRESS_ABBREVS = [
(r'\bste\b', ''), (r'\bapt\b', ''), (r'\bunit\b', ''), (r'\b#\s*\d+\w*', ''),
(r'\bstreet\b', 'st'), (r'\broad\b', 'rd'), (r'\bavenue\b', 'ave'),
(r'\bboulevard\b', 'blvd'), (r'\bdrive\b', 'dr'), (r'\blane\b', 'ln'),
(r'\bcourt\b', 'ct'), (r'\bplace\b', 'pl'), (r'\bparkway\b', 'pkwy'),
(r'\bhighway\b', 'hwy'), (r'\bfreeway\b', 'fwy'), (r'\bexpressway\b', 'expy'),
(r'\bnorth\b', 'n'), (r'\bsouth\b', 's'), (r'\beast\b', 'e'), (r'\bwest\b', 'w'),
]
# ---------------------------------------------------------------------------
# Step 1: input cleaning
# ---------------------------------------------------------------------------
def normalize_state(state):
"""'New York', 'N.Y.', 'ny' -> 'NY'."""
if not state:
return ''
state_clean = ' '.join(state.replace('.', '').split())
if len(state_clean) == 2:
return state_clean.upper()
return STATE_ABBREVIATIONS.get(state_clean.lower(), state_clean.upper())
def normalize_phone(phone):
"""Any US/Canada format -> E.164 (+15125551234)."""
digits = ''.join(filter(str.isdigit, phone or ''))
if not digits:
return ''
if len(digits) == 11 and digits.startswith('1'):
return f'+{digits}'
return f'+1{digits}'
def normalize_zip(zip_code, country='US'):
"""5-digit US zip (drops ZIP+4, spreadsheet '.0', restores lost leading zeros), Canadian A1A1A1,
Australian 4-digit postcode. Returns '' when invalid."""
if not zip_code:
return ''
zip_clean = zip_code.strip()
if country == 'CA':
ca = re.sub(r'\s+', '', zip_clean).upper()
return ca if re.match(r'^[A-Z]\d[A-Z]\d[A-Z]\d$', ca) else ''
if country == 'AU':
digits = ''.join(filter(str.isdigit, zip_clean))
return digits if len(digits) == 4 else ''
zip_clean = re.sub(r'\.0+$', '', zip_clean.split('-')[0])
digits = ''.join(filter(str.isdigit, zip_clean))
if len(digits) == 8: # ZIP+4 without the hyphen that lost its leading zero
digits = digits.zfill(9)
if 3 <= len(digits) < 5: # leading zeros dropped by a spreadsheet
digits = digits.zfill(5)
return digits[:5] if len(digits) >= 5 else ''
def normalize_country(country):
country_clean = (country or '').strip().upper()
if len(country_clean) == 2:
return country_clean
return {'UNITED STATES': 'US', 'UNITED STATES OF AMERICA': 'US', 'USA': 'US', 'AMERICA': 'US',
'CANADA': 'CA', 'AUSTRALIA': 'AU'}.get(country_clean, country_clean)
def detect_country(state, zip_code=''):
"""Infer the country from the state code when the file has no country column."""
state_upper = (state or '').strip().upper()
zip_is_au = len(''.join(filter(str.isdigit, zip_code or ''))) == 4
if state_upper in AUSTRALIAN_STATES or (state_upper in AUSTRALIAN_AMBIGUOUS and zip_is_au):
return 'AU'
if state_upper in CANADIAN_PROVINCES:
return 'CA'
return 'US'
MOJIBAKE_MARKERS = ('Ã', 'Â', 'â€')
def _undo_mojibake(text):
"""Reverse UTF-8 text that was decoded as Windows-1252: 'Vélez' -> 'Vélez'."""
raw = bytearray()
for ch in text:
try:
raw += ch.encode('cp1252')
except UnicodeEncodeError:
if ord(ch) > 255:
return text # not mojibake
raw.append(ord(ch))
try:
return raw.decode('utf-8')
except UnicodeDecodeError:
return text
def _fold_accents(text):
"""Undo mojibake, then fold accents: 'Vélez Pérez' -> 'Velez Perez'."""
if any(m in text for m in MOJIBAKE_MARKERS):
text = _undo_mojibake(text)
return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('ascii')
def load_first_names(path):
"""first_names.txt lines are 'name,boy_share' (boy_share 0-1, blank if unknown)."""
try:
with open(path, encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
name, _, share = line.partition(',')
FIRST_NAMES.add(name.lower())
if share:
FIRST_NAME_BOY_SHARE[name.lower()] = float(share)
except FileNotFoundError:
pass
# ---------------------------------------------------------------------------
# Step 2: scoring
# ---------------------------------------------------------------------------
def remove_generic_terms(name):
cleaned = name.lower()
for term in GENERIC_TERMS:
cleaned = re.sub(r'\b' + re.escape(term) + r'\b', '', cleaned)
return ' '.join(cleaned.split()).strip()
def calculate_business_name_score(input_name, yelp_name):
"""0-100 name score: best of three fuzzy comparisons (with a length penalty on partial matches),
blended 40/60 with a score that ignores GENERIC_TERMS, plus a floor of 75 for whole-word prefixes
("Example Hardware" vs "Example Hardware Home Center")."""
input_lower = input_name.lower().strip()
yelp_lower = yelp_name.lower().strip()
ratio = fuzz.ratio(input_lower, yelp_lower)
partial = fuzz.partial_ratio(input_lower, yelp_lower)
token_sort = fuzz.token_sort_ratio(input_lower, yelp_lower)
longest = max(len(input_name), len(yelp_name))
len_diff_ratio = min(len(input_name), len(yelp_name)) / longest if longest else 0
if len_diff_ratio < 0.6:
partial = partial * (0.4 + len_diff_ratio * 0.6)
full_score = max(ratio, partial, token_sort)
if full_score == partial and len_diff_ratio < 0.5:
full_score = max(ratio, token_sort)
input_cleaned = remove_generic_terms(input_name)
yelp_cleaned = remove_generic_terms(yelp_name)
if input_cleaned and yelp_cleaned:
cleaned_score = max(fuzz.ratio(input_cleaned, yelp_cleaned),
fuzz.token_sort_ratio(input_cleaned, yelp_cleaned))
else:
cleaned_score = full_score * 0.5
final_score = cleaned_score * 0.6 + full_score * 0.4
if final_score < 75:
def is_word_prefix(shorter, longer):
return (len(shorter) >= 5 and longer.startswith(shorter)
and (len(shorter) == len(longer) or longer[len(shorter)] == ' '))
if is_word_prefix(input_lower, yelp_lower) or is_word_prefix(yelp_lower, input_lower):
final_score = max(final_score, 75.0)
return round(final_score, 2)
# ---------------------------------------------------------------------------
# Street matching: a house number only counts on the same street
# ---------------------------------------------------------------------------
STREET_SAME_SCORE = 70 # street_match_score at or above this = same street
# A listing on a different street than the input is kept only if the business name is this strong: real road
# aliases (US-69 = Memorial Blvd, 6th Ave = Avenue of the Americas) keep the exact name; a neighbour or old tenant
# at the same number doesn't. Tune this bar on your own data.
STREET_ALIAS_MIN_NAME = 85
_STATES = {
"alabama":"al","alaska":"ak","arizona":"az","arkansas":"ar","california":"ca","colorado":"co","connecticut":"ct",
"delaware":"de","florida":"fl","georgia":"ga","hawaii":"hi","idaho":"id","illinois":"il","indiana":"in","iowa":"ia",
"kansas":"ks","kentucky":"ky","louisiana":"la","maine":"me","maryland":"md","massachusetts":"ma","michigan":"mi",
"minnesota":"mn","mississippi":"ms","missouri":"mo","montana":"mt","nebraska":"ne","nevada":"nv",
"new hampshire":"nh","new jersey":"nj","new mexico":"nm","new york":"ny","north carolina":"nc","north dakota":"nd",
"ohio":"oh","oklahoma":"ok","oregon":"or","pennsylvania":"pa","rhode island":"ri","south carolina":"sc",
"south dakota":"sd","tennessee":"tn","texas":"tx","utah":"ut","vermont":"vt","virginia":"va","washington":"wa",
"west virginia":"wv","wisconsin":"wi","wyoming":"wy",
}
_ORDINALS = {"first":"1","second":"2","third":"3","fourth":"4","fifth":"5","sixth":"6","seventh":"7","eighth":"8",
"ninth":"9","tenth":"10","eleventh":"11","twelfth":"12",
"one":"1","two":"2","three":"3","four":"4","five":"5","six":"6","seven":"7","eight":"8","nine":"9",
"ten":"10","eleven":"11","twelve":"12","fourteen":"14","fifteen":"15","sixteen":"16","eighteen":"18",
"twenty":"20","thirty":"30"}
_STREET_WORDS = [(r"\bstreet\b","st"),(r"\broad\b","rd"),(r"\bavenue\b","ave"),(r"\bav\b","ave"),
(r"\bboulevard\b","blvd"),(r"\bdrive\b","dr"),(r"\blane\b","ln"),(r"\bcourt\b","ct"),(r"\bplace\b","pl"),
(r"\bparkway\b","pkwy"),(r"\bfreeway\b","fwy"),(r"\bexpressway\b","expy"),(r"\bterrace\b","ter"),(r"\bterr\b","ter"),
(r"\bcircle\b","cir"),(r"\btrail\b","trl"),(r"\blp\b","loop"),(r"\bpike\b","pk"),(r"\bturnpike\b","tpke"),
(r"\bnortheast\b","ne"),(r"\bnorthwest\b","nw"),(r"\bsoutheast\b","se"),(r"\bsouthwest\b","sw"),
(r"\bnorth\b","n"),(r"\bsouth\b","s"),(r"\beast\b","e"),(r"\bwest\b","w")]
_STREET_UNIT = re.compile(r"\b(ste|suite|bldg|building|unit|apt|fl|floor|rm|room|shop|frnt|leasing office|medical office.*)\b.*$")
_STREET_QUALIFIERS = re.compile(r"\b(frontage rd|frontage|service rd|access rd|bypass|byp|bus|business|alternate|alt|"
r"spur|ext|extension|connector)\b")
_st_re = "|".join(sorted(map(re.escape, _STATES), key=len, reverse=True))
_ab_re = "|".join(sorted(set(_STATES.values())))
_ROUTE = re.compile(
r"\b(?:(?:" + _st_re + r"|" + _ab_re + r"|us|u s|i|ih|i h|interstate|sr|st|state|cr|county|fm|rr|"
r"m|k)\s*(?:hwy|highway|rte|route|rt|road|rd)?|(?:us|state|st|county|farm to market|ranch rd)?\s*"
r"(?:hwy|highway|rte|route|rt|road)|hwy|highway|rte|route|rt)\s*-?\s*(\d{1,4})[a-z]?\b")
_STREET_TYPES = {"st","rd","ave","blvd","dr","ln","ct","pl","pkwy","fwy","expy","ter","cir","trl","pk","tpke","way","hwy"}
_STREET_DIRS = {"n","s","e","w","ne","nw","se","sw"}
def normalize_street_name(addr):
"""Street part of an address line with road aliases collapsed. "1258 New York 29" -> "rte 29"."""
s = fold_text(re.sub(r"^[^0-9A-Za-z]+|^[\u00c0-\u00ff]+\s+(?=\d)", "", (addr or "").strip())).lower() # junk / mojibake ("Â 707")
s = re.sub(r"^(\d+[a-z]?\d*)\s+([nsew])\s*,\s*", r"\1 \2 ", s) # "11N250 N, Gale St"
s = re.sub(r"^(\d+\w*(?:\s+(?:n|s|e|w|ne|nw|se|sw|north|south|east|west))+)\s*,\s*", r"\1 ", s) # "11660 Se North, US-441"
s = s.split(",")[0]
s = re.sub(r"#\s*\d\w*", " ", s) # unit "#115", "#4" (not "# Ih-45")
s = s.replace("#", " ")
s = re.sub(r"[.']|\s-\s|^-|\s-(?=[a-z])", " ", s)
s = re.sub(r"\s-\s*[a-z]?\d+\w*\s*$", " ", s) # "Highland Rd - F101984"
s = re.sub(r"(?<=\d)-(?=[a-z])|(?<=[a-z])-(?=\d)|(?<=[a-z])-(?=\s)", " ", s)
s = re.sub(r"\s+", " ", s).strip()
s = re.sub(r"^\d+(?:-\d+)?[a-z]?\d*(?:\s*1/2)?\s+", "", s) # 554-581, 122-1700, 11N250
s = _STREET_UNIT.sub("", s).strip()
s = re.sub(r"\s+[a-z]\d{4,}\w*$", "", s) # trailing store/unit code (F101984)
for w, n in _ORDINALS.items():
s = re.sub(r"\b" + w + r"\b", n, s)
s = re.sub(r"\b(\d+)(st|nd|rd|th)\b", r"\1", s)
s = re.sub(r"\b(farm|ranch)\s+to\s+market\s+(?:road|rd)\b", "fm", s)
s = re.sub(r"\branch\s+(?:road|rd)\b", "fm", s)
s = re.sub(r"\b(north|south)\s+(east|west)\b", lambda m: m.group(1)[0] + m.group(2)[0], s)
s = re.sub(r"\b(highway|hiway|hwy)\b", "hwy", s)
s = re.sub(r"\bexpwy\b|\bexpressway\b", "expy", s)
s = re.sub(r"\bus\s+hwy\s+[nsew]\s+(\d)", r"us hwy \1", s) # "Us Hwy S 1"
s = re.sub(r"\b(" + _st_re + r")\s+(?=[a-z]*\d)", " ", s) if not re.search(r"\b(" + _st_re + r")\s+\d", s) else s # "Florida A1a"
s = re.sub(r"\broutes\s+(\d+)\s*(?:&|and)\s*(\d+)", r"route \1 route \2", s) # "Routes 6 & 209"
s = re.sub(r"\b(route|rte|hwy)\s+(\d+)\s*(?:&|and)\s*(\d+)", r"\1 \2 \1 \3", s)
s = re.sub(r"\bloop\s+(\d{1,4})\b", r"rte \1", s) # "Loop 410" is a route
s = re.sub(r"\b(?:business|bus)\s+(\d{1,4})\b", r"rte \1", s) # "Business 83"
s_route = _ROUTE.sub(lambda m: f" rte {m.group(1)} ", s)
s_route = re.sub(r"\b(\d{1,4})\s+(?:hwy|highway|rte|route)\b", r" rte \1 ", s_route)
s = s_route
for p, r in _STREET_WORDS:
s = re.sub(p, r, s)
s = re.sub(r"\bsaint\b", "st", s)
s = re.sub(r"\b(alternate|alt)\b", " ", s)
kept = _STREET_QUALIFIERS.sub(" ", s)
s = kept if kept.strip() else s # "Frontage Rd" alone stays
return re.sub(r"\s+", " ", s).strip()
def street_match_score(a, b):
"""0-100: are these the same street?
Both name a route -> any shared route number = 100, else 0, unless both also carry a name part
("Long Run Rd Rte 48" vs "Long Run Rd") which is then compared. Name words are compared with
street type and direction words ignored (so "Main St" vs "Maple St" isn't padded by "st");
a conflicting direction (N vs S Main) takes 40 off."""
sa, sb = normalize_street_name(a), normalize_street_name(b)
if not sa or not sb:
return 0
if sa == sb:
return 100
ra, rb = set(re.findall(r"\brte (\w+)\b", sa)), set(re.findall(r"\brte (\w+)\b", sb))
if ra and rb:
return 100 if ra & rb else 0
def core(x):
x = re.sub(r"\brte \w+\b", " ", x) if (ra or rb) else x
return " ".join(t for t in x.split() if t not in _STREET_TYPES and t not in _STREET_DIRS)
ca, cb = core(sa), core(sb)
if not ca or not cb:
ca, cb = sa, sb
na, nb = set(re.findall(r"\d+", ca)), set(re.findall(r"\d+", cb))
if na and nb and not (na & nb):
return 0 # "10 Mile Rd" vs "1 Mile Rd", "22nd Ave" vs "20th Ave"
score = max(fuzz.ratio(ca, cb), fuzz.token_sort_ratio(ca, cb), fuzz.ratio(ca.replace(" ", ""), cb.replace(" ", "")))
# Opposite directions (N vs S, E vs W) are different streets; SE vs E share a letter = same street.
da = "".join(t for t in sa.split() if t in _STREET_DIRS)
db = "".join(t for t in sb.split() if t in _STREET_DIRS)
if da and db and not (set(da) & set(db)):
score -= 40
return max(score, 0)
def calculate_address_score(input_address, yelp_address1):
"""0-100: 50% house number + 50% street name. The number only counts when the street matches
(street_match_score >= STREET_SAME_SCORE), so a wrong street at the same number scores under 35."""
if not input_address or not yelp_address1:
return 0
in_nums, yelp_nums = house_numbers(input_address), house_numbers(yelp_address1)
street_score = street_match_score(input_address, yelp_address1)
if in_nums and yelp_nums:
same_number = bool(in_nums & yelp_nums) or numbers_in_range(input_address, yelp_address1)
number_score = 100 if (same_number and street_score >= STREET_SAME_SCORE) else 0
return round(number_score * 0.5 + street_score * 0.5, 1)
return round(street_score, 1)
def house_numbers(addr):
"""Every reading of the leading house number, so formats from either side can meet:
"74-710 CA-111" -> {74710, 74, 710}; "122-1700 Garcia St" (suite-number) -> {1221700, 122, 1700};
"139-07 Hillside Ave" -> {13907, 139, 07}; "11N250 Gale St" -> {11n250}. Junk before the
number (mojibake "Â 707") is skipped. Empty set if there is no number."""
a = fold_text(re.sub(r"^[^0-9A-Za-z]+|^[\u00c0-\u00ff]+\s+(?=\d)", "", (addr or "").strip())).lower()
m = re.match(r"^(\d+)(?:-(\d+))?([a-z]?\d*)\b", a)
if not m:
return set()
first, second, tail = m.group(1), m.group(2), m.group(3) or ""
if second is None:
return {first + tail}
return {first + second + tail, first, second + tail}
def numbers_in_range(a, b):
""""2258 Washington St" vs "2253-73 Washington St": a number inside the other side's range."""
def rng(x):
m = re.match(r"^\s*(\d+)-(\d+)\b", x or "")
if not m:
return None
lo, hi = m.group(1), m.group(2)
if len(hi) < len(lo):
hi = lo[:len(lo) - len(hi)] + hi # 2253-73 -> 2253..2273
lo, hi = int(lo), int(hi)
return (lo, hi) if lo < hi and hi - lo <= 200 else None
def num(x):
m = re.match(r"^\s*(\d+)\b(?!-)", x or "")
return int(m.group(1)) if m else None
for x, y in ((a, b), (b, a)):
r, n = rng(y), num(x)
if r and n is not None and r[0] <= n <= r[1]:
return True
return False
def fold_text(s):
return "".join(c for c in unicodedata.normalize("NFKD", s) if not unicodedata.combining(c))
def haversine_distance(lat1, lon1, lat2, lon2):
"""Distance in miles, or None if a coordinate is missing."""
if not all([lat1, lon1, lat2, lon2]):
return None
try:
lon1, lat1, lon2, lat2 = map(radians, [float(lon1), float(lat1), float(lon2), float(lat2)])
a = sin((lat2 - lat1) / 2) ** 2 + cos(lat1) * cos(lat2) * sin((lon2 - lon1) / 2) ** 2
return round(3956 * 2 * asin(sqrt(a)), 2)
except (TypeError, ValueError):
return None
def strip_city_from_name(name, city):
"""Remove a city qualifier before scoring multi-result Business Match responses, so a shared city
can't carry the score: "Example Hardware of Springfield" -> "Example Hardware",
"Example Care-Springfield" -> "Example Care", "Example Centres Springfield" -> "Example Centres"."""
if not city or not name:
return name
city_esc = re.escape(city.strip())
of_match = re.search(r'\s+of\s+', name, re.IGNORECASE)
if of_match:
suffix = name[of_match.start():]
# " of <city>" or " of <street address>"
if re.search(city_esc, suffix, re.IGNORECASE) or re.search(r'\d', suffix):
stripped = name[:of_match.start()].strip()
if stripped:
return stripped
result = re.sub(r'\s*[-–]\s*' + city_esc + r'.*$', '', name, flags=re.IGNORECASE).strip()
if result and result.lower() != name.lower():
return result
result = re.sub(r'\s+' + city_esc + r'\b.*$', '', name, flags=re.IGNORECASE).strip()
if result and result.lower() != name.lower():
return result
return name
# ---------------------------------------------------------------------------
# People: detection and person-only scoring
# ---------------------------------------------------------------------------
def _credential_key(token):
"""'M.D.' -> 'MD', 'PA-C' -> 'PAC'."""
return re.sub(r'[^A-Za-z]', '', token).upper()
def _name_tokens(text):
"""Lowercase name tokens: accents folded, punctuation removed, hyphenated names joined, noise dropped."""
text = re.sub(r"(?<=\w)-(?=\w)", '', _fold_accents(text).lower())
tokens = re.sub(r"[^a-z0-9\s]", ' ', text).split()
return [t for t in tokens if t not in NAME_NOISE and t not in NAME_SUFFIXES]
def _is_credential(raw_tokens, j, allow_combos=False):
token = raw_tokens[j]
if token == ',' or not CREDENTIAL_TOKEN.match(token):
return False
key = _credential_key(token)
if key not in PERSON_CREDENTIALS:
# Labels only: combos like "APRN-CNP" (every part short, one a credential)
parts = [part for part in token.strip('.,').split('-') if part]
if not (allow_combos and len(parts) > 1 and all(len(part) <= 6 for part in parts)
and any(_credential_key(part) in PERSON_CREDENTIALS for part in parts)):
return False
if key in COMMA_ONLY_CREDENTIALS and (j == 0 or raw_tokens[j - 1] != ','):
return False
return True
def _empty_person():
return {'is_provider': False, 'kind': '', 'medical': False, 'person_tokens': [], 'first': '',
'last': '', 'credentials': frozenset(), 'org': '', 'person_text': ''}
@lru_cache(maxsize=200_000)
def _parse_provider_name(name, label_only=False):
"""Detect a person written with a credential and split out person / credentials / org:
"Jane Doe, MD | Riverside Health" -> person 'jane doe', creds {MD}, org 'Riverside Health'
"Riverside Health: Doe Jane MD" -> person 'doe jane', creds {MD}
"Doe, Jane M, MD" -> 'Last, First' order -> first 'jane', last 'doe'
A segment counts when a credential follows 2-5 name tokens."""
empty = _empty_person()
if not name:
return empty
segments = [s for s in NAME_SEGMENT_SPLIT.split(name) if s.strip()]
for i, seg in enumerate(segments):
raw_tokens = re.sub(r'[,]', ' , ', seg).split()
cred_idx = next((j for j in range(len(raw_tokens)) if _is_credential(raw_tokens, j, label_only)), None)
if cred_idx is None:
continue
person_raw = ' '.join(raw_tokens[:cred_idx]).strip(' ,')
if '&' in person_raw or '(' in person_raw or re.search(r'\d', person_raw):
continue # addresses and business names ("6240 S. Transit Rd")
person_tokens = _name_tokens(person_raw)
if not 2 <= len(person_tokens) <= 5 or any(t in NON_PERSON_WORDS for t in person_tokens):
continue
credentials = frozenset(_credential_key(raw_tokens[j]) for j in range(cred_idx, len(raw_tokens))
if _is_credential(raw_tokens, j, label_only))
if credentials <= SECONDARY_CREDENTIALS and person_tokens[0] not in FIRST_NAMES:
continue # "Pine Creek MPH" is a mobile home park; "Ann Lee, MPH" is a person
org_parts = segments[:i] + segments[i + 1:]
trailing = ' '.join(raw_tokens[j] for j in range(cred_idx, len(raw_tokens))
if raw_tokens[j] != ',' and not _is_credential(raw_tokens, j, label_only))
if trailing:
org_parts.append(trailing)
# "Last, First M" when a comma separates two non-suffix parts
comma_parts = [p.strip() for p in person_raw.split(',')
if p.strip() and p.strip().lower().strip('.') not in NAME_SUFFIXES]
ordered = (_name_tokens(comma_parts[1]) + _name_tokens(comma_parts[0])
if len(comma_parts) == 2 else person_tokens)
full_tokens = [t for t in ordered if len(t) > 1]
return {'is_provider': True, 'kind': 'credential',
'medical': bool(credentials & PROVIDER_CREDENTIALS),
'person_tokens': person_tokens,
'first': full_tokens[0] if len(full_tokens) >= 2 else '',
'last': full_tokens[-1] if full_tokens else '',
'credentials': credentials, 'org': ' '.join(org_parts).strip(),
'person_text': ' '.join(person_raw.replace(',', ' ').split())}
# Labels only: "Dr. Jane Doe", "The Office of Dr. Jane Doe"
title = DOCTOR_TITLE.match(segments[0]) if label_only and segments else None
if title:
person_raw = title.group(1).strip(' ,')
person_tokens = _name_tokens(person_raw)
if (2 <= len(person_tokens) <= 4 and not re.search(r'[\d&(]', person_raw)
and not any(t in NON_PERSON_WORDS for t in person_tokens)):
full_tokens = [t for t in person_tokens if len(t) > 1]
return {'is_provider': True, 'kind': 'credential', 'medical': True,
'person_tokens': person_tokens,
'first': full_tokens[0] if len(full_tokens) >= 2 else '',
'last': full_tokens[-1] if full_tokens else '',
'credentials': frozenset(), 'org': ' '.join(segments[1:]).strip(),
'person_text': ' '.join(person_raw.replace(',', ' ').split())}
return empty
def _company_key(text):
"""'Example Mortgage, Inc.' -> 'example mortgage'."""
text = re.sub(r'(?i)\b(?:inc|llc|ltd|co|corp|company|limited partnership|lp)\b\.?', ' ', text)
return ' '.join(re.sub(r'[^a-z0-9\s]', ' ', text.lower()).split())
def _affiliation_segments(name):
segments = [s.strip() for s in AFFILIATION_SPLIT.split(name) if s and s.strip()]
if len(segments) < 2:
parts = AFFILIATION_TIGHT_HYPHEN.split(name, maxsplit=1)
if len(parts) == 2 and AFFILIATE_COMPANY_WORDS.search(parts[1]):
segments = [p.strip() for p in parts]
return segments
@lru_cache(maxsize=200_000)
def _parse_affiliated_person(name):
"""Structural check for "First [M.] Last - Company" with no credential."""
empty = _empty_person()
if not name or not FIRST_NAMES:
return empty
segments = _affiliation_segments(name)
if len(segments) < 2:
return empty
person_raw, org = segments[0], ' '.join(segments[1:])
# Digits, '&', parens, commas or a possessive mean a place or brand
if re.search(r"[\d&(),]|'s\b", person_raw) or not re.search(r'[A-Za-z]', org):
return empty
raw_tokens = person_raw.replace(',', ' ').split()
# Title-case names only; hyphenated surnames and lowercase particles are fine
if not re.match(r"^[A-Z]", raw_tokens[0]) or not all(
re.match(r"^[A-Za-z][a-zA-Z'\.\-]*$", t) and not (len(t) > 2 and t.isupper()) for t in raw_tokens):
return empty
person_tokens = _name_tokens(person_raw)
full_tokens = [t for t in person_tokens if len(t) > 1]
if not 2 <= len(person_tokens) <= 4 or len(full_tokens) < 2:
return empty
if any(t in NON_PERSON_WORDS or t in AFFILIATION_PLACE_WORDS for t in person_tokens):
return empty
return {'is_provider': True, 'kind': 'affiliated', 'medical': False,
'person_tokens': person_tokens, 'first': full_tokens[0], 'last': full_tokens[-1],
'credentials': frozenset(), 'org': org, 'person_text': ' '.join(raw_tokens)}
def parse_provider_name(name):
"""Parse a name as one person, or return is_provider=False. Two routes: a credential
("Jane Doe, MD | Riverside Health", "Jane Doe, Realtor"), or "First Last - Company" where the
company side has a company word, the first name is known (or the company is an employer seen
with 3+ people in this file), and the person side isn't a brand prefix."""
if name in NOT_PROVIDER_NAMES:
return _empty_person()
parsed = _parse_provider_name(name)
if parsed['is_provider']:
return parsed
aff = _parse_affiliated_person(name)
if not aff['is_provider'] or aff['person_text'].lower() in BRAND_PREFIXES:
return _empty_person()
if AFFILIATE_COMPANY_WORDS.search(aff['org']) and (
aff['first'] in FIRST_NAMES or _company_key(aff['org']) in EMPLOYERS):
return aff
return _empty_person()
def register_name_overrides(names_and_cities):
"""Per-run context from the whole file, computed before matching:
- BRAND_PREFIXES: left sides of "X - Y" seen with 3+ different right sides (brands, not people)
- EMPLOYERS: companies seen with 3+ known-first-name people (their other people may have
uncommon first names)
- NOT_PROVIDER_NAMES: names whose "person" is just the row's city, or "<Business> <City> PA"
"""
partners_by_left = defaultdict(set)
people_by_company = defaultdict(set)
for name, _ in names_and_cities:
segments = _affiliation_segments(name)
if len(segments) >= 2:
partners_by_left[segments[0].lower()].add(_company_key(' '.join(segments[1:])))
aff = _parse_affiliated_person(name)
if aff['is_provider'] and aff['first'] in FIRST_NAMES and AFFILIATE_COMPANY_WORDS.search(aff['org']):
people_by_company[_company_key(aff['org'])].add(aff['person_text'].lower())
BRAND_PREFIXES.update(left for left, rights in partners_by_left.items()
if len(rights) > AFFILIATION_MAX_PARTNERS)
EMPLOYERS.update(company for company, people in people_by_company.items()
if len(people) >= AFFILIATION_MIN_PEOPLE)
for name, city in names_and_cities:
city_tokens = set(_name_tokens(city))
parsed = _parse_provider_name(name)
if not parsed['is_provider'] or not city_tokens:
continue
if set(parsed['person_tokens']) <= city_tokens:
NOT_PROVIDER_NAMES.add(name)
continue
m = re.search(re.escape(city) + r'\s+([A-Za-z]{2})\.?$', name, re.IGNORECASE)
if m and m.group(1).upper() in STATE_CODE_CREDENTIALS:
NOT_PROVIDER_NAMES.add(name)
def build_query_names(business_name):
"""Names to send to Yelp, in order. Medical people get a cleaned 'First Last MD' query first,
then the original string."""
parsed = parse_provider_name(business_name)
if not parsed['is_provider'] or not parsed['medical']:
return [business_name]
primary_cred = next((c for c in ('MD', 'DO', 'DDS', 'DMD', 'DPM', 'OD', 'DC', 'NP', 'PAC', 'PA')
if c in parsed['credentials']), '')
primary_cred = 'PA-C' if primary_cred == 'PAC' else primary_cred
cleaned = f"{parsed['person_text']} {primary_cred}".strip()
if cleaned.lower() == business_name.lower().strip():
return [business_name]
return [cleaned, business_name]
def _phonetic(name):
return name.replace('ck', 'k').replace('ph', 'f')
def _first_name_match(a, b):
"""'full' for the same first name, 'nickname' for a nickname or short form, else ''."""
if len(a) < 2 or len(b) < 2:
return ''
if fuzz.ratio(a, b) >= PROVIDER_FIRST_NAME_CUTOFF:
return 'full'
# Names that are usually opposite genders aren't nicknames of each other (Dan / Danielle)
sa, sb = FIRST_NAME_BOY_SHARE.get(a), FIRST_NAME_BOY_SHARE.get(b)
if sa is not None and sb is not None and abs(sa - sb) >= 2 * OPPOSITE_GENDER_MARGIN - 1:
return ''
if b in NICKNAMES.get(a, ()):
return 'nickname'
short, long = sorted((_phonetic(a), _phonetic(b)), key=len)
if len(short) >= 3 and long.startswith(short):
return 'nickname'
return ''
def _split_credential_hyphens(name):
"""'Doe, MD-Lakeside ENT' -> 'Doe, MD - Lakeside ENT' when the left side is a credential."""
def fix(m):
left = re.findall(r"[A-Za-z.]+$", name[:m.start()])
return ' - ' if left and _credential_key(left[0]) in PERSON_CREDENTIALS else m.group(0)
return CREDENTIAL_HYPHEN.sub(fix, name)
def is_company_listing_for_person(inp, yelp_name):
"""True when the listing is a business named after or shared by the person, not their own page:
the person's segment joins people with &/and, or names another profession ("Jane Doe Photography")."""
name = _split_credential_hyphens(yelp_name)
segments = [seg for seg in NAME_SEGMENT_SPLIT.split(name) if seg.strip()] or [name]
keys = [k for k in (inp['last'], inp['first']) if k]
segment = next((seg for seg in segments
if any(fuzz.ratio(k, t) >= PROVIDER_SURNAME_CUTOFF for k in keys for t in _name_tokens(seg))),
name)
own = set(inp['person_tokens']) | set(_name_tokens(inp['org']))
joined = re.search(r"(?:&|\band\b)\s+([A-Za-z]+)", segment, re.IGNORECASE)
if joined and joined.group(1).lower() in FIRST_NAMES and joined.group(1).lower() not in own:
return True
return any(t in OTHER_BUSINESS_WORDS and t not in own for t in _name_tokens(segment))
def calculate_provider_name_score(input_name, yelp_name):
"""0-100 for a person record, comparing people only (credentials and company text ignored).
Surname missing -> 0. Then: first name -> at least 90; nickname or initial -> at least 80;
different first name -> at most 50; surname only -> at most 65. Both name orders are tried;
the reversed order needs a full first name or nickname, not an initial."""
inp = parse_provider_name(input_name)
cand = parse_provider_name(yelp_name)
cand_tokens = cand['person_tokens'] if cand['is_provider'] else _name_tokens(yelp_name)
if not inp['last'] or not cand_tokens:
return 0.0
# Adjacent pairs cover split surnames ("De Young" vs "DeYoung")
cand_keys = set(cand_tokens) | {a + b for a, b in zip(cand_tokens, cand_tokens[1:])}
cand_initials = {c for c in cand_tokens if len(c) == 1}
base = fuzz.token_sort_ratio(' '.join(inp['person_tokens']), ' '.join(cand_tokens))
if is_company_listing_for_person(inp, yelp_name):
return 0.0
def score_as(first, last, allow_initial=True):
surname_hits = {c for c in cand_keys if len(c) > 1 and fuzz.ratio(last, c) >= PROVIDER_SURNAME_CUTOFF}
if not surname_hits:
return 0.0
others = [c for c in cand_tokens if len(c) > 1 and c not in surname_hits]
matches = {_first_name_match(first, c) for c in others} if first else set()
if 'full' in matches:
return max(base, PROVIDER_FULL_NAME_FLOOR)
if 'nickname' in matches:
return max(base, PROVIDER_NICKNAME_FLOOR)
if allow_initial and first and first[0] in cand_initials:
# The initial must not be the listing's middle initial behind a different first name
# ("Ann S. Rivera" is not "Rivera Thomas A")
middle = [t for t in inp['person_tokens'] if t not in (first, last)]
if not others or not middle or any(c[0] == middle[0][0] for c in others):
return max(base, PROVIDER_INITIAL_FLOOR)
return min(base, PROVIDER_FIRST_NAME_CONFLICT_CAP)
return min(base, PROVIDER_FIRST_NAME_CONFLICT_CAP if others else PROVIDER_SURNAME_ONLY_CAP)
score = score_as(inp['first'], inp['last'])
if inp['first']:
score = max(score, score_as(inp['last'], inp['first'], allow_initial=False))
return round(score, 2)
def is_individual_listing_for_other(input_name, yelp_name):
"""The listing is one person's page and that person isn't named in the (business) record."""
cand = parse_provider_name(yelp_name)
if not cand['is_provider']:
aff = _parse_affiliated_person(yelp_name)
if not (aff['is_provider'] and aff['first'] in FIRST_NAMES
and aff['person_text'].lower() not in BRAND_PREFIXES):
return False
cand = aff
input_tokens = set(_name_tokens(input_name))
if all(t in input_tokens for t in cand['person_tokens']):
return False
return calculate_provider_name_score(yelp_name, input_name) < PROVIDER_INITIAL_FLOOR
def is_person_listing(name):
if parse_provider_name(name)['is_provider']:
return True
aff = _parse_affiliated_person(name)
return bool(aff['is_provider'] and aff['first'] in FIRST_NAMES and aff['person_text'].lower() not in BRAND_PREFIXES)
def classify_entity(name):
"""'person' or 'business' (label only)."""
if not name:
return ''
if parse_provider_name(name)['is_provider']:
return 'person'
if name not in NOT_PROVIDER_NAMES and _parse_provider_name(name, label_only=True)['is_provider']:
return 'person'
return 'business'
def calculate_name_score(input_name, yelp_name):
"""Name score entry point: person records use person-only scoring; business records use the
business score, capped when the candidate is some other individual's page."""
if parse_provider_name(input_name)['is_provider']:
return calculate_provider_name_score(input_name, yelp_name)
score = calculate_business_name_score(input_name, yelp_name)
if is_individual_listing_for_other(input_name, yelp_name):
return min(score, INDIVIDUAL_LISTING_MAX_SCORE)
if parse_provider_name(yelp_name)['is_provider']:
# Same person written without a credential ("Phil Carter" vs "Carter Phillip P DO")
score = max(score, calculate_provider_name_score(yelp_name, input_name))
return score
# ---------------------------------------------------------------------------
# Brand, department and parent checks
# ---------------------------------------------------------------------------
def _plain_tokens(text):
"""Name tokens with hyphenated words split and common abbreviations expanded."""
return [NAME_ABBREVIATIONS.get(t, t) for t in _name_tokens(re.sub(r'(?<=\w)-(?=\w)', ' ', text))]
def brand_head_present(input_name, yelp_name, city='', strict=False):
"""One of the record's first three distinctive words appears in the listing name. Distinctive
means not a category word, car make or the city (unless the name starts with the city).
"X at Y" uses X, since Y is the host location ("Corner Clinic at QuickMart Pharmacy").
strict: the lead word itself must appear."""
city_tokens = set(_plain_tokens(city))
# "Quick Lane at <dealer>" is the dealer's own service center, so it keeps the dealer name
name = input_name if re.match(r'(?i)\s*quick\s+lane\b', input_name) else re.split(r'(?i)\s+at\s+', input_name)[0]
raw = _plain_tokens(name)
tokens = [t for i, t in enumerate(raw)
if (len(t) >= 3 or (i == 0 and len(t) == 2)) and t not in BRAND_HEAD_SKIP
and (t not in city_tokens or i == 0)]
heads = [t for t in tokens if t not in BRAND_GENERIC_WORDS][:3] or tokens[:3]
if not heads:
return False
if strict:
heads = heads[:1]
yelp_tokens = _plain_tokens(yelp_name)
joined = ''.join(yelp_tokens)
return any(h in joined or any(fuzz.ratio(h, t) >= 85 for t in yelp_tokens) for h in heads)
def _makes(name):
return {MAKE_ALIASES.get(t, t) for t in _plain_tokens(name)} & CAR_MAKES
def department_conflict(input_name, yelp_name):
"""The listing is a different part of the same system: it names a department the record doesn't,
or sells a different car make ("Summit Chevrolet" vs "Summit Subaru")."""
input_tokens = set(_plain_tokens(input_name))
if any(t in DEPARTMENT_WORDS and t not in input_tokens for t in _plain_tokens(yelp_name)):
return True
in_makes, yelp_makes = _makes(input_name), _makes(yelp_name)
return bool(in_makes and yelp_makes and not in_makes & yelp_makes)
def is_parent_listing(input_name, yelp_name, city=''):
"""The record is a part of the listing's business: a hospital department ("Lakeside Pediatrics" ->
"Lakeside Medical Center"), a dealer department ("Example Ford Parts" -> "Example Ford"), a
store-in-store service ("Example Pets Grooming" -> "Example Pets"), or something hosted there."""
if department_conflict(input_name, yelp_name):
return False
host = re.split(r'(?i)\s+at\s+', input_name, maxsplit=1)
if len(host) == 2 and brand_head_present(host[1], yelp_name, city) and not brand_head_present(host[0], yelp_name, city):
return True
ignore = LEGAL_SUFFIXES | set(_plain_tokens(city))
yelp_tokens = [t for t in _plain_tokens(yelp_name) if t not in ignore]
extra = [t for t in _plain_tokens(input_name) if t not in ignore
and not any(fuzz.ratio(t, y) >= 85 for y in yelp_tokens)]
return any(t in SUBUNIT_WORDS for t in extra) and brand_head_present(input_name, yelp_name, city)
def _looks_like_medical_practice(name):
text = name.lower()
return (not any(k in text for k in PRACTICE_EXCLUDE_KEYWORDS)) and bool(PRACTICE_PATTERN.search(text))
# ---------------------------------------------------------------------------
# Yelp API client
# ---------------------------------------------------------------------------
class RateLimiter:
"""Spaces requests to a steady QPS. Each 429 slows it down, and it never speeds back up."""
def __init__(self, qps):
self.interval = 1.0 / qps
self.next_time = 0.0
self.lock = threading.Lock()
def wait(self):
with self.lock:
now = time.monotonic()
slot = max(now, self.next_time)
self.next_time = slot + self.interval
time.sleep(max(0.0, slot - now))
def slow_down(self):
with self.lock:
self.interval = min(self.interval * 1.25, 5.0)
class ApiAuthError(Exception):
"""The API refused the key (401/403): stop the run instead of writing empty results."""
_call_errors = threading.local() # failed calls for the row this thread is matching
def _note_call_error(url, detail):
endpoint = {YELP_MATCH_URL: 'Business Match', YELP_PHONE_SEARCH_URL: 'Phone Search',
YELP_SEARCH_URL: 'Business Search'}.get(url, url)
if not hasattr(_call_errors, 'items'):
_call_errors.items = []
_call_errors.items.append(f'{endpoint} {detail}')
class YelpClient:
def __init__(self, api_key, qps=DEFAULT_QPS):
self.session = requests.Session()
self.session.headers['Authorization'] = f'Bearer {api_key}'
adapter = requests.adapters.HTTPAdapter(pool_maxsize=64)
self.session.mount('https://', adapter)
self.limiters = {url: RateLimiter(qps) for url in (YELP_MATCH_URL, YELP_PHONE_SEARCH_URL, YELP_SEARCH_URL)}
def _get(self, url, params):
"""GET with retries: 429, 5xx and timeouts up to MAX_RETRIES (1, 2, 4s); other 4xx once;
VALIDATION_ERROR never (the request itself needs fixing). A call that still fails is noted
on the row (input_error), so it isn't mistaken for "no match". 401/403 stops the run."""
limiter = self.limiters[url]
detail = ''
for attempt in range(MAX_RETRIES + 1):
limiter.wait()
try:
response = self.session.get(url, params=params, timeout=10)
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as e:
detail = 'timeout' if isinstance(e, requests.exceptions.Timeout) else 'connection error'
if attempt < MAX_RETRIES:
time.sleep(RETRY_BASE_DELAY * 2 ** attempt)
continue
break
if response.status_code == 200:
return response.json()
try:
code = response.json().get('error', {}).get('code')
except (ValueError, AttributeError):
code = None
detail = f'HTTP {response.status_code}' + (f' {code}' if code else '')
if response.status_code in (401, 403):
raise ApiAuthError(f'Yelp refused the API key ({detail}). Check YELP_API_KEY and your access.')
if response.status_code == 429:
limiter.slow_down()
elif 400 <= response.status_code < 500:
if code == 'VALIDATION_ERROR' or attempt >= 1:
break
if attempt < MAX_RETRIES:
time.sleep(RETRY_BASE_DELAY * 2 ** attempt)
_note_call_error(url, detail)
return None
def business_match(self, name, address1, address2, city, state, zip_code, country):
params = {'name': name, 'city': city, 'state': state, 'country': country}
if address1:
params['address1'] = address1
if address2:
params['address2'] = address2
if zip_code:
params['zip_code'] = zip_code
result = self._get(YELP_MATCH_URL, params)
return result.get('businesses', []) if result else []
def phone_search(self, phone):
result = self._get(YELP_PHONE_SEARCH_URL, {'phone': phone if phone.startswith('+') else f'+{phone}'})
businesses = result.get('businesses', []) if result else []
return businesses[0] if businesses else None
def search(self, term, city, state):
result = self._get(YELP_SEARCH_URL, {'term': term, 'location': f'{city}, {state}', 'limit': SEARCH_LIMIT})
return result.get('businesses', []) if result else []
def extract_business_info(business):
location = business.get('location', {}) or {}
coordinates = business.get('coordinates', {}) or {}
return {
'id': business.get('id', ''),
'name': business.get('name', ''),
'address': ', '.join(location.get('display_address', []) or []),
'address1': location.get('address1', '') or '',
'city': location.get('city', '') or '',
'state': location.get('state', '') or '',
'zip_code': location.get('zip_code', '') or '',
'phone': business.get('phone', ''),
'latitude': coordinates.get('latitude', ''),
'longitude': coordinates.get('longitude', ''),
'is_closed': bool(business.get('is_closed')),
}
def _squash_name(name):
"""Lowercase letters and digits only, accents folded, '&' read as 'and', legal suffixes and 'the' dropped."""
text = fold_text(_undo_mojibake(name or '')).lower().replace('&', ' and ')
words = [w for w in re.findall(r"[a-z0-9']+", text) if w.replace("'", '') not in LEGAL_SUFFIXES | {'the'}]
return ''.join(words).replace("'", '')
def names_agree(rec, yelp_name):
"""True when the listing's name is plainly the record's name: a high name score, or one name
contained in the other (at least NAME_CONTAINED_MIN_CHARS long)."""
if calculate_name_score(rec.name, yelp_name) >= NAME_AGREES_SCORE:
return True
a, b = _squash_name(rec.name), _squash_name(yelp_name)
short, long_ = sorted((a, b), key=len)
return len(short) >= NAME_CONTAINED_MIN_CHARS and short in long_
def phones_match(phone_a, phone_b):
a = ''.join(filter(str.isdigit, phone_a or ''))[-10:]
b = ''.join(filter(str.isdigit, phone_b or ''))[-10:]
return len(a) == 10 and a == b
def drop_closed_other_names(rec, businesses, method):
"""Closed listings are often the former tenant at the address: keep one only when its name
agrees with the record. (Open vs closed preference is decided in match_record.)"""
kept = []
for business in businesses or []:
if not business:
continue
if business.get('is_closed') and not names_agree(rec, business.get('name', '')):
if method != 'city_state_match' or calculate_name_score(rec.name, business.get('name', '')) >= CITY_STATE_ZIP_VERIFIED_THRESHOLD:
rec.reject(method, 'Closed listing with a different name', extract_business_info(business))
continue
kept.append(business)
return kept
# ---------------------------------------------------------------------------
# Step 3: the three tries
# ---------------------------------------------------------------------------
class Record:
"""One cleaned input row plus what the tries learn about it."""
def __init__(self, name, city, state, address='', address2='', zip_code='', phone='', country='',
location_count=None):
self.name, self.city, self.state = name, city, state
self.address, self.address2 = address, address2
self.zip_code, self.phone, self.country = zip_code, phone, country
self.location_count = location_count # how many locations the business has, from your own data (optional)
self.company_candidates = [] # a person's office / company listings at their address
self.individual_listing_rejected = False
self.rejections = []
self.address_check = ''
def reject(self, method, reason, info=None):
info = info or {}
self.rejections.append({'method': method, 'reason': reason, 'rejected_biz_id': info.get('id', ''),
'rejected_name': info.get('name', ''), 'rejected_address': info.get('address', '')})
def note_rejected_individual_listings(rec, businesses, threshold):
"""For business records: remember when one person's listing would have passed on business scoring,
so a weak alternative isn't promoted in its place."""
if parse_provider_name(rec.name)['is_provider']:
return
for business in businesses or []:
yelp_name = (business or {}).get('name', '')
if (yelp_name and is_individual_listing_for_other(rec.name, yelp_name)
and calculate_business_name_score(rec.name, yelp_name) >= threshold):
rec.individual_listing_rejected = True
return
def collect_company_candidates(rec, businesses, source):
"""For person records: remember listings at the person's address that look like their company
(matches the record's company text, is named after the person, or is a medical practice)."""
parsed = parse_provider_name(rec.name)
if not parsed['is_provider'] or not rec.address:
return
org_key = _company_key(parsed['org'])
for business in businesses or []:
if not business:
continue
info = extract_business_info(business)
if info['is_closed']:
continue # a closed office isn't a useful parent
named_after = (fuzz.partial_ratio(parsed['last'], info['name'].lower()) >= PROVIDER_SURNAME_CUTOFF
and is_company_listing_for_person(parsed, info['name']))
if parse_provider_name(info['name'])['is_provider'] and not named_after:
continue # another person's listing
org_score = fuzz.token_set_ratio(org_key, _company_key(info['name'])) if org_key else 0
if org_score < COMPANY_MIN_ORG_SCORE and not named_after and not (
parsed['medical'] and _looks_like_medical_practice(info['name'])):
continue
addr_score = calculate_address_score(rec.address, info['address1'])
if addr_score < COMPANY_MIN_ADDRESS_SCORE:
continue
rec.company_candidates.append((addr_score, org_score, source, info))
def select_biz_candidate(rec, candidates):
"""Pick the Business Match result to accept. Returns (business, score, rejection)."""
is_provider = parse_provider_name(rec.name)['is_provider']
if not candidates:
return None, 0, None
if len(candidates) == 1:
info = extract_business_info(candidates[0])
score = calculate_name_score(rec.name, info['name'])
needs_gate = is_provider or parse_provider_name(info['name'])['is_provider']
if needs_gate and score < PROVIDER_MIN_NAME_SCORE:
return None, score, (f'Person name mismatch on single result: {score}', info)
if not needs_gate and score < BIZ_SINGLE_RESULT_CONFIDENT_SCORE and (
not brand_head_present(rec.name, info['name'], rec.city)
or department_conflict(rec.name, info['name'])):
return None, score, (f'Low-score single result, different business or department: {score}', info)
return candidates[0], score, None
# Several results: strip the city from both sides so a shared city name can't carry the score
effective_input = rec.name if is_provider else strip_city_from_name(rec.name, rec.city)
best, best_score = candidates[0], 0
for candidate in candidates:
info = extract_business_info(candidate)
effective_yelp = info['name'] if is_provider else strip_city_from_name(info['name'], rec.city)
score = calculate_name_score(effective_input, effective_yelp)
if score > best_score or (score == best_score and best.get('is_closed') and not candidate.get('is_closed')):
best, best_score = candidate, score # ties go to the open listing
min_score = PROVIDER_MIN_NAME_SCORE if is_provider else BIZ_MULTI_RESULT_MIN_SCORE
if best_score < min_score:
return None, best_score, (f'Low name score: {best_score} (best of {len(candidates)})',
extract_business_info(best))
return best, best_score, None
def same_street_candidates(rec, candidates):
"""Drop Business Match candidates on a different street than the input, unless the name is very
strong (STREET_ALIAS_MIN_NAME: real road aliases keep the exact name). Kept when either side has
no street address."""
if not rec.address or not candidates:
return candidates
kept = []
for c in candidates:
a1 = (c.get('location') or {}).get('address1') or ''
if (not a1 or street_match_score(rec.address, a1) >= STREET_SAME_SCORE
or calculate_name_score(rec.name, c.get('name') or '') >= STREET_ALIAS_MIN_NAME):
kept.append(c)
return kept
def try_business_match(rec, api):
"""Try 1: Business Match, with the cleaned person name first for medical people."""
rejection = None
for query_name in build_query_names(rec.name):
candidates = api.business_match(query_name, rec.address, rec.address2, rec.city,
rec.state, rec.zip_code, rec.country)
collect_company_candidates(rec, candidates, 'biz_match')
note_rejected_individual_listings(rec, candidates, BIZ_MULTI_RESULT_MIN_SCORE)
candidates = drop_closed_other_names(rec, candidates, 'biz_match')
candidates = same_street_candidates(rec, candidates)
match, score, attempt_rejection = select_biz_candidate(rec, candidates)
if match:
return {**extract_business_info(match), 'score': score, 'method': 'biz_match'}
rejection = attempt_rejection or rejection
if rejection:
rec.reject('biz_match', *rejection)
return None
def location_check(rec, info):
"""'zip_city_match', 'zip_match', 'city_match', 'state_match' or ''."""
in_zip = ''.join(filter(str.isdigit, str(rec.zip_code)))[:5]
yelp_zip = ''.join(filter(str.isdigit, str(info['zip_code'])))[:5]
zip_ok = bool(in_zip and yelp_zip and in_zip == yelp_zip)
city_ok = bool(rec.city and info['city'] and rec.city.lower().strip() == info['city'].lower().strip())
state_ok = bool(rec.state and info['state'] and rec.state.lower().strip() == info['state'].lower().strip())
if zip_ok and city_ok:
return 'zip_city_match'
if zip_ok:
return 'zip_match'
if city_ok:
return 'city_match'
return 'state_match' if state_ok else ''
def try_phone_search(rec, api):
"""Try 2: Phone Search. The result must share the city or zip (state alone isn't enough)
and score at least MINIMUM_NAME_SCORE on name."""
if not rec.phone:
return None
business = api.phone_search(rec.phone)
collect_company_candidates(rec, [business], 'phone_match')
business = (drop_closed_other_names(rec, [business], 'phone_match') or [None])[0]
if not business:
return None
info = extract_business_info(business)
if location_check(rec, info) not in ('city_match', 'zip_match', 'zip_city_match'):
rec.reject('phone_match', f"Wrong location: {info['city']}, {info['state']}", info)
return None
score = calculate_name_score(rec.name, info['name'])
if score < MINIMUM_NAME_SCORE:
rec.reject('phone_match', f'Low name score: {score}', info)
return None
return {**info, 'score': score, 'method': 'phone_match'}
def pick_by_name_and_address(rec, businesses, name_threshold, address_threshold=None):
"""Among candidates passing the name threshold: without an address threshold take the best name;
with one, take the best address and require it to pass. Returns (business, name_score)."""
passing = []
for business in businesses:
score = calculate_name_score(rec.name, business.get('name', ''))
if score >= name_threshold:
addr1 = (business.get('location') or {}).get('address1', '')
addr = calculate_address_score(rec.address, addr1)
if address_threshold is not None and house_numbers(rec.address) and not house_numbers(addr1):
# Input names a number, this listing has none: the street alone can't place it on the block
addr = min(addr, address_threshold - 1)
passing.append((business, score, addr))
if not passing:
return None, 0
open_first = lambda x: not x[0].get('is_closed') # ties go to the open listing
if address_threshold is None:
best = max(passing, key=lambda x: (x[1], open_first(x)))
return best[0], best[1]
best = max(passing, key=lambda x: (x[2], open_first(x)))
return (best[0], best[1]) if best[2] >= address_threshold else (None, 0)
def try_city_state_search(rec, api, known_coords):
"""Try 3: Business Search by name in "city, state". Chains return every location and they all
score 100 on name, so narrow by zip first and let the address decide between candidates."""
businesses = api.search(build_query_names(rec.name)[0], rec.city, rec.state)
collect_company_candidates(rec, businesses, 'city_state_match')
note_rejected_individual_listings(rec, businesses, CITY_STATE_ZIP_VERIFIED_THRESHOLD)
businesses = drop_closed_other_names(rec, businesses, 'city_state_match')
match, score, verified = None, 0, False
if rec.zip_code:
in_zip = [b for b in businesses if ((b.get('location') or {}).get('zip_code') or '')[:5] == rec.zip_code[:5]]
if len(in_zip) == 1:
match, score = pick_by_name_and_address(rec, in_zip, CITY_STATE_ZIP_VERIFIED_THRESHOLD)
verified = bool(match)
elif len(in_zip) >= 2:
match, score = pick_by_name_and_address(rec, in_zip, CITY_STATE_ZIP_VERIFIED_THRESHOLD,
CITY_STATE_MULTI_MATCH_ADDRESS_THRESHOLD)
if not match:
rec.reject('city_state_match', f'{len(in_zip)} candidates in the zip, no address match')
return None
verified = True
if not match:
if len(businesses) == 1:
match, score = pick_by_name_and_address(rec, businesses, CITY_STATE_UNVERIFIED_THRESHOLD)
elif len(businesses) >= 2:
match, score = pick_by_name_and_address(rec, businesses, CITY_STATE_UNVERIFIED_THRESHOLD,
CITY_STATE_MULTI_MATCH_ADDRESS_THRESHOLD)
if not match:
rec.reject('city_state_match', f'{len(businesses)} candidates in the city, no address match')
return None
if not match:
return None
info = extract_business_info(match)
if known_coords and not verified:
distance = haversine_distance(known_coords[0], known_coords[1], info['latitude'], info['longitude'])
if distance is not None and distance > CITY_STATE_MAX_MISMATCH_MILES:
rec.reject('city_state_match', f'{distance:.1f} miles from the Business Match / Phone result', info)
return None
return {**info, 'score': score, 'method': 'city_state_match'}
# ---------------------------------------------------------------------------
# Steps 4 and 5: pick the best result, then final checks
# ---------------------------------------------------------------------------
def _postal_key(value):
value = re.sub(r'\s', '', str(value or '')).upper()
return value[:5] if value[:5].isdigit() else value[:6]
# ---- Business matched at another address ----
NEAR_NUMBER_MAX = 50 # same street and zip, house numbers this close = the same block
def _first_numbered_line(addr):
"""Display addresses can lead with a building ("Example Medical Plaza Bldg, 4647 Zion Ave, San Diego"):
take the first comma part that starts with a number, else the first part."""
parts = [p.strip() for p in str(addr or "").split(",") if p.strip()]
for p in parts:
if re.match(r"^\d", p):
return p
return parts[0] if parts else ""
def _clean_house_line(s):
"""Cut suite / PO box text in front of the house number: "Unit 3 - 18126 Yonge St", "A 10 - 360 Main St",
"150 - 838 48th St E", "306- 5227 55 Ave NW", "Unit 926-8249 Eagle Landing", "P.O. Box 789 (3606 Jefferson St)",
"Maple Tree Industrial Center 21 Wilbraham St"."""
s = str(s or "")
s = re.sub(r"\bp\.?\s*o\.?\s*box\s*\w+", " ", s, flags=re.I).replace("(", " ").replace(")", " ")
s = re.sub(r"^\s*(unit|ste|suite|#)?\s*\w+\s*-\s*(?=\d)", "", s, flags=re.I)
s = re.sub(r"^\s*(unit|ste|suite)\s+\w+\s+(?=\d)", "", s, flags=re.I)
s = re.sub(r"^\s*\d+-(?=\d)", "", s).strip()
if not re.match(r"^\s*[nsew]?\d", s, flags=re.I):
hits = [h for h in re.finditer(r"\b(\d+[a-z]?)\s+(?=[a-z])", s, flags=re.I)
if not re.search(r"(hwy|highway|route|rte|rt|interstate|us|sr|box)\s*-?\s*$", s[:h.start()], flags=re.I)]
if hits:
s = s[hits[-1].start():]
return s.strip()
_GRID = re.compile(r"^\s*([nsew])\s?(\d+)\s?([nsew])\s?(\d+)\b", re.I) # Wisconsin grid "W231N1440", "S68W15500"
def _grid_or_house_numbers(line):
g = _GRID.match(line or "")
if g:
return {"".join(g.groups()).lower()}
return house_numbers(line)
def _strip_grid(line):
return _GRID.sub("1", line or "", count=1)
def business_address_check(rec, best):
"""'same_building', 'near_number_same_street', 'same_street_no_number', 'other_address', or ''
(the rule doesn't apply: the match has no street address, or the input has no address at all)."""
in_raw = str(rec.address or '').strip()
m_raw = _first_numbered_line(best.get('address'))
# Read each side two ways: as written (house_numbers handles 74-710 / 139-07 / 2253-73 ranges) and with
# suite prefixes cut ("Unit 3 - 18126 Yonge St"). The numbers agree if any reading agrees.
in_lines = [x for x in {in_raw, _clean_house_line(in_raw)} if x]
m_lines = [x for x in {m_raw, _clean_house_line(m_raw)} if x]
in_nums = set().union(*[_grid_or_house_numbers(x) for x in in_lines]) if in_lines else set()
m_nums = set().union(*[_grid_or_house_numbers(x) for x in m_lines]) if m_lines else set()
if not m_nums:
return '' # match has no street address (service-area listing): nothing to compare
street = 0
if in_nums:
base = lambda ns: {re.sub(r"(?<=\d)[a-z]$", "", n) for n in ns} # 4604D = 4604
same_num = bool(base(in_nums) & base(m_nums)) or any(numbers_in_range(a, b) for a in in_lines for b in m_lines)
street = max((street_match_score(_strip_grid(a), _strip_grid(b)) for a in in_lines for b in m_lines), default=0)
if same_num and street >= STREET_SAME_SCORE:
return 'same_building'
if same_num:
return '' # same number, other street name: same_street_candidates / alias rule already decided
elif not in_raw or re.match(r"^\s*(n/?a|none|null|-+)\s*$", in_raw, re.I):
return '' # input has no address at all: city/zip match, rule doesn't apply
elif max((street_match_score('1 ' + a, b) for a in in_lines for b in m_lines), default=0) >= STREET_SAME_SCORE:
return 'same_street_no_number' # "Waverley Dr" -> "1 Waverley Dr", "Clio Rd" -> "G5100 Clio Rd"
# input is a PO box / intersection / text with no house number, or a different house number
in_zip, m_zip = _postal_key(rec.zip_code), _postal_key(best.get('zip_code'))
if in_nums and in_zip and in_zip == m_zip and street >= STREET_SAME_SCORE:
ints = lambda ns: {int(re.match(r"\d+", n).group()) for n in ns if re.match(r"\d+", n)}
if any(abs(a - b) <= NEAR_NUMBER_MAX for a in ints(in_nums) for b in ints(m_nums)):
return 'near_number_same_street'
return 'other_address'
def person_location_matches(rec, best):
"""A person's match must be their page at this location: same zip, or the street address matches."""
in_zip, match_zip = _postal_key(rec.zip_code), _postal_key(best['zip_code'])
if in_zip and match_zip and in_zip == match_zip:
return True
if rec.address and calculate_address_score(rec.address, best['address'].split(',')[0]) >= PERSON_MIN_ADDRESS_SCORE:
return True
if not in_zip and not rec.address:
return best['city'].strip().lower() == rec.city.strip().lower()
return False
def final_checks(rec, best, input_is_person):
"""Step 5. Returns (match or None, listing to keep as the parent or None)."""
if input_is_person and not person_location_matches(rec, best):
rec.reject(best['method'], f"Person matched at a different location: {best['address']}", best)
return None, None
is_business = not input_is_person and not is_person_listing(best['name'])
if is_business and NO_STREET_LISTINGS == 'reject' and rec.address and not best['address1'].strip():
rec.reject(best['method'], 'Listing has no street address (no-street listings rejected for this list)', best)
return None, None
if is_business:
rec.address_check = business_address_check(rec, best)
if (rec.address_check == 'other_address' and rec.location_count is not None
and 1 <= rec.location_count <= SMALL_BUSINESS_MAX_LOCATIONS
and _postal_key(rec.zip_code) and _postal_key(rec.zip_code) == _postal_key(best['zip_code'])
and names_agree(rec, best['name'])):
rec.address_check = 'small_business_nearby' # your data says 1-2 locations: same name, same zip
if rec.address_check == 'other_address':
rec.reject(best['method'], f"Business matched at a different address: {best['address']}", best)
return None, None
if rec.individual_listing_rejected and float(best['score']) < CONFIDENCE_THRESHOLD:
rec.reject(best['method'], f"Weak fallback after rejecting a person's listing: {best['score']}", best)
return None, None
if not input_is_person:
if is_parent_listing(rec.name, best['name'], rec.city):
return None, best
if department_conflict(rec.name, best['name']):
rec.reject(best['method'], 'Different department or car make of the same business', best)
return None, None
if (float(best['score']) < BIZ_CONFIDENT_SCORE
and not brand_head_present(rec.name, best['name'], rec.city,
strict=float(best['score']) < BIZ_VERY_LOW_SCORE)):
rec.reject(best['method'], f"Different business, lead word missing: {best['score']}", best)
return None, None
if (is_business and rec.address_check == 'same_building' and not names_agree(rec, best['name'])
and not brand_head_present(rec.name, best['name'], rec.city, strict=True)
and not phones_match(rec.phone, best['phone'])):
# a neighbor or new tenant at your address: not even the lead word of your name appears
rec.reject(best['method'], f"Same address, different name, no phone match: {best['score']}", best)
return None, None
return best, None
def match_record(rec, api):
"""Run the three tries for one record and apply the final checks.
Returns (match, parent, entity_type, match_entity_type); match and parent are info dicts or None."""
biz = try_business_match(rec, api)
phone = try_phone_search(rec, api)
known = None
for result in (biz, phone):
if result and result['latitude'] and result['longitude']:
known = (result['latitude'], result['longitude'])
break
city_state = try_city_state_search(rec, api, known)
# Step 4: highest name score wins (ties keep the order biz_match, phone_match, city_state_match).
# Open beats closed: when the best result is closed and an open result's name agrees, try the open
# one first and fall back to the closed one only if the open one fails the final checks.
tried = [r for r in (biz, phone, city_state) if r and r['score']]
best = max(tried, key=lambda r: float(r['score'])) if tried else None
order = [best] if best else []
if best and best['is_closed']:
open_ok = [r for r in tried if not r['is_closed'] and names_agree(rec, r['name'])]
if open_ok:
order = [max(open_ok, key=lambda r: float(r['score'])), best]
input_is_person = parse_provider_name(rec.name)['is_provider']
entity_type = classify_entity(rec.name)
parent = None
if rec.company_candidates:
_, _, source, info = max(rec.company_candidates, key=lambda c: (c[0], c[1]))
parent = {**info, 'method': source}
best = None
for candidate in order:
rec.address_check = ''
best, as_parent = final_checks(rec, candidate, input_is_person)
if as_parent:
parent = as_parent
if best or as_parent:
break
# Labels: a "business" record that matched a person's page with the same name was a person all along
if (best and not input_is_person and is_person_listing(best['name'])
and calculate_provider_name_score(best['name'], rec.name) >= PROVIDER_INITIAL_FLOOR):
entity_type = 'person'
match_entity_type = ('person' if best and entity_type == 'person'
else classify_entity(best['name'] if best else ''))
return best, parent, entity_type, match_entity_type
# ---------------------------------------------------------------------------
# CSV handling
# ---------------------------------------------------------------------------
COLUMN_ALIASES = {
'name': ['business name', 'business_name', 'businessname', 'name', 'location_name', 'location name'],
'city': ['city', 'city_name', 'town'],
'state': ['state', 'state_code', 'province', 'region'],
'address': ['address', 'address1', 'address_1', 'address_line_1', 'street_address', 'street'],
'address2': ['address2', 'address_2', 'address_line_2', 'street_address_2', 'suite', 'unit'],
'zip': ['zip', 'zip_code', 'zipcode', 'postal_code', 'postcode'],
'phone': ['phone', 'phone_number', 'telephone'],
'country': ['country', 'country_code'],
'location_count': ['location_count', 'locations', 'num_locations', 'store_count', 'brand_location_count'],
}
MATCH_COLUMNS = [
'input_entity_type', 'input_error', 'best_matched_biz_id', 'best_matched_method', 'best_match_score',
'best_match_name', 'best_match_address', 'best_match_city', 'best_match_state', 'best_match_zip',
'best_match_phone', 'best_match_entity_type', 'best_matched_parent_biz_id', 'best_matched_parent_name',
'best_matched_parent_address', 'best_matched_parent_source', 'best_match_address_check',
'best_match_is_closed',
]
REVIEW_COLUMNS = ['best_match_shared_id_count', 'needs_manual_review']
def find_column(headers, aliases, exclude=()):
"""Exact (case-insensitive) header match first, then fuzzy >= 80."""
candidates = [h for h in headers if h not in exclude]
lower = {h.lower().strip(): h for h in candidates}
for alias in aliases:
if alias in lower:
return lower[alias]
best, best_score = None, 0
for alias in aliases:
for h in candidates:
score = fuzz.ratio(alias, h.lower().strip())
if score > best_score:
best, best_score = h, score
if best_score >= 80:
print(f"Note: using column '{best}' (fuzzy header match, score {best_score:.0f})")
return best
return None
def clean_row(row, cols):
def get(key):
return ' '.join((row.get(cols[key]) or '').split()) if cols.get(key) else ''
state = normalize_state(get('state'))
zip_raw = get('zip')
country = normalize_country(get('country')) if get('country') else detect_country(state, zip_raw)
count = re.sub(r'\.0+$', '', get('location_count'))
return Record(name=get('name'), city=get('city'), state=state, address=get('address'),
address2=get('address2'), zip_code=normalize_zip(zip_raw, country),
phone=normalize_phone(get('phone')), country=country,
location_count=int(count) if count.isdigit() else None)
def process_row(row, cols, api):
rec = clean_row(row, cols)
out = dict(row)
out.update({c: '' for c in MATCH_COLUMNS})
missing = [label for label, value in (('name', rec.name), ('city', rec.city), ('state', rec.state)) if not value]
if missing:
out['input_error'] = 'Missing required input: ' + ', '.join(missing)
return out, []
_call_errors.items = []
try:
best, parent, entity_type, match_entity_type = match_record(rec, api)
except ApiAuthError:
raise
except Exception as e: # keep the row; one bad record shouldn't stop the run
out['input_error'] = f'Error: {e}'
return out, rec.rejections
if _call_errors.items:
# Some calls failed, so a blank match here means "didn't find out", not "no match"
out['input_error'] = 'API error, rerun this row: ' + '; '.join(dict.fromkeys(_call_errors.items))
out['input_entity_type'] = entity_type
out['best_match_entity_type'] = match_entity_type
if best:
out.update({'best_matched_biz_id': best['id'], 'best_matched_method': best['method'],
'best_match_score': best['score'], 'best_match_name': best['name'],
'best_match_address': best['address'], 'best_match_city': best['city'],
'best_match_state': best['state'], 'best_match_zip': best['zip_code'],
'best_match_phone': best['phone'], 'best_match_address_check': rec.address_check,
'best_match_is_closed': best['is_closed']})
if parent:
out.update({'best_matched_parent_biz_id': parent['id'], 'best_matched_parent_name': parent['name'],
'best_matched_parent_address': parent['address'],
'best_matched_parent_source': parent['method']})
rejections = [{'input_name': rec.name, 'input_city': rec.city, 'input_state': rec.state, **r}
for r in rec.rejections]
return out, rejections
def flag_shared_biz_ids(rows):
"""Count distinct records (name + address + city) per matched business ID, so exact duplicate rows
don't count twice but two branches of a chain on one Yelp page do. Flag IDs shared by 2 or more."""
names_by_id = defaultdict(set)
for r in rows:
if r.get('best_matched_biz_id'):
names_by_id[r['best_matched_biz_id']].add(r['_key'])
for r in rows:
count = len(names_by_id[r['best_matched_biz_id']]) if r.get('best_matched_biz_id') else 0
r['best_match_shared_id_count'] = count
r['needs_manual_review'] = count >= SHARED_ID_REVIEW_THRESHOLD
def write_csv(path, rows, fieldnames):
with open(path, 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames, extrasaction='ignore')
writer.writeheader()
writer.writerows(rows)
def main():
global NO_STREET_LISTINGS
parser = argparse.ArgumentParser(description='Match business records in a CSV to Yelp business IDs.')
parser.add_argument('input_file')
parser.add_argument('--qps', type=float, default=DEFAULT_QPS, help='requests per second per endpoint')
parser.add_argument('--workers', type=int, default=DEFAULT_WORKERS)
parser.add_argument('--batch-size', type=int, default=DEFAULT_BATCH_SIZE,
help='rows per batch file; finished batch files are skipped on rerun')
parser.add_argument('--test-name', help='only process rows whose name contains this text')
parser.add_argument('--no-street-listings', choices=['keep', 'reject'], default=NO_STREET_LISTINGS,
help="Yelp listings that show no street address: 'reject' for storefront lists "
"(restaurants, shops), 'keep' for service-area businesses (default)")
parser.add_argument('--first-names', default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'first_names.txt'))
args = parser.parse_args()
if not API_KEY:
sys.exit('Set the YELP_API_KEY environment variable first.')
NO_STREET_LISTINGS = args.no_street_listings
load_first_names(args.first_names)
if not FIRST_NAMES:
print(f"Note: {args.first_names} not found. 'First Last - Company' people won't be detected; "
"people with credentials (MD, NP, Realtor...) still are.")
with open(args.input_file, encoding='utf-8-sig', newline='') as f:
reader = csv.DictReader(f)
headers = reader.fieldnames or []
rows = list(reader)
cols = {}
for key, aliases in COLUMN_ALIASES.items():
cols[key] = find_column(headers, aliases, exclude=[c for c in cols.values() if c])
if not (cols['name'] and cols['city'] and cols['state']):
sys.exit(f'Need name, city and state columns. Found headers: {headers}')
print('Columns: ' + ', '.join(f'{k}={v}' for k, v in cols.items() if v))
if args.test_name:
rows = [r for r in rows if args.test_name.lower() in (r.get(cols['name']) or '').lower()]
print(f'Test mode: {len(rows)} rows contain "{args.test_name}"')
register_name_overrides([(' '.join((r.get(cols['name']) or '').split()), (r.get(cols['city']) or '').strip())
for r in rows])
base = os.path.splitext(args.input_file)[0]
if args.test_name:
base += '_test_' + re.sub(r'[^A-Za-z0-9]+', '_', args.test_name).strip('_')
out_base = os.path.join(os.path.dirname(base), 'matched_' + os.path.basename(base))
api = YelpClient(API_KEY, qps=args.qps)
fieldnames = headers + [c for c in MATCH_COLUMNS if c not in headers]
rejection_fields = ['input_name', 'input_city', 'input_state', 'method', 'reason',
'rejected_biz_id', 'rejected_name', 'rejected_address']
batch_files = []
for start in range(0, len(rows), args.batch_size):
batch = rows[start:start + args.batch_size]
batch_file = f'{out_base}_rows{start + 1}-{start + len(batch)}.csv'
rejection_file = batch_file[:-4] + '_rejections.csv'
batch_files.append((batch_file, rejection_file))
if os.path.exists(batch_file):
print(f'Skipping {batch_file} (already done)')
continue
started = time.time()
try:
with ThreadPoolExecutor(max_workers=args.workers) as pool:
results = list(pool.map(lambda r: process_row(r, cols, api), batch))
except ApiAuthError as e:
sys.exit(f'Stopped: {e}')
write_csv(batch_file, [r for r, _ in results], fieldnames)
write_csv(rejection_file, [x for _, rej in results for x in rej], rejection_fields)
matched = sum(1 for r, _ in results if r['best_matched_biz_id'])
print(f'{batch_file}: {matched:,}/{len(batch):,} matched in {time.time() - started:.0f}s')
# Combine batches and flag business IDs shared by many different records
combined, rejections = [], []
for batch_file, rejection_file in batch_files:
with open(batch_file, encoding='utf-8', newline='') as f:
combined.extend(csv.DictReader(f))
if os.path.exists(rejection_file):
with open(rejection_file, encoding='utf-8', newline='') as f:
rejections.extend(csv.DictReader(f))
for r in combined:
r['_key'] = tuple(' '.join((r.get(cols[k]) or '').lower().split()) if cols.get(k) else ''
for k in ('name', 'address', 'city'))
flag_shared_biz_ids(combined)
all_fields = fieldnames + REVIEW_COLUMNS
write_csv(f'{out_base}.csv', combined, all_fields)
write_csv(f'{out_base}_rejections.csv', rejections, rejection_fields)
review = sorted((r for r in combined if r['needs_manual_review']),
key=lambda r: (-r['best_match_shared_id_count'], r['best_matched_biz_id']))
write_csv(f'{out_base}_manual_review.csv', review, all_fields)
total = len(combined)
matched = sum(1 for r in combined if r['best_matched_biz_id'])
with_parent = sum(1 for r in combined if r['best_matched_biz_id'] or r['best_matched_parent_biz_id'])
print(f'\nDone: {total:,} rows')
if total:
print(f' matched (same business): {matched:,} ({matched / total:.1%})')
print(f' matched or parent listing: {with_parent:,} ({with_parent / total:.1%})')
print(f' rows needing manual review: {len(review):,}')
api_errors = sum(1 for r in combined if (r.get('input_error') or '').startswith('API error'))
if api_errors:
print(f' rows with API errors: {api_errors:,} (input_error starts with "API error": unknown, not'
f' "no match". Save those rows to a new CSV and run it again.)')
print(f' output: {out_base}.csv')
if __name__ == '__main__':
main()
Updated 1 day ago
