|
""" |
|
Cannabis Licenses | Get Maine Licenses |
|
Copyright (c) 2022 Cannlytics |
|
|
|
Authors: |
|
Keegan Skeate <https://github.com/keeganskeate> |
|
Candace O'Sullivan-Sutherland <https://github.com/candy-o> |
|
Created: 9/29/2022 |
|
Updated: 9/30/2022 |
|
License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE> |
|
|
|
Description: |
|
|
|
Collect Maine cannabis license data. |
|
|
|
Data Source: |
|
|
|
- Maine Office of Cannabis Policy |
|
URL: <https://www.maine.gov/dafs/ocp/open-data/adult-use> |
|
|
|
""" |
|
|
|
from datetime import datetime |
|
import os |
|
from typing import Optional |
|
|
|
|
|
from bs4 import BeautifulSoup |
|
from cannlytics.data.gis import geocode_addresses |
|
from dotenv import dotenv_values |
|
import pandas as pd |
|
import requests |
|
|
|
|
|
|
|
DATA_DIR = '../data/me' |
|
ENV_FILE = '../.env' |
|
|
|
|
|
STATE = 'ME' |
|
MAINE = { |
|
'licensing_authority_id': 'MEOCP', |
|
'licensing_authority': 'Maine Office of Cannabis Policy', |
|
'licenses': { |
|
'url': 'https://www.maine.gov/dafs/ocp/open-data/adult-use', |
|
'key': 'Adult_Use_Establishments_And_Contacts', |
|
'columns': { |
|
'LICENSE': 'license_number', |
|
'LICENSE_CATEGORY': 'license_type', |
|
'LICENSE_TYPE': 'license_designation', |
|
'LICENSE_NAME': 'business_legal_name', |
|
'DBA': 'business_dba_name', |
|
'LICENSE_STATUS': 'license_status', |
|
'LICENSE_CITY': 'premise_city', |
|
'WEBSITE': 'business_website', |
|
'CONTACT_NAME': 'business_owner_name', |
|
'CONTACT_TYPE': 'contact_type', |
|
'CONTACT_CITY': 'contact_city', |
|
'CONTACT_DESCRIPTION': 'contact_description', |
|
}, |
|
} |
|
} |
|
|
|
|
|
def get_licenses_me( |
|
data_dir: Optional[str] = None, |
|
env_file: Optional[str] = '.env', |
|
): |
|
"""Get Maine cannabis license data.""" |
|
|
|
|
|
file_dir = f'{data_dir}/.datasets' |
|
if not os.path.exists(data_dir): os.makedirs(data_dir) |
|
if not os.path.exists(file_dir): os.makedirs(file_dir) |
|
|
|
|
|
licenses_url = None |
|
licenses_key = MAINE['licenses']['key'] |
|
url = MAINE['licenses']['url'] |
|
response = requests.get(url) |
|
soup = BeautifulSoup(response.content, 'html.parser') |
|
links = soup.find_all('a') |
|
for link in links: |
|
try: |
|
href = link['href'] |
|
except KeyError: |
|
continue |
|
if licenses_key in href: |
|
licenses_url = href |
|
break |
|
|
|
|
|
filename = licenses_url.split('/')[-1] |
|
licenses_source_file = os.path.join(file_dir, filename) |
|
response = requests.get(licenses_url) |
|
with open(licenses_source_file, 'wb') as doc: |
|
doc.write(response.content) |
|
|
|
|
|
licenses = pd.read_excel(licenses_source_file) |
|
licenses.rename(columns=MAINE['licenses']['columns'], inplace=True) |
|
licenses['licensing_authority_id'] = MAINE['licensing_authority_id'] |
|
licenses['licensing_authority'] = MAINE['licensing_authority'] |
|
licenses['license_designation'] = 'Adult-Use' |
|
licenses['premise_state'] = STATE |
|
licenses['license_status_date'] = None |
|
licenses['license_term'] = None |
|
licenses['issue_date'] = None |
|
licenses['expiration_date'] = None |
|
licenses['business_structure'] = None |
|
licenses['business_email'] = None |
|
licenses['business_phone'] = None |
|
licenses['activity'] = None |
|
licenses['parcel_number'] = None |
|
licenses['premise_street_address'] = None |
|
licenses['id'] = licenses['license_number'] |
|
|
|
|
|
licenses.drop_duplicates(subset='license_number', inplace=True) |
|
|
|
|
|
criterion = licenses['business_dba_name'].isnull() |
|
licenses.loc[criterion,'business_dba_name'] = licenses['business_legal_name'] |
|
|
|
|
|
cols = ['business_legal_name', 'business_dba_name', 'business_owner_name'] |
|
for col in cols: |
|
licenses[col] = licenses[col].apply( |
|
lambda x: x.title().strip() if isinstance(x, str) else x |
|
) |
|
|
|
|
|
date = licenses_source_file.split('\\')[-1].split('.')[0].replace(licenses_key, '') |
|
date = date.replace('%20', '') |
|
date = '-'.join([date[:2], date[2:4], date[4:]]) |
|
licenses['data_refreshed_date'] = pd.to_datetime(date).isoformat() |
|
|
|
|
|
config = dotenv_values(env_file) |
|
google_maps_api_key = config['GOOGLE_MAPS_API_KEY'] |
|
cols = ['premise_city', 'premise_state'] |
|
licenses['address'] = licenses[cols].apply( |
|
lambda row: ', '.join(row.values.astype(str)), |
|
axis=1, |
|
) |
|
licenses = geocode_addresses( |
|
licenses, |
|
api_key=google_maps_api_key, |
|
address_field='address', |
|
) |
|
drop_cols = ['state', 'state_name', 'address', 'formatted_address', |
|
'contact_type', 'contact_city', 'contact_description'] |
|
licenses.drop(columns=drop_cols, inplace=True) |
|
gis_cols = { |
|
'county': 'premise_county', |
|
'latitude': 'premise_latitude', |
|
'longitude': 'premise_longitude', |
|
} |
|
licenses.rename(columns=gis_cols, inplace=True) |
|
|
|
|
|
if data_dir is not None: |
|
timestamp = datetime.now().isoformat()[:19].replace(':', '-') |
|
licenses.to_excel(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.xlsx') |
|
return licenses |
|
|
|
|
|
|
|
if __name__ == '__main__': |
|
|
|
|
|
import argparse |
|
try: |
|
arg_parser = argparse.ArgumentParser() |
|
arg_parser.add_argument('--d', dest='data_dir', type=str) |
|
arg_parser.add_argument('--data_dir', dest='data_dir', type=str) |
|
arg_parser.add_argument('--env', dest='env_file', type=str) |
|
args = arg_parser.parse_args() |
|
except SystemExit: |
|
args = {'d': DATA_DIR, 'env_file': ENV_FILE} |
|
|
|
|
|
data_dir = args.get('d', args.get('data_dir')) |
|
env_file = args.get('env_file') |
|
data = get_licenses_me(data_dir, env_file=env_file) |
|
|