keeganskeate commited on
Commit
c0464cb
1 Parent(s): ee3a127

cannabis-licenses-2023-08-13 (#5)

Browse files

- Updated `cannabis_licenses` dataset 2023-09-22 (e22ba518ade0ec3a029f740c0536ab9d43bb3602)

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +22 -25
  2. algorithms/get_licenses_ak.py +137 -88
  3. algorithms/get_licenses_az.py +155 -115
  4. algorithms/get_licenses_ca.py +7 -3
  5. algorithms/get_licenses_co.py +21 -4
  6. algorithms/get_licenses_ct.py +12 -6
  7. algorithms/get_licenses_de.py +182 -0
  8. algorithms/get_licenses_fl.py +292 -0
  9. algorithms/get_licenses_il.py +13 -6
  10. algorithms/get_licenses_ma.py +84 -55
  11. algorithms/get_licenses_md.py +252 -0
  12. algorithms/get_licenses_me.py +27 -11
  13. algorithms/get_licenses_mi.py +43 -33
  14. algorithms/get_licenses_mo.py +257 -0
  15. algorithms/get_licenses_mt.py +15 -7
  16. algorithms/get_licenses_nj.py +7 -4
  17. algorithms/get_licenses_nm.py +119 -72
  18. algorithms/get_licenses_nv.py +25 -18
  19. algorithms/get_licenses_ny.py +445 -0
  20. algorithms/get_licenses_or.py +5 -2
  21. algorithms/get_licenses_ri.py +27 -10
  22. algorithms/get_licenses_south_africa.py +134 -0
  23. algorithms/get_licenses_vt.py +42 -33
  24. algorithms/get_licenses_wa.py +6 -3
  25. algorithms/main.py +118 -26
  26. analysis/figures/cannabis-licenses-map.html +0 -0
  27. analysis/license_map.py +39 -56
  28. cannabis_licenses.py +72 -41
  29. analysis/figures/cannabis-licenses-map.png → data/ak/licenses-ak-2023-04-24T18-17-38.csv +2 -2
  30. data/ak/licenses-ak-2023-08-12T10-49-50.csv +3 -0
  31. data/ak/licenses-ak-latest.csv +3 -0
  32. data/ak/retailers-ak-2023-04-24T18-17-38.csv +3 -0
  33. data/ak/retailers-ak-2023-08-12T10-49-50.csv +3 -0
  34. data/all/licenses-2022-10-06.csv +3 -0
  35. data/all/licenses-all-latest.csv +3 -0
  36. data/az/cultivators-az-2023-08-13T12-34-02.csv +3 -0
  37. data/az/licenses-az-2023-04-25T13-29-54.csv +3 -0
  38. data/az/licenses-az-2023-08-13T12-34-02.csv +3 -0
  39. data/az/licenses-az-latest.csv +3 -0
  40. data/az/manufacturers-az-2023-08-13T12-34-02.csv +3 -0
  41. data/az/retailers-az-2023-04-25T13-29-54.csv +3 -0
  42. data/az/retailers-az-2023-08-13T12-34-02.csv +3 -0
  43. data/ca/licenses-ca-2023-04-24T16-09-51.csv +3 -0
  44. data/ca/licenses-ca-2023-05-09.csv +3 -0
  45. data/ca/licenses-ca-2023-06-06.csv +3 -0
  46. data/ca/licenses-ca-2023-08-13T15-49-47.csv +3 -0
  47. data/ca/licenses-ca-latest.csv +3 -0
  48. data/co/licenses-co-2023-04-24T18-47-58.csv +3 -0
  49. data/co/licenses-co-2023-08-13T12-47-32.csv +3 -0
  50. data/co/licenses-co-2023-09-20T08-09-13.csv +3 -0
README.md CHANGED
@@ -1,27 +1,22 @@
1
  ---
 
2
  annotations_creators:
3
  - expert-generated
4
  language_creators:
5
  - expert-generated
6
  license:
7
  - cc-by-4.0
8
- pretty_name: cannabis_licenses
9
- size_categories:
10
- - 10K<n<100K
11
- source_datasets:
12
- - original
13
  tags:
14
  - cannabis
15
  - licenses
16
- - licensees
17
- - retail
18
  ---
19
 
20
- # Cannabis Licenses, Curated by Cannlytics
21
 
 
22
  <div align="center" style="text-align:center; margin-top:1rem; margin-bottom: 1rem;">
23
  <img style="max-height:365px;width:100%;max-width:720px;" alt="" src="analysis/figures/cannabis-licenses-map.png">
24
- </div>
25
 
26
  ## Table of Contents
27
  - [Table of Contents](#table-of-contents)
@@ -68,33 +63,34 @@ The dataset is partitioned into 18 subsets for each state and the aggregate.
68
  | [California](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/ca) | `ca` | ✅ |
69
  | [Colorado](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/co) | `co` | ✅ |
70
  | [Connecticut](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/ct) | `ct` | ✅ |
 
71
  | [Illinois](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/il) | `il` | ✅ |
72
  | [Maine](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/me) | `me` | ✅ |
 
73
  | [Massachusetts](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/ma) | `ma` | ✅ |
74
  | [Michigan](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/mi) | `mi` | ✅ |
 
75
  | [Montana](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/mt) | `mt` | ✅ |
76
  | [Nevada](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/nv) | `nv` | ✅ |
77
  | [New Jersey](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/nj) | `nj` | ✅ |
78
- | New York | `ny` | Expected 2022 Q4 |
79
- | [New Mexico](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/nm) | `nm` | ⚠️ Under development |
80
  | [Oregon](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/or) | `or` | ✅ |
81
  | [Rhode Island](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/ri) | `ri` | ✅ |
82
  | [Vermont](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/vt) | `vt` | ✅ |
83
  | Virginia | `va` | ⏳ Expected 2024 |
84
  | [Washington](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/wa) | `wa` | ✅ |
85
 
86
- The following (18) states have issued medical cannabis licenses, but are not (yet) included in the dataset:
87
 
88
  - Alabama
89
  - Arkansas
90
- - Delaware
91
  - District of Columbia (D.C.)
92
  - Florida
 
93
  - Louisiana
94
- - Maryland
95
  - Minnesota
96
  - Mississippi
97
- - Missouri
98
  - New Hampshire
99
  - North Dakota
100
  - Ohio
@@ -112,15 +108,13 @@ You can load the licenses for each state. For example:
112
  from datasets import load_dataset
113
 
114
  # Get the licenses for a specific state.
115
- dataset = load_dataset('cannlytics/cannabis_licenses', 'ca')
116
  data = dataset['data']
117
- assert len(data) > 0
118
- print('%i licenses.' % len(data))
119
  ```
120
 
121
  ### Data Fields
122
 
123
- Below is a non-exhaustive list of fields, used to standardize the various data that are encountered, that you may expect encounter in the parsed COA data.
124
 
125
  | Field | Example | Description |
126
  |-------|-----|-------------|
@@ -161,8 +155,7 @@ The data is split into subsets by state. You can retrieve all licenses by reques
161
  from datasets import load_dataset
162
 
163
  # Get all cannabis licenses.
164
- repo = 'cannlytics/cannabis_licenses'
165
- dataset = load_dataset(repo, 'all')
166
  data = dataset['data']
167
  ```
168
 
@@ -181,14 +174,18 @@ Data about organizations operating in the cannabis industry for each state is va
181
  | California | <https://search.cannabis.ca.gov/> |
182
  | Colorado | <https://sbg.colorado.gov/med/licensed-facilities> |
183
  | Connecticut | <https://portal.ct.gov/DCP/Medical-Marijuana-Program/Connecticut-Medical-Marijuana-Dispensary-Facilities> |
 
184
  | Illinois | <https://www.idfpr.com/LicenseLookup/AdultUseDispensaries.pdf> |
185
  | Maine | <https://www.maine.gov/dafs/ocp/open-data/adult-use> |
 
186
  | Massachusetts | <https://masscannabiscontrol.com/open-data/data-catalog/> |
187
  | Michigan | <https://michigan.maps.arcgis.com/apps/webappviewer/index.html?id=cd5a1a76daaf470b823a382691c0ff60> |
 
188
  | Montana | <https://mtrevenue.gov/cannabis/#CannabisLicenses> |
189
  | Nevada | <https://ccb.nv.gov/list-of-licensees/> |
190
  | New Jersey | <https://data.nj.gov/stories/s/ggm4-mprw> |
191
  | New Mexico | <https://nmrldlpi.force.com/bcd/s/public-search-license?division=CCD&language=en_US> |
 
192
  | Oregon | <https://www.oregon.gov/olcc/marijuana/pages/recreational-marijuana-licensing.aspx> |
193
  | Rhode Island | <https://dbr.ri.gov/office-cannabis-regulation/compassion-centers/licensed-compassion-centers> |
194
  | Vermont | <https://ccb.vermont.gov/licenses> |
@@ -218,7 +215,7 @@ python algorithms/main.py
218
  Or you can run each algorithm individually. For example:
219
 
220
  ```
221
- python algorithms/get_licenses_ca.py
222
  ```
223
 
224
  ### Personal and Sensitive Information
@@ -249,7 +246,7 @@ Curated by [🔥Cannlytics](https://cannlytics.com)<br>
249
  ### License
250
 
251
  ```
252
- Copyright (c) 2022 Cannlytics and the Cannabis Data Science Team
253
 
254
  The files associated with this dataset are licensed under a
255
  Creative Commons Attribution 4.0 International license.
@@ -268,11 +265,11 @@ to a third party.
268
  Please cite the following if you use the code examples in your research:
269
 
270
  ```bibtex
271
- @misc{cannlytics2022,
272
  title={Cannabis Data Science},
273
  author={Skeate, Keegan and O'Sullivan-Sutherland, Candace},
274
  journal={https://github.com/cannlytics/cannabis-data-science},
275
- year={2022}
276
  }
277
  ```
278
 
 
1
  ---
2
+ pretty_name: cannabis_licenses
3
  annotations_creators:
4
  - expert-generated
5
  language_creators:
6
  - expert-generated
7
  license:
8
  - cc-by-4.0
 
 
 
 
 
9
  tags:
10
  - cannabis
11
  - licenses
 
 
12
  ---
13
 
14
+ # Cannabis Licenses
15
 
16
+ <!-- FIXME:
17
  <div align="center" style="text-align:center; margin-top:1rem; margin-bottom: 1rem;">
18
  <img style="max-height:365px;width:100%;max-width:720px;" alt="" src="analysis/figures/cannabis-licenses-map.png">
19
+ </div> -->
20
 
21
  ## Table of Contents
22
  - [Table of Contents](#table-of-contents)
 
63
  | [California](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/ca) | `ca` | ✅ |
64
  | [Colorado](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/co) | `co` | ✅ |
65
  | [Connecticut](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/ct) | `ct` | ✅ |
66
+ | [Delaware](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/de) | `md` | ✅ |
67
  | [Illinois](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/il) | `il` | ✅ |
68
  | [Maine](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/me) | `me` | ✅ |
69
+ | [Maryland](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/md) | `md` | ⚠️ Under development |
70
  | [Massachusetts](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/ma) | `ma` | ✅ |
71
  | [Michigan](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/mi) | `mi` | ✅ |
72
+ | [Missouri](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/mo) | `mo` | ✅ |
73
  | [Montana](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/mt) | `mt` | ✅ |
74
  | [Nevada](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/nv) | `nv` | ✅ |
75
  | [New Jersey](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/nj) | `nj` | ✅ |
76
+ | [New Mexico](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/nm) | `nm` | |
77
+ | [New York](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/ny) | `ny` | ⚠️ Under development |
78
  | [Oregon](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/or) | `or` | ✅ |
79
  | [Rhode Island](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/ri) | `ri` | ✅ |
80
  | [Vermont](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/vt) | `vt` | ✅ |
81
  | Virginia | `va` | ⏳ Expected 2024 |
82
  | [Washington](https://huggingface.co/datasets/cannlytics/cannabis_licenses/tree/main/data/wa) | `wa` | ✅ |
83
 
84
+ The following states have issued medical cannabis licenses, but are not (yet) included in the dataset:
85
 
86
  - Alabama
87
  - Arkansas
 
88
  - District of Columbia (D.C.)
89
  - Florida
90
+ - Kentucky (2024)
91
  - Louisiana
 
92
  - Minnesota
93
  - Mississippi
 
94
  - New Hampshire
95
  - North Dakota
96
  - Ohio
 
108
  from datasets import load_dataset
109
 
110
  # Get the licenses for a specific state.
111
+ dataset = load_dataset('cannlytics/cannabis_licenses', 'all')
112
  data = dataset['data']
 
 
113
  ```
114
 
115
  ### Data Fields
116
 
117
+ Below is a non-exhaustive list of fields, used to standardize the various data that are encountered, that you may expect to find for each observation.
118
 
119
  | Field | Example | Description |
120
  |-------|-----|-------------|
 
155
  from datasets import load_dataset
156
 
157
  # Get all cannabis licenses.
158
+ dataset = load_dataset('cannlytics/cannabis_licenses', 'all')
 
159
  data = dataset['data']
160
  ```
161
 
 
174
  | California | <https://search.cannabis.ca.gov/> |
175
  | Colorado | <https://sbg.colorado.gov/med/licensed-facilities> |
176
  | Connecticut | <https://portal.ct.gov/DCP/Medical-Marijuana-Program/Connecticut-Medical-Marijuana-Dispensary-Facilities> |
177
+ | Delaware | <https://dhss.delaware.gov/dhss/dph/hsp/medmarcc.html> |
178
  | Illinois | <https://www.idfpr.com/LicenseLookup/AdultUseDispensaries.pdf> |
179
  | Maine | <https://www.maine.gov/dafs/ocp/open-data/adult-use> |
180
+ | Maryland | <https://mmcc.maryland.gov/Pages/Dispensaries.aspx> |
181
  | Massachusetts | <https://masscannabiscontrol.com/open-data/data-catalog/> |
182
  | Michigan | <https://michigan.maps.arcgis.com/apps/webappviewer/index.html?id=cd5a1a76daaf470b823a382691c0ff60> |
183
+ | Missouri | <https://health.mo.gov/safety/cannabis/licensed-facilities.php> |
184
  | Montana | <https://mtrevenue.gov/cannabis/#CannabisLicenses> |
185
  | Nevada | <https://ccb.nv.gov/list-of-licensees/> |
186
  | New Jersey | <https://data.nj.gov/stories/s/ggm4-mprw> |
187
  | New Mexico | <https://nmrldlpi.force.com/bcd/s/public-search-license?division=CCD&language=en_US> |
188
+ | New York | <https://cannabis.ny.gov/licensing> |
189
  | Oregon | <https://www.oregon.gov/olcc/marijuana/pages/recreational-marijuana-licensing.aspx> |
190
  | Rhode Island | <https://dbr.ri.gov/office-cannabis-regulation/compassion-centers/licensed-compassion-centers> |
191
  | Vermont | <https://ccb.vermont.gov/licenses> |
 
215
  Or you can run each algorithm individually. For example:
216
 
217
  ```
218
+ python algorithms/get_licenses_ny.py
219
  ```
220
 
221
  ### Personal and Sensitive Information
 
246
  ### License
247
 
248
  ```
249
+ Copyright (c) 2022-2023 Cannlytics and the Cannabis Data Science Team
250
 
251
  The files associated with this dataset are licensed under a
252
  Creative Commons Attribution 4.0 International license.
 
265
  Please cite the following if you use the code examples in your research:
266
 
267
  ```bibtex
268
+ @misc{cannlytics2023,
269
  title={Cannabis Data Science},
270
  author={Skeate, Keegan and O'Sullivan-Sutherland, Candace},
271
  journal={https://github.com/cannlytics/cannabis-data-science},
272
+ year={2023}
273
  }
274
  ```
275
 
algorithms/get_licenses_ak.py CHANGED
@@ -1,12 +1,12 @@
1
  """
2
  Cannabis Licenses | Get Alaska Licenses
3
- Copyright (c) 2022 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
- Updated: 10/6/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -35,16 +35,10 @@ import pandas as pd
35
  from selenium import webdriver
36
  from selenium.webdriver.chrome.options import Options
37
  from selenium.webdriver.common.by import By
38
- from selenium.webdriver.chrome.service import Service
39
- try:
40
- import chromedriver_binary # Adds chromedriver binary to path.
41
- except ImportError:
42
- pass # Otherwise, ChromeDriver should be in your path.
43
-
44
 
45
  # Specify where your data lives.
46
  DATA_DIR = '../data/ak'
47
- ENV_FILE = '../.env'
48
 
49
  # Specify state-specific constants.
50
  STATE = 'AK'
@@ -65,42 +59,20 @@ ALASKA = {
65
  }
66
 
67
 
68
- def get_licenses_ak(
69
- data_dir: Optional[str] = None,
70
- env_file: Optional[str] = '.env',
71
- ):
72
- """Get Alaska cannabis license data."""
73
-
74
- # Initialize Selenium and specify options.
75
- service = Service()
76
- options = Options()
77
- options.add_argument('--window-size=1920,1200')
78
-
79
- # DEV: Run with the browser open.
80
- # options.headless = False
81
-
82
- # PRODUCTION: Run with the browser closed.
83
- options.add_argument('--headless')
84
- options.add_argument('--disable-gpu')
85
- options.add_argument('--no-sandbox')
86
-
87
- # Initiate a Selenium driver.
88
- driver = webdriver.Chrome(options=options, service=service)
89
-
90
- # Load the license page.
91
- driver.get(ALASKA['licenses_url'])
92
-
93
- # Get the license type select.
94
  license_types = []
95
  options = driver.find_elements(by=By.TAG_NAME, value='option')
96
  for option in options:
97
  text = option.text
98
  if text:
99
  license_types.append(text)
 
 
100
 
101
- # Iterate over all of the license types.
 
102
  data = []
103
- columns = list(ALASKA['licenses']['columns'].values())
104
  for license_type in license_types:
105
 
106
  # Set the text into the select.
@@ -124,10 +96,121 @@ def get_licenses_ak(
124
  obs[column] = cell.text.replace('\n', ', ')
125
  data.append(obs)
126
 
127
- # End the browser session.
128
- service.stop()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
 
130
- # Standardize the license data.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  licenses = pd.DataFrame(data)
132
  licenses = licenses.assign(
133
  business_legal_name=licenses['business_dba_name'],
@@ -163,49 +246,18 @@ def get_licenses_ak(
163
  )
164
 
165
  # Search for address for each retail license.
166
- # Only search for a query once, then re-use the response.
167
- # Note: There is probably a much, much more efficient way to do this!!!
168
- config = dotenv_values(env_file)
169
- api_key = config['GOOGLE_MAPS_API_KEY']
170
- queries = {}
171
- fields = [
172
- 'formatted_address',
173
- 'formatted_phone_number',
174
- 'geometry/location/lat',
175
- 'geometry/location/lng',
176
- 'website',
177
- ]
178
- licenses = licenses.reset_index(drop=True)
179
- licenses = licenses.assign(
180
- premise_street_address=None,
181
- premise_county=None,
182
- premise_latitude=None,
183
- premise_longitude=None,
184
- business_phone=None,
185
- business_website=None,
186
- )
187
- for index, row in licenses.iterrows():
188
-
189
- # Query Google Place API, if necessary.
190
- query = ', '.join([row['business_dba_name'], row['address']])
191
- gis_data = queries.get(query)
192
- if gis_data is None:
193
- try:
194
- gis_data = search_for_address(query, api_key=api_key, fields=fields)
195
- except:
196
- gis_data = {}
197
- queries[query] = gis_data
198
-
199
- # Record the query.
200
- licenses.iat[index, licenses.columns.get_loc('premise_street_address')] = gis_data.get('street')
201
- licenses.iat[index, licenses.columns.get_loc('premise_county')] = gis_data.get('county')
202
- licenses.iat[index, licenses.columns.get_loc('premise_latitude')] = gis_data.get('latitude')
203
- licenses.iat[index, licenses.columns.get_loc('premise_longitude')] = gis_data.get('longitude')
204
- licenses.iat[index, licenses.columns.get_loc('business_phone')] = gis_data.get('formatted_phone_number')
205
- licenses.iat[index, licenses.columns.get_loc('business_website')] = gis_data.get('website')
206
-
207
- # Clean-up after GIS.
208
- licenses.drop(columns=['address'], inplace=True)
209
 
210
  # Optional: Search for business website for email and a photo.
211
  licenses['business_email'] = None
@@ -216,15 +268,12 @@ def get_licenses_ak(
216
 
217
  # Save and return the data.
218
  if data_dir is not None:
219
- if not os.path.exists(data_dir): os.makedirs(data_dir)
220
- timestamp = datetime.now().isoformat()[:19].replace(':', '-')
221
- retailers = licenses.loc[licenses['license_type'] == 'Retail Marijuana Store']
222
- licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
223
- retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False)
224
  return licenses
225
 
226
 
227
  # === Test ===
 
228
  if __name__ == '__main__':
229
 
230
  # Support command line usage.
 
1
  """
2
  Cannabis Licenses | Get Alaska Licenses
3
+ Copyright (c) 2022-2023 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
+ Updated: 8/17/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
35
  from selenium import webdriver
36
  from selenium.webdriver.chrome.options import Options
37
  from selenium.webdriver.common.by import By
 
 
 
 
 
 
38
 
39
  # Specify where your data lives.
40
  DATA_DIR = '../data/ak'
41
+ ENV_FILE = '../../../.env'
42
 
43
  # Specify state-specific constants.
44
  STATE = 'AK'
 
59
  }
60
 
61
 
62
+ def get_license_types(driver):
63
+ """Get all license types from the select on the page."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  license_types = []
65
  options = driver.find_elements(by=By.TAG_NAME, value='option')
66
  for option in options:
67
  text = option.text
68
  if text:
69
  license_types.append(text)
70
+ return license_types
71
+
72
 
73
+ def extract_table_data(driver, columns, license_types):
74
+ """Extract data from the table on the page."""
75
  data = []
 
76
  for license_type in license_types:
77
 
78
  # Set the text into the select.
 
96
  obs[column] = cell.text.replace('\n', ', ')
97
  data.append(obs)
98
 
99
+ return data
100
+
101
+
102
+ def search_for_license_addresses(
103
+ licenses: pd.DataFrame,
104
+ api_key: str,
105
+ fields: Optional[list] = None,
106
+ ) -> pd.DataFrame:
107
+ """
108
+ Search for address for each retail license.
109
+ Args:
110
+ licenses (pd.DataFrame): A DataFrame containing retail license information, including business names and addresses.
111
+ api_key (str): A Google Places API key.
112
+ fields (list, optional): A list of fields to be returned by the API. Defaults to None.
113
+ Returns:
114
+ pd.DataFrame: A DataFrame containing the original license information, as well as corresponding address, phone, and website data.
115
+ """
116
+
117
+ # Initialize variables.
118
+ queries = {}
119
+ if fields is None:
120
+ fields = [
121
+ 'formatted_address',
122
+ 'formatted_phone_number',
123
+ 'geometry/location/lat',
124
+ 'geometry/location/lng',
125
+ 'website',
126
+ ]
127
+
128
+ # Reset and assign new columns to the licenses DataFrame.
129
+ licenses = licenses.reset_index(drop=True)
130
+ licenses = licenses.assign(
131
+ premise_street_address=None,
132
+ premise_county=None,
133
+ premise_latitude=None,
134
+ premise_longitude=None,
135
+ business_phone=None,
136
+ business_website=None,
137
+ )
138
+
139
+ # Iterate over each license, search for the address, and record the results in the DataFrame.
140
+ for index, row in licenses.iterrows():
141
+ query = ', '.join([row['business_dba_name'], row['address']])
142
+ gis_data = queries.get(query)
143
+
144
+ # Query Google Place API, if necessary.
145
+ if gis_data is None:
146
+ try:
147
+ gis_data = search_for_address(query, api_key=api_key, fields=fields)
148
+ except:
149
+ gis_data = {}
150
+ queries[query] = gis_data
151
+
152
+ # Record the query results.
153
+ licenses.iat[index, licenses.columns.get_loc('premise_street_address')] = gis_data.get('street')
154
+ licenses.iat[index, licenses.columns.get_loc('premise_county')] = gis_data.get('county')
155
+ licenses.iat[index, licenses.columns.get_loc('premise_latitude')] = gis_data.get('latitude')
156
+ licenses.iat[index, licenses.columns.get_loc('premise_longitude')] = gis_data.get('longitude')
157
+ licenses.iat[index, licenses.columns.get_loc('business_phone')] = gis_data.get('formatted_phone_number')
158
+ licenses.iat[index, licenses.columns.get_loc('business_website')] = gis_data.get('website')
159
+
160
+ return licenses
161
+
162
+
163
+ def save_license_data(
164
+ licenses: pd.DataFrame,
165
+ state: str,
166
+ data_dir: str = '.',
167
+ ) -> None:
168
+ """
169
+ Save license data to CSV files.
170
+ Args:
171
+ licenses (pd.DataFrame): A DataFrame containing license information.
172
+ state (str): The two-letter abbreviation for the state associated with the licenses.
173
+ data_dir (str, optional): The directory in which to save the data. If None, the data will not be saved. Defaults to None.
174
+ """
175
+ if not os.path.exists(data_dir):
176
+ os.makedirs(data_dir)
177
+ date = datetime.now().strftime('%Y-%m-%d')
178
+ retailers = licenses.loc[licenses['license_type'] == 'Retail Marijuana Store']
179
+ licenses.to_csv(f'{data_dir}/licenses-{state.lower()}-{date}.csv', index=False)
180
+ licenses.to_csv(f'{data_dir}/licenses-{state.lower()}-latest.csv', index=False)
181
+ retailers.to_csv(f'{data_dir}/retailers-{state.lower()}-{date}.csv', index=False)
182
 
183
+
184
+ def get_licenses_ak(
185
+ data_dir: Optional[str] = None,
186
+ env_file: Optional[str] = '.env',
187
+ ):
188
+ """Get Alaska cannabis license data."""
189
+
190
+ # Load the environment variables.
191
+ config = dotenv_values(env_file)
192
+ google_maps_api_key = config.get('GOOGLE_MAPS_API_KEY')
193
+
194
+ # Initiate a Selenium driver.
195
+ # FIXME: ChromeDriver is not working on Windows.
196
+ try:
197
+ options = Options()
198
+ options.add_argument('--headless')
199
+ driver = webdriver.Chrome(options=options)
200
+ except:
201
+ driver = webdriver.Edge()
202
+
203
+ # Load the licenses page.
204
+ driver.get(ALASKA['licenses_url'])
205
+
206
+ # Get the license type select.
207
+ license_types = get_license_types(driver)
208
+
209
+ # Get all licenses by type.
210
+ columns = list(ALASKA['licenses']['columns'].values())
211
+ data = extract_table_data(driver, columns, license_types)
212
+
213
+ # Standardize the licenses.
214
  licenses = pd.DataFrame(data)
215
  licenses = licenses.assign(
216
  business_legal_name=licenses['business_dba_name'],
 
246
  )
247
 
248
  # Search for address for each retail license.
249
+ if google_maps_api_key:
250
+ fields = [
251
+ 'formatted_address',
252
+ 'formatted_phone_number',
253
+ 'geometry/location/lat',
254
+ 'geometry/location/lng',
255
+ 'website',
256
+ ]
257
+ licenses = search_for_license_addresses(licenses, google_maps_api_key, fields)
258
+
259
+ # Clean-up after adding GIS data.
260
+ licenses.drop(columns=['address'], inplace=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
 
262
  # Optional: Search for business website for email and a photo.
263
  licenses['business_email'] = None
 
268
 
269
  # Save and return the data.
270
  if data_dir is not None:
271
+ save_license_data(licenses, STATE, data_dir)
 
 
 
 
272
  return licenses
273
 
274
 
275
  # === Test ===
276
+ # [✓] Tested: 2023-08-12 by Keegan Skeate <keegan@cannlytics>
277
  if __name__ == '__main__':
278
 
279
  # Support command line usage.
algorithms/get_licenses_az.py CHANGED
@@ -1,12 +1,12 @@
1
  """
2
  Cannabis Licenses | Get Arizona Licenses
3
- Copyright (c) 2022 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/27/2022
9
- Updated: 10/7/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -18,16 +18,22 @@ Data Source:
18
  - Arizona Department of Health Services | Division of Licensing
19
  URL: <https://azcarecheck.azdhs.gov/s/?licenseType=null>
20
 
 
 
 
 
 
 
21
  """
22
  # Standard imports.
23
  from datetime import datetime
24
- from dotenv import dotenv_values
25
  import os
26
  from time import sleep
27
- from typing import Optional
28
 
29
  # External imports.
30
- from cannlytics.data.gis import geocode_addresses
31
  import pandas as pd
32
  import zipcodes
33
 
@@ -38,15 +44,15 @@ from selenium.webdriver.common.by import By
38
  from selenium.webdriver.chrome.service import Service
39
  from selenium.webdriver.support import expected_conditions as EC
40
  from selenium.webdriver.support.ui import WebDriverWait
41
- try:
42
- import chromedriver_binary # Adds chromedriver binary to path.
43
- except ImportError:
44
- pass # Otherwise, ChromeDriver should be in your path.
45
 
46
 
47
  # Specify where your data lives.
48
  DATA_DIR = '../data/az'
49
- ENV_FILE = '../.env'
50
 
51
  # Specify state-specific constants.
52
  STATE = 'AZ'
@@ -57,7 +63,7 @@ ARIZONA = {
57
  }
58
 
59
 
60
- def county_from_zip(x):
61
  """Find a county given a zip code. Returns `None` if no match."""
62
  try:
63
  return zipcodes.matching(x)[0]['county']
@@ -65,6 +71,70 @@ def county_from_zip(x):
65
  return None
66
 
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  def get_licenses_az(
69
  data_dir: Optional[str] = None,
70
  env_file: Optional[str] = '.env',
@@ -74,21 +144,8 @@ def get_licenses_az(
74
  # Create directories if necessary.
75
  if not os.path.exists(data_dir): os.makedirs(data_dir)
76
 
77
- # Initialize Selenium and specify options.
78
- service = Service()
79
- options = Options()
80
- options.add_argument('--window-size=1920,1200')
81
-
82
- # DEV: Run with the browser open.
83
- # options.headless = False
84
-
85
- # PRODUCTION: Run with the browser closed.
86
- options.add_argument('--headless')
87
- options.add_argument('--disable-gpu')
88
- options.add_argument('--no-sandbox')
89
-
90
- # Initiate a Selenium driver.
91
- driver = webdriver.Chrome(options=options, service=service)
92
 
93
  # Load the license page.
94
  driver.get(ARIZONA['licenses_url'])
@@ -98,52 +155,18 @@ def get_licenses_az(
98
  # Get the map container.
99
  container = driver.find_element(by=By.CLASS_NAME, value='slds-container_center')
100
 
 
 
 
 
101
  # Click "Load more" until all of the licenses are visible.
102
- more = True
103
- while(more):
104
- button = container.find_element(by=By.TAG_NAME, value='button')
105
- driver.execute_script('arguments[0].scrollIntoView(true);', button)
106
- button.click()
107
- counter = container.find_element(by=By.CLASS_NAME, value='count-text')
108
- more = int(counter.text.replace(' more', ''))
109
 
110
  # Get license data for each retailer.
111
  data = []
112
  els = container.find_elements(by=By.CLASS_NAME, value='map-list__item')
113
- for i, el in enumerate(els):
114
-
115
- # Get a retailer's data.
116
- count = i + 1
117
- xpath = f'/html/body/div[3]/div[2]/div/div[2]/div[2]/div/div/c-azcc-portal-home/c-azcc-map/div/div[2]/div[2]/div[2]/div[{count}]/c-azcc-map-list-item/div'
118
- list_item = el.find_element(by=By.XPATH, value=xpath)
119
- body = list_item.find_element(by=By.CLASS_NAME, value='slds-media__body')
120
- divs = body.find_elements(by=By.TAG_NAME, value='div')
121
- name = divs[0].text
122
- legal_name = divs[1].text
123
- if not name:
124
- name = legal_name
125
- address = divs[3].text
126
- address_parts = address.split(',')
127
- parts = divs[2].text.split(' · ')
128
-
129
- # Get the retailer's link to get more details.
130
- link = divs[-1].find_element(by=By.TAG_NAME, value='a')
131
- href = link.get_attribute('href')
132
-
133
- # Record the retailer's data.
134
- obs = {
135
- 'address': address,
136
- 'details_url': href,
137
- 'business_legal_name': legal_name,
138
- 'business_dba_name': name,
139
- 'business_phone': parts[-1],
140
- 'license_status': parts[0],
141
- 'license_type': parts[1],
142
- 'premise_street_address': address_parts[0].strip(),
143
- 'premise_city': address_parts[1].strip(),
144
- 'premise_zip_code': address_parts[-1].replace('AZ ', '').strip(),
145
- }
146
- data.append(obs)
147
 
148
  # Standardize the retailer data.
149
  retailers = pd.DataFrame(data)
@@ -181,30 +204,24 @@ def get_licenses_az(
181
  container = driver.find_element(by=By.CLASS_NAME, value='slds-container_center')
182
  sleep(4)
183
 
184
- # Get the `business_email`.
185
  links = container.find_elements(by=By.TAG_NAME, value='a')
186
- for link in links:
187
- href = link.get_attribute('href')
188
- if href is None: continue
189
- if href.startswith('mailto'):
190
- business_email = href.replace('mailto:', '')
191
- col = retailers.columns.get_loc('business_email')
192
- retailers.iat[index, col] = business_email
193
- break
194
 
195
- # Get the `license_number`
196
- for link in links:
197
- href = link.get_attribute('href')
198
- if href is None: continue
199
- if href.startswith('https://azdhs-licensing'):
200
- col = retailers.columns.get_loc('license_number')
201
- retailers.iat[index, col] = link.text
202
- break
 
203
 
204
  # Get the `premise_latitude` and `premise_longitude`.
205
  for link in links:
206
  href = link.get_attribute('href')
207
- if href is None: continue
 
208
  if href.startswith('https://maps.google.com/'):
209
  coords = href.split('=')[1].split('&')[0].split(',')
210
  lat_col = retailers.columns.get_loc('premise_latitude')
@@ -213,35 +230,45 @@ def get_licenses_az(
213
  retailers.iat[index, long_col] = float(coords[1])
214
  break
215
 
 
 
 
 
216
  # Get the `issue_date`.
217
  key = 'License Effective'
218
- el = container.find_element_by_xpath(f"//p[contains(text(),'{key}')]/following-sibling::lightning-formatted-text")
219
  col = retailers.columns.get_loc('issue_date')
220
  retailers.iat[index, col] = el.text
221
 
222
  # Get the `expiration_date`.
223
  key = 'License Expires'
224
- el = container.find_element_by_xpath(f"//p[contains(text(),'{key}')]/following-sibling::lightning-formatted-text")
225
  col = retailers.columns.get_loc('expiration_date')
226
  retailers.iat[index, col] = el.text
227
 
228
  # Get the `business_owner_name`.
229
  key = 'Owner / License'
230
- el = container.find_element_by_xpath(f"//p[contains(text(),'{key}')]/following-sibling::lightning-formatted-text")
231
  col = retailers.columns.get_loc('expiration_date')
232
  retailers.iat[index, col] = el.text
233
 
234
  # Get the `license_designation` ("Services").
235
  key = 'Services'
236
- el = container.find_element_by_xpath(f"//p[contains(text(),'{key}')]/following-sibling::lightning-formatted-rich-text")
237
- col = retailers.columns.get_loc('license_designation')
238
- retailers.iat[index, col] = el.text
 
 
 
239
 
240
  # Create entries for cultivations.
241
  cultivator = retailers.iloc[index].copy()
242
  key = 'Offsite Cultivation Address'
243
- el = container.find_element_by_xpath(f"//p[contains(text(),'{key}')]/following-sibling::lightning-formatted-text")
244
- address = el.text
 
 
 
245
  if address:
246
  parts = address.split(',')
247
  cultivator['address'] = address
@@ -249,13 +276,17 @@ def get_licenses_az(
249
  cultivator['premise_city'] = parts[1].strip()
250
  cultivator['premise_zip_code'] = parts[-1].replace(STATE, '').strip()
251
  cultivator['license_type'] = 'Offsite Cultivation'
252
- cultivators.append(cultivator, ignore_index=True)
 
253
 
254
  # Create entries for manufacturers.
255
  manufacturer = retailers.iloc[index].copy()
256
  key = 'Manufacture Address'
257
- el = container.find_element_by_xpath(f"//p[contains(text(),'{key}')]/following-sibling::lightning-formatted-text")
258
- address = el.text
 
 
 
259
  if address:
260
  parts = address.split(',')
261
  manufacturer['address'] = address
@@ -263,22 +294,28 @@ def get_licenses_az(
263
  manufacturer['premise_city'] = parts[1].strip()
264
  manufacturer['premise_zip_code'] = parts[-1].replace(STATE, '').strip()
265
  manufacturer['license_type'] = 'Offsite Cultivation'
266
- manufacturers.append(manufacturer, ignore_index=True)
 
267
 
268
  # End the browser session.
269
- service.stop()
270
- retailers.drop(column=['address', 'details_url'], inplace=True)
 
 
 
 
 
271
 
272
  # Lookup counties by zip code.
273
- retailers['premise_county'] = retailers['premise_zip_code'].apply(county_from_zip)
274
- cultivators['premise_county'] = cultivators['premise_zip_code'].apply(county_from_zip)
275
- manufacturers['premise_county'] = manufacturers['premise_zip_code'].apply(county_from_zip)
276
 
277
- # Setup geocoding
278
- config = dotenv_values(env_file)
279
- api_key = config['GOOGLE_MAPS_API_KEY']
280
- drop_cols = ['state', 'state_name', 'county', 'address', 'formatted_address']
281
- gis_cols = {'latitude': 'premise_latitude', 'longitude': 'premise_longitude'}
282
 
283
  # # Geocode cultivators.
284
  # cultivators = geocode_addresses(cultivators, api_key=api_key, address_field='address')
@@ -299,20 +336,24 @@ def get_licenses_az(
299
  timestamp = datetime.now().isoformat()
300
  licenses['data_refreshed_date'] = timestamp
301
  retailers['data_refreshed_date'] = timestamp
302
- # cultivators['data_refreshed_date'] = timestamp
303
- # manufacturers['data_refreshed_date'] = timestamp
304
 
305
  # Save and return the data.
306
  if data_dir is not None:
307
- timestamp = timestamp[:19].replace(':', '-')
308
- licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
309
- retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False)
310
- # cultivators.to_csv(f'{data_dir}/cultivators-{STATE.lower()}-{timestamp}.csv', index=False)
311
- # manufacturers.to_csv(f'{data_dir}/manufacturers-{STATE.lower()}-{timestamp}.csv', index=False)
 
 
 
312
  return licenses
313
 
314
 
315
  # === Test ===
 
316
  if __name__ == '__main__':
317
 
318
  # Support command line usage.
@@ -330,4 +371,3 @@ if __name__ == '__main__':
330
  data_dir = args.get('d', args.get('data_dir'))
331
  env_file = args.get('env_file')
332
  data = get_licenses_az(data_dir, env_file=env_file)
333
-
 
1
  """
2
  Cannabis Licenses | Get Arizona Licenses
3
+ Copyright (c) 2022-2023 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/27/2022
9
+ Updated: 8/17/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
18
  - Arizona Department of Health Services | Division of Licensing
19
  URL: <https://azcarecheck.azdhs.gov/s/?licenseType=null>
20
 
21
+ TODO:
22
+
23
+ [ ] Separate the functionality into functions.
24
+ [ ] Make the code more robust to errors.
25
+ [ ] Make Google Maps API key optional.
26
+
27
  """
28
  # Standard imports.
29
  from datetime import datetime
30
+ # from dotenv import dotenv_values
31
  import os
32
  from time import sleep
33
+ from typing import List, Optional
34
 
35
  # External imports.
36
+ # from cannlytics.data.gis import geocode_addresses
37
  import pandas as pd
38
  import zipcodes
39
 
 
44
  from selenium.webdriver.chrome.service import Service
45
  from selenium.webdriver.support import expected_conditions as EC
46
  from selenium.webdriver.support.ui import WebDriverWait
47
+ # try:
48
+ # import chromedriver_binary # Adds chromedriver binary to path.
49
+ # except ImportError:
50
+ # pass # Otherwise, ChromeDriver should be in your path.
51
 
52
 
53
  # Specify where your data lives.
54
  DATA_DIR = '../data/az'
55
+ ENV_FILE = '../../../.env'
56
 
57
  # Specify state-specific constants.
58
  STATE = 'AZ'
 
63
  }
64
 
65
 
66
+ def get_county_from_zip(x):
67
  """Find a county given a zip code. Returns `None` if no match."""
68
  try:
69
  return zipcodes.matching(x)[0]['county']
 
71
  return None
72
 
73
 
74
+ def initialize_selenium():
75
+ """Initialize a web driver."""
76
+ try:
77
+ service = Service()
78
+ options = Options()
79
+ options.add_argument('--window-size=1920,1200')
80
+ options.add_argument('--headless')
81
+ options.add_argument('--disable-gpu')
82
+ options.add_argument('--no-sandbox')
83
+ return webdriver.Chrome(options=options, service=service)
84
+ except:
85
+ return webdriver.Edge()
86
+
87
+
88
+ def click_load_more(driver, container):
89
+ """Click "Load more" until all of the licenses are visible."""
90
+ more = True
91
+ while(more):
92
+ button = container.find_element(by=By.TAG_NAME, value='button')
93
+ driver.execute_script('arguments[0].scrollIntoView(true);', button)
94
+ button.click()
95
+ counter = container.find_element(by=By.CLASS_NAME, value='count-text')
96
+ more = int(counter.text.replace(' more', ''))
97
+
98
+
99
+ def get_license_data_from_html(index, el):
100
+ """Get a retailer's data."""
101
+ xpath = f'/html/body/div[3]/div[2]/div/div[2]/div[2]/div/div/c-azcc-portal-home/c-azcc-map/div/div[2]/div[2]/div[2]/div[{index + 1}]/c-azcc-map-list-item/div'
102
+ list_item = el.find_element(by=By.XPATH, value=xpath)
103
+ body = list_item.find_element(by=By.CLASS_NAME, value='slds-media__body')
104
+ divs = body.find_elements(by=By.TAG_NAME, value='div')
105
+ name = divs[0].text
106
+ legal_name = divs[1].text
107
+ if not name:
108
+ name = legal_name
109
+ address = divs[3].text
110
+ address_parts = address.split(',')
111
+ parts = divs[2].text.split(' · ')
112
+ link = divs[-1].find_element(by=By.TAG_NAME, value='a')
113
+ href = link.get_attribute('href')
114
+ return {
115
+ 'address': address,
116
+ 'details_url': href,
117
+ 'business_legal_name': legal_name,
118
+ 'business_dba_name': name,
119
+ 'business_phone': parts[-1],
120
+ 'license_status': parts[0],
121
+ 'license_type': parts[1],
122
+ 'premise_street_address': address_parts[0].strip(),
123
+ 'premise_city': address_parts[1].strip(),
124
+ 'premise_zip_code': address_parts[-1].replace('AZ ', '').strip(),
125
+ }
126
+
127
+
128
+ def get_value_from_links(links: List[str], prefix: str):
129
+ """Get a certain key from given links."""
130
+ for link in links:
131
+ href = link.get_attribute('href')
132
+ if href is None:
133
+ continue
134
+ if href.startswith(prefix):
135
+ return link.text
136
+
137
+
138
  def get_licenses_az(
139
  data_dir: Optional[str] = None,
140
  env_file: Optional[str] = '.env',
 
144
  # Create directories if necessary.
145
  if not os.path.exists(data_dir): os.makedirs(data_dir)
146
 
147
+ # Initialize Selenium.
148
+ driver = initialize_selenium()
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
  # Load the license page.
151
  driver.get(ARIZONA['licenses_url'])
 
155
  # Get the map container.
156
  container = driver.find_element(by=By.CLASS_NAME, value='slds-container_center')
157
 
158
+ # Scroll to the bottom of the page.
159
+ driver.execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', container)
160
+ sleep(1)
161
+
162
  # Click "Load more" until all of the licenses are visible.
163
+ click_load_more(driver, container)
 
 
 
 
 
 
164
 
165
  # Get license data for each retailer.
166
  data = []
167
  els = container.find_elements(by=By.CLASS_NAME, value='map-list__item')
168
+ for index, el in enumerate(els):
169
+ data.append(get_license_data_from_html(index, el))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
  # Standardize the retailer data.
172
  retailers = pd.DataFrame(data)
 
204
  container = driver.find_element(by=By.CLASS_NAME, value='slds-container_center')
205
  sleep(4)
206
 
207
+ # Get links.
208
  links = container.find_elements(by=By.TAG_NAME, value='a')
 
 
 
 
 
 
 
 
209
 
210
+ # Get the `business_email`.
211
+ business_email = get_value_from_links(links, 'mailto:')
212
+ col = retailers.columns.get_loc('business_email')
213
+ retailers.iat[index, col] = business_email
214
+
215
+ # Get the `license_number`.
216
+ license_number = get_value_from_links(links, 'https://azdhs-licensing')
217
+ col = retailers.columns.get_loc('license_number')
218
+ retailers.iat[index, col] = license_number
219
 
220
  # Get the `premise_latitude` and `premise_longitude`.
221
  for link in links:
222
  href = link.get_attribute('href')
223
+ if href is None:
224
+ continue
225
  if href.startswith('https://maps.google.com/'):
226
  coords = href.split('=')[1].split('&')[0].split(',')
227
  lat_col = retailers.columns.get_loc('premise_latitude')
 
230
  retailers.iat[index, long_col] = float(coords[1])
231
  break
232
 
233
+ # FIXME: Scroll down to the bottom of the page.
234
+ driver.execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', container)
235
+ sleep(1)
236
+
237
  # Get the `issue_date`.
238
  key = 'License Effective'
239
+ el = container.find_element('xpath', f"//p[contains(text(),'{key}')]/following-sibling::lightning-formatted-text")
240
  col = retailers.columns.get_loc('issue_date')
241
  retailers.iat[index, col] = el.text
242
 
243
  # Get the `expiration_date`.
244
  key = 'License Expires'
245
+ el = container.find_element('xpath', f"//p[contains(text(),'{key}')]/following-sibling::lightning-formatted-text")
246
  col = retailers.columns.get_loc('expiration_date')
247
  retailers.iat[index, col] = el.text
248
 
249
  # Get the `business_owner_name`.
250
  key = 'Owner / License'
251
+ el = container.find_element('xpath', f"//p[contains(text(),'{key}')]/following-sibling::lightning-formatted-text")
252
  col = retailers.columns.get_loc('expiration_date')
253
  retailers.iat[index, col] = el.text
254
 
255
  # Get the `license_designation` ("Services").
256
  key = 'Services'
257
+ try:
258
+ el = container.find_element('xpath', f"//p[contains(text(),'{key}')]/following-sibling::lightning-formatted-rich-text")
259
+ col = retailers.columns.get_loc('license_designation')
260
+ retailers.iat[index, col] = el.text
261
+ except:
262
+ pass
263
 
264
  # Create entries for cultivations.
265
  cultivator = retailers.iloc[index].copy()
266
  key = 'Offsite Cultivation Address'
267
+ try:
268
+ el = container.find_element('xpath', f"//p[contains(text(),'{key}')]/following-sibling::lightning-formatted-text")
269
+ address = el.text
270
+ except:
271
+ address = None
272
  if address:
273
  parts = address.split(',')
274
  cultivator['address'] = address
 
276
  cultivator['premise_city'] = parts[1].strip()
277
  cultivator['premise_zip_code'] = parts[-1].replace(STATE, '').strip()
278
  cultivator['license_type'] = 'Offsite Cultivation'
279
+ # cultivators.append(cultivator, ignore_index=True)
280
+ cultivators.loc[len(cultivators)] = cultivator
281
 
282
  # Create entries for manufacturers.
283
  manufacturer = retailers.iloc[index].copy()
284
  key = 'Manufacture Address'
285
+ try:
286
+ el = container.find_element('xpath', f"//p[contains(text(),'{key}')]/following-sibling::lightning-formatted-text")
287
+ address = el.text
288
+ except:
289
+ address = None
290
  if address:
291
  parts = address.split(',')
292
  manufacturer['address'] = address
 
294
  manufacturer['premise_city'] = parts[1].strip()
295
  manufacturer['premise_zip_code'] = parts[-1].replace(STATE, '').strip()
296
  manufacturer['license_type'] = 'Offsite Cultivation'
297
+ # manufacturers.append(manufacturer, ignore_index=True)
298
+ manufacturers.loc[len(manufacturers)] = manufacturer
299
 
300
  # End the browser session.
301
+ try:
302
+ driver.close()
303
+ except:
304
+ pass
305
+
306
+ # Drop unnecessary columns.
307
+ retailers.drop(columns=['address', 'details_url'], inplace=True)
308
 
309
  # Lookup counties by zip code.
310
+ retailers['premise_county'] = retailers['premise_zip_code'].apply(get_county_from_zip)
311
+ cultivators['premise_county'] = cultivators['premise_zip_code'].apply(get_county_from_zip)
312
+ manufacturers['premise_county'] = manufacturers['premise_zip_code'].apply(get_county_from_zip)
313
 
314
+ # TODO: Setup geocoding
315
+ # config = dotenv_values(env_file)
316
+ # api_key = config['GOOGLE_MAPS_API_KEY']
317
+ # drop_cols = ['state', 'state_name', 'county', 'address', 'formatted_address']
318
+ # gis_cols = {'latitude': 'premise_latitude', 'longitude': 'premise_longitude'}
319
 
320
  # # Geocode cultivators.
321
  # cultivators = geocode_addresses(cultivators, api_key=api_key, address_field='address')
 
336
  timestamp = datetime.now().isoformat()
337
  licenses['data_refreshed_date'] = timestamp
338
  retailers['data_refreshed_date'] = timestamp
339
+ cultivators['data_refreshed_date'] = timestamp
340
+ manufacturers['data_refreshed_date'] = timestamp
341
 
342
  # Save and return the data.
343
  if data_dir is not None:
344
+ date = timestamp[:10]
345
+ licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{date}.csv', index=False)
346
+ licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
347
+ retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{date}.csv', index=False)
348
+ cultivators.to_csv(f'{data_dir}/cultivators-{STATE.lower()}-{date}.csv', index=False)
349
+ manufacturers.to_csv(f'{data_dir}/manufacturers-{STATE.lower()}-{date}.csv', index=False)
350
+
351
+ # Return the licenses.
352
  return licenses
353
 
354
 
355
  # === Test ===
356
+ # [✓] Tested: 2023-08-13 by Keegan Skeate <keegan@cannlytics>
357
  if __name__ == '__main__':
358
 
359
  # Support command line usage.
 
371
  data_dir = args.get('d', args.get('data_dir'))
372
  env_file = args.get('env_file')
373
  data = get_licenses_az(data_dir, env_file=env_file)
 
algorithms/get_licenses_ca.py CHANGED
@@ -6,7 +6,7 @@ Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/16/2022
9
- Updated: 9/27/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -90,10 +90,14 @@ def get_licenses_ca(
90
  # Save and return the data.
91
  if data_dir is not None:
92
  if not os.path.exists(data_dir): os.makedirs(data_dir)
93
- timestamp = datetime.now().isoformat()[:19].replace(':', '-')
94
- license_data.to_csv(f'{data_dir}/licenses-ca-{timestamp}.csv', index=False)
 
95
  return license_data
96
 
 
 
 
97
  if __name__ == '__main__':
98
 
99
  # Support command line usage.
 
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/16/2022
9
+ Updated: 8/17/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
90
  # Save and return the data.
91
  if data_dir is not None:
92
  if not os.path.exists(data_dir): os.makedirs(data_dir)
93
+ date = datetime.now().strftime('%Y-%m-%d')
94
+ license_data.to_csv(f'{data_dir}/licenses-ca-{date}.csv', index=False)
95
+ license_data.to_csv(f'{data_dir}/licenses-ca-latest.csv', index=False)
96
  return license_data
97
 
98
+
99
+ # === Test ===
100
+ # [✓] Tested: 2023-08-13 by Keegan Skeate <keegan@cannlytics>
101
  if __name__ == '__main__':
102
 
103
  # Support command line usage.
algorithms/get_licenses_co.py CHANGED
@@ -6,7 +6,7 @@ Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
- Updated: 10/4/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -36,7 +36,7 @@ import requests
36
 
37
  # Specify where your data lives.
38
  DATA_DIR = '../data/co'
39
- ENV_FILE = '../.env'
40
 
41
  # Specify state-specific constants.
42
  STATE = 'CO'
@@ -151,8 +151,8 @@ def get_licenses_co(
151
  config = dotenv_values(env_file)
152
  api_key = config['GOOGLE_MAPS_API_KEY']
153
  cols = ['business_dba_name', 'premise_city', 'premise_state', 'premise_zip_code']
154
- retailers = licenses.loc[licenses['license_type'] == 'Stores']
155
- retailers['query'] = retailers[cols].apply(
156
  lambda row: ', '.join(row.values.astype(str)),
157
  axis=1,
158
  )
@@ -192,16 +192,33 @@ def get_licenses_co(
192
  # Clean-up after getting GIS data.
193
  retailers.drop(columns=['query'], inplace=True)
194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  # Save and return the data.
196
  if data_dir is not None:
197
  if not os.path.exists(data_dir): os.makedirs(data_dir)
198
  timestamp = datetime.now().isoformat()[:19].replace(':', '-')
199
  licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
 
200
  retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False)
201
  return licenses
202
 
203
 
204
  # === Test ===
 
205
  if __name__ == '__main__':
206
 
207
  # Support command line usage.
 
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
+ Updated: 9/20/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
36
 
37
  # Specify where your data lives.
38
  DATA_DIR = '../data/co'
39
+ ENV_FILE = '../../../.env'
40
 
41
  # Specify state-specific constants.
42
  STATE = 'CO'
 
151
  config = dotenv_values(env_file)
152
  api_key = config['GOOGLE_MAPS_API_KEY']
153
  cols = ['business_dba_name', 'premise_city', 'premise_state', 'premise_zip_code']
154
+ retailers = licenses.loc[licenses['license_type'] == 'Stores'].copy()
155
+ retailers['query'] = retailers.loc[:, cols].apply(
156
  lambda row: ', '.join(row.values.astype(str)),
157
  axis=1,
158
  )
 
192
  # Clean-up after getting GIS data.
193
  retailers.drop(columns=['query'], inplace=True)
194
 
195
+ # TODO: Merge retailer fields with licenses.
196
+ new_fields = [
197
+ 'license_number',
198
+ 'premise_street_address',
199
+ 'premise_county',
200
+ 'premise_latitude',
201
+ 'premise_longitude',
202
+ 'business_website',
203
+ 'business_phone'
204
+ ]
205
+ licenses = pd.merge(licenses, retailers[new_fields], how='left', on='license_number')
206
+ licenses.loc[licenses['business_phone_y'].notna(), 'business_phone_x'] = licenses['business_phone_y']
207
+ licenses.drop(columns=['business_phone_y'], inplace=True)
208
+ licenses.rename(columns={'business_phone_x': 'business_phone'}, inplace=True)
209
+
210
  # Save and return the data.
211
  if data_dir is not None:
212
  if not os.path.exists(data_dir): os.makedirs(data_dir)
213
  timestamp = datetime.now().isoformat()[:19].replace(':', '-')
214
  licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
215
+ licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
216
  retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False)
217
  return licenses
218
 
219
 
220
  # === Test ===
221
+ # [✓] Tested: 2023-09-20 by Keegan Skeate <keegan@cannlytics>
222
  if __name__ == '__main__':
223
 
224
  # Support command line usage.
algorithms/get_licenses_ct.py CHANGED
@@ -6,7 +6,7 @@ Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
- Updated: 10/3/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -34,7 +34,7 @@ import requests
34
 
35
  # Specify where your data lives.
36
  DATA_DIR = '../data/ct'
37
- ENV_FILE = '../.env'
38
 
39
  # Specify state-specific constants.
40
  STATE = 'CT'
@@ -133,17 +133,23 @@ def get_licenses_ct(
133
  retailers.rename(columns=gis_cols, inplace=True)
134
 
135
  # Get the refreshed date.
136
- retailers['data_refreshed_date'] = datetime.now().isoformat()
 
137
 
138
- # Save and return the data.
139
  if data_dir is not None:
140
  if not os.path.exists(data_dir): os.makedirs(data_dir)
141
- timestamp = datetime.now().isoformat()[:19].replace(':', '-')
142
- retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False)
 
 
 
 
143
  return retailers
144
 
145
 
146
  # === Test ===
 
147
  if __name__ == '__main__':
148
 
149
  # Support command line usage.
 
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
+ Updated: 8/17/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
34
 
35
  # Specify where your data lives.
36
  DATA_DIR = '../data/ct'
37
+ ENV_FILE = '../../../.env'
38
 
39
  # Specify state-specific constants.
40
  STATE = 'CT'
 
133
  retailers.rename(columns=gis_cols, inplace=True)
134
 
135
  # Get the refreshed date.
136
+ timestamp = datetime.now().isoformat()
137
+ retailers['data_refreshed_date'] = timestamp
138
 
139
+ # Save the data.
140
  if data_dir is not None:
141
  if not os.path.exists(data_dir): os.makedirs(data_dir)
142
+ date = timestamp[:10]
143
+ retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{date}.csv', index=False)
144
+ retailers.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{date}.csv', index=False)
145
+ retailers.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
146
+
147
+ # Return the licenses.
148
  return retailers
149
 
150
 
151
  # === Test ===
152
+ # [✓] Tested: 2023-08-13 by Keegan Skeate <keegan@cannlytics>
153
  if __name__ == '__main__':
154
 
155
  # Support command line usage.
algorithms/get_licenses_de.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Cannabis Licenses | Get Delaware Licenses
3
+ Copyright (c) 2023 Cannlytics
4
+
5
+ Authors:
6
+ Keegan Skeate <https://github.com/keeganskeate>
7
+ Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
+ Created: 4/25/2023
9
+ Updated: 8/13/2023
10
+ License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
+
12
+ Description:
13
+
14
+ Collect Delaware cannabis license data.
15
+
16
+ Data Source:
17
+
18
+ - Delaware Health Care Commission
19
+ URL: <https://dhss.delaware.gov/dhss/dph/hsp/medmarcc.html>
20
+
21
+ """
22
+ # Standard imports:
23
+ from datetime import datetime
24
+ import os
25
+ from typing import Optional
26
+
27
+ # External imports:
28
+ from bs4 import BeautifulSoup
29
+ from cannlytics.data.gis import geocode_addresses
30
+ from dotenv import dotenv_values
31
+ import pandas as pd
32
+ import requests
33
+
34
+
35
+ # Specify where your data lives.
36
+ DATA_DIR = '../data/de'
37
+ ENV_FILE = '../../../.env'
38
+
39
+ # Specify state-specific constants.
40
+ STATE = 'DE'
41
+ DELAWARE = {
42
+ 'licensing_authority_id': 'DHCC',
43
+ 'licensing_authority': 'Delaware Health Care Commission',
44
+ 'licenses_url': 'https://dhss.delaware.gov/dhss/dph/hsp/medmarcc.html',
45
+ }
46
+
47
+
48
+ def get_gis_data(df: pd.DataFrame, api_key: str) -> pd.DataFrame:
49
+ """Get GIS data."""
50
+ drop_cols = ['state', 'state_name', 'address', 'formatted_address']
51
+ rename_cols = {
52
+ 'county': 'premise_county',
53
+ 'latitude': 'premise_latitude',
54
+ 'longitude': 'premise_longitude'
55
+ }
56
+ df = geocode_addresses(df, api_key=api_key, address_field='address')
57
+ get_city = lambda x: x.split(', ')[1].split(',')[0] if STATE in str(x) else x
58
+ df['premise_city'] = df['formatted_address'].apply(get_city)
59
+ df.drop(columns=drop_cols, inplace=True)
60
+ return df.rename(columns=rename_cols)
61
+
62
+
63
+ def get_licenses_de(
64
+ data_dir: Optional[str] = None,
65
+ env_file: Optional[str] = '.env',
66
+ ):
67
+ """Get Delaware cannabis license data."""
68
+
69
+ # Load the environment variables.
70
+ config = dotenv_values(env_file)
71
+ google_maps_api_key = config.get('GOOGLE_MAPS_API_KEY')
72
+ if google_maps_api_key is None:
73
+ print('Proceeding without `GOOGLE_MAPS_API_KEY`.')
74
+
75
+ # Get the license webpage.
76
+ url = DELAWARE['licenses_url']
77
+ response = requests.get(url)
78
+ soup = BeautifulSoup(response.content, 'html.parser')
79
+
80
+ # Get the licenses table.
81
+ table = soup.find('table')
82
+
83
+ # Extract the license names.
84
+ license_names = [x.text for x in table.find_all('strong') + table.find_all('b')]
85
+ license_names = [x for x in license_names if x != 'Additional Links']
86
+
87
+ # Extract the license websites.
88
+ websites = [x.text for x in table.find_all('a') if x]
89
+ websites = [x for x in websites if x.startswith('http')]
90
+
91
+ # Get address and phone number.
92
+ pars = table.find_all('p')
93
+ addresses, phone_numbers = [], []
94
+ for par in pars:
95
+
96
+ # Identify the company name.
97
+ names = [x.text for x in par.find_all('strong') + par.find_all('b')]
98
+ if not names:
99
+ continue
100
+
101
+ # Iterate over all companies.
102
+ for name in names:
103
+
104
+ # Get the lines.
105
+ lines = par.text.split(name)[-1].split('http')[0].split('\t\t\t\t\t\t')
106
+ lines = [x.replace('\r', '').replace('\n', '') for x in lines[1:]]
107
+
108
+ # Get the phone number.
109
+ phone_number = lines[-1]
110
+ phone_numbers.append(phone_number)
111
+
112
+ # Get the address.
113
+ address = ' '.join(lines[:-1])
114
+ addresses.append(address)
115
+
116
+ # Compile the license data.
117
+ data = pd.DataFrame({
118
+ 'business_legal_name': license_names,
119
+ 'business_website': websites,
120
+ 'address': addresses,
121
+ 'phone_number': phone_numbers,
122
+ })
123
+
124
+ # Augment with GIS data.
125
+ if google_maps_api_key:
126
+ data = get_gis_data(data, google_maps_api_key)
127
+
128
+ # Standardize the licenses.
129
+ data = data.assign(
130
+ id=data.index.astype(str),
131
+ business_dba_name=data['business_legal_name'],
132
+ licensing_authority_id=DELAWARE['licensing_authority_id'],
133
+ licensing_authority=DELAWARE['licensing_authority'],
134
+ premise_state=STATE,
135
+ license_status_date=None,
136
+ license_type='Commercial - Retailer',
137
+ license_term=None,
138
+ issue_date=None,
139
+ expiration_date=None,
140
+ business_structure=None,
141
+ activity=None,
142
+ parcel_number=None,
143
+ business_image_url=None,
144
+ )
145
+
146
+ # Define metadata.
147
+ data['data_refreshed_date'] = datetime.now().isoformat()
148
+
149
+ # Sort the columns in alphabetical order
150
+ data.sort_index(axis=1, inplace=True)
151
+
152
+ # Save all of the licenses.
153
+ if data_dir is not None:
154
+ if not os.path.exists(data_dir):
155
+ os.makedirs(data_dir)
156
+ date = datetime.now().isoformat()[:10]
157
+ data.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{date}.csv', index=False)
158
+ data.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
159
+
160
+ # Return the licenses.
161
+ return data
162
+
163
+
164
+ # === Test ===
165
+ # [✓] Tested: 2023-08-13 by Keegan Skeate <keegan@cannlytics>
166
+ if __name__ == '__main__':
167
+
168
+ # Support command line usage.
169
+ import argparse
170
+ try:
171
+ arg_parser = argparse.ArgumentParser()
172
+ arg_parser.add_argument('--d', dest='data_dir', type=str)
173
+ arg_parser.add_argument('--data_dir', dest='data_dir', type=str)
174
+ arg_parser.add_argument('--env', dest='env_file', type=str)
175
+ args = arg_parser.parse_args()
176
+ except SystemExit:
177
+ args = {'d': DATA_DIR, 'env_file': ENV_FILE}
178
+
179
+ # Get licenses, saving them to the specified directory.
180
+ data_dir = args.get('d', args.get('data_dir'))
181
+ env_file = args.get('env_file')
182
+ data = get_licenses_de(data_dir, env_file=env_file)
algorithms/get_licenses_fl.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Florida cannabis licenses and lab results
3
+ Copyright (c) 2023 Cannlytics
4
+
5
+ Authors:
6
+ Keegan Skeate <https://github.com/keeganskeate>
7
+ Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
+ Created: 5/18/2023
9
+ Updated: 8/14/2023
10
+ License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
+
12
+ Description:
13
+
14
+ Archive Florida cannabis license data.
15
+
16
+ Data Sources:
17
+
18
+ - [Florida Labs](https://knowthefactsmmj.com/cmtl/)
19
+ - [Florida Licenses](https://knowthefactsmmj.com/mmtc/)
20
+
21
+ Resources:
22
+
23
+ - 'https://www.reddit.com/r/FLMedicalTrees/search/?q=COA'
24
+ - https://www.reddit.com/r/FLMedicalTrees/comments/1272per/anyone_have_batch_s_they_can_share_for_our/
25
+ - https://www.reddit.com/r/FLMedicalTrees/comments/vdnpqf/coa_accumulation/
26
+
27
+ """
28
+ # Standard imports:
29
+ from datetime import datetime
30
+ import os
31
+ from typing import Optional
32
+
33
+ # External imports:
34
+ from bs4 import BeautifulSoup
35
+ from cannlytics.data.gis import geocode_addresses
36
+ from dotenv import dotenv_values
37
+ import pandas as pd
38
+ import requests
39
+
40
+
41
+ # Specify state-specific constants.
42
+ STATE = 'FL'
43
+ FLORIDA = {
44
+ 'licensing_authority_id': 'OMMU',
45
+ 'licensing_authority': 'Florida Office of Medical Marijuana Use',
46
+ 'licenses_url': 'https://knowthefactsmmj.com/mmtc/',
47
+ 'labs_url': 'https://knowthefactsmmj.com/cmtl/',
48
+ 'columns': {
49
+ 'Name': 'business_dba_name',
50
+ 'Phone': 'business_phone',
51
+ 'Email': 'business_email',
52
+ 'Authorization Status': 'license_status',
53
+ 'License Number': 'license_number',
54
+ },
55
+ 'labs_columns': {
56
+ 'Name': 'business_dba_name',
57
+ 'Phone': 'business_phone',
58
+ 'Email': 'business_email',
59
+ 'Address': 'address',
60
+ 'Date Certified': 'issue_date',
61
+ }
62
+ }
63
+
64
+
65
+ #-----------------------------------------------------------------------
66
+ # Get Florida labs.
67
+ #-----------------------------------------------------------------------
68
+
69
+ def get_labs_fl(
70
+ data_dir: Optional[str] = None,
71
+ env_file: Optional[str] = '.env',
72
+ ) -> pd.DataFrame:
73
+ """Get labs in Florida."""
74
+
75
+ # Load the environment variables.
76
+ config = dotenv_values(env_file)
77
+ google_maps_api_key = config.get('GOOGLE_MAPS_API_KEY')
78
+ if google_maps_api_key is None:
79
+ print('Proceeding without `GOOGLE_MAPS_API_KEY`.')
80
+
81
+ # Get the licenses URL.
82
+ url = FLORIDA['labs_url']
83
+ response = requests.get(url)
84
+ if response.status_code != 200:
85
+ print(f"Request failed with status {response.status_code}")
86
+
87
+ # Get the table data.
88
+ soup = BeautifulSoup(response.content, 'html.parser')
89
+ table = soup.find('table')
90
+ rows = table.find_all('tr')[1:]
91
+ columns = FLORIDA['labs_columns']
92
+ observations = []
93
+ for row in rows:
94
+ cells = row.find_all('td')
95
+ cells = [x.text.replace('\n', ' ').strip() for x in cells]
96
+ observations.append(cells)
97
+
98
+ # Convert the list of rows into a DataFrame.
99
+ df = pd.DataFrame(observations)
100
+ df.columns = list(columns.values())
101
+
102
+ # Geocode licenses.
103
+ if google_maps_api_key is not None:
104
+ df = geocode_addresses(
105
+ df,
106
+ api_key=google_maps_api_key,
107
+ address_field='address',
108
+ )
109
+ df.rename(columns={
110
+ # 'county': 'premise_county',
111
+ 'latitude': 'premise_latitude',
112
+ 'longitude': 'premise_longitude'
113
+ }, inplace=True)
114
+ parts = df['formatted_address'].str.split(',', n=3, expand=True)
115
+ df['premise_street'] = parts[0]
116
+ df['premise_city'] = parts[1]
117
+ df['premise_state'] = STATE
118
+ df['premise_zip_code'] = parts[2].str.replace(STATE, '').str.strip()
119
+ drop_cols = ['address', 'formatted_address', 'county', 'state', 'state_name']
120
+ df.drop(columns=drop_cols, inplace=True)
121
+
122
+ # Standardize the licenses data.
123
+ df = df.assign(
124
+ business_legal_name=df['business_dba_name'],
125
+ licensing_authority_id=FLORIDA['licensing_authority_id'],
126
+ licensing_authority=FLORIDA['licensing_authority'],
127
+ business_structure=None,
128
+ business_owner_name=None,
129
+ parcel_number=None,
130
+ expiration_date=None,
131
+ business_image_url=None,
132
+ business_website=None,
133
+ license_status_date=None,
134
+ license_type='Lab',
135
+ license_designation=None,
136
+ activity=None,
137
+ )
138
+
139
+ # Set metadata.
140
+ df['data_refreshed_date'] = datetime.now().isoformat()
141
+
142
+ # Save the data.
143
+ if data_dir is not None:
144
+ if not os.path.exists(data_dir): os.makedirs(data_dir)
145
+ df.to_csv(f'{data_dir}/labs-{STATE.lower()}-latest.csv', index=False)
146
+
147
+ # Return the data.
148
+ return df
149
+
150
+
151
+ #-----------------------------------------------------------------------
152
+ # Get Florida retailers.
153
+ #-----------------------------------------------------------------------
154
+
155
+ def get_retailers_fl(
156
+ data_dir: Optional[str] = None,
157
+ env_file: Optional[str] = '.env',
158
+ ) -> pd.DataFrame:
159
+ """Get retailers in Florida."""
160
+
161
+ # Get the licenses URL.
162
+ url = FLORIDA['licenses_url']
163
+ response = requests.get(url)
164
+ if response.status_code != 200:
165
+ print(f"Request failed with status {response.status_code}")
166
+
167
+ # TODO: Get the retailers from each page!
168
+
169
+ # Geocode licenses.
170
+ if google_maps_api_key is not None:
171
+ df = geocode_addresses(
172
+ df,
173
+ api_key=google_maps_api_key,
174
+ address_field='address',
175
+ )
176
+ # FIXME: Would be ideal to also get the county.
177
+ df['premise_county'] = None
178
+ df.rename(columns={
179
+ # 'county': 'premise_county',
180
+ 'latitude': 'premise_latitude',
181
+ 'longitude': 'premise_longitude'
182
+ }, inplace=True)
183
+ parts = df['formatted_address'].str.split(',', n=3, expand=True)
184
+ df['premise_street'] = parts[0]
185
+ df['premise_city'] = parts[1]
186
+ df['premise_state'] = STATE
187
+ df['premise_zip_code'] = parts[2].str.replace(STATE, '').str.strip()
188
+ drop_cols = ['address', 'formatted_address']
189
+ df.drop(columns=drop_cols, inplace=True)
190
+
191
+ raise NotImplementedError
192
+
193
+
194
+ #-----------------------------------------------------------------------
195
+ # Get Florida licenses.
196
+ #-----------------------------------------------------------------------
197
+
198
+ def get_licenses_fl(
199
+ data_dir: Optional[str] = None,
200
+ env_file: Optional[str] = '.env',
201
+ ) -> pd.DataFrame:
202
+ """Get licenses in Florida."""
203
+
204
+ # Load the environment variables.
205
+ config = dotenv_values(env_file)
206
+ google_maps_api_key = config.get('GOOGLE_MAPS_API_KEY')
207
+ if google_maps_api_key is None:
208
+ print('Proceeding without `GOOGLE_MAPS_API_KEY`.')
209
+
210
+ # Get the licenses URL.
211
+ url = FLORIDA['licenses_url']
212
+ response = requests.get(url)
213
+ if response.status_code != 200:
214
+ print(f"Request failed with status {response.status_code}")
215
+
216
+ # Get the table data.
217
+ soup = BeautifulSoup(response.content, 'html.parser')
218
+ table = soup.find('table')
219
+ cells = table.text.split('\n')
220
+ cells = [x for x in cells if x]
221
+ columns = FLORIDA['columns']
222
+ rows = cells[len(columns):]
223
+ rows = [rows[i:i+len(columns)] for i in range(0, len(rows), len(columns))]
224
+
225
+ # Convert the list of rows into a DataFrame.
226
+ df = pd.DataFrame(rows)
227
+ df.columns = list(columns.values())
228
+
229
+ # Get the business website and license URLs from each row.
230
+ business_websites, license_urls = [], []
231
+ table_rows = table.find_all('tr')[1:]
232
+ for row in table_rows:
233
+ columns = row.find_all('td')
234
+ business_link = columns[0].find('a')
235
+ business_websites.append(business_link['href'] if business_link else None)
236
+ license_link = columns[-1].find('a')
237
+ license_urls.append(license_link['href'] if license_link else None)
238
+ df['business_website'] = business_websites
239
+ df['license_url'] = license_urls
240
+
241
+ # TODO: Get issue date from the license PDF.
242
+ # (Will need to apply OCR to get a PDF first.)
243
+ df['issue_date'] = None
244
+
245
+ # TODO: Get the business legal name from the license PDF.
246
+ df['business_legal_name'] = df['business_dba_name']
247
+
248
+ # Standardize the licenses data.
249
+ df = df.assign(
250
+ licensing_authority_id=FLORIDA['licensing_authority_id'],
251
+ licensing_authority=FLORIDA['licensing_authority'],
252
+ business_structure=None,
253
+ business_owner_name=None,
254
+ parcel_number=None,
255
+ expiration_date=None,
256
+ business_image_url=None,
257
+ business_website=None,
258
+ license_status='Active',
259
+ license_status_date=None,
260
+ license_type='Medical - Retailer',
261
+ license_designation=None,
262
+ activity=None,
263
+ )
264
+
265
+ # Set metadata.
266
+ df['data_refreshed_date'] = datetime.now().isoformat()
267
+
268
+ # Save the data.
269
+ if data_dir is not None:
270
+ if not os.path.exists(data_dir): os.makedirs(data_dir)
271
+ df.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
272
+
273
+ # Return the data.
274
+ return df
275
+
276
+
277
+ # === Tests ===
278
+ # [✓] Tested: 2023-08-14 by Keegan Skeate <keegan@cannlytics>
279
+ if __name__ == '__main__':
280
+
281
+ # Specify where your data lives.
282
+ data_dir = '../data/fl'
283
+ env_file = '../../../.env'
284
+
285
+ # [✓] TEST: Get Florida labs.
286
+ labs = get_labs_fl(data_dir=data_dir, env_file=env_file)
287
+
288
+ # [ ] TEST: Get Florida retailers.
289
+
290
+
291
+ # [✓] TEST: Get Florida licenses.
292
+ licenses = get_licenses_fl(data_dir=data_dir, env_file=env_file)
algorithms/get_licenses_il.py CHANGED
@@ -1,12 +1,12 @@
1
  """
2
  Cannabis Licenses | Get Illinois Licenses
3
- Copyright (c) 2022 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
- Updated: 10/3/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -35,7 +35,7 @@ import requests
35
 
36
  # Specify where your data lives.
37
  DATA_DIR = '../data/il'
38
- ENV_FILE = '../.env'
39
 
40
  # Specify state-specific constants.
41
  STATE = 'IL'
@@ -43,7 +43,7 @@ ILLINOIS = {
43
  'licensing_authority_id': 'IDFPR',
44
  'licensing_authority': 'Illinois Department of Financial and Professional Regulation',
45
  'retailers': {
46
- 'url': 'https://www.idfpr.com/LicenseLookup/AdultUseDispensaries.pdf',
47
  'columns': [
48
  'business_legal_name',
49
  'business_dba_name',
@@ -53,6 +53,8 @@ ILLINOIS = {
53
  'license_number',
54
  ],
55
  },
 
 
56
  }
57
 
58
 
@@ -89,6 +91,7 @@ def get_licenses_il(
89
  table_data += table
90
 
91
  # Standardize the data.
 
92
  licensee_columns = ILLINOIS['retailers']['columns']
93
  retailers = pd.DataFrame(table_data, columns=licensee_columns)
94
  retailers = retailers.assign(
@@ -122,8 +125,9 @@ def get_licenses_il(
122
 
123
  # Separate address into 'street', 'city', 'state', 'zip_code', 'phone_number'.
124
  streets, cities, states, zip_codes, phone_numbers = [], [], [], [], []
125
- for index, row in retailers.iterrows():
126
- parts = row.address.split(' \n')
 
127
  streets.append(parts[0])
128
  phone_numbers.append(parts[-1])
129
  locales = parts[1]
@@ -171,10 +175,13 @@ def get_licenses_il(
171
  if data_dir is not None:
172
  timestamp = datetime.now().isoformat()[:19].replace(':', '-')
173
  retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False)
 
 
174
  return retailers
175
 
176
 
177
  # === Test ===
 
178
  if __name__ == '__main__':
179
 
180
  # Support command line usage.
 
1
  """
2
  Cannabis Licenses | Get Illinois Licenses
3
+ Copyright (c) 2022-2023 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
+ Updated: 8/13/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
35
 
36
  # Specify where your data lives.
37
  DATA_DIR = '../data/il'
38
+ ENV_FILE = '../../../.env'
39
 
40
  # Specify state-specific constants.
41
  STATE = 'IL'
 
43
  'licensing_authority_id': 'IDFPR',
44
  'licensing_authority': 'Illinois Department of Financial and Professional Regulation',
45
  'retailers': {
46
+ 'url': 'https://idfpr.illinois.gov/content/dam/soi/en/web/idfpr/licenselookup/adultusedispensaries.pdf',
47
  'columns': [
48
  'business_legal_name',
49
  'business_dba_name',
 
53
  'license_number',
54
  ],
55
  },
56
+ # Alt: https://idfpr.illinois.gov/content/dam/soi/en/web/idfpr/forms/auc/2022-10-11-conditional-licenses-list.pdf
57
+ # Medical: https://idfpr.illinois.gov/content/dam/soi/en/web/idfpr/forms/mc/listoflicenseddispensaries.pdf
58
  }
59
 
60
 
 
91
  table_data += table
92
 
93
  # Standardize the data.
94
+ # rows = [[x for x in row if x] for row in table_data]
95
  licensee_columns = ILLINOIS['retailers']['columns']
96
  retailers = pd.DataFrame(table_data, columns=licensee_columns)
97
  retailers = retailers.assign(
 
125
 
126
  # Separate address into 'street', 'city', 'state', 'zip_code', 'phone_number'.
127
  streets, cities, states, zip_codes, phone_numbers = [], [], [], [], []
128
+ for _, row in retailers.iterrows():
129
+ parts = row.address.split('\n')
130
+ parts = [part.strip() for part in parts]
131
  streets.append(parts[0])
132
  phone_numbers.append(parts[-1])
133
  locales = parts[1]
 
175
  if data_dir is not None:
176
  timestamp = datetime.now().isoformat()[:19].replace(':', '-')
177
  retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False)
178
+ retailers.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
179
+ retailers.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
180
  return retailers
181
 
182
 
183
  # === Test ===
184
+ # [✓] Tested: 2023-08-13 by Keegan Skeate <keegan@cannlytics>
185
  if __name__ == '__main__':
186
 
187
  # Support command line usage.
algorithms/get_licenses_ma.py CHANGED
@@ -1,12 +1,12 @@
1
  """
2
  Cannabis Licenses | Get Massachusetts Licenses
3
- Copyright (c) 2022 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
- Updated: 10/7/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -25,7 +25,8 @@ import os
25
  from typing import Optional
26
 
27
  # External imports.
28
- from cannlytics.data.opendata import OpenData
 
29
 
30
 
31
  # Specify where your data lives.
@@ -38,45 +39,71 @@ MASSACHUSETTS = {
38
  'licensing_authority': 'Massachusetts Cannabis Control Commission',
39
  'licenses': {
40
  'columns': {
41
- 'license_number': 'license_number',
42
- 'business_name': 'business_legal_name',
43
- 'establishment_address_1': 'premise_street_address',
44
- 'establishment_address_2': 'premise_street_address_2',
45
  'establishment_city': 'premise_city',
46
- 'establishment_zipcode': 'premise_zip_code',
47
- 'county': 'premise_county',
48
- 'license_type': 'license_type',
49
- 'application_status': 'license_status',
50
- 'lic_status': 'license_term',
51
- 'approved_license_type': 'license_designation',
52
- 'commence_operations_date': 'license_status_date',
53
- 'massachusetts_business': 'id',
54
- 'dba_name': 'business_dba_name',
55
- 'establishment_activities': 'activity',
56
- 'cccupdatedate': 'data_refreshed_date',
57
- 'establishment_state': 'premise_state',
58
  'latitude': 'premise_latitude',
 
 
 
 
 
 
 
59
  'longitude': 'premise_longitude',
60
- },
61
- 'drop': [
62
- 'square_footage_establishment',
63
- 'cooperative_total_canopy',
64
- 'cooperative_cultivation_environment',
65
- 'establishment_cultivation_environment',
66
- 'abutters_count',
67
- 'is_abutters_notified',
68
- 'business_zipcode',
69
- 'dph_rmd_number',
70
- 'geocoded_county',
71
- 'geocoded_address',
72
- 'name_of_rmd',
73
- 'priority_applicant_type',
74
- 'rmd_priority_certification',
75
- 'dba_registration_city',
76
- 'county_lat',
77
- 'county_long',
78
- ]
79
- },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  }
81
 
82
 
@@ -90,45 +117,45 @@ def get_licenses_ma(
90
  ccc = OpenData()
91
  licenses = ccc.get_licensees('approved')
92
 
 
 
 
 
 
 
 
 
 
93
  # Standardize the licenses data.
94
- constants = MASSACHUSETTS['licenses']
95
- licenses.drop(columns=constants['drop'], inplace=True)
96
- licenses.rename(columns=constants['columns'], inplace=True)
97
  licenses = licenses.assign(
 
98
  licensing_authority_id=MASSACHUSETTS['licensing_authority_id'],
99
  licensing_authority=MASSACHUSETTS['licensing_authority'],
 
100
  business_structure=None,
101
  business_email=None,
102
  business_owner_name=None,
103
  parcel_number=None,
104
- issue_date=None,
105
- expiration_date=None,
106
  business_image_url=None,
107
  business_website=None,
108
  business_phone=None,
109
  )
110
 
111
- # Append `premise_street_address_2` to `premise_street_address`.
112
- cols = ['premise_street_address', 'premise_street_address_2']
113
- licenses['premise_street_address'] = licenses[cols].apply(
114
- lambda x : '{} {}'.format(x[0].strip(), x[1]).replace('nan', '').strip().replace(' ', ' '),
115
- axis=1,
116
- )
117
- licenses.drop(columns=['premise_street_address_2'], inplace=True)
118
-
119
  # Optional: Look-up business websites for each license.
120
 
121
  # Save and return the data.
122
  if data_dir is not None:
123
  if not os.path.exists(data_dir): os.makedirs(data_dir)
124
- timestamp = datetime.now().isoformat()[:19].replace(':', '-')
125
  retailers = licenses.loc[licenses['license_type'].str.contains('Retailer')]
126
- retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False)
127
- licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
 
128
  return licenses
129
 
130
 
131
  # === Test ===
 
132
  if __name__ == '__main__':
133
 
134
  # Support command line usage.
@@ -142,5 +169,7 @@ if __name__ == '__main__':
142
  args = {'d': DATA_DIR}
143
 
144
  # Get licenses, saving them to the specified directory.
 
145
  data_dir = args.get('d', args.get('data_dir'))
146
  data = get_licenses_ma(data_dir)
 
 
1
  """
2
  Cannabis Licenses | Get Massachusetts Licenses
3
+ Copyright (c) 2022-2023 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
+ Updated: 9/19/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
25
  from typing import Optional
26
 
27
  # External imports.
28
+ from cannlytics.data import OpenData
29
+ from cannlytics.utils import snake_case
30
 
31
 
32
  # Specify where your data lives.
 
39
  'licensing_authority': 'Massachusetts Cannabis Control Commission',
40
  'licenses': {
41
  'columns': {
42
+ 'mailing_address_1': 'mailing_address_1',
43
+ 'zip': 'premise_zip_code',
44
+ 'ee_priority_number_from_account': 'ee_priority_number_from_account',
 
45
  'establishment_city': 'premise_city',
46
+ 'rmd_priority_number_from_account': 'rmd_priority_number_from_account',
47
+ 'cultivation_environment': 'cultivation_environment',
48
+ 'application_classification_split_2': 'application_classification_split_2',
49
+ 'mailing_city': 'mailing_city',
 
 
 
 
 
 
 
 
50
  'latitude': 'premise_latitude',
51
+ 'ee_priority_number_from_application': 'ee_priority_number_from_application',
52
+ 'business_address_2': 'business_address_2',
53
+ 'establishment_zipcode': 'establishment_zipcode',
54
+ 'submitted_date': 'submitted_date',
55
+ 'county_lat': 'county_lat',
56
+ 'mailing_address_2': 'mailing_address_2',
57
+ 'approved_license_type': 'approved_license_type',
58
  'longitude': 'premise_longitude',
59
+ 'license_type': 'license_type',
60
+ 'application_number': 'application_number',
61
+ 'first_compliance_review_date': 'first_compliance_review_date',
62
+ 'establishment_address_2': 'establishment_address_2',
63
+ 'cccupdatedate': 'cccupdatedate',
64
+ 'license_number': 'license_number',
65
+ 'business_name': 'business_legal_name',
66
+ 'business_state': 'business_state',
67
+ 'lic_fee_amount': 'lic_fee_amount',
68
+ 'region': 'region',
69
+ 'business_city': 'business_city',
70
+ 'fee_waiver_ee_or_se_number': 'fee_waiver_ee_or_se_number',
71
+ 'geocoded_county': 'geocoded_county',
72
+ 'business_zipcode': 'business_zipcode',
73
+ 'application_approved_date': 'application_approved_date',
74
+ 'town': 'town',
75
+ 'cultivation_tier': 'cultivation_tier',
76
+ 'application_classification': 'application_classification',
77
+ 'application_status': 'application_status',
78
+ 'ein_tin': 'ein_tin',
79
+ 'priority': 'priority',
80
+ 'dbe': 'dbe',
81
+ 'rmd_priority_status': 'rmd_priority_status',
82
+ 'lic_status': 'license_status',
83
+ 'lic_fee_payment_submitted_date': 'lic_fee_payment_submitted_date',
84
+ 'establishment_state': 'establishment_state',
85
+ 'business_address_1': 'business_address_1',
86
+ 'ee_priority_status': 'ee_priority_status',
87
+ 'cnb_deemed_complete_date': 'cnb_deemed_complete_date',
88
+ 'mailing_zipcode': 'mailing_zipcode',
89
+ 'lic_expiration_date': 'expiration_date',
90
+ 'commence_operations_date': 'commence_operations_date',
91
+ 'establishment_county': 'establishment_county',
92
+ 'pmt_amount': 'pmt_amount',
93
+ 'fee_waiver_request': 'fee_waiver_request',
94
+ 'lic_start_date': 'lic_start_date',
95
+ 'county': 'premise_county',
96
+ 'application_classification_split_1': 'application_classification_split_1',
97
+ 'establishment_address': 'establishment_address',
98
+ 'county_long': 'county_long',
99
+ 'mailing_state': 'mailing_state',
100
+ 'approved_license_stages': 'approved_license_stages',
101
+ 'application_created_date': 'issue_date',
102
+ 'rmd_priority_number_from_application': 'rmd_priority_number_from_application',
103
+ 'geocoded_address': 'geocoded_address',
104
+ 'cnb_dt_of_final_licensure': 'cnb_dt_of_final_licensure',
105
+ }
106
+ }
107
  }
108
 
109
 
 
117
  ccc = OpenData()
118
  licenses = ccc.get_licensees('approved')
119
 
120
+ # Standardize the fields.
121
+ columns = MASSACHUSETTS['licenses']['columns']
122
+ licenses.columns = [snake_case(col) for col in licenses.columns]
123
+ licenses.rename(columns=columns, inplace=True)
124
+ licenses['business_dba_name'] = licenses['business_legal_name']
125
+
126
+ # Remove duplicates.
127
+ licenses.drop_duplicates(subset=['business_legal_name'], inplace=True)
128
+
129
  # Standardize the licenses data.
 
 
 
130
  licenses = licenses.assign(
131
+ premise_state=STATE,
132
  licensing_authority_id=MASSACHUSETTS['licensing_authority_id'],
133
  licensing_authority=MASSACHUSETTS['licensing_authority'],
134
+ # business_dba_name=licenses['business_legal_name'],
135
  business_structure=None,
136
  business_email=None,
137
  business_owner_name=None,
138
  parcel_number=None,
 
 
139
  business_image_url=None,
140
  business_website=None,
141
  business_phone=None,
142
  )
143
 
 
 
 
 
 
 
 
 
144
  # Optional: Look-up business websites for each license.
145
 
146
  # Save and return the data.
147
  if data_dir is not None:
148
  if not os.path.exists(data_dir): os.makedirs(data_dir)
149
+ date = datetime.now().strftime('%Y-%m-%d')
150
  retailers = licenses.loc[licenses['license_type'].str.contains('Retailer')]
151
+ retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{date}.csv', index=False)
152
+ licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{date}.csv', index=False)
153
+ licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
154
  return licenses
155
 
156
 
157
  # === Test ===
158
+ # [✓] Tested: 2023-09-19 by Keegan Skeate <keegan@cannlytics>
159
  if __name__ == '__main__':
160
 
161
  # Support command line usage.
 
169
  args = {'d': DATA_DIR}
170
 
171
  # Get licenses, saving them to the specified directory.
172
+ # FIXME: This results in a different number of licenses each time!
173
  data_dir = args.get('d', args.get('data_dir'))
174
  data = get_licenses_ma(data_dir)
175
+ print(len(data))
algorithms/get_licenses_md.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Cannabis Licenses | Get Maryland Licenses
3
+ Copyright (c) 2022-2023 Cannlytics
4
+
5
+ Authors:
6
+ Keegan Skeate <https://github.com/keeganskeate>
7
+ Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
+ Created: 11/29/2022
9
+ Updated: 8/13/2023
10
+ License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
+
12
+ Description:
13
+
14
+ Collect Maryland cannabis license data.
15
+
16
+ Data Source:
17
+
18
+ - Maryland Medical Cannabis Commission
19
+ URL: <https://mmcc.maryland.gov/Pages/Dispensaries.aspx>
20
+
21
+ """
22
+ # Standard imports:
23
+ from datetime import datetime
24
+ import os
25
+ import re
26
+ from typing import Optional
27
+ from urllib.parse import urlparse
28
+
29
+ # External imports:
30
+ from bs4 import BeautifulSoup
31
+ from cannlytics.data.gis import geocode_addresses
32
+ from dotenv import dotenv_values
33
+ import pandas as pd
34
+ import requests
35
+
36
+
37
+ # Specify where your data lives.
38
+ DATA_DIR = '../data/md'
39
+ ENV_FILE = '../../../.env'
40
+
41
+ # Specify state-specific constants.
42
+ STATE = 'MD'
43
+ MARYLAND = {
44
+ 'licensing_authority_id': 'MMCC',
45
+ 'licensing_authority': 'Maryland Medical Cannabis Commission',
46
+ 'licenses_url': 'https://mmcc.maryland.gov/Pages/Dispensaries.aspx',
47
+ }
48
+
49
+
50
+ def get_gis_data(df, api_key):
51
+ """Get GIS data."""
52
+ drop_cols = ['state', 'state_name', 'address', 'formatted_address']
53
+ rename_cols = {
54
+ 'county': 'premise_county',
55
+ 'latitude': 'premise_latitude',
56
+ 'longitude': 'premise_longitude'
57
+ }
58
+ df = geocode_addresses(df, api_key=api_key, address_field='address')
59
+ get_city = lambda x: x.split(', ')[1].split(',')[0] if STATE in str(x) else x
60
+ get_street = lambda x: str(x).split(', ')[0]
61
+ df['premise_city'] = df['formatted_address'].apply(get_city)
62
+ df['premise_street_address'] = df['formatted_address'].apply(get_street)
63
+ df.drop(columns=drop_cols, inplace=True)
64
+ return df.rename(columns=rename_cols)
65
+
66
+
67
+ def get_licenses_md(
68
+ data_dir: Optional[str] = None,
69
+ env_file: Optional[str] = '.env',
70
+ ):
71
+ """Get Maryland cannabis license data."""
72
+
73
+ # Load the environment variables.
74
+ config = dotenv_values(env_file)
75
+ google_maps_api_key = config.get('GOOGLE_MAPS_API_KEY')
76
+ if google_maps_api_key is None:
77
+ print('Proceeding without `GOOGLE_MAPS_API_KEY`.')
78
+
79
+ # Get the license webpage.
80
+ url = MARYLAND['licenses_url']
81
+ response = requests.get(url)
82
+ soup = BeautifulSoup(response.content, 'html.parser')
83
+
84
+ # Extract the license data.
85
+ data = []
86
+ for td in soup.find_all('td'):
87
+ entry = {}
88
+
89
+ # Record license data if there is an image.
90
+ img = td.find('img')
91
+ if img:
92
+
93
+ # TODO: Record the image.
94
+ # entry['image'] = img['src']
95
+
96
+ # Record the email and website.
97
+ entry['business_website'] = None
98
+ links = td.find_all('a')
99
+ for link in links:
100
+ if 'mailto' in link['href']:
101
+ entry['business_email'] = link['href'][7:]
102
+ elif 'http' in link['href']:
103
+ entry['business_website'] = link['href']
104
+
105
+ # Handle plain text websites.
106
+ if entry['business_website'] is None and entry['business_email']:
107
+ domain = entry['business_email'].split('@')[1]
108
+ entry['business_website'] = 'https://www.' + domain
109
+
110
+ # Get the business name.
111
+ entry['business_legal_name'] = img['alt']
112
+ if not entry['business_legal_name']:
113
+ parsed_url = urlparse(url)
114
+ entry['business_legal_name'] = parsed_url.netloc.split('.')[0].title()
115
+
116
+ # Hot-fix: Get the business name from the website.
117
+ # FIXME: This is sub-perfect.
118
+ if entry['business_legal_name'] == 'Mmcc':
119
+ website = entry['business_website']
120
+ if 'www' in website:
121
+ entry['business_legal_name'] = \
122
+ website \
123
+ .split('www.')[1] \
124
+ .split('.')[0] \
125
+ .title()
126
+ else:
127
+ entry['business_legal_name'] = \
128
+ website \
129
+ .split('//')[1] \
130
+ .split('.')[0] \
131
+ .title()
132
+
133
+ # Find phone numbers in text.
134
+ # Note: Uses regular expression to match: xxx-xxx-xxxx
135
+ text = td.text.strip()
136
+ phone_number_pattern = re.compile(r'\d{3}-\d{3}-\d{4}')
137
+ phone_numbers = phone_number_pattern.findall(text)
138
+ if phone_numbers:
139
+ entry['business_phone'] = phone_numbers[0]
140
+ else:
141
+ entry['business_phone'] = None
142
+
143
+ # Otherwise record just the name and address.
144
+ else:
145
+ lines = [x.text.replace('\u200b', '') for x in td.contents]
146
+ lines = [x for x in lines if x]
147
+ if not lines:
148
+ continue
149
+ entry['business_legal_name'] = lines[0].strip()
150
+
151
+ # Get the street address.
152
+ address = ', '.join(line.strip() for line in lines[1:])
153
+ address = address.replace('\xa0', ' ')
154
+ entry['address'] = address
155
+
156
+ # Look for phone number below address.
157
+ phone_number_pattern = re.compile(r'\d{3}-\d{3}-\d{4}')
158
+ phone_numbers = phone_number_pattern.findall(address)
159
+ if phone_numbers:
160
+ entry['business_phone'] = phone_numbers[0]
161
+ entry['address'] = address.split(phone_numbers[0])[0].strip()
162
+ else:
163
+ entry['business_phone'] = None
164
+
165
+ # Handle missed addresses.
166
+ if not entry.get('address'):
167
+ address = td.text.split(', MD ')[0] \
168
+ .replace('\u200b', ' ') \
169
+ .replace('\n', ' ') \
170
+ .replace('\xa0', ' ') \
171
+ .replace(' ', ' ') \
172
+ .strip()
173
+ zip_code = re.findall(r'MD \b\d{5}\b', td.text)
174
+ if zip_code:
175
+ zip_code = zip_code[0].split('MD ')[-1]
176
+ else:
177
+ zip_code = ''
178
+ address = f'{address}, MD {zip_code}'.strip()
179
+
180
+ # Clean address.
181
+ address = address.split('http')[0].strip()
182
+ if entry.get('business_phone'):
183
+ address = address.split(entry['business_phone'])[0].strip()
184
+ if entry.get('business_email'):
185
+ address = address.split(entry['business_email'])[0].strip()
186
+ entry['address'] = address
187
+
188
+ # Add the entry to the data.
189
+ data.append(entry)
190
+
191
+ # Standardize the license data.
192
+ retailers = pd.DataFrame(data)
193
+ retailers = retailers.assign(
194
+ id=retailers.index,
195
+ license_status=None,
196
+ business_dba_name=retailers['business_legal_name'],
197
+ license_number=None,
198
+ licensing_authority_id=MARYLAND['licensing_authority_id'],
199
+ licensing_authority=MARYLAND['licensing_authority'],
200
+ license_designation='Adult-Use',
201
+ premise_state=STATE,
202
+ license_status_date=None,
203
+ license_term=None,
204
+ issue_date=None,
205
+ expiration_date=None,
206
+ business_owner_name=None,
207
+ business_structure=None,
208
+ activity=None,
209
+ parcel_number=None,
210
+ business_image_url=None,
211
+ license_type=None,
212
+ )
213
+
214
+ # Get GIS data.
215
+ if google_maps_api_key:
216
+ retailers = get_gis_data(retailers, google_maps_api_key)
217
+
218
+ # Define metadata.
219
+ retailers['data_refreshed_date'] = datetime.now().isoformat()
220
+
221
+ # Save the data.
222
+ if data_dir is not None:
223
+ if not os.path.exists(data_dir):
224
+ os.makedirs(data_dir)
225
+ date = datetime.now().isoformat()[:10]
226
+ retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{date}.csv', index=False)
227
+ retailers.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{date}.csv', index=False)
228
+ retailers.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
229
+
230
+ # Return the licenses.
231
+ return retailers
232
+
233
+
234
+ # === Test ===
235
+ # [✓] Tested: 2023-08-13 by Keegan Skeate <keegan@cannlytics>
236
+ if __name__ == '__main__':
237
+
238
+ # Support command line usage.
239
+ import argparse
240
+ try:
241
+ arg_parser = argparse.ArgumentParser()
242
+ arg_parser.add_argument('--d', dest='data_dir', type=str)
243
+ arg_parser.add_argument('--data_dir', dest='data_dir', type=str)
244
+ arg_parser.add_argument('--env', dest='env_file', type=str)
245
+ args = arg_parser.parse_args()
246
+ except SystemExit:
247
+ args = {'d': DATA_DIR, 'env_file': ENV_FILE}
248
+
249
+ # Get licenses, saving them to the specified directory.
250
+ data_dir = args.get('d', args.get('data_dir'))
251
+ env_file = args.get('env_file')
252
+ data = get_licenses_md(data_dir, env_file=env_file)
algorithms/get_licenses_me.py CHANGED
@@ -1,12 +1,12 @@
1
  """
2
  Cannabis Licenses | Get Maine Licenses
3
- Copyright (c) 2022 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
- Updated: 10/7/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -18,6 +18,13 @@ Data Source:
18
  - Maine Office of Cannabis Policy
19
  URL: <https://www.maine.gov/dafs/ocp/open-data/adult-use>
20
 
 
 
 
 
 
 
 
21
  """
22
  # Standard imports.
23
  from datetime import datetime
@@ -34,7 +41,7 @@ import requests
34
 
35
  # Specify where your data lives.
36
  DATA_DIR = '../data/me'
37
- ENV_FILE = '../.env'
38
 
39
  # Specify state-specific constants.
40
  STATE = 'ME'
@@ -68,6 +75,10 @@ def get_licenses_me(
68
  ):
69
  """Get Maine cannabis license data."""
70
 
 
 
 
 
71
  # Create the necessary directories.
72
  file_dir = f'{data_dir}/.datasets'
73
  if not os.path.exists(data_dir): os.makedirs(data_dir)
@@ -133,14 +144,14 @@ def get_licenses_me(
133
  )
134
 
135
  # Get the refreshed date.
136
- date = licenses_source_file.split('\\')[-1].split('.')[0].replace(licenses_key, '')
137
- date = date.replace('%20', '')
138
- date = '-'.join([date[:2], date[2:4], date[4:]])
139
- licenses['data_refreshed_date'] = pd.to_datetime(date).isoformat()
 
 
140
 
141
  # Geocode licenses to get `premise_latitude` and `premise_longitude`.
142
- config = dotenv_values(env_file)
143
- api_key = config['GOOGLE_MAPS_API_KEY']
144
  cols = ['premise_city', 'premise_state']
145
  licenses['address'] = licenses[cols].apply(
146
  lambda row: ', '.join(row.values.astype(str)),
@@ -162,12 +173,17 @@ def get_licenses_me(
162
 
163
  # Save and return the data.
164
  if data_dir is not None:
165
- timestamp = datetime.now().isoformat()[:19].replace(':', '-')
166
- licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
 
 
 
 
167
  return licenses
168
 
169
 
170
  # === Test ===
 
171
  if __name__ == '__main__':
172
 
173
  # Support command line usage.
 
1
  """
2
  Cannabis Licenses | Get Maine Licenses
3
+ Copyright (c) 2022-2023 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
+ Updated: 8/17/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
18
  - Maine Office of Cannabis Policy
19
  URL: <https://www.maine.gov/dafs/ocp/open-data/adult-use>
20
 
21
+ # TODO:
22
+
23
+ [ ] Priority: Save the retailers in a stand-alone data file.
24
+ [ ] Separate the functionality into functions.
25
+ [ ] Make the code more robust to errors.
26
+ [ ] Make Google Maps API key optional.
27
+
28
  """
29
  # Standard imports.
30
  from datetime import datetime
 
41
 
42
  # Specify where your data lives.
43
  DATA_DIR = '../data/me'
44
+ ENV_FILE = '../../../.env'
45
 
46
  # Specify state-specific constants.
47
  STATE = 'ME'
 
75
  ):
76
  """Get Maine cannabis license data."""
77
 
78
+ # Load the environment variables.
79
+ config = dotenv_values(env_file)
80
+ api_key = config['GOOGLE_MAPS_API_KEY']
81
+
82
  # Create the necessary directories.
83
  file_dir = f'{data_dir}/.datasets'
84
  if not os.path.exists(data_dir): os.makedirs(data_dir)
 
144
  )
145
 
146
  # Get the refreshed date.
147
+ try:
148
+ date = licenses_source_file[-15:]
149
+ date = date.replace('_', '-').replace('.xlsx', '')
150
+ licenses['data_refreshed_date'] = pd.to_datetime(date).isoformat()
151
+ except:
152
+ licenses['data_refreshed_date'] = datetime.now().isoformat()
153
 
154
  # Geocode licenses to get `premise_latitude` and `premise_longitude`.
 
 
155
  cols = ['premise_city', 'premise_state']
156
  licenses['address'] = licenses[cols].apply(
157
  lambda row: ', '.join(row.values.astype(str)),
 
173
 
174
  # Save and return the data.
175
  if data_dir is not None:
176
+ date = datetime.now().strftime('%Y-%m-%d')
177
+ licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{date}.csv', index=False)
178
+ licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
179
+ # TODO: Save the retailers in a stand-alone data file.
180
+
181
+ # Return the licenses.
182
  return licenses
183
 
184
 
185
  # === Test ===
186
+ # [✓] Tested: 2023-08-13 by Keegan Skeate <keegan@cannlytics>
187
  if __name__ == '__main__':
188
 
189
  # Support command line usage.
algorithms/get_licenses_mi.py CHANGED
@@ -1,12 +1,12 @@
1
  """
2
  Cannabis Licenses | Get Michigan Licenses
3
- Copyright (c) 2022 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
- Updated: 10/8/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -18,11 +18,16 @@ Data Source:
18
  - Michigan Cannabis Regulatory Agency
19
  URL: <https://michigan.maps.arcgis.com/apps/webappviewer/index.html?id=cd5a1a76daaf470b823a382691c0ff60>
20
 
 
 
 
 
 
 
21
  """
22
  # Standard imports.
23
  from datetime import datetime
24
  import os
25
- from time import sleep
26
  from typing import Optional
27
 
28
  # External imports.
@@ -38,15 +43,15 @@ from selenium.webdriver.chrome.service import Service
38
  from selenium.webdriver.support import expected_conditions as EC
39
  from selenium.webdriver.support.ui import WebDriverWait
40
  from selenium.webdriver.support.ui import Select
41
- try:
42
- import chromedriver_binary # Adds chromedriver binary to path.
43
- except ImportError:
44
- pass # Otherwise, ChromeDriver should be in your path.
45
 
46
 
47
  # Specify where your data lives.
48
  DATA_DIR = '../data/mi'
49
- ENV_FILE = '../.env'
50
 
51
  # Specify state-specific constants.
52
  STATE = 'MI'
@@ -73,9 +78,8 @@ MICHIGAN = {
73
 
74
  def wait_for_id_invisible(driver, value, seconds=30):
75
  """Wait for a given value to be invisible."""
76
- WebDriverWait(driver, seconds).until(
77
- EC.invisibility_of_element((By.ID, value))
78
- )
79
 
80
 
81
  def get_licenses_mi(
@@ -84,21 +88,21 @@ def get_licenses_mi(
84
  ):
85
  """Get Michigan cannabis license data."""
86
 
87
- # Initialize Selenium and specify options.
88
- service = Service()
89
- options = Options()
90
- options.add_argument('--window-size=1920,1200')
91
-
92
- # DEV: Run with the browser open.
93
- options.headless = False
94
-
95
- # PRODUCTION: Run with the browser closed.
96
- # options.add_argument('--headless')
97
- # options.add_argument('--disable-gpu')
98
- # options.add_argument('--no-sandbox')
99
 
100
- # Initiate a Selenium driver.
101
- driver = webdriver.Chrome(options=options, service=service)
 
 
 
 
 
 
 
 
 
102
 
103
  # Load the license page.
104
  url = MICHIGAN['licenses_url']
@@ -112,11 +116,11 @@ def get_licenses_mi(
112
  text = option.text
113
  if text and '--' not in text:
114
  license_types.append(text)
115
-
116
  # Restrict certain license types.
117
  license_types = license_types[1:-2]
118
 
119
- # FIXME: Iterate over license types.
120
  data = []
121
  columns = list(MICHIGAN['licenses']['columns'].values())
122
  for license_type in license_types:
@@ -164,7 +168,10 @@ def get_licenses_mi(
164
  # https://aca-prod.accela.com/MIMM/Cap/CapHome.aspx?module=Licenses&TabName=Licenses&TabList=Home%7C0%7CLicenses%7C1%7CAdult_Use%7C2%7CEnforcement%7C3%7CRegistryCards%7C4%7CCurrentTabIndex%7C1
165
 
166
  # End the browser session.
167
- service.stop()
 
 
 
168
 
169
  # Standardize the data.
170
  licenses = pd.DataFrame(data)
@@ -203,8 +210,6 @@ def get_licenses_mi(
203
  )
204
 
205
  # Geocode the licenses.
206
- config = dotenv_values(env_file)
207
- google_maps_api_key = config['GOOGLE_MAPS_API_KEY']
208
  licenses = geocode_addresses(
209
  licenses,
210
  api_key=google_maps_api_key,
@@ -229,17 +234,22 @@ def get_licenses_mi(
229
  licenses.rename(columns=gis_cols, inplace=True)
230
 
231
  # Get the refreshed date.
232
- licenses['data_refreshed_date'] = datetime.now().isoformat()
 
233
 
234
  # Save and return the data.
235
  if data_dir is not None:
236
  if not os.path.exists(data_dir): os.makedirs(data_dir)
237
- timestamp = datetime.now().isoformat()[:19].replace(':', '-')
238
- licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
 
 
 
239
  return licenses
240
 
241
 
242
  # === Test ===
 
243
  if __name__ == '__main__':
244
 
245
  # Support command line usage.
 
1
  """
2
  Cannabis Licenses | Get Michigan Licenses
3
+ Copyright (c) 2022-2023 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
+ Updated: 8/17/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
18
  - Michigan Cannabis Regulatory Agency
19
  URL: <https://michigan.maps.arcgis.com/apps/webappviewer/index.html?id=cd5a1a76daaf470b823a382691c0ff60>
20
 
21
+ TODO:
22
+
23
+ [ ] Separate the functionality into functions.
24
+ [ ] Make the code more robust to errors.
25
+ [ ] Make Google Maps API key optional.
26
+
27
  """
28
  # Standard imports.
29
  from datetime import datetime
30
  import os
 
31
  from typing import Optional
32
 
33
  # External imports.
 
43
  from selenium.webdriver.support import expected_conditions as EC
44
  from selenium.webdriver.support.ui import WebDriverWait
45
  from selenium.webdriver.support.ui import Select
46
+ # try:
47
+ # import chromedriver_binary # Adds chromedriver binary to path.
48
+ # except ImportError:
49
+ # pass # Otherwise, ChromeDriver should be in your path.
50
 
51
 
52
  # Specify where your data lives.
53
  DATA_DIR = '../data/mi'
54
+ ENV_FILE = '../../../.env'
55
 
56
  # Specify state-specific constants.
57
  STATE = 'MI'
 
78
 
79
  def wait_for_id_invisible(driver, value, seconds=30):
80
  """Wait for a given value to be invisible."""
81
+ el = (By.ID, value)
82
+ WebDriverWait(driver, seconds).until(EC.invisibility_of_element(el))
 
83
 
84
 
85
  def get_licenses_mi(
 
88
  ):
89
  """Get Michigan cannabis license data."""
90
 
91
+ # Load the environment variables.
92
+ config = dotenv_values(env_file)
93
+ google_maps_api_key = config['GOOGLE_MAPS_API_KEY']
 
 
 
 
 
 
 
 
 
94
 
95
+ # Initialize Selenium.
96
+ try:
97
+ service = Service()
98
+ options = Options()
99
+ options.add_argument('--window-size=1920,1200')
100
+ options.add_argument('--headless')
101
+ options.add_argument('--disable-gpu')
102
+ options.add_argument('--no-sandbox')
103
+ driver = webdriver.Chrome(options=options, service=service)
104
+ except:
105
+ driver = webdriver.Edge()
106
 
107
  # Load the license page.
108
  url = MICHIGAN['licenses_url']
 
116
  text = option.text
117
  if text and '--' not in text:
118
  license_types.append(text)
119
+
120
  # Restrict certain license types.
121
  license_types = license_types[1:-2]
122
 
123
+ # Iterate over license types to get the data.
124
  data = []
125
  columns = list(MICHIGAN['licenses']['columns'].values())
126
  for license_type in license_types:
 
168
  # https://aca-prod.accela.com/MIMM/Cap/CapHome.aspx?module=Licenses&TabName=Licenses&TabList=Home%7C0%7CLicenses%7C1%7CAdult_Use%7C2%7CEnforcement%7C3%7CRegistryCards%7C4%7CCurrentTabIndex%7C1
169
 
170
  # End the browser session.
171
+ try:
172
+ service.stop()
173
+ except:
174
+ pass
175
 
176
  # Standardize the data.
177
  licenses = pd.DataFrame(data)
 
210
  )
211
 
212
  # Geocode the licenses.
 
 
213
  licenses = geocode_addresses(
214
  licenses,
215
  api_key=google_maps_api_key,
 
234
  licenses.rename(columns=gis_cols, inplace=True)
235
 
236
  # Get the refreshed date.
237
+ timestamp = datetime.now().isoformat()
238
+ licenses['data_refreshed_date'] = timestamp
239
 
240
  # Save and return the data.
241
  if data_dir is not None:
242
  if not os.path.exists(data_dir): os.makedirs(data_dir)
243
+ date = timestamp[:10]
244
+ licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{date}.csv', index=False)
245
+ licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
246
+
247
+ # Return the licenses.
248
  return licenses
249
 
250
 
251
  # === Test ===
252
+ # [✓] Tested: 2023-08-13 by Keegan Skeate <keegan@cannlytics>
253
  if __name__ == '__main__':
254
 
255
  # Support command line usage.
algorithms/get_licenses_mo.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Cannabis Licenses | Get Missouri Licenses
3
+ Copyright (c) 2023 Cannlytics
4
+
5
+ Authors:
6
+ Keegan Skeate <https://github.com/keeganskeate>
7
+ Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
+ Created: 4/26/2023
9
+ Updated: 8/13/2023
10
+ License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
+
12
+ Description:
13
+
14
+ Collect Missouri cannabis license data.
15
+
16
+ Requirements:
17
+
18
+ The script leverages Google Maps to attempt to geocode license
19
+ addresses. Ensure that you have a `.env` file with a valid
20
+ Google Maps API specified as `GOOGLE_MAPS_API_KEY`.
21
+
22
+ Command-line Usage:
23
+
24
+ python get_licenses_mo.py --data_dir <DATA_DIR> --env <ENV_FILE>
25
+
26
+ Data Source:
27
+
28
+ - Missouri Medical Cannabis Licenses
29
+ URL: <https://health.mo.gov/safety/medical-marijuana/licensed-facilities.php>
30
+
31
+ """
32
+ # Standard imports:
33
+ from datetime import datetime
34
+ import os
35
+ import re
36
+ from typing import Optional
37
+
38
+ # External imports:
39
+ from bs4 import BeautifulSoup
40
+ from cannlytics.data.gis import geocode_addresses
41
+ from dotenv import dotenv_values
42
+ import numpy as np
43
+ import pandas as pd
44
+ import requests
45
+ import zipcodes
46
+
47
+
48
+ # Specify where your data lives.
49
+ DATA_DIR = '../data/mo'
50
+ ENV_FILE = '../../../.env'
51
+
52
+ # Specify state-specific constants.
53
+ STATE = 'MO'
54
+ MISSOURI = {
55
+ 'licensing_authority_id': 'MDHSS',
56
+ 'licensing_authority': 'Missouri Department of Health and Senior Services',
57
+ 'licenses_url': 'https://health.mo.gov/safety/cannabis/licensed-facilities.php',
58
+ 'columns': {
59
+ 'Medical': 'medical',
60
+ 'Comprehensive': 'adult_use',
61
+ 'Approved to Operate': 'license_status',
62
+ 'License \nNumber': 'license_number',
63
+ 'Entity Name': 'business_legal_name',
64
+ 'City': 'premise_city',
65
+ 'State': 'premise_state',
66
+ 'Postal Code': 'premise_zip_code',
67
+ ' Contact \nInformation 1': 'first_name',
68
+ 'Contact \nInformation 1': 'first_name',
69
+ 'Contact \nInformation 2': 'last_name',
70
+ 'Contact \nPhone': 'business_phone'
71
+ },
72
+ 'drop': ['first_name', 'last_name'],
73
+ }
74
+
75
+
76
+ def format_phone_number(x):
77
+ """Format phone numbers as ###-###-####."""
78
+ digits = re.sub(r'\D', '', x)
79
+ return '{}-{}-{}'.format(digits[:3], digits[3:6], digits[6:])
80
+
81
+
82
+ def get_gis_data(df: pd.DataFrame, api_key: str) -> pd.DataFrame:
83
+ """Get GIS data."""
84
+ drop_cols = ['state', 'state_name', 'address', 'formatted_address']
85
+ rename_cols = {
86
+ 'county': 'premise_county',
87
+ 'latitude': 'premise_latitude',
88
+ 'longitude': 'premise_longitude'
89
+ }
90
+ df = geocode_addresses(df, api_key=api_key, address_field='address')
91
+ get_city = lambda x: x.split(', ')[1].split(',')[0] if STATE in str(x) else x
92
+ df['premise_city'] = df['formatted_address'].apply(get_city)
93
+ df.drop(columns=drop_cols, inplace=True)
94
+ return df.rename(columns=rename_cols)
95
+
96
+
97
+ def get_licenses_mo(
98
+ data_dir: Optional[str] = None,
99
+ env_file: Optional[str] = '.env',
100
+ ):
101
+ """Get Missouri cannabis license data."""
102
+
103
+ # Load the environment variables.
104
+ config = dotenv_values(env_file)
105
+ google_maps_api_key = config.get('GOOGLE_MAPS_API_KEY')
106
+ if google_maps_api_key is None:
107
+ print('Proceeding without `GOOGLE_MAPS_API_KEY`.')
108
+
109
+ # Create the download directory if it doesn't exist.
110
+ download_dir = os.path.join(data_dir, '.datasets')
111
+ if not os.path.exists(download_dir):
112
+ os.makedirs(download_dir)
113
+
114
+ # Get the licenses website content.
115
+ url = MISSOURI['licenses_url']
116
+ response = requests.get(url)
117
+ soup = BeautifulSoup(response.content, 'html.parser')
118
+
119
+ # Find all workbook links on the website.
120
+ links = soup.find_all('a')
121
+ xlsx_links = [x for x in links if x.get('href').endswith('.xlsx')]
122
+
123
+ # Download the files to the download directory.
124
+ datafiles = []
125
+ base = 'https://health.mo.gov/safety/cannabis/xls/'
126
+ for link in xlsx_links:
127
+ file_url = base + link.get('href').split('/')[-1]
128
+ file_name = os.path.join(download_dir, os.path.basename(file_url))
129
+ with open(file_name, 'wb') as file:
130
+ response = requests.get(file_url)
131
+ file.write(response.content)
132
+ datafiles.append(file_name)
133
+
134
+ # Open each datafile and extract the data.
135
+ licenses = []
136
+ for datafile in datafiles:
137
+
138
+ # Get the license type from the filename.
139
+ license_type = datafile.split('\\')[-1].replace('.xlsx', '') \
140
+ .replace('licensed-', '') \
141
+ .replace('-facilities', '')
142
+
143
+ # Open the workbook.
144
+ data = pd.read_excel(datafile, skiprows=1)
145
+
146
+ # Rename columns.
147
+ data.rename(columns=MISSOURI['columns'], inplace=True)
148
+
149
+ # Replace non-NaN columns with True and NaN columns with False.
150
+ data['license_status'] = data['license_status'].notna() \
151
+ .map({True: 'Active', False: 'Inactive'})
152
+
153
+ # Combine medical / adult_use into `license_designation`.
154
+ try:
155
+ data['medical'] = data['medical'].notna().map({True: True, False: False})
156
+ data['adult_use'] = data['adult_use'].notna().map({True: True, False: False})
157
+ conditions = [
158
+ (data['medical'] & data['adult_use']),
159
+ (data['medical']),
160
+ (data['adult_use'])
161
+ ]
162
+ choices = [
163
+ 'medical and adult-use',
164
+ 'medical',
165
+ 'adult-use'
166
+ ]
167
+ data['license_designation'] = np.select(conditions, choices, default=None)
168
+ except KeyError:
169
+ data['license_designation'] = 'adult-use'
170
+
171
+ # Combine owner name columns.
172
+ data['business_owner_name'] = data['first_name'].str.cat(
173
+ data['last_name'],
174
+ sep=' ',
175
+ )
176
+
177
+ # Clean the phone numbers.
178
+ data['business_phone'] = data['business_phone'].apply(str).apply(format_phone_number)
179
+
180
+ # Drop unused columns.
181
+ unnamed = [x for x in data.columns if re.match('^Unnamed', x)]
182
+ to_drop = MISSOURI['drop'] + unnamed
183
+ data.drop(to_drop, axis=1, inplace=True)
184
+
185
+ # Augment GIS data.
186
+ data['address'] = data['business_legal_name'] + ', ' + data['premise_city'] + ', ' + data['premise_state'] + ' ' + data['premise_zip_code'].astype(str)
187
+ data = get_gis_data(data, google_maps_api_key)
188
+
189
+ # Get the county.
190
+ get_county = lambda x: zipcodes.matching(x)[0]['county']
191
+ data['county'] = data['premise_zip_code'].astype(str).apply(get_county)
192
+
193
+ # Standardize the license data.
194
+ data = data.assign(
195
+ id=data['license_number'].astype(str),
196
+ business_dba_name=data['business_legal_name'],
197
+ licensing_authority_id=MISSOURI['licensing_authority_id'],
198
+ licensing_authority=MISSOURI['licensing_authority'],
199
+ premise_state=STATE,
200
+ license_status_date=None,
201
+ license_type=license_type,
202
+ license_term=None,
203
+ issue_date=None,
204
+ expiration_date=None,
205
+ business_structure=None,
206
+ activity=None,
207
+ parcel_number=None,
208
+ business_image_url=None,
209
+ )
210
+
211
+ # Define metadata.
212
+ data['data_refreshed_date'] = datetime.now().isoformat()
213
+
214
+ # Sort the columns in alphabetical order
215
+ data.sort_index(axis=1, inplace=True)
216
+
217
+ # Save the data.
218
+ if data_dir is not None:
219
+ if not os.path.exists(data_dir):
220
+ os.makedirs(data_dir)
221
+ date = datetime.now().isoformat()[:10]
222
+ outfile = f'{data_dir}/{license_type}-{STATE.lower()}-{date}.csv'
223
+ data.to_csv(outfile, index=False)
224
+
225
+ # Record the licenses.
226
+ licenses.append(data)
227
+
228
+ # Save all of the licenses.
229
+ licenses = pd.concat(licenses)
230
+ if data_dir is not None:
231
+ date = datetime.now().isoformat()[:10]
232
+ licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{date}.csv', index=False)
233
+ licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
234
+
235
+ # Return the licenses.
236
+ return licenses
237
+
238
+
239
+ # === Test ===
240
+ # [✓] Tested: 2023-08-13 by Keegan Skeate <keegan@cannlytics>
241
+ if __name__ == '__main__':
242
+
243
+ # Support command line usage.
244
+ import argparse
245
+ try:
246
+ arg_parser = argparse.ArgumentParser()
247
+ arg_parser.add_argument('--d', dest='data_dir', type=str)
248
+ arg_parser.add_argument('--data_dir', dest='data_dir', type=str)
249
+ arg_parser.add_argument('--env', dest='env_file', type=str)
250
+ args = arg_parser.parse_args()
251
+ except SystemExit:
252
+ args = {'data_dir': DATA_DIR, 'env_file': ENV_FILE}
253
+
254
+ # Get licenses, saving them to the specified directory.
255
+ data_dir = args.get('d', args.get('data_dir'))
256
+ env_file = args.get('env_file')
257
+ data = get_licenses_mo(data_dir, env_file=env_file)
algorithms/get_licenses_mt.py CHANGED
@@ -6,7 +6,7 @@ Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/27/2022
9
- Updated: 10/5/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -35,7 +35,7 @@ import requests
35
 
36
  # Specify where your data lives.
37
  DATA_DIR = '../data/mt'
38
- ENV_FILE = '../.env'
39
 
40
  # Specify state-specific constants.
41
  STATE = 'MT'
@@ -67,9 +67,11 @@ MONTANA = {
67
  ]
68
  },
69
  'retailers': {
70
- 'url': 'https://mtrevenue.gov/?mdocs-file=60245',
71
  'columns': ['city', 'dba', 'license_type', 'phone']
72
  },
 
 
73
  'processors': {'url': 'https://mtrevenue.gov/?mdocs-file=60250'},
74
  'cultivators': {'url': 'https://mtrevenue.gov/?mdocs-file=60252'},
75
  'labs': {'url': 'https://mtrevenue.gov/?mdocs-file=60248'},
@@ -248,17 +250,23 @@ def get_licenses_mt(
248
  retailers.drop(columns=['query'], inplace=True)
249
 
250
  # Get the refreshed date.
251
- retailers['data_refreshed_date'] = datetime.now().isoformat()
 
252
 
253
- # Save and return the data.
254
  if data_dir is not None:
255
  if not os.path.exists(data_dir): os.makedirs(data_dir)
256
- timestamp = datetime.now().isoformat()[:19].replace(':', '-')
257
- retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False)
 
 
 
 
258
  return retailers
259
 
260
 
261
  # === Test ===
 
262
  if __name__ == '__main__':
263
 
264
  # Support command line usage.
 
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/27/2022
9
+ Updated: 8/17/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
35
 
36
  # Specify where your data lives.
37
  DATA_DIR = '../data/mt'
38
+ ENV_FILE = '../../../.env'
39
 
40
  # Specify state-specific constants.
41
  STATE = 'MT'
 
67
  ]
68
  },
69
  'retailers': {
70
+ 'url': 'https://mtrevenue.gov/wp-content/uploads/dlm_uploads/2023/08/Dispensary-8-2023.pdf',
71
  'columns': ['city', 'dba', 'license_type', 'phone']
72
  },
73
+ # FIXME: Add other license types.
74
+ # https://mtrevenue.gov/cannabis/#CannabisLicenses
75
  'processors': {'url': 'https://mtrevenue.gov/?mdocs-file=60250'},
76
  'cultivators': {'url': 'https://mtrevenue.gov/?mdocs-file=60252'},
77
  'labs': {'url': 'https://mtrevenue.gov/?mdocs-file=60248'},
 
250
  retailers.drop(columns=['query'], inplace=True)
251
 
252
  # Get the refreshed date.
253
+ timestamp = datetime.now().isoformat()
254
+ retailers['data_refreshed_date'] = timestamp
255
 
256
+ # Save the data.
257
  if data_dir is not None:
258
  if not os.path.exists(data_dir): os.makedirs(data_dir)
259
+ date = timestamp[:10]
260
+ retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{date}.csv', index=False)
261
+ retailers.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{date}.csv', index=False)
262
+ retailers.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
263
+
264
+ # Return the data.
265
  return retailers
266
 
267
 
268
  # === Test ===
269
+ # [✓] Tested: 2023-08-13 by Keegan Skeate <keegan@cannlytics>
270
  if __name__ == '__main__':
271
 
272
  # Support command line usage.
algorithms/get_licenses_nj.py CHANGED
@@ -6,7 +6,7 @@ Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
- Updated: 9/29/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -75,6 +75,7 @@ def get_licenses_nj(
75
  )
76
 
77
  # Standardize the data.
 
78
  drop_cols = ['dispensary_location', 'location', 'website']
79
  data.drop(columns=drop_cols, inplace=True)
80
  data.rename(columns=NEW_JERSEY['retailers']['columns'], inplace=True)
@@ -96,7 +97,7 @@ def get_licenses_nj(
96
  data['id'] = None
97
  data['license_number'] = None
98
  data['license_status'] = None
99
- data['data_refreshed_date'] = datetime.now().isoformat()
100
 
101
  # Convert certain columns from upper case title case.
102
  cols = ['premise_city', 'premise_county', 'premise_street_address']
@@ -106,12 +107,14 @@ def get_licenses_nj(
106
  # Save and return the data.
107
  if data_dir is not None:
108
  if not os.path.exists(data_dir): os.makedirs(data_dir)
109
- timestamp = datetime.now().isoformat()[:19].replace(':', '-')
110
- data.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
 
111
  return data
112
 
113
 
114
  # === Test ===
 
115
  if __name__ == '__main__':
116
 
117
  # Support command line usage.
 
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
+ Updated: 8/17/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
75
  )
76
 
77
  # Standardize the data.
78
+ timestamp = datetime.now().isoformat()
79
  drop_cols = ['dispensary_location', 'location', 'website']
80
  data.drop(columns=drop_cols, inplace=True)
81
  data.rename(columns=NEW_JERSEY['retailers']['columns'], inplace=True)
 
97
  data['id'] = None
98
  data['license_number'] = None
99
  data['license_status'] = None
100
+ data['data_refreshed_date'] = timestamp
101
 
102
  # Convert certain columns from upper case title case.
103
  cols = ['premise_city', 'premise_county', 'premise_street_address']
 
107
  # Save and return the data.
108
  if data_dir is not None:
109
  if not os.path.exists(data_dir): os.makedirs(data_dir)
110
+ date = timestamp[:10]
111
+ data.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{date}.csv', index=False)
112
+ data.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
113
  return data
114
 
115
 
116
  # === Test ===
117
+ # [✓] Tested: 2023-08-13 by Keegan Skeate <keegan@cannlytics>
118
  if __name__ == '__main__':
119
 
120
  # Support command line usage.
algorithms/get_licenses_nm.py CHANGED
@@ -1,12 +1,12 @@
1
  """
2
  Cannabis Licenses | Get New Mexico Licenses
3
- Copyright (c) 2022 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
- Updated: 10/6/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -18,6 +18,15 @@ Data Source:
18
  - New Mexico Regulation and Licensing Department | Cannabis Control Division
19
  URL: <https://nmrldlpi.force.com/bcd/s/public-search-license?division=CCD&language=en_US>
20
 
 
 
 
 
 
 
 
 
 
21
  """
22
  # Standard imports.
23
  from datetime import datetime
@@ -37,15 +46,11 @@ from selenium.webdriver.common.by import By
37
  from selenium.webdriver.chrome.service import Service
38
  from selenium.webdriver.support import expected_conditions as EC
39
  from selenium.webdriver.support.ui import WebDriverWait
40
- try:
41
- import chromedriver_binary # Adds chromedriver binary to path.
42
- except ImportError:
43
- pass # Otherwise, ChromeDriver should be in your path.
44
-
45
 
46
- # Specify where your data lives.
47
- DATA_DIR = '../data/nm'
48
- ENV_FILE = '../.env'
49
 
50
  # Specify state-specific constants.
51
  STATE = 'NM'
@@ -59,29 +64,39 @@ NEW_MEXICO = {
59
  def get_licenses_nm(
60
  data_dir: Optional[str] = None,
61
  env_file: Optional[str] = '.env',
 
62
  ):
63
  """Get New Mexico cannabis license data."""
64
 
 
 
 
 
 
 
 
 
 
 
 
65
  # Create directories if necessary.
66
  if not os.path.exists(data_dir): os.makedirs(data_dir)
67
 
68
- # Initialize Selenium and specify options.
69
- service = Service()
70
- options = Options()
71
- options.add_argument('--window-size=1920,1200')
72
-
73
- # DEV: Run with the browser open.
74
- options.headless = False
75
-
76
- # PRODUCTION: Run with the browser closed.
77
- # options.add_argument('--headless')
78
- # options.add_argument('--disable-gpu')
79
- # options.add_argument('--no-sandbox')
80
-
81
- # Initiate a Selenium driver.
82
- driver = webdriver.Chrome(options=options, service=service)
83
 
84
  # Load the license page.
 
 
85
  driver.get(NEW_MEXICO['licenses_url'])
86
 
87
  # FIXME: Wait for the page to load by waiting to detect the image.
@@ -90,22 +105,25 @@ def get_licenses_nm(
90
  # WebDriverWait(driver, 15).until(EC.presence_of_element_located(el))
91
  # except TimeoutException:
92
  # print('Failed to load page within %i seconds.' % (30))
93
- sleep(5)
94
 
95
- # Get the main content and click "License Type" raido.
96
  content = driver.find_element(by=By.CLASS_NAME, value='siteforceContentArea')
97
  radio = content.find_element(by=By.CLASS_NAME, value='slds-radio--faux')
98
  radio.click()
99
- sleep(2)
100
 
101
  # Select retailers.
102
  # TODO: Also get "Cannabis Manufacturer", "Cannabis Producer", and
103
  # "Cannabis Producer Microbusiness".
 
104
  search = content.find_element(by=By.ID, value='comboboxId-40')
105
  search.click()
106
  choices = content.find_elements(by=By.CLASS_NAME, value='slds-listbox__item')
107
  for choice in choices:
108
  if choice.text == 'Cannabis Retailer':
 
 
109
  choice.click()
110
  sleep(2)
111
  break
@@ -120,6 +138,8 @@ def get_licenses_nm(
120
  sleep(5)
121
  data = []
122
  iterate = True
 
 
123
  while(iterate):
124
 
125
  # Get all of the licenses.
@@ -138,10 +158,11 @@ def get_licenses_nm(
138
  })
139
 
140
  # Get the page number and stop at the last page.
141
- # FIXME: This doesn't correctly break!
142
  par = content.find_elements(by=By.TAG_NAME, value='p')[-1].text
143
  page_number = int(par.split(' ')[2])
144
  total_pages = int(par.split(' ')[-2])
 
 
145
  if page_number == total_pages:
146
  iterate = False
147
 
@@ -149,12 +170,17 @@ def get_licenses_nm(
149
  buttons = content.find_elements(by=By.TAG_NAME, value='button')
150
  for button in buttons:
151
  if button.text == 'Next Page':
152
- button.click()
 
 
 
153
  sleep(5)
154
  break
155
 
156
  # Search for each license name, 1 by 1, to get details.
157
  retailers = pd.DataFrame(columns=['business_legal_name'])
 
 
158
  for i, licensee in enumerate(data):
159
 
160
  # Skip recorded rows.
@@ -162,6 +188,7 @@ def get_licenses_nm(
162
  continue
163
 
164
  # Click the "Business Name" search field.
 
165
  content = driver.find_element(by=By.CLASS_NAME, value='siteforceContentArea')
166
  radio = content.find_elements(by=By.CLASS_NAME, value='slds-radio--faux')[1]
167
  radio.click()
@@ -176,30 +203,28 @@ def get_licenses_nm(
176
  search = content.find_element(by=By.CLASS_NAME, value='vlocity-btn')
177
  search.click()
178
 
179
- # FIXME: Wait for the table to load.
 
180
  # WebDriverWait(content, 5).until(EC.presence_of_element_located((By.CLASS_NAME, 'slds-button_icon')))
181
- sleep(1.5)
182
 
183
  # Click the "Action" button to get to the details page.
184
- # FIXME: There can be multiple search candidates!
185
  action = content.find_element(by=By.CLASS_NAME, value='slds-button_icon')
186
  try:
187
  action.click()
188
  except:
189
- continue # FIXME: Formally check if "No record found!".
 
190
 
191
- # FIXME: Wait for the details page to load.
192
- el = (By.CLASS_NAME, 'body')
193
- WebDriverWait(driver, 5).until(EC.presence_of_element_located(el))
 
194
 
195
  # Get the page
196
  page = driver.find_element(by=By.CLASS_NAME, value='body')
197
 
198
- # FIXME: Wait for the details to load!
199
- # el = (By.TAG_NAME, 'vlocity_ins-omniscript-step')
200
- # WebDriverWait(page, 5).until(EC.presence_of_element_located(el))
201
- sleep(1.5)
202
-
203
  # Get all of the details!
204
  fields = [
205
  'license_number',
@@ -218,7 +243,7 @@ def get_licenses_nm(
218
  for j, value in enumerate(values):
219
  data[i][fields[j]] = value.text
220
 
221
- # Create multiple entries for each address!!!
222
  premises = page.find_elements(by=By.CLASS_NAME, value='block-header')
223
  for premise in premises:
224
  values = premise.text.split('\n')
@@ -226,13 +251,24 @@ def get_licenses_nm(
226
  licensee['license_number'] = values[2]
227
  retailers = pd.concat([retailers, pd.DataFrame([licensee])])
228
 
229
- # Click the "Back to Search" button.
230
- back_button = page.find_element(by=By.CLASS_NAME, value='vlocity-btn')
231
- back_button.click()
232
  sleep(1)
233
 
 
 
 
 
 
 
 
 
 
234
  # End the browser session.
235
- service.stop()
 
 
 
236
 
237
  # Standardize the data, restricting to "Approved" retailers.
238
  retailers = retailers.loc[retailers['license_status'] == 'Active']
@@ -258,40 +294,51 @@ def get_licenses_nm(
258
  retailers['data_refreshed_date'] = datetime.now().isoformat()
259
 
260
  # Geocode licenses.
261
- # FIXME: This is not working as intended. Perhaps try `search_for_address`?
262
- config = dotenv_values(env_file)
263
- api_key = config['GOOGLE_MAPS_API_KEY']
264
- retailers = geocode_addresses(retailers, api_key=api_key, address_field='address')
265
- retailers['premise_street_address'] = retailers['formatted_address'].apply(
266
- lambda x: x.split(',')[0] if STATE in str(x) else x
267
- )
268
- retailers['premise_city'] = retailers['formatted_address'].apply(
269
- lambda x: x.split(', ')[1].split(',')[0] if STATE in str(x) else x
270
- )
271
- retailers['premise_zip_code'] = retailers['formatted_address'].apply(
272
- lambda x: x.split(', ')[2].split(',')[0].split(' ')[-1] if STATE in str(x) else x
273
- )
274
- drop_cols = ['state', 'state_name', 'address', 'formatted_address',
275
- 'details_url']
276
- gis_cols = {
277
- 'county': 'premise_county',
278
- 'latitude': 'premise_latitude',
279
- 'longitude': 'premise_longitude'
280
- }
281
- retailers.drop(columns=drop_cols, inplace=True)
282
- retailers.rename(columns=gis_cols, inplace=True)
 
283
 
284
  # Save and return the data.
285
  if data_dir is not None:
286
- if not os.path.exists(data_dir): os.makedirs(data_dir)
287
- timestamp = datetime.now().isoformat()[:19].replace(':', '-')
288
- retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False)
 
 
 
 
 
289
  return retailers
290
 
291
 
292
  # === Test ===
 
293
  if __name__ == '__main__':
294
 
 
 
 
 
295
  # Support command line usage.
296
  import argparse
297
  try:
 
1
  """
2
  Cannabis Licenses | Get New Mexico Licenses
3
+ Copyright (c) 2022-2023 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
+ Updated: 8/18/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
18
  - New Mexico Regulation and Licensing Department | Cannabis Control Division
19
  URL: <https://nmrldlpi.force.com/bcd/s/public-search-license?division=CCD&language=en_US>
20
 
21
+ TODO:
22
+ - [ ] Also collect:
23
+ * "Cannabis Manufacturer"
24
+ * "Cannabis Producer"
25
+ * "Cannabis Producer Microbusiness"
26
+ - [ ] Replace `sleep` with `WebDriverWait` where possible.
27
+ - [ ] Handle multiple search results for a single address.
28
+ - [ ] Ensure geocoding is working correctly.
29
+
30
  """
31
  # Standard imports.
32
  from datetime import datetime
 
46
  from selenium.webdriver.chrome.service import Service
47
  from selenium.webdriver.support import expected_conditions as EC
48
  from selenium.webdriver.support.ui import WebDriverWait
49
+ # try:
50
+ # import chromedriver_binary # Adds chromedriver binary to path.
51
+ # except ImportError:
52
+ # pass # Otherwise, ChromeDriver should be in your path.
 
53
 
 
 
 
54
 
55
  # Specify state-specific constants.
56
  STATE = 'NM'
 
64
  def get_licenses_nm(
65
  data_dir: Optional[str] = None,
66
  env_file: Optional[str] = '.env',
67
+ verbose: Optional[bool] = True,
68
  ):
69
  """Get New Mexico cannabis license data."""
70
 
71
+ # Load environment variables.
72
+ geocode = False
73
+ try:
74
+ config = dotenv_values(env_file)
75
+ api_key = config['GOOGLE_MAPS_API_KEY']
76
+ geocode = True
77
+ if verbose:
78
+ print('Retrieved Google Maps API key for geocoding addresses.')
79
+ except:
80
+ print('Proceeding without geocoding. Set `GOOGLE_MAPS_API_KEY` in your `env_file` to enable the geocoding of addresses.')
81
+
82
  # Create directories if necessary.
83
  if not os.path.exists(data_dir): os.makedirs(data_dir)
84
 
85
+ # Initialize Selenium.
86
+ try:
87
+ service = Service()
88
+ options = Options()
89
+ options.add_argument('--window-size=1920,1200')
90
+ options.add_argument('--headless')
91
+ options.add_argument('--disable-gpu')
92
+ options.add_argument('--no-sandbox')
93
+ driver = webdriver.Chrome(options=options, service=service)
94
+ except:
95
+ driver = webdriver.Edge()
 
 
 
 
96
 
97
  # Load the license page.
98
+ if verbose:
99
+ print('Driver initialized. Loading license page...')
100
  driver.get(NEW_MEXICO['licenses_url'])
101
 
102
  # FIXME: Wait for the page to load by waiting to detect the image.
 
105
  # WebDriverWait(driver, 15).until(EC.presence_of_element_located(el))
106
  # except TimeoutException:
107
  # print('Failed to load page within %i seconds.' % (30))
108
+ sleep(6)
109
 
110
+ # Get the main content and click "License Type" radio.
111
  content = driver.find_element(by=By.CLASS_NAME, value='siteforceContentArea')
112
  radio = content.find_element(by=By.CLASS_NAME, value='slds-radio--faux')
113
  radio.click()
114
+ sleep(3)
115
 
116
  # Select retailers.
117
  # TODO: Also get "Cannabis Manufacturer", "Cannabis Producer", and
118
  # "Cannabis Producer Microbusiness".
119
+ # FIXME: Handle NoSuchElementException
120
  search = content.find_element(by=By.ID, value='comboboxId-40')
121
  search.click()
122
  choices = content.find_elements(by=By.CLASS_NAME, value='slds-listbox__item')
123
  for choice in choices:
124
  if choice.text == 'Cannabis Retailer':
125
+ if verbose:
126
+ print('Searching cannabis retailers...')
127
  choice.click()
128
  sleep(2)
129
  break
 
138
  sleep(5)
139
  data = []
140
  iterate = True
141
+ if verbose:
142
+ print('Getting all licenses...')
143
  while(iterate):
144
 
145
  # Get all of the licenses.
 
158
  })
159
 
160
  # Get the page number and stop at the last page.
 
161
  par = content.find_elements(by=By.TAG_NAME, value='p')[-1].text
162
  page_number = int(par.split(' ')[2])
163
  total_pages = int(par.split(' ')[-2])
164
+ if verbose:
165
+ print('Retrieved licenses from page %i/%i' % (page_number, total_pages))
166
  if page_number == total_pages:
167
  iterate = False
168
 
 
170
  buttons = content.find_elements(by=By.TAG_NAME, value='button')
171
  for button in buttons:
172
  if button.text == 'Next Page':
173
+ try:
174
+ button.click()
175
+ except:
176
+ break
177
  sleep(5)
178
  break
179
 
180
  # Search for each license name, 1 by 1, to get details.
181
  retailers = pd.DataFrame(columns=['business_legal_name'])
182
+ if verbose:
183
+ print('Getting details for %i licenses...' % len(data))
184
  for i, licensee in enumerate(data):
185
 
186
  # Skip recorded rows.
 
188
  continue
189
 
190
  # Click the "Business Name" search field.
191
+ sleep(2)
192
  content = driver.find_element(by=By.CLASS_NAME, value='siteforceContentArea')
193
  radio = content.find_elements(by=By.CLASS_NAME, value='slds-radio--faux')[1]
194
  radio.click()
 
203
  search = content.find_element(by=By.CLASS_NAME, value='vlocity-btn')
204
  search.click()
205
 
206
+ # Wait for the table to load.
207
+ # TODO: Prefer to use WebDriverWait over sleep.
208
  # WebDriverWait(content, 5).until(EC.presence_of_element_located((By.CLASS_NAME, 'slds-button_icon')))
209
+ sleep(3)
210
 
211
  # Click the "Action" button to get to the details page.
212
+ # FIXME: There can be multiple search candidates! How to handle this?
213
  action = content.find_element(by=By.CLASS_NAME, value='slds-button_icon')
214
  try:
215
  action.click()
216
  except:
217
+ # TODO: Formally check if "No record found!".
218
+ continue
219
 
220
+ # Wait for the details page to load.
221
+ # TODO: Prefer to use WebDriverWait over sleep.
222
+ # WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, 'body')))
223
+ sleep(5)
224
 
225
  # Get the page
226
  page = driver.find_element(by=By.CLASS_NAME, value='body')
227
 
 
 
 
 
 
228
  # Get all of the details!
229
  fields = [
230
  'license_number',
 
243
  for j, value in enumerate(values):
244
  data[i][fields[j]] = value.text
245
 
246
+ # Create multiple entries for each address.
247
  premises = page.find_elements(by=By.CLASS_NAME, value='block-header')
248
  for premise in premises:
249
  values = premise.text.split('\n')
 
251
  licensee['license_number'] = values[2]
252
  retailers = pd.concat([retailers, pd.DataFrame([licensee])])
253
 
254
+ # Scroll to the bottom of the page.
255
+ driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
 
256
  sleep(1)
257
 
258
+ # Click the "Back to Search" button.
259
+ if verbose:
260
+ print('%i. Details collected for %s' % (i + 1, licensee['business_legal_name']))
261
+ try:
262
+ back_button = page.find_element(by=By.CLASS_NAME, value='vlocity-btn')
263
+ back_button.click()
264
+ except:
265
+ driver.get(NEW_MEXICO['licenses_url']) # FIXME: Hot-fix.
266
+
267
  # End the browser session.
268
+ try:
269
+ driver.close()
270
+ except:
271
+ pass
272
 
273
  # Standardize the data, restricting to "Approved" retailers.
274
  retailers = retailers.loc[retailers['license_status'] == 'Active']
 
294
  retailers['data_refreshed_date'] = datetime.now().isoformat()
295
 
296
  # Geocode licenses.
297
+ if geocode:
298
+
299
+ # FIXME: This is not working as intended.
300
+ # Perhaps try `search_for_address`?
301
+ retailers = geocode_addresses(retailers, api_key=api_key, address_field='address')
302
+ retailers['premise_street_address'] = retailers['formatted_address'].apply(
303
+ lambda x: x.split(',')[0] if STATE in str(x) else x
304
+ )
305
+ retailers['premise_city'] = retailers['formatted_address'].apply(
306
+ lambda x: x.split(', ')[1].split(',')[0] if STATE in str(x) else x
307
+ )
308
+ retailers['premise_zip_code'] = retailers['formatted_address'].apply(
309
+ lambda x: x.split(', ')[2].split(',')[0].split(' ')[-1] if STATE in str(x) else x
310
+ )
311
+ drop_cols = ['state', 'state_name', 'address', 'formatted_address',
312
+ 'details_url']
313
+ gis_cols = {
314
+ 'county': 'premise_county',
315
+ 'latitude': 'premise_latitude',
316
+ 'longitude': 'premise_longitude'
317
+ }
318
+ retailers.drop(columns=drop_cols, inplace=True)
319
+ retailers.rename(columns=gis_cols, inplace=True)
320
 
321
  # Save and return the data.
322
  if data_dir is not None:
323
+ if not os.path.exists(data_dir):
324
+ os.makedirs(data_dir)
325
+ date = datetime.now().isoformat()[:10]
326
+ retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{date}.csv', index=False)
327
+ retailers.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{date}.csv', index=False)
328
+ retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-latest.csv', index=False)
329
+
330
+ # Return the licenses.
331
  return retailers
332
 
333
 
334
  # === Test ===
335
+ # [✓] Tested: 2023-08-14 by Keegan Skeate <keegan@cannlytics>
336
  if __name__ == '__main__':
337
 
338
+ # Specify where your data lives.
339
+ DATA_DIR = '../data/nm'
340
+ ENV_FILE = '../../../.env'
341
+
342
  # Support command line usage.
343
  import argparse
344
  try:
algorithms/get_licenses_nv.py CHANGED
@@ -1,12 +1,12 @@
1
  """
2
  Cannabis Licenses | Get Nevada Licenses
3
- Copyright (c) 2022 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
- Updated: 9/29/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -34,7 +34,7 @@ import requests
34
 
35
  # Specify where your data lives.
36
  DATA_DIR = '../data/nv'
37
- ENV_FILE = '../.env'
38
 
39
  # Specify state-specific constants.
40
  STATE = 'NV'
@@ -61,6 +61,10 @@ def get_licenses_nv(
61
  ):
62
  """Get Nevada cannabis license data."""
63
 
 
 
 
 
64
  # Create the necessary directories.
65
  file_dir = f'{data_dir}/.datasets'
66
  if not os.path.exists(data_dir): os.makedirs(data_dir)
@@ -128,6 +132,7 @@ def get_licenses_nv(
128
  if data_dir is not None:
129
  timestamp = datetime.now().isoformat()[:19].replace(':', '-')
130
  licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
 
131
 
132
  #--------------------------------------------------------------------------
133
  # Get retailer data
@@ -142,18 +147,19 @@ def get_licenses_nv(
142
  except AttributeError:
143
  continue
144
  rows = table.find_all('td')
145
- for row in rows:
146
- cells = row.text.split(' – ')
147
- name = cells[0]
148
- street = cells[1]
149
- designation = cells[-1]
150
- retailers.append({
151
- 'business_legal_name': name,
152
- 'business_dba_name': name,
153
- 'license_designation': designation,
154
- 'premise_city': city,
155
- 'premise_street_address': street,
156
- })
 
157
 
158
  # Standardize the retailers.
159
  retailers = pd.DataFrame(retailers)
@@ -183,8 +189,6 @@ def get_licenses_nv(
183
  retailers['data_refreshed_date'] = datetime.now().isoformat()
184
 
185
  # Geocode the retailers.
186
- config = dotenv_values(env_file)
187
- google_maps_api_key = config['GOOGLE_MAPS_API_KEY']
188
  cols = ['premise_street_address', 'premise_city', 'premise_state']
189
  retailers['address'] = retailers[cols].apply(
190
  lambda row: ', '.join(row.values.astype(str)),
@@ -201,7 +205,7 @@ def get_licenses_nv(
201
  'latitude': 'premise_latitude',
202
  'longitude': 'premise_longitude'
203
  }
204
- licenses['premise_zip_code'] = licenses['formatted_address'].apply(
205
  lambda x: x.split(', ')[2].split(',')[0].split(' ')[-1] if STATE in str(x) else x
206
  )
207
  retailers.drop(columns=drop_cols, inplace=True)
@@ -211,11 +215,14 @@ def get_licenses_nv(
211
  if data_dir is not None:
212
  timestamp = datetime.now().isoformat()[:19].replace(':', '-')
213
  retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False)
 
214
 
215
  # Return all of the data.
216
  return pd.concat([licenses, retailers])
217
 
218
 
 
 
219
  if __name__ == '__main__':
220
 
221
  # Support command line usage.
 
1
  """
2
  Cannabis Licenses | Get Nevada Licenses
3
+ Copyright (c) 2022-2023 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
+ Updated: 8/13/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
34
 
35
  # Specify where your data lives.
36
  DATA_DIR = '../data/nv'
37
+ ENV_FILE = '../../../.env'
38
 
39
  # Specify state-specific constants.
40
  STATE = 'NV'
 
61
  ):
62
  """Get Nevada cannabis license data."""
63
 
64
+ # Get the environment variables.
65
+ config = dotenv_values(env_file)
66
+ google_maps_api_key = config['GOOGLE_MAPS_API_KEY']
67
+
68
  # Create the necessary directories.
69
  file_dir = f'{data_dir}/.datasets'
70
  if not os.path.exists(data_dir): os.makedirs(data_dir)
 
132
  if data_dir is not None:
133
  timestamp = datetime.now().isoformat()[:19].replace(':', '-')
134
  licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
135
+ licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
136
 
137
  #--------------------------------------------------------------------------
138
  # Get retailer data
 
147
  except AttributeError:
148
  continue
149
  rows = table.find_all('td')
150
+ vector = [x.text for x in rows]
151
+ retailer = {}
152
+ for cell in vector:
153
+ if ' – ' in cell:
154
+ parts = cell.split(' – ')
155
+ retailer['business_legal_name'] = parts[0]
156
+ retailer['business_dba_name'] = parts[0]
157
+ retailer['premise_street_address'] = parts[1]
158
+ retailer['license_designation'] = parts[-1]
159
+ retailer['premise_city'] = city
160
+ else:
161
+ retailer['delivery'] = cell
162
+ retailers.append(retailer)
163
 
164
  # Standardize the retailers.
165
  retailers = pd.DataFrame(retailers)
 
189
  retailers['data_refreshed_date'] = datetime.now().isoformat()
190
 
191
  # Geocode the retailers.
 
 
192
  cols = ['premise_street_address', 'premise_city', 'premise_state']
193
  retailers['address'] = retailers[cols].apply(
194
  lambda row: ', '.join(row.values.astype(str)),
 
205
  'latitude': 'premise_latitude',
206
  'longitude': 'premise_longitude'
207
  }
208
+ retailers['premise_zip_code'] = retailers['formatted_address'].apply(
209
  lambda x: x.split(', ')[2].split(',')[0].split(' ')[-1] if STATE in str(x) else x
210
  )
211
  retailers.drop(columns=drop_cols, inplace=True)
 
215
  if data_dir is not None:
216
  timestamp = datetime.now().isoformat()[:19].replace(':', '-')
217
  retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False)
218
+ retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-latest.csv', index=False)
219
 
220
  # Return all of the data.
221
  return pd.concat([licenses, retailers])
222
 
223
 
224
+ # === Test ===
225
+ # [✓] Tested: 2023-08-13 by Keegan Skeate <keegan@cannlytics>
226
  if __name__ == '__main__':
227
 
228
  # Support command line usage.
algorithms/get_licenses_ny.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Cannabis Licenses | Get New York Licenses
3
+ Copyright (c) 2022-2023 Cannlytics
4
+
5
+ Authors:
6
+ Keegan Skeate <https://github.com/keeganskeate>
7
+ Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
+ Created: 11/29/2022
9
+ Updated: 9/20/2023
10
+ License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
+
12
+ Description:
13
+
14
+ Collect New York cannabis license data.
15
+
16
+ Data Source:
17
+
18
+ - New York State Office of Cannabis Management
19
+ URL: <https://cannabis.ny.gov/licensing>
20
+
21
+ """
22
+ # Standard imports:
23
+ from datetime import datetime
24
+ import json
25
+ import os
26
+ from typing import Optional
27
+
28
+ # External imports:
29
+ from bs4 import BeautifulSoup
30
+ from cannlytics.data.gis import geocode_addresses
31
+ from dotenv import dotenv_values
32
+ import pandas as pd
33
+ import pdfplumber
34
+ import requests
35
+
36
+
37
+ # Specify where your data lives.
38
+ DATA_DIR = '../data/ny'
39
+ ENV_FILE = '../../../.env'
40
+
41
+ # Specify state-specific constants.
42
+ STATE = 'NY'
43
+ NEW_YORK = {
44
+ 'licensing_authority_id': 'OCM',
45
+ 'licensing_authority': 'New York State Office of Cannabis Management',
46
+ 'cultivators': {
47
+ 'source': 'https://cannabis.ny.gov/adult-use-conditional-cultivator',
48
+ 'url': 'https://cannabis.ny.gov/list-aucc-licenses',
49
+ },
50
+ 'retailers': {
51
+ 'source': 'https://cannabis.ny.gov/conditional-adult-use-retail-dispensary',
52
+ 'url': 'https://cannabis.ny.gov/caurd-licenses',
53
+ },
54
+ 'processors': {
55
+ 'source': 'https://cannabis.ny.gov/adult-use-conditional-processor',
56
+ 'url': 'https://cannabis.ny.gov/list-aucp-licenses',
57
+ },
58
+ 'labs': {
59
+ 'source': 'https://cannabis.ny.gov/cannabis-laboratories',
60
+ 'url': 'https://cannabis.ny.gov/cannabis-laboratories',
61
+ 'limits': 'https://cannabis.ny.gov/laboratory-testing-limits',
62
+ 'qc': 'https://cannabis.ny.gov/laboratory-quality-system-standard',
63
+ 'regulations': 'https://cannabis.ny.gov/part-130-cannabis-laboratories-adopted',
64
+ 'columns': {
65
+ 'Permit # (OCM-CPL-XXXX)': 'license_number',
66
+ 'Lab Name': 'business_legal_name',
67
+ 'City': 'premise_city',
68
+ 'Cannabinoids (including d-10 THC)': 'cannabinoids',
69
+ 'Filth/Foreign Material': 'foreign_matter',
70
+ 'Metals (Heavy)': 'heavy_metals',
71
+ 'Microbiology*': 'microbes',
72
+ 'Moisture Content': 'moisture_content',
73
+ 'Mycotoxins/Aflatoxins': 'mycotoxins',
74
+ 'Pesticides': 'pesticides',
75
+ 'Residual Solvents': 'residual_solvents',
76
+ 'Terpenes': 'terpenes',
77
+ 'Water Activity': 'water_activity',
78
+ }
79
+ },
80
+ }
81
+
82
+
83
+ def get_gis_data(df, api_key):
84
+ """Get GIS data."""
85
+ drop_cols = ['state', 'state_name', 'address', 'formatted_address']
86
+ rename_cols = {
87
+ 'county': 'premise_county',
88
+ 'latitude': 'premise_latitude',
89
+ 'longitude': 'premise_longitude'
90
+ }
91
+ df = geocode_addresses(df, api_key=api_key, address_field='address')
92
+ get_city = lambda x: x.split(', ')[1].split(',')[0] if STATE in str(x) else x
93
+ get_street = lambda x: str(x).split(', ')[0]
94
+ df['premise_city'] = df['formatted_address'].apply(get_city)
95
+ df['premise_street_address'] = df['formatted_address'].apply(get_street)
96
+ df.drop(columns=drop_cols, inplace=True)
97
+ return df.rename(columns=rename_cols)
98
+
99
+
100
+ def get_retailers_ny(
101
+ data_dir: Optional[str] = None,
102
+ env_file: Optional[str] = '.env',
103
+ ) -> pd.DataFrame:
104
+ """Get New York cannabis retailers."""
105
+
106
+ # Load the environment variables.
107
+ config = dotenv_values(env_file)
108
+ google_maps_api_key = config.get('GOOGLE_MAPS_API_KEY')
109
+ if google_maps_api_key is None:
110
+ print('Proceeding without `GOOGLE_MAPS_API_KEY`.')
111
+
112
+ # Create a dataset directory.
113
+ dataset_dir = os.path.join(data_dir, '.datasets')
114
+ if not os.path.exists(dataset_dir):
115
+ os.mkdir(dataset_dir)
116
+
117
+ # Download the licenses document.
118
+ url = NEW_YORK['retailers']['url']
119
+ response = requests.get(url)
120
+ pdf_file = os.path.join(dataset_dir, 'ny-retailers.pdf')
121
+ with open(pdf_file, 'wb') as f:
122
+ f.write(response.content)
123
+
124
+ # Read the PDF.
125
+ doc = pdfplumber.open(pdf_file)
126
+ data = []
127
+ for page in doc.pages:
128
+ table = page.extract_table()
129
+ if table is None:
130
+ continue
131
+ rows = [x for x in table if x[0] and x[0] != 'License Number' and x[0] != 'Application ID']
132
+ data.extend(rows)
133
+
134
+ # Close the PDF.
135
+ doc.close()
136
+
137
+ # Remove the empty columns.
138
+ data = [[x for x in sublist if x is not None] for sublist in data]
139
+
140
+ # Create a dataframe.
141
+ columns = [
142
+ 'license_number',
143
+ 'business_legal_name',
144
+ 'county',
145
+ 'business_email',
146
+ 'business_phone',
147
+ ]
148
+ df = pd.DataFrame(data, columns=columns)
149
+
150
+ # TODO: Determine active vs inactive licenses by * in `business_legal_name`.
151
+
152
+
153
+ # TODO: Standardize the licenses.
154
+ df['premise_state'] = STATE
155
+
156
+
157
+ # TODO: Augment GIS data.
158
+
159
+
160
+ # Define metadata.
161
+ df['data_refreshed_date'] = datetime.now().isoformat()
162
+
163
+ # Sort the columns in alphabetical order
164
+ df.sort_index(axis=1, inplace=True)
165
+
166
+ # Save the data.
167
+ if data_dir is not None:
168
+ if not os.path.exists(data_dir):
169
+ os.makedirs(data_dir)
170
+ date = datetime.now().isoformat()[:10]
171
+ outfile = f'{data_dir}/retailers-{STATE.lower()}-{date}.csv'
172
+ df.to_csv(outfile, index=False)
173
+
174
+ # Return the data.
175
+ return df
176
+
177
+
178
+ def get_cultivators_ny(
179
+ data_dir: Optional[str] = None,
180
+ env_file: Optional[str] = '.env',
181
+ ) -> pd.DataFrame:
182
+ """Get New York cannabis cultivators."""
183
+
184
+ # Load the environment variables.
185
+ config = dotenv_values(env_file)
186
+ google_maps_api_key = config.get('GOOGLE_MAPS_API_KEY')
187
+ if google_maps_api_key is None:
188
+ print('Proceeding without `GOOGLE_MAPS_API_KEY`.')
189
+
190
+ # Create a dataset directory.
191
+ dataset_dir = os.path.join(data_dir, '.datasets')
192
+ if not os.path.exists(dataset_dir):
193
+ os.mkdir(dataset_dir)
194
+
195
+ # Download the licenses document.
196
+ url = NEW_YORK['cultivators']['url']
197
+ response = requests.get(url)
198
+ pdf_file = os.path.join(dataset_dir, 'ny-cultivators.pdf')
199
+ with open(pdf_file, 'wb') as f:
200
+ f.write(response.content)
201
+
202
+ # Read the PDF.
203
+ doc = pdfplumber.open(pdf_file)
204
+ data = []
205
+ for page in doc.pages:
206
+ table = page.extract_table()
207
+ if table is None:
208
+ continue
209
+ rows = [x for x in table if x[0] and x[0] != 'License Number' and x[0] != 'Application ID']
210
+ data.extend(rows)
211
+
212
+ # Close the PDF.
213
+ doc.close()
214
+
215
+ # Remove the empty columns.
216
+ data = [[x for x in sublist if x is not None] for sublist in data]
217
+
218
+ # Create a dataframe.
219
+ columns = [
220
+ 'license_number',
221
+ 'business_legal_name',
222
+ 'county',
223
+ 'business_email',
224
+ 'business_phone',
225
+ ]
226
+ df = pd.DataFrame(data, columns=columns)
227
+
228
+
229
+
230
+ # TODO: Standardize the data.
231
+
232
+
233
+
234
+ # TODO: Augment GIS data.
235
+
236
+
237
+
238
+ # # Define metadata.
239
+ # df['data_refreshed_date'] = datetime.now().isoformat()
240
+
241
+ # # Sort the columns in alphabetical order
242
+ # df.sort_index(axis=1, inplace=True)
243
+
244
+ # # Save the data.
245
+ # if data_dir is not None:
246
+ # if not os.path.exists(data_dir):
247
+ # os.makedirs(data_dir)
248
+ # date = datetime.now().isoformat()[:10]
249
+ # outfile = f'{data_dir}/cultivators-{STATE.lower()}-{date}.csv'
250
+ # df.to_csv(outfile, index=False)
251
+
252
+ # # Return the data.
253
+ # return df
254
+
255
+
256
+ raise NotImplementedError
257
+
258
+
259
+ def get_processors_ny(
260
+ data_dir: Optional[str] = None,
261
+ env_file: Optional[str] = '.env',
262
+ ) -> pd.DataFrame:
263
+ """Get New York cannabis processors."""
264
+
265
+ # Load the environment variables.
266
+ config = dotenv_values(env_file)
267
+ google_maps_api_key = config.get('GOOGLE_MAPS_API_KEY')
268
+ if google_maps_api_key is None:
269
+ print('Proceeding without `GOOGLE_MAPS_API_KEY`.')
270
+
271
+
272
+ # TODO: Get the data from the web / PDF.
273
+
274
+
275
+
276
+ # TODO: Standardize the data.
277
+
278
+
279
+
280
+ # TODO: Augment GIS data.
281
+
282
+
283
+
284
+ # # Define metadata.
285
+ # df['data_refreshed_date'] = datetime.now().isoformat()
286
+
287
+ # # Sort the columns in alphabetical order
288
+ # df.sort_index(axis=1, inplace=True)
289
+
290
+ # # Save the data.
291
+ # if data_dir is not None:
292
+ # if not os.path.exists(data_dir):
293
+ # os.makedirs(data_dir)
294
+ # date = datetime.now().isoformat()[:10]
295
+ # outfile = f'{data_dir}/processors-{STATE.lower()}-{date}.csv'
296
+ # df.to_csv(outfile, index=False)
297
+
298
+ # # Return the data.
299
+ # return df
300
+
301
+ raise NotImplementedError
302
+
303
+
304
+ def get_labs_ny(
305
+ data_dir: Optional[str] = None,
306
+ env_file: Optional[str] = '.env',
307
+ ) -> pd.DataFrame:
308
+ """Get New York cannabis labs."""
309
+
310
+ # Load the environment variables.
311
+ config = dotenv_values(env_file)
312
+ google_maps_api_key = config.get('GOOGLE_MAPS_API_KEY')
313
+ if google_maps_api_key is None:
314
+ print('Proceeding without `GOOGLE_MAPS_API_KEY`.')
315
+
316
+ # Get the lab list from the web.
317
+ url = NEW_YORK['labs']['source']
318
+ response = requests.get(url)
319
+ soup = BeautifulSoup(response.content, 'html.parser')
320
+
321
+ # Find the table.
322
+ table = soup.find('table')
323
+
324
+ # Get the table headers.
325
+ data = []
326
+ header_row = table.find('thead').find('tr')
327
+ headers = [header.get_text(strip=True) for header in header_row.find_all('th')]
328
+ data.append(headers)
329
+
330
+ # Get the table rows.
331
+ table_body = table.find('tbody')
332
+ rows = table_body.find_all('tr')
333
+ for row in rows:
334
+ cols = row.find_all('td')
335
+ cols = [col.get_text(strip=True) for col in cols]
336
+ data.append(cols)
337
+
338
+ # Format a DataFrame.
339
+ df = pd.DataFrame(data[1:], columns=data[0])
340
+
341
+ # Rename columns.
342
+ df.rename(columns=NEW_YORK['labs']['columns'], inplace=True)
343
+
344
+ # Identify analyses for each lab.
345
+ analyses = list(df.columns[3:])
346
+ combine_analyses = lambda x: json.dumps([n for n in analyses if x[n] == 'x'])
347
+ df['analyses'] = df.apply(combine_analyses, axis=1)
348
+ df.drop(columns=analyses, inplace=True)
349
+
350
+ # Augment GIS data.
351
+ if google_maps_api_key:
352
+ df['address'] = df['business_legal_name'] + ', ' + df['premise_city'] + ', ' + STATE
353
+ df = get_gis_data(df, api_key=google_maps_api_key)
354
+
355
+ # Standardize the data.
356
+ df = df.assign(
357
+ id=df['license_number'].astype(str),
358
+ business_dba_name=df['business_legal_name'],
359
+ licensing_authority_id=NEW_YORK['licensing_authority_id'],
360
+ licensing_authority=NEW_YORK['licensing_authority'],
361
+ premise_state=STATE,
362
+ license_status_date=None,
363
+ license_type='lab',
364
+ license_term=None,
365
+ issue_date=None,
366
+ expiration_date=None,
367
+ business_structure=None,
368
+ activity=None,
369
+ parcel_number=None,
370
+ business_image_url=None,
371
+ )
372
+
373
+ # Define metadata.
374
+ df['data_refreshed_date'] = datetime.now().isoformat()
375
+
376
+ # Sort the columns in alphabetical order
377
+ df.sort_index(axis=1, inplace=True)
378
+
379
+ # Save the data.
380
+ if data_dir is not None:
381
+ if not os.path.exists(data_dir):
382
+ os.makedirs(data_dir)
383
+ date = datetime.now().isoformat()[:10]
384
+ outfile = f'{data_dir}/labs-{STATE.lower()}-{date}.csv'
385
+ df.to_csv(outfile, index=False)
386
+
387
+ # Return the data.
388
+ return df
389
+
390
+
391
+ def get_medical_ny():
392
+ """Get New York medical cannabis dispensaries."""
393
+ raise NotImplementedError
394
+
395
+
396
+ def get_licenses_ny(
397
+ data_dir: Optional[str] = None,
398
+ env_file: Optional[str] = '.env',
399
+ ):
400
+ """Get New York cannabis license data."""
401
+
402
+ # Get the data for the various licenses.
403
+ retailers = get_retailers_ny(data_dir, env_file)
404
+ labs = get_labs_ny(data_dir, env_file)
405
+ # FIXME: The following are not yet implemented.
406
+ # cultivators = get_cultivators_ny(data_dir, env_file)
407
+ # processors = get_processors_ny(data_dir, env_file)
408
+ # Future work:
409
+ # medical = get_medical_ny(data_dir, env_file)
410
+
411
+ # Compile the data.
412
+ # sets = [retailers, cultivators, processors, labs]
413
+ sets = [retailers, labs]
414
+ licenses = pd.concat(sets, ignore_index=True)
415
+ licenses['premise_state'] = STATE
416
+
417
+ # Save all of the licenses.
418
+ if data_dir is not None:
419
+ date = datetime.now().isoformat()[:10]
420
+ licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{date}.csv', index=False)
421
+ licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
422
+
423
+ # Return the licenses.
424
+ return licenses
425
+
426
+
427
+ # === Test ===
428
+ # [✓] Tested: 2023-08-13 by Keegan Skeate <keegan@cannlytics>
429
+ if __name__ == '__main__':
430
+
431
+ # Support command line usage.
432
+ import argparse
433
+ try:
434
+ arg_parser = argparse.ArgumentParser()
435
+ arg_parser.add_argument('--d', dest='data_dir', type=str)
436
+ arg_parser.add_argument('--data_dir', dest='data_dir', type=str)
437
+ arg_parser.add_argument('--env', dest='env_file', type=str)
438
+ args = arg_parser.parse_args()
439
+ except SystemExit:
440
+ args = {'d': DATA_DIR, 'env_file': ENV_FILE}
441
+
442
+ # Get licenses, saving them to the specified directory.
443
+ data_dir = args.get('d', args.get('data_dir'))
444
+ env_file = args.get('env_file')
445
+ data = get_licenses_ny(data_dir, env_file=env_file)
algorithms/get_licenses_or.py CHANGED
@@ -6,7 +6,7 @@ Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/28/2022
9
- Updated: 10/7/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -33,7 +33,7 @@ from cannlytics.data.gis import geocode_addresses
33
 
34
  # Specify where your data lives.
35
  DATA_DIR = '../data/or'
36
- ENV_FILE = '../.env'
37
 
38
  # Specify state-specific constants.
39
  OREGON = {
@@ -191,9 +191,12 @@ def get_licenses_or(
191
  if data_dir is not None:
192
  timestamp = datetime.now().isoformat()[:19].replace(':', '-')
193
  data.to_csv(f'{data_dir}/licenses-or-{timestamp}.csv', index=False)
 
194
  return data
195
 
196
 
 
 
197
  if __name__ == '__main__':
198
 
199
  # Support command line usage.
 
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/28/2022
9
+ Updated: 8/13/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
33
 
34
  # Specify where your data lives.
35
  DATA_DIR = '../data/or'
36
+ ENV_FILE = '../../../.env'
37
 
38
  # Specify state-specific constants.
39
  OREGON = {
 
191
  if data_dir is not None:
192
  timestamp = datetime.now().isoformat()[:19].replace(':', '-')
193
  data.to_csv(f'{data_dir}/licenses-or-{timestamp}.csv', index=False)
194
+ data.to_csv(f'{data_dir}/licenses-or-latest.csv', index=False)
195
  return data
196
 
197
 
198
+ # === Test ===
199
+ # [✓] Tested: 2023-08-13 by Keegan Skeate <keegan@cannlytics>
200
  if __name__ == '__main__':
201
 
202
  # Support command line usage.
algorithms/get_licenses_ri.py CHANGED
@@ -1,12 +1,12 @@
1
  """
2
  Cannabis Licenses | Get Rhode Island Licenses
3
- Copyright (c) 2022 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
- Updated: 10/3/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -18,6 +18,12 @@ Data Source:
18
  - Rhode Island
19
  URL: <https://dbr.ri.gov/office-cannabis-regulation/compassion-centers/licensed-compassion-centers>
20
 
 
 
 
 
 
 
21
  """
22
  # Standard imports.
23
  from datetime import datetime
@@ -34,7 +40,7 @@ import requests
34
 
35
  # Specify where your data lives.
36
  DATA_DIR = '../data/ri'
37
- ENV_FILE = '../.env'
38
 
39
  # Specify state-specific constants.
40
  STATE = 'RI'
@@ -48,7 +54,9 @@ RHODE_ISLAND = {
48
  'business_legal_name',
49
  'address',
50
  'business_phone',
51
- 'license_designation',
 
 
52
  ],
53
  }
54
  }
@@ -60,6 +68,10 @@ def get_licenses_ri(
60
  ):
61
  """Get Rhode Island cannabis license data."""
62
 
 
 
 
 
63
  # Get the licenses webpage.
64
  url = RHODE_ISLAND['retailers']['url']
65
  response = requests.get(url)
@@ -75,7 +87,10 @@ def get_licenses_ri(
75
  obs = {}
76
  for i, cell in enumerate(cells):
77
  column = columns[i]
78
- obs[column] = cell.text
 
 
 
79
  data.append(obs)
80
 
81
  # Optional: It's possible to download the certificate to get it's `issue_date`.
@@ -85,8 +100,8 @@ def get_licenses_ri(
85
  retailers['id'] = retailers['license_number']
86
  retailers['licensing_authority_id'] = RHODE_ISLAND['licensing_authority_id']
87
  retailers['licensing_authority'] = RHODE_ISLAND['licensing_authority']
88
- retailers['premise_state'] = STATE
89
  retailers['license_type'] = 'Commercial - Retailer'
 
90
  retailers['license_status'] = 'Active'
91
  retailers['license_status_date'] = None
92
  retailers['license_term'] = None
@@ -98,11 +113,10 @@ def get_licenses_ri(
98
  retailers['activity'] = None
99
  retailers['parcel_number'] = None
100
  retailers['business_image_url'] = None
101
- retailers['business_website'] = None
102
 
103
  # Correct `license_designation`.
104
  coding = dict(Yes='Adult Use and Cultivation', No='Adult Use')
105
- retailers['license_designation'] = retailers['license_designation'].map(coding)
106
 
107
  # Correct `business_dba_name`.
108
  criterion = retailers['business_legal_name'].str.contains('D/B/A')
@@ -127,8 +141,6 @@ def get_licenses_ri(
127
  retailers['data_refreshed_date'] = pd.to_datetime(date).isoformat()
128
 
129
  # Geocode the licenses.
130
- config = dotenv_values(env_file)
131
- google_maps_api_key = config['GOOGLE_MAPS_API_KEY']
132
  retailers = geocode_addresses(
133
  retailers,
134
  api_key=google_maps_api_key,
@@ -157,9 +169,14 @@ def get_licenses_ri(
157
  if not os.path.exists(data_dir): os.makedirs(data_dir)
158
  timestamp = datetime.now().isoformat()[:19].replace(':', '-')
159
  retailers.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
 
 
 
160
  return retailers
161
 
162
 
 
 
163
  if __name__ == '__main__':
164
 
165
  # Support command line usage.
 
1
  """
2
  Cannabis Licenses | Get Rhode Island Licenses
3
+ Copyright (c) 2022-2023 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
+ Updated: 8/13/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
18
  - Rhode Island
19
  URL: <https://dbr.ri.gov/office-cannabis-regulation/compassion-centers/licensed-compassion-centers>
20
 
21
+ TODO:
22
+
23
+ [ ] Split up functionality into re-usable functions.
24
+ [ ] Make geocoding optional.
25
+ [ ] Make the code more robust to errors.
26
+
27
  """
28
  # Standard imports.
29
  from datetime import datetime
 
40
 
41
  # Specify where your data lives.
42
  DATA_DIR = '../data/ri'
43
+ ENV_FILE = '../../../.env'
44
 
45
  # Specify state-specific constants.
46
  STATE = 'RI'
 
54
  'business_legal_name',
55
  'address',
56
  'business_phone',
57
+ 'business_website',
58
+ 'cultivator',
59
+ 'retailer',
60
  ],
61
  }
62
  }
 
68
  ):
69
  """Get Rhode Island cannabis license data."""
70
 
71
+ # Load environment variables.
72
+ config = dotenv_values(env_file)
73
+ google_maps_api_key = config['GOOGLE_MAPS_API_KEY']
74
+
75
  # Get the licenses webpage.
76
  url = RHODE_ISLAND['retailers']['url']
77
  response = requests.get(url)
 
87
  obs = {}
88
  for i, cell in enumerate(cells):
89
  column = columns[i]
90
+ if column == 'business_website':
91
+ obs[column] = cell.find('a')['href']
92
+ else:
93
+ obs[column] = cell.text.replace('\n', '').replace('\t\t\t', ' ')
94
  data.append(obs)
95
 
96
  # Optional: It's possible to download the certificate to get it's `issue_date`.
 
100
  retailers['id'] = retailers['license_number']
101
  retailers['licensing_authority_id'] = RHODE_ISLAND['licensing_authority_id']
102
  retailers['licensing_authority'] = RHODE_ISLAND['licensing_authority']
 
103
  retailers['license_type'] = 'Commercial - Retailer'
104
+ retailers['premise_state'] = STATE
105
  retailers['license_status'] = 'Active'
106
  retailers['license_status_date'] = None
107
  retailers['license_term'] = None
 
113
  retailers['activity'] = None
114
  retailers['parcel_number'] = None
115
  retailers['business_image_url'] = None
 
116
 
117
  # Correct `license_designation`.
118
  coding = dict(Yes='Adult Use and Cultivation', No='Adult Use')
119
+ retailers['license_designation'] = retailers['cultivator'].map(coding)
120
 
121
  # Correct `business_dba_name`.
122
  criterion = retailers['business_legal_name'].str.contains('D/B/A')
 
141
  retailers['data_refreshed_date'] = pd.to_datetime(date).isoformat()
142
 
143
  # Geocode the licenses.
 
 
144
  retailers = geocode_addresses(
145
  retailers,
146
  api_key=google_maps_api_key,
 
169
  if not os.path.exists(data_dir): os.makedirs(data_dir)
170
  timestamp = datetime.now().isoformat()[:19].replace(':', '-')
171
  retailers.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
172
+ retailers.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
173
+
174
+ # Return the curated licenses.
175
  return retailers
176
 
177
 
178
+ # === Test ===
179
+ # [✓] Tested: 2023-08-13 by Keegan Skeate <keegan@cannlytics>
180
  if __name__ == '__main__':
181
 
182
  # Support command line usage.
algorithms/get_licenses_south_africa.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Get South Africa cannabis license data.
3
+ Copyright (c) 2023 Cannlytics
4
+
5
+ Authors: Keegan Skeate <https://github.com/keeganskeate>
6
+ Created: 5/10/2023
7
+ Updated: 8/13/2023
8
+ License: MIT License <https://github.com/cannlytics/cannabis-data-science/blob/main/LICENSE>
9
+
10
+ Data Source:
11
+
12
+ - [South Africa Cannabis Licenses](https://www.sahpra.org.za/approved-licences/)
13
+
14
+ Resources:
15
+
16
+ - [South Africa Cannabis Licensing Press Release](https://www.sahpra.org.za/press-releases/cannabis-licensing/)
17
+ - [First-level Administrative Divisions, South Africa, 2015](https://earthworks.stanford.edu/catalog/stanford-js788dt6134)
18
+
19
+ """
20
+ # Standard imports:
21
+ from datetime import datetime
22
+ from time import sleep
23
+ from typing import Optional
24
+
25
+ # External imports:
26
+ import pandas as pd
27
+ from selenium import webdriver
28
+ from selenium.webdriver.common.by import By
29
+
30
+
31
+ # Specify where your data lives.
32
+ DATA_DIR = '../data/south-africa'
33
+ ENV_FILE = '../../../.env'
34
+
35
+
36
+ def get_licenses_south_africa(
37
+ data_dir: Optional[str] = None,
38
+ env_file: Optional[str] = '.env',
39
+ ):
40
+ """Get South Africa cannabis license data."""
41
+
42
+ # Open the licenses webpage.
43
+ url = 'http://www.sahpra.org.za/approved-licences/'
44
+ driver = webdriver.Edge()
45
+ driver.get(url)
46
+
47
+ # Click on the cultivations tab.
48
+ sleep(3)
49
+ link = driver.find_element(By.ID, 'ui-id-5')
50
+ link.click()
51
+
52
+ # Iterate over all of the pages.
53
+ data = []
54
+ iterate = True
55
+ while iterate:
56
+
57
+ # Find the table.
58
+ table = driver.find_element(By.CSS_SELECTOR, '[aria-label="Cannabis Cultivation licences"]')
59
+
60
+ # Get all the rows from the table.
61
+ rows = table.find_elements(By.TAG_NAME, 'tr')
62
+
63
+ # Extract the data from each cell.
64
+ for row in rows[3:]:
65
+ cells = row.find_elements(By.TAG_NAME, 'td')
66
+ row_data = {
67
+ 'business_legal_name': cells[0].text,
68
+ 'license_number': cells[1].text,
69
+ 'business_owner_name': cells[2].text,
70
+ 'premise_state': cells[3].text,
71
+ 'issue_date': cells[4].text,
72
+ 'expiration_date': cells[5].text,
73
+ }
74
+ data.append(row_data)
75
+
76
+ # Click the next button, if not disabled.
77
+ li = driver.find_element(By.CSS_SELECTOR, '[aria-label="next"]')
78
+ action = li.find_element(By.TAG_NAME, 'a')
79
+ style = li.get_attribute('class')
80
+ if 'disabled' in style.split():
81
+ iterate = False
82
+ action.click()
83
+ sleep(3)
84
+
85
+ # Standardize the license data.
86
+ df = pd.DataFrame(data)
87
+ df['id'] = df['license_number']
88
+ df['licensing_authority_id'] = 'SAHPRA'
89
+ df['licensing_authority'] = 'South African Health Products Regulatory Authority'
90
+ df['license_type'] = 'Medical - Cultivator'
91
+ df['license_status'] = 'Active'
92
+ df['license_status_date'] = None
93
+ df['license_term'] = None
94
+ df['business_structure'] = None
95
+ df['business_email'] = None
96
+ df['activity'] = None
97
+ df['parcel_number'] = None
98
+ df['business_image_url'] = None
99
+
100
+ # TODO: Get `data_refreshed_at` from the webpage.
101
+
102
+ # TODO: Geocode licenses.
103
+
104
+ # Close the browser.
105
+ driver.close()
106
+
107
+ # Save the data.
108
+ date = datetime.now().strftime('%Y-%m-%d')
109
+ df.to_csv(f'{data_dir}/licenses-south-africa-{date}.csv', index=False)
110
+ df.to_csv(f'{data_dir}/licenses-south-africa-latest.csv', index=False)
111
+
112
+ # Return the licenses.
113
+ return df
114
+
115
+
116
+ # === Test ===
117
+ # [ ] Tested:
118
+ if __name__ == '__main__':
119
+
120
+ # Support command line usage.
121
+ import argparse
122
+ try:
123
+ arg_parser = argparse.ArgumentParser()
124
+ arg_parser.add_argument('--d', dest='data_dir', type=str)
125
+ arg_parser.add_argument('--data_dir', dest='data_dir', type=str)
126
+ arg_parser.add_argument('--env', dest='env_file', type=str)
127
+ args = arg_parser.parse_args()
128
+ except SystemExit:
129
+ args = {'d': DATA_DIR, 'env_file': ENV_FILE}
130
+
131
+ # Get licenses, saving them to the specified directory.
132
+ data_dir = args.get('d', args.get('data_dir'))
133
+ env_file = args.get('env_file')
134
+ data = get_licenses_south_africa(data_dir, env_file=env_file)
algorithms/get_licenses_vt.py CHANGED
@@ -1,12 +1,12 @@
1
  """
2
  Cannabis Licenses | Get Vermont Licenses
3
- Copyright (c) 2022 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
- Updated: 10/7/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -34,7 +34,7 @@ import requests
34
 
35
  # Specify where your data lives.
36
  DATA_DIR = '../data/vt'
37
- ENV_FILE = '../.env'
38
 
39
  # Specify state-specific constants.
40
  STATE = 'VT'
@@ -118,6 +118,10 @@ def get_licenses_vt(
118
  ):
119
  """Get Vermont cannabis license data."""
120
 
 
 
 
 
121
  # Get the licenses from the webpage.
122
  url = VERMONT['licenses_url']
123
  response = requests.get(url)
@@ -160,46 +164,47 @@ def get_licenses_vt(
160
  licenses['business_website'] = None
161
 
162
  # Separate the `license_designation` from `license_type` if (Tier x).
163
- criterion = licenses['license_type'].str.contains('Tier ')
164
- licenses.loc[criterion, 'license_designation'] = licenses.loc[criterion]['license_type'].apply(
165
- lambda x: 'Tier ' + x.split('(Tier ')[1].rstrip(')')
166
- )
167
- licenses.loc[criterion, 'license_type'] = licenses.loc[criterion]['license_type'].apply(
168
- lambda x: x.split('(Tier ')[0].strip()
169
- )
 
170
 
171
  # Separate labs' `business_email` and `business_phone` from the `address`.
172
- criterion = licenses['license_type'] == 'Testing Lab'
173
- licenses.loc[criterion, 'business_email'] = licenses.loc[criterion]['address'].apply(
174
- lambda x: x.split('Email: ')[-1].rstrip('\n') if isinstance(x, str) else x
175
- )
176
- licenses.loc[criterion, 'business_phone'] = licenses.loc[criterion]['address'].apply(
177
- lambda x: x.split('Phone: ')[-1].split('Email: ')[0].rstrip('\n') if isinstance(x, str) else x
178
- )
179
- licenses.loc[criterion, 'address'] = licenses.loc[criterion]['address'].apply(
180
- lambda x: x.split('Phone: ')[0].replace('\n', ' ').strip() if isinstance(x, str) else x
181
- )
 
182
 
183
  # Split any DBA from the legal name.
184
- splits = [';', 'DBA - ', '(DBA)', 'DBA ', 'dba ']
185
- licenses['business_dba_name'] = licenses['business_legal_name']
186
- for split in splits:
187
- criterion = licenses['business_legal_name'].str.contains(split)
188
- licenses.loc[criterion, 'business_dba_name'] = licenses.loc[criterion]['business_legal_name'].apply(
189
- lambda x: x.split(split)[1].replace(')', '').strip() if split in x else x
190
- )
191
- licenses.loc[criterion, 'business_legal_name'] = licenses.loc[criterion]['business_legal_name'].apply(
192
- lambda x: x.split(split)[0].replace('(', '').strip()
193
- )
194
- licenses.loc[licenses['business_legal_name'] == '', 'business_legal_name'] = licenses['business_dba_name']
 
195
 
196
  # Get the refreshed date.
197
  licenses['data_refreshed_date'] = datetime.now().isoformat()
198
 
199
  # Geocode the licenses.
200
  # FIXME: There are some wonky addresses that are output!
201
- config = dotenv_values(env_file)
202
- google_maps_api_key = config['GOOGLE_MAPS_API_KEY']
203
  licenses = geocode_addresses(
204
  licenses,
205
  api_key=google_maps_api_key,
@@ -229,11 +234,15 @@ def get_licenses_vt(
229
  timestamp = datetime.now().isoformat()[:19].replace(':', '-')
230
  retailers = licenses.loc[licenses['license_type'] == 'Retail']
231
  licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
 
232
  retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False)
 
 
233
  return licenses
234
 
235
 
236
  # === Test ===
 
237
  if __name__ == '__main__':
238
 
239
  # Support command line usage.
 
1
  """
2
  Cannabis Licenses | Get Vermont Licenses
3
+ Copyright (c) 2022-2023 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
+ Updated: 8/13/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
34
 
35
  # Specify where your data lives.
36
  DATA_DIR = '../data/vt'
37
+ ENV_FILE = '../../../.env'
38
 
39
  # Specify state-specific constants.
40
  STATE = 'VT'
 
118
  ):
119
  """Get Vermont cannabis license data."""
120
 
121
+ # Load the environment variables.
122
+ config = dotenv_values(env_file)
123
+ google_maps_api_key = config['GOOGLE_MAPS_API_KEY']
124
+
125
  # Get the licenses from the webpage.
126
  url = VERMONT['licenses_url']
127
  response = requests.get(url)
 
164
  licenses['business_website'] = None
165
 
166
  # Separate the `license_designation` from `license_type` if (Tier x).
167
+ # FIXME: The data has changed and this is no longer relevant.
168
+ # criterion = licenses['license_type'].str.contains('Tier ')
169
+ # licenses.loc[criterion, 'license_designation'] = licenses.loc[criterion]['license_type'].apply(
170
+ # lambda x: 'Tier ' + x.split('(Tier ')[1].rstrip(')')
171
+ # )
172
+ # licenses.loc[criterion, 'license_type'] = licenses.loc[criterion]['license_type'].apply(
173
+ # lambda x: x.split('(Tier ')[0].strip()
174
+ # )
175
 
176
  # Separate labs' `business_email` and `business_phone` from the `address`.
177
+ # FIXME: The data has changed and this is no longer relevant.
178
+ # criterion = licenses['license_type'] == 'Testing Lab'
179
+ # licenses.loc[criterion, 'business_email'] = licenses.loc[criterion]['address'].apply(
180
+ # lambda x: x.split('Email: ')[-1].rstrip('\n') if isinstance(x, str) else x
181
+ # )
182
+ # licenses.loc[criterion, 'business_phone'] = licenses.loc[criterion]['address'].apply(
183
+ # lambda x: x.split('Phone: ')[-1].split('Email: ')[0].rstrip('\n') if isinstance(x, str) else x
184
+ # )
185
+ # licenses.loc[criterion, 'address'] = licenses.loc[criterion]['address'].apply(
186
+ # lambda x: x.split('Phone: ')[0].replace('\n', ' ').strip() if isinstance(x, str) else x
187
+ # )
188
 
189
  # Split any DBA from the legal name.
190
+ # FIXME: The data has changed and this is no longer relevant.
191
+ # splits = [';', 'DBA - ', '(DBA)', 'DBA ', 'dba ']
192
+ # licenses['business_dba_name'] = licenses['business_legal_name']
193
+ # for split in splits:
194
+ # criterion = licenses['business_legal_name'].str.contains(split)
195
+ # licenses.loc[criterion, 'business_dba_name'] = licenses.loc[criterion]['business_legal_name'].apply(
196
+ # lambda x: x.split(split)[1].replace(')', '').strip() if split in x else x
197
+ # )
198
+ # licenses.loc[criterion, 'business_legal_name'] = licenses.loc[criterion]['business_legal_name'].apply(
199
+ # lambda x: x.split(split)[0].replace('(', '').strip()
200
+ # )
201
+ # licenses.loc[licenses['business_legal_name'] == '', 'business_legal_name'] = licenses['business_dba_name']
202
 
203
  # Get the refreshed date.
204
  licenses['data_refreshed_date'] = datetime.now().isoformat()
205
 
206
  # Geocode the licenses.
207
  # FIXME: There are some wonky addresses that are output!
 
 
208
  licenses = geocode_addresses(
209
  licenses,
210
  api_key=google_maps_api_key,
 
234
  timestamp = datetime.now().isoformat()[:19].replace(':', '-')
235
  retailers = licenses.loc[licenses['license_type'] == 'Retail']
236
  licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
237
+ licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
238
  retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False)
239
+
240
+ # Return the curated licenses.
241
  return licenses
242
 
243
 
244
  # === Test ===
245
+ # [✓] Tested: 2023-08-13 by Keegan Skeate <keegan@cannlytics>
246
  if __name__ == '__main__':
247
 
248
  # Support command line usage.
algorithms/get_licenses_wa.py CHANGED
@@ -1,12 +1,12 @@
1
  """
2
  Cannabis Licenses | Get Washington Licenses
3
- Copyright (c) 2022 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
- Updated: 10/7/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
@@ -34,7 +34,7 @@ import requests
34
 
35
  # Specify where your data lives.
36
  DATA_DIR = '../data/wa'
37
- ENV_FILE = '../.env'
38
 
39
  # Specify state-specific constants.
40
  STATE = 'WA'
@@ -245,6 +245,7 @@ def get_licenses_wa(
245
  if data_dir is not None:
246
  timestamp = datetime.now().isoformat()[:19].replace(':', '-')
247
  licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
 
248
  retailers = licenses.loc[licenses['license_type'] == 'Adult-Use Retailer']
249
  retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False)
250
  labs = licenses.loc[licenses['license_type'] == 'Lab']
@@ -252,6 +253,8 @@ def get_licenses_wa(
252
  return retailers
253
 
254
 
 
 
255
  if __name__ == '__main__':
256
 
257
  # Support command line usage.
 
1
  """
2
  Cannabis Licenses | Get Washington Licenses
3
+ Copyright (c) 2022-2023 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
+ Updated: 8/9/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
 
34
 
35
  # Specify where your data lives.
36
  DATA_DIR = '../data/wa'
37
+ ENV_FILE = '../../../.env'
38
 
39
  # Specify state-specific constants.
40
  STATE = 'WA'
 
245
  if data_dir is not None:
246
  timestamp = datetime.now().isoformat()[:19].replace(':', '-')
247
  licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-{timestamp}.csv', index=False)
248
+ licenses.to_csv(f'{data_dir}/licenses-{STATE.lower()}-latest.csv', index=False)
249
  retailers = licenses.loc[licenses['license_type'] == 'Adult-Use Retailer']
250
  retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False)
251
  labs = licenses.loc[licenses['license_type'] == 'Lab']
 
253
  return retailers
254
 
255
 
256
+ # === Test ===
257
+ # [✓] Tested: 2023-08-09 by Keegan Skeate <keegan@cannlytics>
258
  if __name__ == '__main__':
259
 
260
  # Support command line usage.
algorithms/main.py CHANGED
@@ -1,31 +1,36 @@
1
  """
2
  Cannabis Licenses | Get All Licenses
3
- Copyright (c) 2022 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
- Updated: 10/7/2022
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
13
 
14
  Collect all cannabis license data from states with permitted adult-use:
15
 
16
- ✓ Alaska (Selenium)
17
- ✓ Arizona (Selenium)
18
  ✓ California
19
  ✓ Colorado
20
  ✓ Connecticut
21
- Illinois
 
22
  ✓ Maine
 
23
  ✓ Massachusetts
24
- ✓ Michigan (Selenium)
 
 
25
  ✓ Montana
26
  ✓ Nevada
27
  ✓ New Jersey
28
- x New Mexico (Selenium) (FIXME)
 
29
  ✓ Oregon
30
  ✓ Rhode Island
31
  ✓ Vermont
@@ -35,8 +40,10 @@ Description:
35
  from datetime import datetime
36
  import importlib
37
  import os
 
38
 
39
  # External imports.
 
40
  import pandas as pd
41
 
42
 
@@ -47,47 +54,124 @@ ALGORITHMS = {
47
  'ca': 'get_licenses_ca',
48
  'co': 'get_licenses_co',
49
  'ct': 'get_licenses_ct',
 
50
  'il': 'get_licenses_il',
51
  'ma': 'get_licenses_ma',
 
52
  'me': 'get_licenses_me',
53
  'mi': 'get_licenses_mi',
 
54
  'mt': 'get_licenses_mt',
55
  'nj': 'get_licenses_nj',
56
- # 'nm': 'get_licenses_nm',
57
  'nv': 'get_licenses_nv',
 
58
  'or': 'get_licenses_or',
59
  'ri': 'get_licenses_ri',
60
  'vt': 'get_licenses_vt',
61
  'wa': 'get_licenses_wa',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  }
63
- DATA_DIR = '../data'
64
-
65
 
66
  def main(data_dir, env_file):
67
  """Collect all cannabis license data from states with permitted adult-use,
68
  dynamically importing modules and finding the entry point for each of the
69
  `ALGORITHMS`."""
 
 
70
  licenses = pd.DataFrame()
 
 
 
 
 
 
 
71
  for state, algorithm in ALGORITHMS.items():
72
- module = importlib.import_module(f'{algorithm}')
 
 
73
  entry_point = getattr(module, algorithm)
74
- try:
75
- print(f'Getting license data for {state.upper()}.')
76
- data = entry_point(data_dir, env_file=env_file)
77
- if not os.path.exists(f'{DATA_DIR}/{state}'): os.makedirs(f'{DATA_DIR}/{state}')
78
- timestamp = datetime.now().isoformat()[:19].replace(':', '-')
79
- data.to_csv(f'{DATA_DIR}/{state}/licenses-{state}-{timestamp}.csv', index=False)
80
- licenses = pd.concat([licenses, data])
81
- except:
82
- print(f'Failed to collect {state.upper()} licenses.')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
- # Save all of the retailers.
85
- timestamp = datetime.now().isoformat()[:19].replace(':', '-')
86
- licenses.to_csv(f'{DATA_DIR}/all/licenses-{timestamp}.csv', index=False)
87
  return licenses
88
 
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  # === Test ===
 
91
  if __name__ == '__main__':
92
 
93
  # Support command line usage.
@@ -99,11 +183,19 @@ if __name__ == '__main__':
99
  arg_parser.add_argument('--env', dest='env_file', type=str)
100
  args = arg_parser.parse_args()
101
  except SystemExit:
102
- args = {'d': '../data/all', 'env_file': '../.env'}
103
-
104
  # Get arguments.
105
  data_dir = args.get('d', args.get('data_dir'))
106
  env_file = args.get('env_file')
107
 
108
  # Get licenses for each state.
109
- all_licenses = main(data_dir, env_file)
 
 
 
 
 
 
 
 
 
1
  """
2
  Cannabis Licenses | Get All Licenses
3
+ Copyright (c) 2022-2023 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
+ Updated: 9/20/2023
10
  License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE>
11
 
12
  Description:
13
 
14
  Collect all cannabis license data from states with permitted adult-use:
15
 
16
+ ✓ Alaska (Requires Selenium)
17
+ ✓ Arizona (Requires Selenium)
18
  ✓ California
19
  ✓ Colorado
20
  ✓ Connecticut
21
+ Delaware
22
+ ✓ Illinois (FIXME)
23
  ✓ Maine
24
+ ✓ Maryland
25
  ✓ Massachusetts
26
+ ✓ Michigan (Requires Selenium)
27
+ ✓ Minnesota
28
+ ✓ Missouri
29
  ✓ Montana
30
  ✓ Nevada
31
  ✓ New Jersey
32
+ New York
33
+ ✓ New Mexico (Requires Selenium) (FIXME)
34
  ✓ Oregon
35
  ✓ Rhode Island
36
  ✓ Vermont
 
40
  from datetime import datetime
41
  import importlib
42
  import os
43
+ import sys
44
 
45
  # External imports.
46
+ from cannlytics import Cannlytics
47
  import pandas as pd
48
 
49
 
 
54
  'ca': 'get_licenses_ca',
55
  'co': 'get_licenses_co',
56
  'ct': 'get_licenses_ct',
57
+ 'de': 'get_licenses_de',
58
  'il': 'get_licenses_il',
59
  'ma': 'get_licenses_ma',
60
+ 'md': 'get_licenses_md',
61
  'me': 'get_licenses_me',
62
  'mi': 'get_licenses_mi',
63
+ 'mo': 'get_licenses_mo',
64
  'mt': 'get_licenses_mt',
65
  'nj': 'get_licenses_nj',
66
+ 'nm': 'get_licenses_nm',
67
  'nv': 'get_licenses_nv',
68
+ 'ny': 'get_licenses_ny',
69
  'or': 'get_licenses_or',
70
  'ri': 'get_licenses_ri',
71
  'vt': 'get_licenses_vt',
72
  'wa': 'get_licenses_wa',
73
+ # Future:
74
+ # 'va': 'get_licenses_va',
75
+ # 'mn': 'get_licenses_mn',
76
+ # Medical:
77
+ # 'al': 'get_licenses_al',
78
+ # 'ar': 'get_licenses_ar',
79
+ # 'fl': 'get_licenses_fl',
80
+ # 'ky': 'get_licenses_ky',
81
+ # 'la': 'get_licenses_la',
82
+ # 'ms': 'get_licenses_ms',
83
+ # 'nd': 'get_licenses_nd',
84
+ # 'nh': 'get_licenses_nh',
85
+ # 'oh': 'get_licenses_oh',
86
+ # 'ok': 'get_licenses_ok',
87
+ # 'pa': 'get_licenses_pa',
88
+ # 'sd': 'get_licenses_sd',
89
+ # 'tx': 'get_licenses_tx',
90
+ # 'ut': 'get_licenses_ut',
91
+ # 'wv': 'get_licenses_wv'
92
  }
 
 
93
 
94
  def main(data_dir, env_file):
95
  """Collect all cannabis license data from states with permitted adult-use,
96
  dynamically importing modules and finding the entry point for each of the
97
  `ALGORITHMS`."""
98
+
99
+ # Initialize.
100
  licenses = pd.DataFrame()
101
+ date = datetime.now().isoformat()[:10]
102
+ manager = Cannlytics()
103
+
104
+ # Add the state_modules directory to sys.path for dynamic imports
105
+ sys.path.append(os.getcwd())
106
+
107
+ # Collect licenses for each state.
108
  for state, algorithm in ALGORITHMS.items():
109
+
110
+ # Import the module and get the entry point.
111
+ module = importlib.import_module(algorithm)
112
  entry_point = getattr(module, algorithm)
113
+
114
+ # Collect licenses for the state.
115
+ # try:
116
+ manager.create_log(f'Getting license data for {state.upper()}.')
117
+ data = entry_point(data_dir, env_file=env_file)
118
+
119
+ state_data_dir = os.path.join(data_dir, state)
120
+ if not os.path.exists(state_data_dir):
121
+ os.makedirs(state_data_dir)
122
+
123
+ state_data_file = os.path.join(state_data_dir, f'licenses-{state}-{date}.csv')
124
+ data.to_csv(state_data_file, index=False)
125
+ manager.create_log(f'Collected {state.upper()} licenses.')
126
+ licenses = pd.concat([licenses, data])
127
+ # except:
128
+ # manager.create_log(f'Failed to aggregate {state.upper()} licenses.')
129
+
130
+ # Save all of the licenses.
131
+ all_data_dir = os.path.join(data_dir, 'all')
132
+ if not os.path.exists(all_data_dir):
133
+ os.makedirs(all_data_dir)
134
+
135
+
136
 
137
+ all_data_file = os.path.join(all_data_dir, f'licenses-{date}.csv')
138
+ licenses.to_csv(all_data_file, index=False)
139
+ manager.create_log(f'Finished collecting licenses data.')
140
  return licenses
141
 
142
 
143
+ def save_all_licenses(data_dir, version='latest'):
144
+ """Save all of the licenses to a single CSV file."""
145
+
146
+ # Read all of the latest license data.
147
+ all_licenses = []
148
+ states = ALGORITHMS.keys()
149
+ for state in states:
150
+ state_data_dir = os.path.join(data_dir, state)
151
+ state_data_file = os.path.join(state_data_dir, f'licenses-{state}-{version}.csv')
152
+ if os.path.exists(state_data_file):
153
+ state_data = pd.read_csv(state_data_file)
154
+ all_licenses.append(state_data)
155
+ print('Aggregated data for', state.upper())
156
+ else:
157
+ print(f'No data for {state.upper()}.')
158
+
159
+ # Save all of the licenses.
160
+ if all_licenses:
161
+ licenses = pd.concat(all_licenses)
162
+ all_data_file = os.path.join(data_dir, f'all/licenses-all-{version}.csv')
163
+ licenses.to_csv(all_data_file, index=False)
164
+ print('Saved all licenses to', all_data_file)
165
+ return licenses
166
+
167
+ # No datafiles found.
168
+ else:
169
+ print('No licenses to save.')
170
+ return None
171
+
172
+
173
  # === Test ===
174
+ # [✓] Tested: 2023-09-20 by Keegan Skeate <keegan@cannlytics>
175
  if __name__ == '__main__':
176
 
177
  # Support command line usage.
 
183
  arg_parser.add_argument('--env', dest='env_file', type=str)
184
  args = arg_parser.parse_args()
185
  except SystemExit:
186
+ args = {'d': '../data', 'env_file': '../../../.env'}
187
+
188
  # Get arguments.
189
  data_dir = args.get('d', args.get('data_dir'))
190
  env_file = args.get('env_file')
191
 
192
  # Get licenses for each state.
193
+ # all_licenses = main(data_dir, env_file)
194
+
195
+ # Save all licenses.
196
+ data_dir = '../data'
197
+ all_licenses = save_all_licenses(data_dir)
198
+ print('Saved %i licenses.' % len(all_licenses))
199
+
200
+ # TODO: Upload all CSVs to Firebase Storage.
201
+
analysis/figures/cannabis-licenses-map.html CHANGED
The diff for this file is too large to render. See raw diff
 
analysis/license_map.py CHANGED
@@ -1,70 +1,46 @@
1
  """
2
  Cannabis Licenses | License Mao
3
- Copyright (c) 2022 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/22/2022
9
- Updated: 10/8/2022
10
  License: <https://github.com/cannlytics/cannabis-data-science/blob/main/LICENSE>
11
 
12
  Description:
13
 
14
  Map the adult-use cannabis retailers permitted in the United States:
15
 
16
- ✓ Alaska
17
- ✓ Arizona
18
- ✓ California
19
- ✓ Colorado
20
- ✓ Connecticut
21
- Illinois
22
- Maine
23
- Massachusetts
24
- Michigan
25
- Montana
26
- Nevada
27
- New Jersey
28
- x New Mexico (FIXME)
29
- Oregon
30
- Rhode Island
31
- Vermont
32
- Washington
 
 
 
 
33
 
34
  """
35
- # Standard imports.
36
- from datetime import datetime
37
- import json
38
- import os
39
-
40
  # External imports.
41
  import folium
42
  import pandas as pd
43
 
44
 
45
- # Specify where your data lives.
46
- DATA_DIR = '../'
47
-
48
- # Read data subsets.
49
- with open('../subsets.json', 'r') as f:
50
- SUBSETS = json.loads(f.read())
51
-
52
-
53
- def aggregate_retailers(
54
- datafiles,
55
- index_col=0,
56
- lat='premise_latitude',
57
- long='premise_longitude',
58
- ):
59
- """Aggregate retailer license data files,
60
- keeping only those with latitude and longitude."""
61
- data = []
62
- for filename in datafiles:
63
- data.append(pd.read_csv(filename, index_col=index_col))
64
- data = pd.concat(data)
65
- return data.loc[(~data[lat].isnull()) & (~data[long].isnull())]
66
-
67
-
68
  def create_retailer_map(
69
  df,
70
  color='crimson',
@@ -92,15 +68,22 @@ def create_retailer_map(
92
  # === Test ===
93
  if __name__ == '__main__':
94
 
95
- # Aggregate retailers.
96
- subsets = list(SUBSETS.values())
97
- datafiles = [DATA_DIR + x['data_url'] for x in subsets]
98
- retailers = aggregate_retailers(datafiles)
 
 
99
 
100
- # Create the retailers map.
101
  map_file = '../analysis/figures/cannabis-licenses-map.html'
102
- m = create_retailer_map(retailers, filename=map_file)
 
 
 
 
 
103
 
104
- # Save all of the retailers.
105
- timestamp = datetime.now().isoformat()[:19].replace(':', '-')
106
- retailers.to_csv(f'{DATA_DIR}/data/all/licenses-{timestamp}.csv', index=False)
 
1
  """
2
  Cannabis Licenses | License Mao
3
+ Copyright (c) 2022-2023 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/22/2022
9
+ Updated: 9/19/2023
10
  License: <https://github.com/cannlytics/cannabis-data-science/blob/main/LICENSE>
11
 
12
  Description:
13
 
14
  Map the adult-use cannabis retailers permitted in the United States:
15
 
16
+ ✓ Alaska
17
+ ✓ Arizona
18
+ ✓ California
19
+ ✓ Colorado
20
+ ✓ Connecticut
21
+ Delaware
22
+ Illinois
23
+ Maine
24
+ Massachusetts
25
+ Michigan
26
+ Missouri
27
+ Montana
28
+ Nevada
29
+ New Jersey
30
+ X New York (Under development)
31
+ New Mexico
32
+ Oregon
33
+ ✓ Rhode Island
34
+ ✓ Vermont
35
+ X Virginia (Expected 2024)
36
+ ✓ Washington
37
 
38
  """
 
 
 
 
 
39
  # External imports.
40
  import folium
41
  import pandas as pd
42
 
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  def create_retailer_map(
45
  df,
46
  color='crimson',
 
68
  # === Test ===
69
  if __name__ == '__main__':
70
 
71
+ # Read all licenses.
72
+ data = pd.read_csv('../data/all/licenses-all-latest.csv')
73
+ data = data.loc[
74
+ (~data['premise_latitude'].isnull()) &
75
+ (~data['premise_longitude'].isnull())
76
+ ]
77
 
78
+ # Create a map of all licenses.
79
  map_file = '../analysis/figures/cannabis-licenses-map.html'
80
+ m = create_retailer_map(data, filename=map_file)
81
+ print('Saved map to', map_file)
82
+
83
+ # FIXME: Create a PNG image of the map.
84
+ # import io
85
+ # from PIL import Image
86
 
87
+ # img_data = m._to_png(30)
88
+ # img = Image.open(io.BytesIO(img_data))
89
+ # img.save('../analysis/figures/cannabis-licenses-map.png')
cannabis_licenses.py CHANGED
@@ -1,17 +1,14 @@
1
  """
2
  Cannabis Licenses
3
- Copyright (c) 2022 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
- Updated: 10/8/2022
10
  License: <https://huggingface.co/datasets/cannlytics/cannabis_licenses/blob/main/LICENSE>
11
  """
12
- # Standard imports.
13
- import json
14
-
15
  # External imports.
16
  import datasets
17
  import pandas as pd
@@ -19,27 +16,51 @@ import pandas as pd
19
 
20
  # Constants.
21
  _SCRIPT = 'cannabis_licenses.py'
22
- _VERSION = '1.0.0'
23
  _HOMEPAGE = 'https://huggingface.co/datasets/cannlytics/cannabis_licenses'
24
  _LICENSE = "https://opendatacommons.org/licenses/by/4-0/"
25
  _DESCRIPTION = """\
26
- Cannabis Licenses (https://cannlytics.com/data/licenses) is a
27
- dataset of curated cannabis license data. The dataset consists of 18
28
- sub-datasets for each state with permitted adult-use cannabis, as well
29
- as a sub-dataset that includes all licenses.
30
  """
31
  _CITATION = """\
32
- @inproceedings{cannlytics2022cannabis_licenses,
33
  author = {Skeate, Keegan and O'Sullivan-Sutherland, Candace},
34
  title = {Cannabis Licenses},
35
  booktitle = {Cannabis Data Science},
36
- month = {October},
37
- year = {2022},
38
  address = {United States of America},
39
  publisher = {Cannlytics}
40
  }
41
  """
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  # Dataset fields.
44
  FIELDS = datasets.Features({
45
  'id': datasets.Value(dtype='string'),
@@ -68,20 +89,11 @@ FIELDS = datasets.Features({
68
  'business_email': datasets.Value(dtype='string'),
69
  'business_phone': datasets.Value(dtype='string'),
70
  'parcel_number': datasets.Value(dtype='string'),
71
- 'premise_latitude': datasets.Value(dtype='float'),
72
- 'premise_longitude': datasets.Value(dtype='float'),
73
  'data_refreshed_date': datasets.Value(dtype='string'),
74
  })
75
 
76
- # DEV: Read subsets from local source.
77
- # with open('subsets.json', 'r') as f:
78
- # SUBSETS = json.loads(f.read())
79
-
80
- # PRODUCTION: Read subsets from the official source.
81
- import urllib.request
82
- with urllib.request.urlopen('https://huggingface.co/datasets/cannlytics/cannabis_licenses/raw/main/subsets.json') as url:
83
- SUBSETS = json.load(url)
84
-
85
 
86
  class CannabisLicensesConfig(datasets.BuilderConfig):
87
  """BuilderConfig for Cannabis Licenses."""
@@ -94,7 +106,12 @@ class CannabisLicensesConfig(datasets.BuilderConfig):
94
  """
95
  description = _DESCRIPTION
96
  description += f'This configuration is for the `{name}` subset.'
97
- super().__init__(name=name, description=description, **kwargs)
 
 
 
 
 
98
 
99
 
100
  class CannabisLicenses(datasets.GeneratorBasedBuilder):
@@ -102,8 +119,8 @@ class CannabisLicenses(datasets.GeneratorBasedBuilder):
102
 
103
  VERSION = datasets.Version(_VERSION)
104
  BUILDER_CONFIG_CLASS = CannabisLicensesConfig
105
- BUILDER_CONFIGS = [CannabisLicensesConfig(s) for s in SUBSETS.keys()]
106
- DEFAULT_CONFIG_NAME = 'ca'
107
 
108
  def _info(self):
109
  """Returns the dataset metadata."""
@@ -119,33 +136,47 @@ class CannabisLicenses(datasets.GeneratorBasedBuilder):
119
 
120
  def _split_generators(self, dl_manager):
121
  """Returns SplitGenerators."""
122
- config_name = self.config.name
123
- data_url = SUBSETS[config_name]['data_url']
124
- urls = {config_name: data_url}
 
 
 
 
125
  downloaded_files = dl_manager.download_and_extract(urls)
126
- filepath = downloaded_files[config_name]
127
- params = {'filepath': filepath}
128
  return [datasets.SplitGenerator(name='data', gen_kwargs=params)]
129
 
130
  def _generate_examples(self, filepath):
131
  """Returns the examples in raw text form."""
132
- with open(filepath) as f:
133
- df = pd.read_csv(filepath)
134
- for index, row in df.iterrows():
135
- obs = row.to_dict()
136
- yield index, obs
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
 
139
  # === Test ===
 
140
  if __name__ == '__main__':
141
 
142
  from datasets import load_dataset
143
 
144
- # Define all of the dataset subsets.
145
- subsets = list(SUBSETS.keys())
146
-
147
  # Load each dataset subset.
148
- for subset in subsets:
149
  dataset = load_dataset(_SCRIPT, subset)
150
  data = dataset['data']
151
  assert len(data) > 0
 
1
  """
2
  Cannabis Licenses
3
+ Copyright (c) 2022-2023 Cannlytics
4
 
5
  Authors:
6
  Keegan Skeate <https://github.com/keeganskeate>
7
  Candace O'Sullivan-Sutherland <https://github.com/candy-o>
8
  Created: 9/29/2022
9
+ Updated: 9/19/2023
10
  License: <https://huggingface.co/datasets/cannlytics/cannabis_licenses/blob/main/LICENSE>
11
  """
 
 
 
12
  # External imports.
13
  import datasets
14
  import pandas as pd
 
16
 
17
  # Constants.
18
  _SCRIPT = 'cannabis_licenses.py'
19
+ _VERSION = '1.0.1'
20
  _HOMEPAGE = 'https://huggingface.co/datasets/cannlytics/cannabis_licenses'
21
  _LICENSE = "https://opendatacommons.org/licenses/by/4-0/"
22
  _DESCRIPTION = """\
23
+ Cannabis Licenses is a dataset of curated cannabis license data. The dataset consists of sub-datasets for each state with permitted adult-use cannabis, as well as a sub-dataset that includes all licenses.
 
 
 
24
  """
25
  _CITATION = """\
26
+ @inproceedings{cannlytics2023cannabis_licenses,
27
  author = {Skeate, Keegan and O'Sullivan-Sutherland, Candace},
28
  title = {Cannabis Licenses},
29
  booktitle = {Cannabis Data Science},
30
+ month = {August},
31
+ year = {2023},
32
  address = {United States of America},
33
  publisher = {Cannlytics}
34
  }
35
  """
36
 
37
+
38
+ # Read subsets from local source.
39
+ SUBSETS = [
40
+ 'all',
41
+ 'ak',
42
+ 'az',
43
+ 'ca',
44
+ 'co',
45
+ 'ct',
46
+ 'il',
47
+ 'ma',
48
+ 'md',
49
+ 'me',
50
+ 'mi',
51
+ 'mo',
52
+ 'mt',
53
+ 'nj',
54
+ 'nm',
55
+ # 'ny',
56
+ 'nv',
57
+ 'or',
58
+ 'ri',
59
+ 'vt',
60
+ 'wa',
61
+ ]
62
+
63
+
64
  # Dataset fields.
65
  FIELDS = datasets.Features({
66
  'id': datasets.Value(dtype='string'),
 
89
  'business_email': datasets.Value(dtype='string'),
90
  'business_phone': datasets.Value(dtype='string'),
91
  'parcel_number': datasets.Value(dtype='string'),
92
+ 'premise_latitude': datasets.Value(dtype='string'),
93
+ 'premise_longitude': datasets.Value(dtype='string'),
94
  'data_refreshed_date': datasets.Value(dtype='string'),
95
  })
96
 
 
 
 
 
 
 
 
 
 
97
 
98
  class CannabisLicensesConfig(datasets.BuilderConfig):
99
  """BuilderConfig for Cannabis Licenses."""
 
106
  """
107
  description = _DESCRIPTION
108
  description += f'This configuration is for the `{name}` subset.'
109
+ super().__init__(
110
+ data_dir='./data',
111
+ description=description,
112
+ name=name,
113
+ **kwargs,
114
+ )
115
 
116
 
117
  class CannabisLicenses(datasets.GeneratorBasedBuilder):
 
119
 
120
  VERSION = datasets.Version(_VERSION)
121
  BUILDER_CONFIG_CLASS = CannabisLicensesConfig
122
+ BUILDER_CONFIGS = [CannabisLicensesConfig(s) for s in SUBSETS]
123
+ DEFAULT_CONFIG_NAME = 'all'
124
 
125
  def _info(self):
126
  """Returns the dataset metadata."""
 
136
 
137
  def _split_generators(self, dl_manager):
138
  """Returns SplitGenerators."""
139
+ subset = self.config.name
140
+ # Deprecated: Use the data from the Cannlytics Hugging Face repository.
141
+ # https://huggingface.co/datasets/cannlytics/cannabis_licenses/raw/main/
142
+ # data_url = SUBSETS[config_name]['data_url']
143
+ # TEST: Use local data.
144
+ data_url = f'./data/{subset}/licenses-{subset}-latest.csv'
145
+ urls = {subset: data_url}
146
  downloaded_files = dl_manager.download_and_extract(urls)
147
+ params = {'filepath': downloaded_files[subset]}
 
148
  return [datasets.SplitGenerator(name='data', gen_kwargs=params)]
149
 
150
  def _generate_examples(self, filepath):
151
  """Returns the examples in raw text form."""
152
+ # Read the data.
153
+ df = pd.read_csv(filepath)
154
+
155
+ # Add missing columns.
156
+ for col in FIELDS.keys():
157
+ if col not in df.columns:
158
+ df[col] = ''
159
+
160
+ # Keep only the feature columns.
161
+ df = df[list(FIELDS.keys())]
162
+
163
+ # Fill missing values.
164
+ df.fillna('', inplace=True)
165
+
166
+ # Return the data as a dictionary.
167
+ for index, row in df.iterrows():
168
+ obs = row.to_dict()
169
+ yield index, obs
170
 
171
 
172
  # === Test ===
173
+ # [✓] Tested: 2023-09-19 by Keegan Skeate <keegan@cannlytics>
174
  if __name__ == '__main__':
175
 
176
  from datasets import load_dataset
177
 
 
 
 
178
  # Load each dataset subset.
179
+ for subset in SUBSETS:
180
  dataset = load_dataset(_SCRIPT, subset)
181
  data = dataset['data']
182
  assert len(data) > 0
analysis/figures/cannabis-licenses-map.png → data/ak/licenses-ak-2023-04-24T18-17-38.csv RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:b2664e0dd4284155fd74655fe94cd1e5eca805da1231276398887b8ac8f2811a
3
- size 470396
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:012304c4a47fb7892f975f7a3d919c1a7b916292158cb1bd9940b95190b221cf
3
+ size 161682
data/ak/licenses-ak-2023-08-12T10-49-50.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e55a69856ba6089420c370da65cca67976bc1cf0497f925dc2f749f7ed3cf28f
3
+ size 168605
data/ak/licenses-ak-latest.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e55a69856ba6089420c370da65cca67976bc1cf0497f925dc2f749f7ed3cf28f
3
+ size 168605
data/ak/retailers-ak-2023-04-24T18-17-38.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f13a0a812d048712dba30fe1e373e07cfd47e596dff03b174f0797112252ec29
3
+ size 59171
data/ak/retailers-ak-2023-08-12T10-49-50.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b6b7d7f82dc8aadfaa1ad017f3c91f534b253a43175f18f8d9b587334436b1f
3
+ size 63901
data/all/licenses-2022-10-06.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:091d343ceee078d47fa9a8c235060f8ee20a500bb3844f752cd243237aeaea0c
3
+ size 6961305
data/all/licenses-all-latest.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:61bcc6787e2fee35016ee2104d8120041ca3bc654658c4328f5d1e1ed8518dc6
3
+ size 10003641
data/az/cultivators-az-2023-08-13T12-34-02.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:177471253cc20dcdf224a07fc64d28d3f243228ac73debb024b5b9d2818a12c2
3
+ size 25530
data/az/licenses-az-2023-04-25T13-29-54.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e79bfb2d2cd4540f1322a52ddcbc63d13a188200d18cb926ea85b4747a434039
3
+ size 54294
data/az/licenses-az-2023-08-13T12-34-02.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7957d849efc48b293f93ac325313f0fe08eaabcde019c2b3a23726ad6159a82
3
+ size 109205
data/az/licenses-az-latest.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7957d849efc48b293f93ac325313f0fe08eaabcde019c2b3a23726ad6159a82
3
+ size 109205
data/az/manufacturers-az-2023-08-13T12-34-02.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fdae174af4d56de3840fffa007fc64365390620cad6ec8e22399fe1c8fb25a2b
3
+ size 8231
data/az/retailers-az-2023-04-25T13-29-54.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:912bc0ba36c244f5d7856270d76d28354dc1c5c0b9ead3d664f0980cb1eade20
3
+ size 53936
data/az/retailers-az-2023-08-13T12-34-02.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d77b68a1fb0c44a3e33e6f373a8d02081ca86ac83e221da860d9a0185f31eb49
3
+ size 76016
data/ca/licenses-ca-2023-04-24T16-09-51.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c3d26ddde407bd2da255f50e6b2d20de6d383e8b8ff621049664b09d60cf7997
3
+ size 5001203
data/ca/licenses-ca-2023-05-09.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cbfb7d4fa78dcd0eff29ff681a26d27a12da871507e29394b9ffb275cf2a7a84
3
+ size 4876316
data/ca/licenses-ca-2023-06-06.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae26e710056fb93d3bdbe0d17c094bbba7220902db275c3663e9900732e420fb
3
+ size 4741926
data/ca/licenses-ca-2023-08-13T15-49-47.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:65e7de95f3aa916fdc180c7c34db53b41d7fa20978f4678e58f17ceafc031c08
3
+ size 4683044
data/ca/licenses-ca-latest.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:65e7de95f3aa916fdc180c7c34db53b41d7fa20978f4678e58f17ceafc031c08
3
+ size 4683044
data/co/licenses-co-2023-04-24T18-47-58.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:982b8aeb74b51bef20452c6dd129d8ac9296acbe9510c80900cc1d73a4bdc861
3
+ size 537944
data/co/licenses-co-2023-08-13T12-47-32.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8dbbd8e0b4fa9429f531d3ba1a855a4fcad30f60714e73da024c93ad5de6bdf8
3
+ size 537375
data/co/licenses-co-2023-09-20T08-09-13.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8843db838fef0a1bcab74266dd92f087348ecce51f1eb0cb6555fc2fb36ed238
3
+ size 655517