zwn22 commited on
Commit
e317c53
1 Parent(s): 2b0b978

Update NC_Crime.py

Browse files
Files changed (1) hide show
  1. NC_Crime.py +18 -123
NC_Crime.py CHANGED
@@ -22,8 +22,6 @@ from typing import List
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,138 +78,35 @@ class NCCrimeDataset(datasets.GeneratorBasedBuilder):
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
- chapel_hill_path = dl_manager.download_and_extract("https://drive.google.com/uc?export=download&id=19cZzyedCLUtQt9Ko4bcOixWIJHBn9CfI")
89
- # raleigh_path = dl_manager.download_and_extract("https://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_df = pd.concat([cary_df, chapel_hill_df], ignore_index=True)
107
-
108
-
109
- combined_file_path = os.path.join(dl_manager.download_dir, "combined_dataset.csv")
110
- combined_df.to_csv(combined_file_path, index=False)
111
 
 
 
 
112
  return [
113
- datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": combined_file_path})
114
  ]
115
 
116
 
117
- def _preprocess_chapel_hill(self, file_path):
118
- # Load the dataset
119
- Chapel = pd.read_csv(file_path, low_memory=False)
120
-
121
- # Replace specified values with None
122
- replace_values = {'<Null>': None, 'NONE': None}
123
- Chapel['Weapon_Description'] = Chapel['Weapon_Description'].replace(replace_values)
124
-
125
- # Define the category mapping
126
- category_mapping = {
127
- 'Theft': ['THEFT/LARCENY', 'LARCENY FROM AU', 'LARCENY FROM PE', 'LARCENY OF OTHE', 'LARCENY FROM BU', 'LARCENY OF BIKE', 'LARCENY FROM RE', 'LARCENY OF AUTO'],
128
- 'Assault': ['ASSAULT/SEXUAL', 'ASSAULT', 'STAB GUNSHOT PE', 'ACTIVE ASSAILAN'],
129
- 'Burglary': ['BURGLARY', 'BURGLARY ATTEMP', 'STRUCTURE COLLAPSE', 'ROBBERY/CARJACK'],
130
- 'Drugs': ['DRUGS'],
131
- 'Traffic Violations': ['TRAFFIC STOP', 'TRAFFIC/TRANSPO', 'TRAFFIC VIOLATI', 'MVC', 'MVC W INJURY', 'MVC W INJURY AB', 'MVC W INJURY DE', 'MVC ENTRAPMENT'],
132
- 'Disorderly Conduct': ['DISTURBANCE/NUI', 'DOMESTIC DISTUR', 'DISPUTE', 'DISTURBANCE', 'LOST PROPERTY', 'TRESPASSING/UNW', 'REFUSAL TO LEAV', 'SUSPICIOUS COND', 'STRUCTURE FIRE'],
133
- 'Fraud': ['FRAUD OR DECEPT'],
134
- 'Sexual Offenses': ['SEXUAL OFFENSE'],
135
- 'Homicide': ['SUICIDE ATTEMPT', 'ABUSE/ABANDOMEN', 'DECEASED PERSON'],
136
- 'Weapons Violations': ['WEAPON/FIREARMS'],
137
- 'Animal-related Offenses': ['ANIMAL BITE', 'ANIMAL', 'ANIMAL CALL'],
138
- 'Missing Person': ['MISSING PERSON'],
139
- 'Public Service': ['PUBLIC SERVICE', 'PUBLICE SERVICE'],
140
- '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']
141
- }
142
- # Function to categorize crime
143
- def categorize_crime(crime):
144
- for category, crimes in category_mapping.items():
145
- if crime in crimes:
146
- return category
147
- return 'Miscellaneous'
148
-
149
- # Create a new DataFrame with simplified crime categories
150
- Chapel_new = pd.DataFrame({
151
- "year": pd.to_datetime(Chapel['Date_of_Occurrence']).dt.year,
152
- "city": "Chapel Hill",
153
- "crime_major_category": Chapel['Reported_As'].apply(categorize_crime),
154
- "crime_detail": Chapel['Offense'].str.title(),
155
- "latitude": Chapel['X'].round(5).fillna(0),
156
- "longitude": Chapel['Y'].round(5).fillna(0),
157
- "occurance_time": pd.to_datetime(Chapel['Date_of_Occurrence'].str.replace(r'\+\d{2}$', '', regex=True)).dt.strftime('%Y/%m/%d %H:%M:%S'),
158
- "clear_status": None,
159
- "incident_address": Chapel['Street'].str.replace("@", " "),
160
- "notes": Chapel['Weapon_Description'].apply(lambda x: f"Weapon: {x}" if pd.notnull(x) else "Weapon: None").str.title()
161
- }).fillna("No Data")
162
-
163
- # Correct the latitude and longitude if necessary
164
- 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
165
-
166
- # Ensure latitude and longitude are in the expected range
167
- Chapel_new = Chapel_new.loc[(Chapel_new['latitude'].between(30, 40)) & (Chapel_new['longitude'].between(-80, -70))]
168
-
169
- # Filter for years 2015 and onwards
170
- Chapel_new = Chapel_new[Chapel_new['year'] >= 2015]
171
-
172
- return Chapel_new
173
-
174
- def _preprocess_cary(self, file_path):
175
- # Load the dataset
176
- df = pd.read_csv(file_path, low_memory=False).dropna(subset=['Year'])
177
-
178
- # Define the crime categorization function
179
- def categorize_crime(crime):
180
- crime_mapping = {
181
- 'Theft': ['BURGLARY', 'MOTOR VEHICLE THEFT', 'LARCENY'],
182
- 'Arson': ['ARSON'],
183
- 'Assault': ['AGGRAVATED ASSAULT'],
184
- 'Homicide': ['MURDER'],
185
- 'Robbery': ['ROBBERY']
186
- }
187
- for category, crimes in crime_mapping.items():
188
- if crime in crimes:
189
- return category
190
- return 'Miscellaneous'
191
-
192
- # Apply the crime categorization function and preprocess the dataset
193
- processed_df = pd.DataFrame({
194
- "year": df["Year"].astype(int),
195
- "city": "Cary",
196
- "crime_major_category": df['Crime Category'].apply(categorize_crime).str.title(),
197
- "crime_detail": df['Crime Type'].str.title(),
198
- "latitude": df['Lat'].fillna(0).round(5).fillna(0),
199
- "longitude": df['Lon'].fillna(0).round(5).fillna(0),
200
- "occurance_time": pd.to_datetime(df['Begin Date Of Occurrence'] + ' ' + df['Begin Time Of Occurrence']).dt.strftime('%Y/%m/%d %H:%M:%S'),
201
- "clear_status": None,
202
- "incident_address": df['Geo Code'],
203
- "notes": 'District: '+ df['District'].str.title() + ' Violent Property: ' + df['Violent Property'].str.title()
204
- }).fillna("No Data")
205
-
206
- # Filter the dataset for records from 2015 onwards
207
- processed_df = processed_df[processed_df['year'] >= 2015]
208
-
209
- return processed_df
210
 
