zwn22 commited on
Commit
815c859
1 Parent(s): e385b11

Update NC_Crime.py

Browse files
Files changed (1) hide show
  1. NC_Crime.py +223 -6
NC_Crime.py CHANGED
@@ -22,6 +22,8 @@ from typing import List
22
  import datasets
23
  import logging
24
  import pandas as pd
 
 
25
 
26
  # TODO: Add BibTeX citation
27
  # Find for instance the citation on arxiv or on the dataset repo/website
@@ -78,21 +80,236 @@ class NCCrimeDataset(datasets.GeneratorBasedBuilder):
78
  )
79
 
80
 
 
81
  def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
82
  # Use the raw GitHub link to download the CSV file
83
- downloaded_file_path = dl_manager.download_and_extract(
84
- "https://data.townofcary.org/api/explore/v2.1/catalog/datasets/cpd-incidents/exports/csv?lang=en&timezone=US%2FEastern&use_labels=true&delimiter=%2C"
85
- )
86
- unzipped_file_path = os.path.join(downloaded_file_path, "DCCR.csv")
87
- # Return a list of split generators
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  return [
89
- datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": unzipped_file_path})
90
  ]
91
 
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
 
 
95
 
 
96
 
97
  def _generate_examples(self, filepath):
98
  # Read the CSV file
 
22
  import datasets
23
  import logging
24
  import pandas as pd
25
+ from pyproj import Transformer
26
+
27
 
28
  # TODO: Add BibTeX citation
29
  # Find for instance the citation on arxiv or on the dataset repo/website
 
80
  )
81
 
82
 
83
+
84
  def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
85
  # Use the raw GitHub link to download the CSV file
86
+ cary_path = dl_manager.download_and_extract("https://data.townofcary.org/api/explore/v2.1/catalog/datasets/cpd-incidents/exports/csv?lang=en&timezone=US%2FEastern&use_labels=true&delimiter=%2C")
87
+ durham_path = dl_manager.download_and_extract("https://www.arcgis.com/sharing/rest/content/items/7132216432df4957830593359b0c4030/data")
88
+ raleigh_path = dl_manager.download_and_extract("https://drive.google.com/uc?export=download&id=19cZzyedCLUtQt9Ko4bcOixWIJHBn9CfI")
89
+ chapel_hill_path = dl_manager.download_and_extract("ttps://drive.google.com/uc?export=download&id=1SZi4e01TxwuDDb6k9EU_7i-qTP1Xq2sm")
90
+ # Cary
91
+ # "https://data.townofcary.org/api/explore/v2.1/catalog/datasets/cpd-incidents/exports/csv?lang=en&timezone=US%2FEastern&use_labels=true&delimiter=%2C",
92
+ # Durham
93
+ # "https://www.arcgis.com/sharing/rest/content/items/7132216432df4957830593359b0c4030/data",
94
+ # Raleigh
95
+ # "https://drive.google.com/uc?export=download&id=19cZzyedCLUtQt9Ko4bcOixWIJHBn9CfI",
96
+ # Chapel Hill
97
+ # "https://drive.google.com/uc?export=download&id=1SZi4e01TxwuDDb6k9EU_7i-qTP1Xq2sm"
98
+
99
+ cary_df = self._preprocess_cary(cary_path)
100
+ durham_df = self._preprocess_durham(durham_path)
101
+ raleigh_df = self._preprocess_raleigh(raleigh_path)
102
+ chapel_hill_df = self._preprocess_chapel_hill(chapel_hill_path)
103
+
104
+ combined_df = pd.concat([cary_df, durham_df, raleigh_df, chapel_hill_df], ignore_index=True)
105
+
106
+ combined_file_path = os.path.join(dl_manager.download_dir, "combined_dataset.csv")
107
+ combined_df.to_csv(combined_file_path, index=False)
108
+
109
  return [
110
+ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": combined_file_path})
111
  ]
112
 
113
 
