File size: 8,757 Bytes
d1ae506
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
"""
Cannabis Tests | Get Connecticut Test Result Data
Copyright (c) 2023 Cannlytics

Authors:
    Keegan Skeate <https://github.com/keeganskeate>
Created: 4/8/2023
Updated: 7/3/2023
License: CC-BY 4.0 <https://huggingface.co/datasets/cannlytics/cannabis_tests/blob/main/LICENSE>

Data Source:

    - Connecticut Medical Marijuana Brand Registry
    URL: <https://data.ct.gov/Health-and-Human-Services/Medical-Marijuana-Brand-Registry/egd5-wb6r/data>

"""
# Standard imports:
from datetime import datetime
import os
import requests
from typing import Optional

# External imports:
import cannlytics
from cannlytics.utils import convert_to_numeric
import pandas as pd


# Connecticut lab results API URL.
CT_RESULTS_URL = 'https://data.ct.gov/api/views/egd5-wb6r/rows.json'

# Connecticut lab results fields.
CT_FIELDS = {
    'sid': 'id',
    'id': 'lab_id',
    'position': None,
    'created_at': None,
    'created_meta': None,
    'updated_at': 'data_refreshed_date',
    'updated_meta': None,
    'meta': None,
    'brand_name': 'product_name',
    'dosage_form': 'product_type',
    'producer': 'producer',
    'product_image': 'image_url',
    'label_image': 'images',
    'lab_analysis': 'lab_results_url',
    'approval_date': 'date_tested',
    'registration_number': 'traceability_id',
}
CT_CANNABINOIDS = {
    'cbg': 'cbg',
    'cbg_a': 'cbga',
    'cannabavarin_cbdv': 'cbdv',
    'cannabichromene_cbc': 'cbc',
    'cannbinol_cbn': 'cbn',
    'tetrahydrocannabivarin_thcv': 'thcv',
    'tetrahydrocannabinol_thc': 'thc',
    'tetrahydrocannabinol_acid_thca': 'thca',
    'cannabidiols_cbd': 'cbd',
    'cannabidiol_acid_cbda': 'cbda',
}
CT_TERPENES = {
    'a_pinene': 'alpha_pinene',
    'b_myrcene': 'beta_myrcene',
    'b_caryophyllene': 'beta_caryophyllene',
    'b_pinene': 'beta_pinene',
    'limonene': 'limonene',
    'ocimene': 'ocimene',
    'linalool_lin': 'linalool_lin',
    'humulene_hum': 'humulene_hum',
    'a_bisabolol': 'alpha_bisabolol',
    'a_phellandrene': 'alpha_phellandrene',
    'a_terpinene': 'alpha_terpinene',
    'b_eudesmol': 'beta_eudesmol',
    'b_terpinene': 'beta_terpinene',
    'fenchone': 'fenchone',
    'pulegol': 'pulegol',
    'borneol': 'borneol',
    'isopulegol': 'isopulegol',
    'carene': 'carene',
    'camphene': 'camphene',
    'camphor': 'camphor',
    'caryophyllene_oxide': 'caryophyllene_oxide',
    'cedrol': 'cedrol',
    'eucalyptol': 'eucalyptol',
    'geraniol': 'geraniol',
    'guaiol': 'guaiol',
    'geranyl_acetate': 'geranyl_acetate',
    'isoborneol': 'isoborneol',
    'menthol': 'menthol',
    'l_fenchone': 'l_fenchone',
    'nerol': 'nerol',
    'sabinene': 'sabinene',
    'terpineol': 'terpineol',
    'terpinolene': 'terpinolene',
    'trans_b_farnesene': 'trans_beta_farnesene',
    'valencene': 'valencene',
    'a_cedrene': 'alpha_cedrene',
    'a_farnesene': 'alpha_farnesene',
    'b_farnesene': 'beta_farnesene',
    'cis_nerolidol': 'cis_nerolidol',
    'fenchol': 'fenchol',
    'trans_nerolidol': 'trans_nerolidol'
}


def flatten_results(x):
    """Flatten the results."""
    results = []
    for name, analyte in CT_CANNABINOIDS.items():
        # print(analyte, x[name])
        results.append({
            'key': analyte,
            'name': name,
            'value': convert_to_numeric(x[name]),
            'units': 'percent',
            'analysis': 'cannabinoids',
        })
    for name, analyte in CT_TERPENES.items():
        # print(analyte, x[name])
        results.append({
            'key': analyte,
            'name': name,
            'value': convert_to_numeric(x[name]),
            'units': 'percent',
            'analysis': 'terpenes',
        })
    return results


