File size: 7,980 Bytes
3bbab5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
import re

def get_docket_ids(search_term):
    url = f"https://api.regulations.gov/v4/dockets"
    params = {
        'filter[searchTerm]': search_term,
        'api_key': "your-api-key"
    }
    response = requests.get(url, params=params)
    if response.status_code == 200:
        data = response.json()
        dockets = data['data']
        docket_ids = [docket['id'] for docket in dockets]
        return docket_ids
    else:
        return f"Error: {response.status_code}"

class RegulationsDataFetcher:
    API_KEY = "your-api-key"
    BASE_COMMENT_URL = 'https://api.regulations.gov/v4/comments'
    BASE_DOCKET_URL = 'https://api.regulations.gov/v4/dockets/'
    HEADERS = {
        'X-Api-Key': API_KEY,
        'Content-Type': 'application/json'
    }

    def __init__(self, docket_id):
        self.docket_id = docket_id
        self.docket_url = self.BASE_DOCKET_URL + docket_id
        self.dataset = []

    def fetch_comments(self):
        """Fetch a single page of 25 comments."""
        url = f'{self.BASE_COMMENT_URL}?filter[docketId]={self.docket_id}&page[number]=1&page[size]=25'
        response = requests.get(url, headers=self.HEADERS)
        
        if response.status_code == 200:
            return response.json()
        else:
            print(f'Failed to retrieve comments: {response.status_code}')
            return None

    def get_docket_info(self):
        """Get docket information."""
        response = requests.get(self.docket_url, headers=self.HEADERS)
        
        if response.status_code == 200:
            docket_data = response.json()
            return (docket_data['data']['attributes']['agencyId'],
                    docket_data['data']['attributes']['title'],
                    docket_data['data']['attributes']['modifyDate'], 
                    docket_data['data']['attributes']['docketType'], 
                    docket_data['data']['attributes']['keywords'])
        else:
            print(f'Failed to retrieve docket info: {response.status_code}')
            return None

    def fetch_comment_details(self, comment_url):
        """Fetch detailed information of a comment."""
        response = requests.get(comment_url, headers=self.HEADERS)
        if response.status_code == 200:
            return response.json()
        else:
            print(f'Failed to retrieve comment details: {response.status_code}')
            return None

    def collect_data(self):
        """Collect data and reshape into nested dictionary format."""
        data = self.fetch_comments()
        if not data:
            return None

        docket_info = self.get_docket_info()
        if not docket_info:
            return None

        # Starting out with docket information
        nested_data = {
            "id": self.docket_id,
            "agency": self.docket_id.split('-')[0],
            "title": docket_info[1] if docket_info else "Unknown Title",
            "update_date": docket_info[2].split('T')[0] if docket_info and docket_info[2] else "Unknown Update Date",
            "update_time": docket_info[2].split('T')[1].strip('Z') if docket_info and docket_info[2] and 'T' in docket_info[2] else "Unknown Update Time",
            "purpose": docket_info[3],
            "keywords": docket_info[4],
            "comments": []
        }

        # Going into each docket for comment information
        if 'data' in data:
            for comment in data['data']:
                if len(nested_data["comments"]) >= 10:
                    break

                comment_details = self.fetch_comment_details(comment['links']['self'])
                if 'data' in comment_details and 'attributes' in comment_details['data']:
                    comment_data = comment_details['data']['attributes']

                    # Basic comment text cleaning
                    comment_text = (comment_data.get('comment', '') or '').strip()
                    comment_text = comment_text.replace("<br/>", "").replace("<span style='padding-left: 30px'></span>", "")
                    comment_text = re.sub(r'&[^;]+;', '', comment_text)

                    # Recording detailed comment information
                    if (comment_text and "attached" not in comment_text.lower() and "attachment" not in comment_text.lower() and comment_text.lower() != "n/a"):
                        nested_comment = {
                            "text": comment_text,
                            "comment_id": comment['id'],
                            "comment_url": comment['links']['self'],
                            "comment_date": comment['attributes']['postedDate'].split('T')[0],
                            "comment_time": comment['attributes']['postedDate'].split('T')[1].strip('Z'),
                            "commenter_fname": ((comment_data.get('firstName') or 'Anonymous').split(',')[0]).capitalize(),
                            "commenter_lname": ((comment_data.get('lastName') or 'Anonymous').split(',')[0]).capitalize(),
                            "comment_length": len(comment_text) if comment_text is not None else 0
                        }
                        nested_data["comments"].append(nested_comment)

        return nested_data


# COLLECTING DATA 
    
substance_related_terms = [
    # Types of Opioids
    "opioids",
    "heroin",
    "morphine",
    "fentanyl",
    "methadone",
    "oxycodone",
    "lofexidine",
    "hydrocodone",
    "codeine",
    "tramadol",
    "prescription opioids",
    # Withdrawal Support
    "lofexidine",
    "buprenorphine",
    "naloxone",
    # Related Phrases
    "opioid epidemic",
    "opioid abuse",
    "opioid crisis",
    "opioid overdose",
    "opioid tolerance",
    "opioid treatment program",
    "medication assisted treatment",
    "substance abuse",
    "narcotics",
    "opioid addiction",
    "opioid withdrawal",
    "opioid dependence",
    "opioid use disorder",
    "opioid receptor",
    "pain management",
    "prescription drug abuse",
    "drug addiction treatment",
    "controlled substances",
    "opioid analgesics",
    # Additional Terms
    "naltrexone",
    "opioid detoxification",
    "opioid therapy",
    "chronic pain",
    "opioid agonist",
    "partial opioid agonist",
    "opioid antagonist",
    "drug rehabilitation",
    "overdose prevention",
    "opioid prescribing guidelines",
    "opioid risk tool",
    "opioid alternative",
    "addiction recovery",
    "addiction counseling",
    "opioid education",
    "opioid policy",
    "opioid regulation",
    # Types of Other Substances
    "marijuana",
    "cannabis",
    "THC",
    "CBD",
    "synthetic cannabinoids",
    "alcohol",
    "ethanol",
    "benzodiazepines",
    "cocaine",
    "amphetamine",
    "methamphetamine",
    "MDMA",
    "ecstasy",
    "hallucinogens",
    "LSD",
    "psilocybin",
    "ketamine",
    "inhalants",
    "steroids",
    "tobacco",
    "nicotine",
    # Related Phrases for Other Substances
    "alcohol abuse",
    "alcohol addiction",
    "alcohol dependence",
    "alcohol withdrawal",
    "alcohol treatment",
    "binge drinking",
    "drug abuse",
    "drug addiction",
    "drug dependence",
    "drug withdrawal",
    "drug treatment",
    "substance use disorder",
    "chemical dependency",
    "intoxication",
    "sobriety",
    "recovery program",
    "detoxification",
    "rehabilitation",
    "12-step program",
    "psychoactive drugs",
    "addictive behavior",
    "harm reduction",
    "substance abuse counseling",
    "addiction therapy",
    "substance abuse prevention",
    "drug education",
    "drug policy",
    "drug regulation"
]
    
docket_ids = set()
all_data = []

for term in substance_related_terms:
    docket_ids.update(get_docket_ids(term))

for docket_id in docket_ids:
    fetcher = RegulationsDataFetcher(docket_id)
    docket_data = fetcher.collect_data()
    if docket_data and len(docket_data["comments"]) != 0:
        all_data.append(docket_data)