|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
"""TODO: Add a description here.""" |
|
|
|
|
|
import csv |
|
import json |
|
import os |
|
from typing import List |
|
import datasets |
|
import logging |
|
import pandas as pd |
|
from pyproj import Transformer |
|
|
|
|
|
|
|
|
|
_CITATION = """\ |
|
@InProceedings{huggingface:dataset, |
|
title = {NC Crime Dataset}, |
|
author={huggingface, Inc. |
|
}, |
|
year={2024} |
|
} |
|
""" |
|
|
|
|
|
|
|
_DESCRIPTION = """\ |
|
The dataset, compiled from public police incident reports across various cities in North Carolina, covers a period from the early 2000s through to 2024. It is intended to facilitate the study of crime trends and patterns. |
|
""" |
|
|
|
|
|
_HOMEPAGE = "" |
|
|
|
|
|
_LICENSE = "" |
|
|
|
|
|
|
|
|
|
_URL = "" |
|
_URLS = "" |
|
|
|
class NCCrimeDataset(datasets.GeneratorBasedBuilder): |
|
"""Dataset for North Carolina Crime Incidents.""" |
|
_URLS = _URLS |
|
|
|
VERSION = datasets.Version("1.0.0") |
|
|
|
def _info(self): |
|
return datasets.DatasetInfo( |
|
description=_DESCRIPTION, |
|
features=datasets.Features( |
|
{ |
|
"year": datasets.Value("int64"), |
|
"city": datasets.Value("string"), |
|
"crime_major_category": datasets.Value("string"), |
|
"crime_detail": datasets.Value("string"), |
|
"latitude": datasets.Value("float64"), |
|
"longitude": datasets.Value("float64"), |
|
"occurance_time": datasets.Value("string"), |
|
"clear_status": datasets.Value("string"), |
|
"incident_address": datasets.Value("string"), |
|
"notes": datasets.Value("string"), |
|
}), |
|
citation=_CITATION, |
|
) |
|
|
|
|
|
|
|
def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]: |
|
|
|
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") |
|
|
|
chapel_hill_path = dl_manager.download_and_extract("https://drive.google.com/uc?export=download&id=19cZzyedCLUtQt9Ko4bcOixWIJHBn9CfI") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cary_df = self._preprocess_cary(cary_path) |
|
|
|
|
|
chapel_hill_df = self._preprocess_chapel_hill(chapel_hill_path) |
|
|
|
|
|
|
|
combined_df = pd.concat([cary_df, chapel_hill_df], ignore_index=True) |
|
|
|
|
|
combined_file_path = os.path.join(dl_manager.download_dir, "combined_dataset.csv") |
|
combined_df.to_csv(combined_file_path, index=False) |
|
|
|
return [ |
|
datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": combined_file_path}) |
|
] |
|
|
|
|
|
def _preprocess_chapel_hill(self, file_path): |
|
|
|
Chapel = pd.read_csv(file_path, low_memory=False) |
|
|
|
|
|
replace_values = {'<Null>': None, 'NONE': None} |
|
Chapel['Weapon_Description'] = Chapel['Weapon_Description'].replace(replace_values) |
|
|
|
|
|
category_mapping = { |
|
'Theft': ['THEFT/LARCENY', 'LARCENY FROM AU', 'LARCENY FROM PE', 'LARCENY OF OTHE', 'LARCENY FROM BU', 'LARCENY OF BIKE', 'LARCENY FROM RE', 'LARCENY OF AUTO'], |
|
'Assault': ['ASSAULT/SEXUAL', 'ASSAULT', 'STAB GUNSHOT PE', 'ACTIVE ASSAILAN'], |
|
'Burglary': ['BURGLARY', 'BURGLARY ATTEMP', 'STRUCTURE COLLAPSE', 'ROBBERY/CARJACK'], |
|
'Drugs': ['DRUGS'], |
|
'Traffic Violations': ['TRAFFIC STOP', 'TRAFFIC/TRANSPO', 'TRAFFIC VIOLATI', 'MVC', 'MVC W INJURY', 'MVC W INJURY AB', 'MVC W INJURY DE', 'MVC ENTRAPMENT'], |
|
'Disorderly Conduct': ['DISTURBANCE/NUI', 'DOMESTIC DISTUR', 'DISPUTE', 'DISTURBANCE', 'LOST PROPERTY', 'TRESPASSING/UNW', 'REFUSAL TO LEAV', 'SUSPICIOUS COND', 'STRUCTURE FIRE'], |
|
'Fraud': ['FRAUD OR DECEPT'], |
|
'Sexual Offenses': ['SEXUAL OFFENSE'], |
|
'Homicide': ['SUICIDE ATTEMPT', 'ABUSE/ABANDOMEN', 'DECEASED PERSON'], |
|
'Weapons Violations': ['WEAPON/FIREARMS'], |
|
'Animal-related Offenses': ['ANIMAL BITE', 'ANIMAL', 'ANIMAL CALL'], |
|
'Missing Person': ['MISSING PERSON'], |
|
'Public Service': ['PUBLIC SERVICE', 'PUBLICE SERVICE'], |
|
'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'] |
|
} |
|
|
|
def categorize_crime(crime): |
|
for category, crimes in category_mapping.items(): |
|
if crime in crimes: |
|
return category |
|
return 'Miscellaneous' |
|
|
|
|
|
Chapel_new = pd.DataFrame({ |
|
"year": pd.to_datetime(Chapel['Date_of_Occurrence']).dt.year, |
|
"city": "Chapel Hill", |
|
"crime_major_category": Chapel['Reported_As'].apply(categorize_crime), |
|
"crime_detail": Chapel['Offense'].str.title(), |
|
"latitude": Chapel['X'].round(5).fillna(0), |
|
"longitude": Chapel['Y'].round(5).fillna(0), |
|
"occurance_time": pd.to_datetime(Chapel['Date_of_Occurrence'].str.replace(r'\+\d{2}$', '', regex=True)).dt.strftime('%Y/%m/%d %H:%M:%S'), |
|
"clear_status": None, |
|
"incident_address": Chapel['Street'].str.replace("@", " "), |
|
"notes": Chapel['Weapon_Description'].apply(lambda x: f"Weapon: {x}" if pd.notnull(x) else "Weapon: None").str.title() |
|
}).fillna("No Data") |
|
|
|
|
|
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 |
|
|
|
|
|
Chapel_new = Chapel_new.loc[(Chapel_new['latitude'].between(30, 40)) & (Chapel_new['longitude'].between(-80, -70))] |
|
|
|
|
|
Chapel_new = Chapel_new[Chapel_new['year'] >= 2015] |
|
|
|
return Chapel_new |
|
|
|
def _preprocess_cary(self, file_path): |
|
|
|
df = pd.read_csv(file_path, low_memory=False).dropna(subset=['Year']) |
|
|
|
|
|
def categorize_crime(crime): |
|
crime_mapping = { |
|
'Theft': ['BURGLARY', 'MOTOR VEHICLE THEFT', 'LARCENY'], |
|
'Arson': ['ARSON'], |
|
'Assault': ['AGGRAVATED ASSAULT'], |
|
'Homicide': ['MURDER'], |
|
'Robbery': ['ROBBERY'] |
|
} |
|
for category, crimes in crime_mapping.items(): |
|
if crime in crimes: |
|
return category |
|
return 'Miscellaneous' |
|
|
|
|
|
processed_df = pd.DataFrame({ |
|
"year": df["Year"].astype(int), |
|
"city": "Cary", |
|
"crime_major_category": df['Crime Category'].apply(categorize_crime).str.title(), |
|
"crime_detail": df['Crime Type'].str.title(), |
|
"latitude": df['Lat'].fillna(0).round(5).fillna(0), |
|
"longitude": df['Lon'].fillna(0).round(5).fillna(0), |
|
"occurance_time": pd.to_datetime(df['Begin Date Of Occurrence'] + ' ' + df['Begin Time Of Occurrence']).dt.strftime('%Y/%m/%d %H:%M:%S'), |
|
"clear_status": None, |
|
"incident_address": df['Geo Code'], |
|
"notes": 'District: '+ df['District'].str.title() + ' Violent Property: ' + df['Violent Property'].str.title() |
|
}).fillna("No Data") |
|
|
|
|
|
processed_df = processed_df[processed_df['year'] >= 2015] |
|
|
|
return processed_df |
|
|
|
|
|
def _generate_examples(self, filepath): |
|
|
|
df = pd.read_csv(filepath) |
|
|
|
for i, row in df.iterrows(): |
|
yield i, { |
|
"year": int(row["year"]), |
|
"city": row["city"], |
|
"crime_major_category": row["crime_major_category"], |
|
"crime_detail": row["crime_detail"], |
|
"latitude": float(row["latitude"]), |
|
"longitude": float(row["longitude"]), |
|
"occurance_time": row["occurance_time"], |
|
"clear_status": row["clear_status"], |
|
"incident_address": row["incident_address"], |
|
"notes": row["notes"], |
|
} |
|
|