def get_results_ct(url: str = CT_RESULTS_URL) -> pd.DataFrame:
    """Get all of the Connecticut test results.
    Args:
        url (str): The URL to the CSV data.
    Returns:
        df (pd.DataFrame): A Pandas DataFrame of the test results.
    """

    # Get the data from the OpenData API.
    response = requests.get(url)
    if response.status_code == 200:
        json_data = response.json()
        metadata = json_data['meta']
        header = metadata['view']['columns']
        headers = [h['name'] for h in header]
        columns = [cannlytics.utils.snake_case(h) for h in headers]
        rows = json_data['data']
        df = pd.DataFrame(rows, columns=columns)
    else:
        print('Failed to fetch CT results. Status code:', response.status_code)
    
    # FIXME: Standardize the results.
    # Note: The results do not match the COAs!!!
    df['results'] = df.apply(flatten_results, axis=1)

    # Drop unnecessary columns.
    drop_columns = ['meta', 'position', 'created_at', 'created_meta',
        'updated_at', 'updated_meta']
    drop_columns += list(CT_CANNABINOIDS.keys()) + list(CT_TERPENES.keys())
    df.drop(columns=drop_columns, inplace=True)

    # Rename the columns.
    df.rename(columns=CT_FIELDS, inplace=True)

    # TODO: Extract product_size, serving_size, servings_per_package, sample_weight
    # from dosage_form and standardize product type.

    # TODO: Format COA URLs.
    # coa_urls

    # Create the directory if it doesn't exist.
    if not os.path.exists(data_dir): os.makedirs(data_dir)

    # Save the results to Excel.
    date = datetime.now().isoformat()[:10]
    datafile = f'{data_dir}/ct-lab-results-{date}.xlsx'
    try:
        cannlytics.utils.to_excel_with_style(df, datafile)
    except:
        df.to_excel(datafile)
    print('Connecticut lab results archived:', datafile)
    return df


def download_pdfs_ct(
        df: pd.DataFrame,
        download_path: str,
        column_name: Optional[str] = 'lab_results_url',
        id_column: Optional[str] = 'id',
        verbose: Optional[bool] = True,
    ) -> None:
    """
    Downloads all PDFs from a specified column in a Pandas DataFrame.
    Args:
        df (pandas.DataFrame): The input DataFrame containing the URLs of the PDFs.
        column_name (str): The name of the column containing the PDF URLs.
        download_path (str): The path to the directory where the PDFs will be downloaded.
    """
    for _, row in df.iterrows():
        pdf_url = row[column_name]
        if isinstance(pdf_url, list):
            pdf_url = pdf_url[0]

        # Create the filename from the ID.
        filename = row[id_column]
        if not filename.endswith('.pdf'):
            filename = filename + '.pdf'

        # Create the local file path for downloading the PDF.
        # Continue if the PDF is already downloaded.
        outfile = os.path.join(download_path, filename)
        if os.path.isfile(outfile) or pdf_url is None:
            continue

        # Download the PDF.
        try:
            response = requests.get(pdf_url)
        except:
            print(f'Failed to download PDF: {pdf_url}')
            continue
        if response.status_code == 200:
            with open(outfile, 'wb') as file:
                file.write(response.content)
            if verbose:
                print(f'Downloaded PDF: {outfile}.')
        else:
            print(f'Failed to download PDF {filename}. Status code:', response.status_code)


# === Test ===
# [✓] Tested: 2024-04-14 by Keegan Skeate <keegan@cannlytics>
if __name__ == '__main__':

    # Command line usage.
    import argparse
    try:
        parser = argparse.ArgumentParser()
        parser.add_argument('--pdf_dir', dest='pdf_dir', type=str)
        parser.add_argument('--data_dir', dest='data_dir', type=str)
        args = parser.parse_args()
    except SystemExit:
        args = {}

    # Specify where your data lives.
    DATA_DIR = 'D://data/connecticut/results'
    PDF_DIR = 'D://data/connecticut/results/pdfs'
    stats_dir = 'D://data/connecticut/results/datasets'

    # Set the destination for the PDFs.
    data_dir = args.get('data_dir', DATA_DIR)
    pdf_dir = args.get('pdf_dir', os.path.join(data_dir, 'pdfs'))

    # Get the test results.
    print('Getting Connecticut test results...')
    results = get_results_ct()

    # Download the PDFs.
    print('Downloading PDFs...')
    if not os.path.exists(pdf_dir): os.makedirs(pdf_dir)
    download_pdfs_ct(results, pdf_dir)

    # Save the results to Excel.
    date = datetime.now().isoformat()[:10]
    if not os.path.exists(stats_dir): os.makedirs(stats_dir)
    results.to_excel(f'{stats_dir}/ct-lab-results-{date}.xlsx', index=False)
    results.to_csv(f'{stats_dir}/ct-lab-results-latest.csv', index=False)
    print('Connecticut lab results archived:', stats_dir)

    # TODO: Integrate with `analyte_results_ct.py`.


    # FIXME: Upload results to Firestore.

    
    # FIXME: Upload PDFs to Google Cloud Storage.


    # FIXME: Upload datafiles to Google Cloud Storage.