File size: 7,437 Bytes
6a105a7
 
 
 
 
 
124701c
6a105a7
1352c88
6a105a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124701c
6a105a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1352c88
 
 
 
6a105a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1352c88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a105a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1352c88
6a105a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124701c
6a105a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1352c88
6a105a7
 
 
 
 
 
 
 
 
 
 
 
 
 
124701c
6a105a7
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
"""
Cannabis Licenses | Get Oregon Licenses
Copyright (c) 2022 Cannlytics

Authors:
    Keegan Skeate <https://github.com/keeganskeate>
    Candace O'Sullivan-Sutherland <https://github.com/candy-o>
Created: 9/28/2022
Updated: 10/7/2022
License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>

Description:

    Collect Oregon cannabis license data.

Data Source:

    - Oregon Liquor and Cannabis Commission
    URL: <https://www.oregon.gov/olcc/marijuana/pages/recreational-marijuana-licensing.aspx>

"""
# Standard imports.
from datetime import datetime
import os
from typing import Optional

# External imports.
from dotenv import dotenv_values
import pandas as pd
import requests
from cannlytics.data.gis import geocode_addresses


# Specify where your data lives.
DATA_DIR = '../data/or'
ENV_FILE = '../.env'

# Specify state-specific constants.
OREGON = {
    'licensing_authority_id': 'OLCC',
    'licensing_authority': 'Oregon Liquor and Cannabis Commission',
    'licenses': {
        'url': 'https://www.oregon.gov/olcc/marijuana/Documents/MarijuanaLicenses_Approved.xlsx',
    },
    'retailers': {
        'url': 'https://www.oregon.gov/olcc/marijuana/Documents/Approved_Retail_Licenses.xlsx',
        'columns': {
            'TRADE NAME': 'business_dba_name',
            'POSTAL CITY': 'premise_city',
            'COUNTY': 'premise_county',
            'STREET ADDRESS': 'premise_street_address',
            'ZIP': 'premise_zip_code',
            'Med Grade': 'medicinal',
            'Delivery': 'delivery',
        },
        'drop_columns': [
            'medicinal',
            'delivery',
        ],
    },
}

def get_licenses_or(
        data_dir: Optional[str] = None,
        env_file: Optional[str] = '.env',
        # Optional: Add print statements.
        # verbose: Optional[bool] = False,
    ):
    """Get California cannabis license data."""

    # Create the necessary directories.
    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)

    # Download the data workbooks.
    timestamp = datetime.now().isoformat()[:19].replace(':', '-')
    outfile = f'{file_dir}/retailers-or-{timestamp}.xlsx'
    response = requests.get(OREGON['retailers']['url'])
    with open(outfile, 'wb') as doc:
        doc.write(response.content)

    # Extract data from the workbooks, removing the footnote.
    data = pd.read_excel(outfile, skiprows=3)
    data = data[:-1]
    data.rename(columns=OREGON['retailers']['columns'], inplace=True)

    # Optional: Remove licenses with an asterisk (*).

    # Curate the data.
    data['licensing_authority_id'] = OREGON['licensing_authority_id']
    data['licensing_authority'] = OREGON['licensing_authority']
    data['license_status'] = 'Active'
    data['license_designation'] = 'Adult-Use'
    data['premise_state'] = 'OR'
    data.loc[data['medicinal'] == 'Yes', 'license_designation'] = 'Adult-Use and Medicinal'
    data['business_image_url'] = None
    data['license_status_date'] = None
    data['license_term'] = None
    data['issue_date'] = None
    data['expiration_date'] = None
    data['business_email'] = None
    data['business_owner_name'] = None
    data['business_structure'] = None
    data['business_website'] = None
    data['activity'] = None
    data['business_phone'] = None
    data['parcel_number'] = None
    data['business_legal_name'] = data['business_dba_name']

    # Optional: Convert `medicinal` and `delivery` columns to boolean.
    # data['medicinal'] = data['medicinal'].map(dict(Yes=1))
    # data['delivery'] = data['delivery'].map(dict(Yes=1))
    # data['medicinal'].fillna(0, inplace=True)
    # data['delivery'].fillna(0, inplace=True)
    data.drop(columns=['medicinal', 'delivery'], inplace=True)

    # Convert certain columns from upper case title case.
    cols = ['business_dba_name', 'premise_city', 'premise_county',
            'premise_street_address']
    for col in cols:
        data[col] = data[col].apply(lambda x: x.title().strip())

    # Convert zip code to a string.
    data.loc[:, 'premise_zip_code'] = data['premise_zip_code'].apply(lambda x: str(int(x)))

    # Get the `data_refreshed_date`.
    df = pd.read_excel(outfile, index_col=None, usecols='C', header=1, nrows=0)
    header = df.columns.values[0]
    date = pd.to_datetime(header.split(' ')[-1])
    data['data_refreshed_date'] = date.isoformat()

    # Get the `license_number` and `license_type` from license list.
    license_file = f'{file_dir}/licenses-or-{timestamp}.xlsx'
    response = requests.get(OREGON['licenses']['url'])
    with open(license_file, 'wb') as doc:
        doc.write(response.content)
    licenses = pd.read_excel(license_file, skiprows=2)
    licenses['BUSINESS NAME'] = licenses['BUSINESS NAME'].apply(
        lambda x: str(x).title().strip(),
    )
    licenses = licenses.loc[licenses['LICENSE TYPE'] == 'Recreational Retailer']
    data = pd.merge(
        data,
        licenses[['BUSINESS NAME', 'COUNTY', 'LICENSE NUMBER', 'LICENSE TYPE']],
        left_on=['business_dba_name', 'premise_county'],
        right_on=['BUSINESS NAME', 'COUNTY'],
        how='left',
    )

    # Clean the merged columns.
    data.drop_duplicates(subset='premise_street_address', inplace=True)
    columns = {
        'LICENSE NUMBER': 'license_number',
        'LICENSE TYPE': 'license_type',
    }
    data.rename(columns=columns, inplace=True)
    data.drop(columns=['BUSINESS NAME', 'COUNTY'], inplace=True)
    data['id'] = data['license_number']

    # Geocode licenses to get `premise_latitude` and `premise_longitude`.
    config = dotenv_values(env_file)
    google_maps_api_key = config['GOOGLE_MAPS_API_KEY']
    cols = ['premise_street_address', 'premise_city', 'premise_state',
            'premise_zip_code']
    data['address'] = data[cols].apply(
        lambda row: ', '.join(row.values.astype(str)),
        axis=1,
    )
    data = geocode_addresses(
        data,
        api_key=google_maps_api_key,
        address_field='address',
    )
    drop_cols = ['state', 'state_name', 'county', 'address', 'formatted_address']
    data.drop(columns=drop_cols, inplace=True)
    gis_cols = {
        'latitude': 'premise_latitude',
        'longitude': 'premise_longitude'
    }
    data.rename(columns=gis_cols, inplace=True)

    # Optional: Lookup details by searching for business' websites.
    # - business_email
    # - business_phone

    # Optional: Create fields for standardization:
    # - id

    # Save the license data.
    if data_dir is not None:
        timestamp = datetime.now().isoformat()[:19].replace(':', '-')
        data.to_csv(f'{data_dir}/licenses-or-{timestamp}.csv', index=False)
    return data


if __name__ == '__main__':

    # Support command line usage.
    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}

    # Get California licenses, saving them to the specified directory.
    data_dir = args.get('d', args.get('data_dir'))
    env_file = args.get('env_file')
    get_licenses_or(data_dir, env_file=env_file)