211
 
212
  def _generate_examples(self, filepath):
213
  # Read the CSV file
214
- df = pd.read_csv(filepath)
215
  # Iterate over the rows and yield examples
216
  for i, row in df.iterrows():
217
  yield i, {
 
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
  )
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://drive.google.com/file/d/109KUBevJNNC_aKcTmGhjh53c3JrlgTW4/view?usp=drive_link
85
+ # "https://drive.google.com/uc?export=download&id=109KUBevJNNC_aKcTmGhjh53c3JrlgTW4"
86
+ # "https://drive.google.com/uc?export=download&id=1SdnSc-e3OwzfXgpCZVdZuq2Fq9iCrd21"
87
+ # "https://drive.google.com/uc?export=download&id=1C1vwAe4nVTdu6P8lHsmyLbJHUsHfT72h"
88
+
89
+ #"https://drive.google.com/uc?export=download&id=1Se-B8Y-SdU0caZzGJyX_0YW44TZwaq3l"
90
+
91
+ # "https://raw.githubusercontent.com/znw2024/NC-Crime/main/DCCR.csv"
92
+ "https://raw.githubusercontent.com/zening-wang2023/NC-Crime-Dataset/main/DCCR.csv.zip"
93
+ # "https://raw.githubusercontent.com/zening-wang2023/NC-Crime-Dataset/main/NC_dataset.csv.zip"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
+ )
96
+ unzipped_file_path = os.path.join(downloaded_file_path, "DCCR.csv")
97
+ # Return a list of split generators
98
  return [
99
+ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": unzipped_file_path})
100
  ]
101
 
102
 
103
+
104
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
 
107
  def _generate_examples(self, filepath):
108
  # Read the CSV file
109
+ df = pd.read_csv(filepath) ## just for test
110
  # Iterate over the rows and yield examples
111
  for i, row in df.iterrows():
112
  yield i, {