""" Cannabis Licenses | Get Montana Licenses Copyright (c) 2022 Cannlytics Authors: Keegan Skeate Candace O'Sullivan-Sutherland Created: 9/27/2022 Updated: 9/30/2022 License: Description: Collect Montana cannabis license data. Data Source: - Montana Department of Revenue | Cannabis Control Division URL: """ # Standard imports. from datetime import datetime import os from time import sleep # External imports. from bs4 import BeautifulSoup from cannlytics.utils import camel_to_snake from cannlytics.utils.constants import DEFAULT_HEADERS import pdfplumber import requests # Specify where your data lives. DATA_DIR = '../data/mt' ENV_FILE = '../.env' # Specify state-specific constants. STATE = 'MT' MONTANA = { 'retailers': { 'url': 'https://mtrevenue.gov/?mdocs-file=60245', 'columns': ['city', 'dba', 'license_type', 'phone'] }, 'processors': {'url': 'https://mtrevenue.gov/?mdocs-file=60250'}, 'cultivators': {'url': 'https://mtrevenue.gov/?mdocs-file=60252'}, 'labs': {'url': 'https://mtrevenue.gov/?mdocs-file=60248'}, 'transporters': {'url': 'https://mtrevenue.gov/?mdocs-file=72489'}, } # DEV: data_dir = DATA_DIR pdf_dir = f'{data_dir}/pdfs' # Create directories if necessary. if not os.path.exists(data_dir): os.makedirs(data_dir) if not os.path.exists(pdf_dir): os.makedirs(pdf_dir) # Download the retailers PDF. timestamp = datetime.now().isoformat()[:19].replace(':', '-') outfile = f'{pdf_dir}/mt-retailers-{timestamp}.pdf' response = requests.get(MONTANA['retailers']['url'], headers=DEFAULT_HEADERS) with open(outfile, 'wb') as pdf: pdf.write(response.content) # FIXME: Extract text by section! # E.g. # doc = pdfplumber.open(outfile) # page = doc.pages[0] # img = page.to_image(resolution=150) # img.draw_rects( # [[0, 0.25 * page.height, 0.2 * page.width, 0.95 * page.height]] # ) # Extract the data from the PDF. rows = [] skip_lines = ['GOVERNOR ', 'DIRECTOR ', 'Cannabis Control Division', 'Licensed Dispensary locations', 'Please note', 'registered ', 'City Location Name Sales Type Phone Number', 'Page '] doc = pdfplumber.open(outfile) for page in doc.pages: text = page.extract_text() lines = text.split('\n') for line in lines: skip = False for skip_line in skip_lines: if line.startswith(skip_line): skip = True break if skip: continue rows.append(line) # Collect licensee data. licensees = [] for row in rows: # FIXME: Rows with double-line text get cut-off. if '(' not in row: continue obs = {} if 'Adult Use' in row: parts = row.split('Adult Use') obs['license_type'] = 'Adult Use' else: parts = row.split('Medical Only') obs['license_type'] = 'Medical Only' obs['dba'] = parts[0].strip() obs['phone'] = parts[-1].strip() licensees.append(obs) # Get a list of Montana cities. cities = [] # response = requests.get('http://www.mlct.org/', headers=DEFAULT_HEADERS) # soup = BeautifulSoup(response.content, 'html.parser') # table = soup.find('table') # for tr in table.findAll('tr'): # if not tr.text.strip().replace('\n', ''): # continue # city = tr.find('td').text # if '©' in city or ',' in city or '\n' in city or city == 'Home' or city == 'City': # continue # cities.append(city) # remove_lines = ['RESOURCES', 'Official State Website', 'State Legislature', # 'Chamber of Commerce', 'Contact Us'] # for ele in remove_lines: # cities.remove(ele) # FIXME: url = 'https://dojmt.gov/wp-content/uploads/2011/05/mvmtcitiescountieszips.pdf' # TODO: Separate `city` from `dba` using list of Montana cities. for i, licensee in enumerate(licensees): dba = licensee['dba'] city_found = False for city in cities: city_name = city.upper() if city_name in dba: licensees[i]['dba'] = dba.replace(city_name, '').strip() licensees[i]['city'] = city city_found = True break if not city_found: print("Couldn't identify city:", dba) # TODO: Remove duplicates. # TODO: Lookup the address of the licenses?