114
+ def _preprocess_durham(self, file_path):
115
+ # Load the dataset
116
+ Durham = pd.read_excel(file_path)
117
+
118
+ # Clean the 'Weapon' column
119
+ Durham['Weapon'] = Durham['Weapon'].replace(['(blank)', 'Not Applicable/None', 'Unknown/Not Stated'], None)
120
+
121
+ # Define the category mapping
122
+ category_mapping = {
123
+ 'Theft': ['LARCENY - AUTOMOBILE PARTS OR ACCESSORIES', 'TOWED/ABANDONED VEHICLE', 'MOTOR VEHICLE THEFT', 'BURGLARY', 'LARCENY - FROM MOTOR VEHICLE', 'LARCENY - SHOPLIFTING', 'LOST PROPERTY', 'VANDALISM', 'LARCENY - ALL OTHER', 'LARCENY - FROM BUILDING', 'RECOVERED STOLEN PROPERTY (OTHER JURISDICTION)', 'LARCENY - POCKET-PICKING', 'LARCENY - FROM COIN-OPERATED DEVICE', 'LARCENY - PURSESNATCHING'],
124
+ 'Fraud': ['FRAUD-IDENTITY THEFT', 'EMBEZZLEMENT', 'COUNTERFEITING/FORGERY', 'FRAUD - CONFIDENCE GAMES/TRICKERY', 'FRAUD - CREDIT CARD/ATM', 'FRAUD - UNAUTHORIZED USE OF CONVEYANCE', 'FRAUD - FALSE PRETENSE', 'FRAUD - IMPERSONATION', 'FRAUD - WIRE/COMPUTER/OTHER ELECTRONIC', 'FRAUD - WORTHLESS CHECKS', 'FRAUD-FAIL TO RETURN RENTAL VEHICLE', 'FRAUD-HACKING/COMPUTER INVASION', 'FRAUD-WELFARE FRAUD'],
125
+ 'Assault': ['SIMPLE ASSAULT', 'AGGRAVATED ASSAULT'],
126
+ 'Drugs': ['DRUG/NARCOTIC VIOLATIONS', 'DRUG EQUIPMENT/PARAPHERNALIA'],
127
+ 'Sexual Offenses': ['SEX OFFENSE - FORCIBLE RAPE', 'SEX OFFENSE - SEXUAL ASSAULT WITH AN OBJECT', 'SEX OFFENSE - FONDLING', 'SEX OFFENSE - INDECENT EXPOSURE', 'SEX OFFENSE - FORCIBLE SODOMY', 'SEX OFFENSE - STATUTORY RAPE', 'SEX OFFENSE - PEEPING TOM', 'SEX OFFENSE - INCEST'],
128
+ 'Homicide': ['HOMICIDE-MURDER/NON-NEGLIGENT MANSLAUGHTER', 'JUSTIFIABLE HOMICIDE', 'HOMICIDE - NEGLIGENT MANSLAUGHTER'],
129
+ 'Arson': ['ARSON'],
130
+ 'Kidnapping': ['KIDNAPPING/ABDUCTION'],
131
+ 'Weapons Violations': ['WEAPON VIOLATIONS'],
132
+ 'Traffic Violations': ['ALL TRAFFIC (EXCEPT DWI)'],
133
+ 'Disorderly Conduct': ['DISORDERLY CONDUCT', 'DISORDERLY CONDUCT-DRUNK AND DISRUPTIVE', 'DISORDERLY CONDUCT-FIGHTING (AFFRAY)', 'DISORDERLY CONDUCT-UNLAWFUL ASSEMBLY'],
134
+ 'Gambling': ['GAMBLING - OPERATING/PROMOTING/ASSISTING', 'GAMBLING - BETTING/WAGERING'],
135
+ 'Animal-related Offenses': ['ANIMAL CRUELTY'],
136
+ 'Prostitution-related Offenses': ['PROSTITUTION', 'PROSTITUTION - ASSISTING/PROMOTING', 'PROSTITUTION - PURCHASING']
137
+ }
138
+
139
+ # Function to categorize crime
140
+ def categorize_crime(crime):
141
+ for category, crimes in category_mapping.items():
142
+ if crime in crimes:
143
+ return category
144
+ return 'Miscellaneous'
145
+
146
+ # Coordinate transformation function
147
+ def convert_coordinates(x, y):
148
+ transformer = Transformer.from_crs("epsg:2264", "epsg:4326", always_xy=True)
149
+ lon, lat = transformer.transform(x, y)
150
+ return pd.Series([lat, lon])
151
+
152
+ # Create a new DataFrame with simplified crime categories
153
+ Durham_new = pd.DataFrame({
154
+ # Your DataFrame creation code
155
+ })
156
+
157
+ # Convert coordinates and round/fill missing values
158
+ Durham_new[['latitude', 'longitude']] = Durham.apply(lambda row: convert_coordinates(row['X'], row['Y']), axis=1).round(5).fillna(0)
159
+
160
+ # Filter records and handle missing values
161
+ Durham_new = Durham_new[Durham_new['year'] >= 2015].fillna("No Data")
162
+
163
+ return Durham_new
164
+
165
+ def _preprocess_chapel_hill(self, file_path):
166
+ # Load the dataset
167
+ Chapel = pd.read_csv(file_path, low_memory=False)
168
+
169
+ # Replace specified values with None
170
+ replace_values = {'<Null>': None, 'NONE': None}
171
+ Chapel['Weapon_Description'] = Chapel['Weapon_Description'].replace(replace_values)
172
+
173
+ # Define the category mapping
174
+ category_mapping = {
175
+ 'Theft': ['THEFT/LARCENY', 'LARCENY FROM AU', 'LARCENY FROM PE', 'LARCENY OF OTHE', 'LARCENY FROM BU', 'LARCENY OF BIKE', 'LARCENY FROM RE', 'LARCENY OF AUTO'],
176
+ 'Assault': ['ASSAULT/SEXUAL', 'ASSAULT', 'STAB GUNSHOT PE', 'ACTIVE ASSAILAN'],
177
+ 'Burglary': ['BURGLARY', 'BURGLARY ATTEMP', 'STRUCTURE COLLAPSE', 'ROBBERY/CARJACK'],
178
+ 'Drugs': ['DRUGS'],
179
+ 'Traffic Violations': ['TRAFFIC STOP', 'TRAFFIC/TRANSPO', 'TRAFFIC VIOLATI', 'MVC', 'MVC W INJURY', 'MVC W INJURY AB', 'MVC W INJURY DE', 'MVC ENTRAPMENT'],
180
+ 'Disorderly Conduct': ['DISTURBANCE/NUI', 'DOMESTIC DISTUR', 'DISPUTE', 'DISTURBANCE', 'LOST PROPERTY', 'TRESPASSING/UNW', 'REFUSAL TO LEAV', 'SUSPICIOUS COND', 'STRUCTURE FIRE'],
181
+ 'Fraud': ['FRAUD OR DECEPT'],
182
+ 'Sexual Offenses': ['SEXUAL OFFENSE'],
183
+ 'Homicide': ['SUICIDE ATTEMPT', 'ABUSE/ABANDOMEN', 'DECEASED PERSON'],
184
+ 'Weapons Violations': ['WEAPON/FIREARMS'],
185
+ 'Animal-related Offenses': ['ANIMAL BITE', 'ANIMAL', 'ANIMAL CALL'],
186
+ 'Missing Person': ['MISSING PERSON'],
187
+ 'Public Service': ['PUBLIC SERVICE', 'PUBLICE SERVICE'],
188
+ 'Miscellaneous': ['<Null>', 'SUSPICIOUS/WANT', 'MISC OFFICER IN', 'INDECENCY/LEWDN', 'PUBLIC SERVICE', 'TRESPASSING', 'UNKNOWN PROBLEM', 'LOUD NOISE', 'ESCORT', 'ABDUCTION/CUSTO', 'THREATS', 'BURGLAR ALARM', 'DOMESTIC', 'PROPERTY FOUND', 'FIREWORKS', 'MISSING/RUNAWAY', 'MENTAL DISORDER', 'CHECK WELL BEIN', 'PSYCHIATRIC', 'OPEN DOOR', 'ABANDONED AUTO', 'HARASSMENT THRE', 'JUVENILE RELATE', 'ASSIST MOTORIST', 'HAZARDOUS DRIVI', 'MVC', 'GAS LEAK FIRE', 'ASSIST OTHER AG', 'DOMESTIC ASSIST', 'SUSPICIOUS VEHI', 'UNKNOWN LE', 'ALARMS', '911 HANGUP', 'BOMB/CBRN/PRODU', 'STATIONARY PATR', 'LITTERING', 'HOUSE CHECK', 'CARDIAC', 'CLOSE PATROL', 'BOMB FOUND/SUSP', 'INFO FOR ALL UN', 'UNCONCIOUS OR F', 'LIFTING ASSISTA', 'ATTEMPT TO LOCA', 'SICK PERSON', 'HEAT OR COLD EX', 'CONFINED SPACE', 'TRAUMATIC INJUR', 'DROWNING', 'CITY ORDINANCE']
189
+ }
190
+
191
+ # Function to categorize crime
192
+ def categorize_crime(crime):
193
+ for category, crimes in category_mapping.items():
194
+ if crime in crimes:
195
+ return category
196
+ return 'Miscellaneous'
197
+
198
+ # Create a new DataFrame with simplified crime categories
199
+ Chapel_new = pd.DataFrame({
200
+ "year": pd.to_datetime(Chapel['Date_of_Occurrence']).dt.year,
201
+ "city": "Chapel Hill",
202
+ "crime_major_category": Chapel['Reported_As'].apply(categorize_crime),
203
+ "crime_detail": Chapel['Offense'].str.title(),
204
+ "latitude": Chapel['X'].round(5).fillna(0),
205
+ "longitude": Chapel['Y'].round(5).fillna(0),
206
+ "occurance_time": pd.to_datetime(Chapel['Date_of_Occurrence'].str.replace(r'\+\d{2}$', '', regex=True)).dt.strftime('%Y/%m/%d %H:%M:%S'),
207
+ "clear_status": None,
208
+ "incident_address": Chapel['Street'].str.replace("@", " "),
209
+ "notes": Chapel['Weapon_Description'].apply(lambda x: f"Weapon: {x}" if pd.notnull(x) else "Weapon: None").str.title()
210
+ }).fillna("No Data")
211
+
212
+ # Correct the latitude and longitude if necessary
213
+ Chapel_new.loc[(Chapel_new['latitude'].between(-80, -70)) & (Chapel_new['longitude'].between(30, 40)), ['latitude', 'longitude']] = Chapel_new.loc[(Chapel_new['latitude'].between(-80, -70)) & (Chapel_new['longitude'].between(30, 40)), ['longitude', 'latitude']].values
214
+
215
+ # Ensure latitude and longitude are in the expected range
216
+ Chapel_new = Chapel_new.loc[(Chapel_new['latitude'].between(30, 40)) & (Chapel_new['longitude'].between(-80, -70))]
217
+
218
+ # Filter for years 2015 and onwards
219
+ Chapel_new = Chapel_new[Chapel_new['year'] >= 2015]
220
+
221
+ return Chapel_new
222
+
223
+ def _preprocess_cary(self, file_path):
224
+ # Load the dataset
225
+ df = pd.read_csv(file_path, low_memory=False).dropna(subset=['Year'])
226
+
227
+ # Define the crime categorization function
228
+ def categorize_crime(crime):
229
+ crime_mapping = {
230
+ 'Theft': ['BURGLARY', 'MOTOR VEHICLE THEFT', 'LARCENY'],
231
+ 'Arson': ['ARSON'],
232
+ 'Assault': ['AGGRAVATED ASSAULT'],
233
+ 'Homicide': ['MURDER'],
234
+ 'Robbery': ['ROBBERY']
235
+ }
236
+ for category, crimes in crime_mapping.items():
237
+ if crime in crimes:
238
+ return category
239
+ return 'Miscellaneous'
240
+
241
+ # Apply the crime categorization function and preprocess the dataset
242
+ processed_df = pd.DataFrame({
243
+ "year": df["Year"].astype(int),
244
+ "city": "Cary",
245
+ "crime_major_category": df['Crime Category'].apply(categorize_crime).str.title(),
246
+ "crime_detail": df['Crime Type'].str.title(),
247
+ "latitude": df['Lat'].fillna(0).round(5).fillna(0),
248
+ "longitude": df['Lon'].fillna(0).round(5).fillna(0),
249
+ "occurance_time": pd.to_datetime(df['Begin Date Of Occurrence'] + ' ' + df['Begin Time Of Occurrence']).dt.strftime('%Y/%m/%d %H:%M:%S'),
250
+ "clear_status": None,
251
+ "incident_address": df['Geo Code'],
252
+ "notes": 'District: '+ df['District'].str.title() + ' Violent Property: ' + df['Violent Property'].str.title()
253
+ }).fillna("No Data")
254
+
255
+ # Filter the dataset for records from 2015 onwards
256
+ processed_df = processed_df[processed_df['year'] >= 2015]
257
+
258
+ return processed_df
259
+
260
+ def _preprocess_raleigh(self, file_path):
261
+ # Load the dataset
262
+ Raleigh = pd.read_csv(file_path, low_memory=False)
263
+
264
+ # Define category mapping
265
+ category_mapping = {
266
+ 'Miscellaneous': ['MISCELLANEOUS', 'ALL OTHER OFFENSES'],
267
+ 'Sexual Offenses': ['SEX OFFENSES'],
268
+ 'Assault': ['ASSAULT', 'SIMPLE ASSAULT'],
269
+ 'Juvenile': ['JUVENILE'],
270
+ 'Traffic Violations': ['TRAFFIC', 'UNAUTHORIZED MOTOR VEHICLE USE', 'TRAFFIC VIOLATIONS', 'LIQUOR LAW VIOLATIONS'],
271
+ 'Fraud': ['FRAUD', 'EMBEZZLEMENT', 'BRIBERY'],
272
+ 'Vandalism': ['VANDALISM'],
273
+ 'Theft': ['LARCENY FROM MV', 'LARCENY', 'MV THEFT', 'STOLEN PROPERTY'],
274
+ 'Burglary': ['BURGLARY/COMMERCIAL', 'BURGLARY/RESIDENTIAL'],
275
+ 'Disorderly Conduct': ['DISORDERLY CONDUCT'],
276
+ 'Weapons Violations': ['WEAPONS VIOLATION'],
277
+ 'Drugs': ['DRUGS', 'DRUG VIOLATIONS'],
278
+ 'Arson': ['ARSON'],
279
+ 'Robbery': ['ROBBERY'],
280
+ 'Kidnapping': ['KIDNAPPING'],
281
+ 'Extortion': ['EXTORTION'],
282
+ 'Human Trafficking': ['HUMAN TRAFFICKING'],
283
+ 'Murder': ['MURDER'],
284
+ 'Prostitution-related Offenses': ['PROSTITUTION'],
285
+ 'Gambling': ['GAMBLING'],
286
+ }
287
+
288
+ # Function to categorize crime based on the mapping dictionary
289
+ def categorize_crime(crime):
290
+ for category, crimes in category_mapping.items():
291
+ if crime in crimes:
292
+ return category
293
+ return 'Miscellaneous'
294
 
295
+ # Create a new DataFrame with simplified crime categories
296
+ Raleigh_new = pd.DataFrame({
297
+ "year": Raleigh['reported_year'],
298
+ "city": "Raleigh",
299
+ "crime_major_category": Raleigh['crime_category'].apply(categorize_crime),
300
+ "crime_detail": Raleigh['crime_description'],
301
+ "latitude": Raleigh['latitude'].round(5).fillna(0),
302
+ "longitude": Raleigh['longitude'].round(5).fillna(0),
303
+ "occurance_time": pd.to_datetime(Raleigh['reported_date'].str.replace(r'\+\d{2}$', '', regex=True), errors='coerce').dt.strftime('%Y/%m/%d %H:%M:%S'),
304
+ "clear_status": None,
305
+ "incident_address": Raleigh['reported_block_address'] + ', ' + Raleigh['district'] + ', Raleigh',
306
+ "notes": 'District: '+ Raleigh['district'].str.title()
307
+ }).fillna("No Data")
308
 
309
+ # Filter the dataset for records from 2015 onwards
310
+ Raleigh_new = Raleigh_new[Raleigh_new['year'] >= 2015]
311
 
312
+ return Raleigh_new
313
 
314
  def _generate_examples(self, filepath):
315
  # Read the CSV file