|
""" |
|
Cannabis Tests | Get PSI Labs Test Result Data |
|
Copyright (c) 2022 Cannlytics |
|
|
|
Authors: |
|
Keegan Skeate <https://github.com/keeganskeate> |
|
Candace O'Sullivan-Sutherland <https://github.com/candy-o> |
|
Created: July 4th, 2022 |
|
Updated: 9/16/2022 |
|
License: CC-BY 4.0 <https://huggingface.co/datasets/cannlytics/cannabis_tests/blob/main/LICENSE> |
|
|
|
Description: |
|
|
|
1. Archive all of the PSI Labs test results. |
|
|
|
2. Analyze all of the PSI Labs test results, separating |
|
training and testing data to use for prediction models. |
|
|
|
3. Create and use re-usable prediction models. |
|
|
|
Setup: |
|
|
|
1. Create a data folder `../../.datasets/lab_results/psi_labs/raw_data`. |
|
|
|
2. Download ChromeDriver and put it in your `C:\Python39\Scripts` folder |
|
or pass the `executable_path` to the `Service`. |
|
|
|
3. Specify the `PAGES` that you want to collect. |
|
|
|
Note: |
|
|
|
It does not appear that new lab results are being added to the |
|
PSI Labs test results website as of 2022-01-01. |
|
|
|
Data Sources: |
|
|
|
- [PSI Labs Test Results](https://results.psilabs.org/test-results/) |
|
|
|
""" |
|
|
|
from ast import literal_eval |
|
from datetime import datetime |
|
from hashlib import sha256 |
|
import hmac |
|
from time import sleep |
|
|
|
|
|
from cannlytics.utils.utils import snake_case |
|
import pandas as pd |
|
|
|
|
|
from selenium import webdriver |
|
from selenium.webdriver.chrome.options import Options |
|
from selenium.webdriver.common.by import By |
|
from selenium.webdriver.chrome.service import Service |
|
from selenium.common.exceptions import ElementNotInteractableException, TimeoutException |
|
from selenium.webdriver.support import expected_conditions as EC |
|
from selenium.webdriver.support.ui import WebDriverWait |
|
|
|
|
|
|
|
DATA_DIR = '../../.datasets/lab_results/raw_data/psi_labs' |
|
TRAINING_DATA = '../../../.datasets/lab_results/training_data' |
|
|
|
|
|
BASE = 'https://results.psilabs.org/test-results/?page={}' |
|
PAGES = range(1, 10) |
|
|
|
|
|
COLUMNS = [ |
|
'sample_id', |
|
'date_tested', |
|
'analyses', |
|
'producer', |
|
'product_name', |
|
'product_type', |
|
'results', |
|
'coa_urls', |
|
'images', |
|
'lab_results_url', |
|
'date_received', |
|
'method', |
|
'qr_code', |
|
'sample_weight', |
|
] |
|
|
|
|
|
def create_sample_id(private_key, public_key, salt='') -> str: |
|
"""Create a hash to be used as a sample ID. |
|
The standard is to use: |
|
1. `private_key = producer` |
|
2. `public_key = product_name` |
|
3. `salt = date_tested` |
|
Args: |
|
private_key (str): A string to be used as the private key. |
|
public_key (str): A string to be used as the public key. |
|
salt (str): A string to be used as the salt, '' by default (optional). |
|
Returns: |
|
(str): A sample ID hash. |
|
""" |
|
secret = bytes(private_key, 'UTF-8') |
|
message = snake_case(public_key) + snake_case(salt) |
|
sample_id = hmac.new(secret, message.encode(), sha256).hexdigest() |
|
return sample_id |
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_psi_labs_test_results(driver, max_delay=5, reverse=True) -> list: |
|
"""Get all test results for PSI labs. |
|
Args: |
|
driver (WebDriver): A Selenium Chrome WebDiver. |
|
max_delay (float): The maximum number of seconds to wait for rendering (optional). |
|
reverse (bool): Whether to collect in reverse order, True by default (optional). |
|
Returns: |
|
(list): A list of dictionaries of sample data. |
|
""" |
|
|
|
|
|
samples = [] |
|
try: |
|
detect = EC.presence_of_element_located((By.TAG_NAME, 'sample-card')) |
|
WebDriverWait(driver, max_delay).until(detect) |
|
except TimeoutException: |
|
print('Failed to load page within %i seconds.' % max_delay) |
|
return samples |
|
cards = driver.find_elements(by=By.TAG_NAME, value='sample-card') |
|
if reverse: |
|
cards.reverse() |
|
for card in cards: |
|
|
|
|
|
details = card.find_element(by=By.TAG_NAME, value='md-card-title') |
|
|
|
|
|
image_elements = details.find_elements(by=By.TAG_NAME, value='img') |
|
images = [] |
|
for image in image_elements: |
|
src = image.get_attribute('src') |
|
filename = src.split('/')[-1] |
|
images.append({'url': src, 'filename': filename}) |
|
|
|
|
|
product_name = details.find_element(by=By.CLASS_NAME, value='md-title').text |
|
|
|
|
|
headers = details.find_elements(by=By.CLASS_NAME, value='md-subhead') |
|
producer = headers[0].text |
|
try: |
|
mm, dd, yy = tuple(headers[1].text.split(': ')[-1].split('/')) |
|
date_tested = f'20{yy}-{mm}-{dd}' |
|
except ValueError: |
|
date_tested = headers[1].text.split(': ')[-1] |
|
product_type = headers[2].text.split(' ')[-1] |
|
|
|
|
|
private_key = bytes(date_tested, 'UTF-8') |
|
public_key = snake_case(product_name) |
|
salt = snake_case(producer) |
|
sample_id = hmac.new(private_key, (public_key + salt).encode(), sha256).hexdigest() |
|
|
|
|
|
analyses = [] |
|
container = details.find_element(by=By.CLASS_NAME, value='layout-row') |
|
chips = container.find_elements(by=By.TAG_NAME, value='md-chip') |
|
for chip in chips: |
|
hidden = chip.get_attribute('aria-hidden') |
|
if hidden == 'false': |
|
analyses.append(chip.text) |
|
|
|
|
|
links = card.find_elements(by=By.TAG_NAME, value='a') |
|
lab_results_url = links[0].get_attribute('href') |
|
|
|
|
|
sample = { |
|
'analyses': analyses, |
|
'date_tested': date_tested, |
|
'images': images, |
|
'lab_results_url': lab_results_url, |
|
'producer': producer, |
|
'product_name': product_name, |
|
'product_type': product_type, |
|
'sample_id': sample_id, |
|
} |
|
samples.append(sample) |
|
|
|
return samples |
|
|
|
|
|
def get_psi_labs_test_result_details(driver, max_delay=5) -> dict: |
|
"""Get the test result details for a specific PSI lab result. |
|
Args: |
|
driver (WebDriver): A Selenium Chrome WebDiver. |
|
max_delay (float): The maximum number of seconds to wait for rendering. |
|
Returns: |
|
(dict): A dictionary of sample details. |
|
""" |
|
|
|
|
|
|
|
qr_code, coa_urls = None, [] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
try: |
|
detect = EC.presence_of_element_located((By.TAG_NAME, 'ng-include')) |
|
WebDriverWait(driver, max_delay).until(detect) |
|
except TimeoutException: |
|
print('Results not loaded within %i seconds.' % max_delay) |
|
|
|
|
|
results = [] |
|
date_received, sample_weight, method = None, None, None |
|
values = ['name', 'value', 'margin_of_error'] |
|
analysis_cards = driver.find_elements(by=By.TAG_NAME, value='ng-include') |
|
for analysis in analysis_cards: |
|
try: |
|
analysis.click() |
|
except ElementNotInteractableException: |
|
continue |
|
rows = analysis.find_elements(by=By.TAG_NAME, value='tr') |
|
if rows: |
|
for row in rows: |
|
result = {} |
|
cells = row.find_elements(by=By.TAG_NAME, value='td') |
|
for i, cell in enumerate(cells): |
|
key = values[i] |
|
result[key] = cell.text |
|
if result: |
|
results.append(result) |
|
|
|
|
|
if analysis == 'potency': |
|
extra = analysis.find_element(by=By.TAG_NAME, value='md-card-content') |
|
headings = extra.find_elements(by=By.TAG_NAME, value='h3') |
|
mm, dd, yy = tuple(headings[0].text.split('/')) |
|
date_received = f'20{yy}-{mm}-{dd}' |
|
sample_weight = headings[1].text |
|
method = headings[-1].text |
|
|
|
|
|
details = { |
|
'coa_urls': coa_urls, |
|
'date_received': date_received, |
|
'method': method, |
|
'qr_code': qr_code, |
|
'results': results, |
|
'sample_weight': sample_weight, |
|
} |
|
return details |
|
|
|
|
|
|
|
def get_all_psi_labs_test_results(service, pages, pause=0.125, verbose=True): |
|
"""Get ALL of PSI Labs test results. |
|
Args: |
|
service (ChromeDriver): A ChromeDriver service. |
|
pages (iterable): A range of pages to get lab results from. |
|
pause (float): A pause between requests to respect PSI Labs' server. |
|
verbose (bool): Whether or not to print out progress, True by default (optional). |
|
Returns: |
|
(list): A list of collected lab results. |
|
""" |
|
|
|
|
|
options = Options() |
|
options.headless = True |
|
options.add_argument('--window-size=1920,1200') |
|
driver = webdriver.Chrome(options=options, service=service) |
|
|
|
|
|
test_results = [] |
|
for page in pages: |
|
if verbose: |
|
print('Getting samples on page:', page) |
|
driver.get(BASE.format(str(page))) |
|
results = get_psi_labs_test_results(driver) |
|
if results: |
|
test_results += results |
|
else: |
|
print('Failed to find samples on page:', page) |
|
sleep(pause) |
|
|
|
|
|
for i, test_result in enumerate(test_results): |
|
if verbose: |
|
print('Getting details for:', test_result['product_name']) |
|
driver.get(test_result['lab_results_url']) |
|
details = get_psi_labs_test_result_details(driver) |
|
test_results[i] = {**test_result, **details} |
|
sleep(pause) |
|
|
|
|
|
driver.quit() |
|
return test_results |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ANALYSES = { |
|
'cannabinoids': ['potency', 'POT'], |
|
'terpenes': ['terpene', 'TERP'], |
|
'residual_solvents': ['solvent', 'RST'], |
|
'pesticides': ['pesticide', 'PEST'], |
|
'microbes': ['microbial', 'MICRO'], |
|
'heavy_metals': ['metal', 'MET'], |
|
} |
|
ANALYTES = { |
|
|
|
} |
|
DECODINGS = { |
|
'<LOQ': 0, |
|
'<LOD': 0, |
|
'ND': 0, |
|
} |
|
|
|
|
|
|
|
datafile = f'{DATA_DIR}/aggregated-cannabis-test-results.xlsx' |
|
data = pd.read_excel(datafile, sheet_name='psi_labs_raw_data') |
|
|
|
|
|
drop = ['coa_urls', 'date_received', 'method', 'qr_code', 'sample_weight'] |
|
data.drop(drop, axis=1, inplace=True) |
|
|
|
|
|
sample = data.sample(100, random_state=420) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
wide_data = pd.DataFrame() |
|
long_data = pd.DataFrame() |
|
for index, row in sample.iterrows(): |
|
series = row.copy() |
|
analyses = literal_eval(series['analyses']) |
|
images = literal_eval(series['images']) |
|
results = literal_eval(series['results']) |
|
series.drop(['analyses', 'images', 'results'], inplace=True) |
|
|
|
|
|
if not analyses: |
|
continue |
|
for analysis in analyses: |
|
series[analysis] = 1 |
|
|
|
|
|
wide_data = pd.concat([wide_data, pd.DataFrame([series])]) |
|
|
|
|
|
|
|
for result in results: |
|
|
|
|
|
analyte_name = result['name'] |
|
measurements = result['value'].split(' ') |
|
try: |
|
measurement = float(measurements[0]) |
|
except: |
|
measurement = None |
|
try: |
|
units = measurements[1] |
|
except: |
|
units = None |
|
key = snake_case(analyte_name) |
|
try: |
|
margin_of_error = float(result['margin_of_error'].split(' ')[-1]) |
|
except: |
|
margin_of_error = None |
|
|
|
|
|
entry = series.copy() |
|
entry['analyte'] = key |
|
entry['analyte_name'] = analyte_name |
|
entry['result'] = measurement |
|
entry['units'] = units |
|
entry['margin_of_error'] = margin_of_error |
|
|
|
|
|
long_data = pd.concat([long_data, pd.DataFrame([entry])]) |
|
|
|
|
|
|
|
wide_data = wide_data.fillna(0) |
|
|
|
|
|
analyses = { |
|
'POT': 'cannabinoids', |
|
'RST': 'residual_solvents', |
|
'TERP': 'terpenes', |
|
'PEST': 'pesticides', |
|
'MICRO': 'micro', |
|
'MET': 'heavy_metals', |
|
} |
|
wide_data.rename(columns=analyses, inplace=True) |
|
long_data.rename(columns=analyses, inplace=True) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
terpenes = wide_data.loc[wide_data['terpenes'] == 1] |
|
|
|
|
|
analytes = list(long_data.analyte.unique()) |
|
|
|
|
|
product_types = list(long_data.product_type.unique()) |
|
|
|
|
|
flower = long_data.loc[long_data['product_type'] == 'Flower'] |
|
flower.loc[flower['analyte'] == '9_thc']['result'].hist(bins=100) |
|
|
|
concentrates = long_data.loc[long_data['product_type'] == 'Concentrate'] |
|
concentrates.loc[concentrates['analyte'] == '9_thc']['result'].hist(bins=100) |
|
|
|
|
|
|
|
terpene = flower.loc[flower['analyte'] == 'dlimonene'] |
|
terpene['result'].hist(bins=100) |
|
|
|
terpene = concentrates.loc[concentrates['analyte'] == 'dlimonene'] |
|
terpene['result'].hist(bins=100) |
|
|
|
|
|
|
|
gorilla_glue = flower.loc[ |
|
(flower['product_name'].str.contains('gorilla', case=False)) | |
|
(flower['product_name'].str.contains('glu', case=False)) |
|
] |
|
|
|
|
|
compound = gorilla_glue.loc[gorilla_glue['analyte'] == '9_thc'] |
|
compound['result'].hist(bins=100) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|