示例#1
0
def main():

    api = PoliceAPI()
    # Force
    print(api.get_forces())  # All forces
    force = Force(api, id='leicestershire')  # Leicestershire Police
    print(force.description)  # description of Leicestershire Police
    # all the Neighbourhood Policing Teams in this Leicestershire Police area
    print(force.neighbourhoods)
    print(force.telephone)  # The force’s main switchboard number
    # Neighbourhood
    neighbourhood = Neighbourhood(api, force=force,
                                  id='NW02')  # neighbourhood with NW02 id
    print(neighbourhood.name)  # Name of neighbourhood (Abbey)
    print(neighbourhood.officers)  # All Abbey officers
    print(neighbourhood.events)  # Events in Abbey
    # Crimes
    anti_social_crimes = PoliceAPI().get_crimes_area(
        neighbourhood.boundary, category='anti-social-behaviour')
    print(anti_social_crimes)  # All crimes in Abbey with anti-social behaviour
    # All crimes in Abbey in October 2008
    crimes = api.get_crimes_area(neighbourhood.boundary, date='2018-10')
    crime = crimes[30]
    print(crime.location.name)  # location of crime
    print(crime.category)  # category of crime
    print(crime.outcomes)  # crime outcomes
def create_crimes(f_name, neighbourhoods, Ward_array):
    """
    Adds crimes to Ward objects.
    (str,Array,Array) -> None
    """
    api = PoliceAPI()
    i = 0
    csv_arr = Array()
    for neighbourhood in neighbourhoods:
        try:
            wrd = Ward_array.get_element(Ward(neighbourhood.item.name))
            mounthes = [str(i) for i in range(1, 13)]
            for m in mounthes:
                crimes = api.get_crimes_area(neighbourhood.item.boundary,
                                             date='2018-' + m)
                wrd.add_number_crimes(len(crimes))
            element = {
                'Ward_name': wrd.get_name(),
                'Price': wrd.get_price(),
                'Schools_number': wrd.get_number_of_schools(),
                'Crimes_number': wrd.get_number_of_crimes()
            }
            wrte_csv(f_name, element, i)
            i += 1
            print(neighbourhood.item.name, end=' ')
            print(i, end=' out of ')
            print(len(neighbourhoods))
        except:
            pass
def filter_crimes(Ward_array):
    """
    Creates an Array of Neighbourhood objects.
    (Array) -> Array
    """
    api = PoliceAPI()
    neighbourhoods = Array()
    for force in api.get_forces():
        for neighbourhood in force.neighbourhoods:
            if Ward(neighbourhood.name) in Ward_array:
                neighbourhoods.add(neighbourhood)
    return neighbourhoods
def list_recent_crime_categories_and_resolutions_in_order(postcode):
    api = PoliceAPI()
    hood = api.locate_neighbourhood(*get_lat_long_of_postcode(postcode))

    recent_crimes = api.get_crimes_area(hood.boundary)

    all_outcomes_of_recent_crimes = []
    for crime in recent_crimes:
        if str(crime.outcome_status) not in all_outcomes_of_recent_crimes:
            all_outcomes_of_recent_crimes.append(str(crime.outcome_status))

    recent_crimes_by_category = {}

    # TODO: it could be richer to have non exclusive categories (tagging vs one category)

    # Build up categories
    for crime in recent_crimes:
        recent_crimes_by_category[crime.category.name] = []

    for crime in recent_crimes:
        if is_ongoing(crime) is False:
            recent_crimes_by_category[crime.category.name].append(crime)

    def get_outcome_breakdown(crime_category_string):
        crime_category = recent_crimes_by_category[crime_category_string]

        crime_outcomes = {}  # Build category specific crime outcomes
        for crime in crime_category:
            status = str(crime.outcome_status)
            crime_outcomes[status] = []
        for crime in crime_category:
            status = str(crime.outcome_status)
            crime_outcomes[status].append(crime)

        counted_crime_outcomes = {}
        for category in crime_outcomes:
            counted_crime_outcomes[category] = len(crime_outcomes[category])

        counted_crime_outcomes_ordered = get_ordered_dict_sorted_by_number_of_definitions(counted_crime_outcomes)
        return counted_crime_outcomes_ordered

    for category in recent_crimes_by_category.keys():
        print(category)
        print(get_outcome_breakdown(category))
        print()
示例#5
0
def main(t_current):
    # Call the police API
    api = PoliceAPI()

    # Define tables
    crime_categories = pd.DataFrame({'id': [], 'description': []})
    outcome_categories = pd.DataFrame({'id': [], 'description': []})
    streets = pd.DataFrame({'id': [], 'name': []})
    crimes = pd.DataFrame({
        'persistent_id': [],
        'category': [],
        'street': [],
        'city': [],
        'latitude': [],
        'longitude': [],
        'date': [],
        'context': []
    })
    outcomes = pd.DataFrame({
        'crime': [],
        'category': [],
        'date': [],
        'person_id': []
    })

    # Transform dates into pandas Series for better manipulation
    dates = pd.Series(api.get_dates())

    # Get Forces
    forces = api.get_forces()
    # Get neighbourhoods
    neighbourhoods = [f.neighbourhoods for f in forces]
    nb_flat = [n for sublist in neighbourhoods for n in sublist]
    s_nb_flat = pd.Series(nb_flat).unique()

    first_job(api, dates, t_current)

    t_last_update = api.get_latest_date()
    second_job(api, dates, t_last_update, t_current)

    last_job(api, t_current)
示例#6
0
def latlng():
    lat = request.form.get('lat')
    lng = request.form.get('lng')
    api = PoliceAPI()
    n = api.locate_neighbourhood(lat, lng)
    ncrimes = len(api.get_crimes_area(n.boundary, date='2020-01'))
    population = n.population
    highRisk = False

    if population > 0:
        cpp = ncrimes / population
        noMonths = 1 / cpp
        noMonths = round(noMonths)
        Mth = str(noMonths)
    else:
        minLat = min(latlong[0] for latlong in n.boundary)
        maxLat = max(latlong[0] for latlong in n.boundary)
        minLong = min(latlong[1] for latlong in n.boundary)
        maxLong = max(latlong[1] for latlong in n.boundary)
        totalLat = maxLat - minLat
        totalLong = maxLong - minLong
        latMeters = totalLat * 111.32
        longCos = math.cos(totalLong)
        longMeters = (longCos / 360) * 40075
        totalArea = latMeters * longMeters
        ukArea = 242495
        numberPeople = 66440000
        ppa = numberPeople / ukArea
        ppn = totalArea * ppa
        ppn = round(ppn)
        cpp = ncrimes / ppn
        noMonths = 1 / cpp
        noMonths = round(noMonths)
        Mth = str(noMonths)
        population = ppn
    if cpp > 0.02:
        highRisk = True
    #as = Antisocial behaviour
    #t = theft
    #b = burglary
    #cda = criminal damage and arson
    #d = drugs
    #pw = possession of weapons
    #po = public order
    #r = robbery
    #s = shoplifting
    #vc = vehicle crime
    #vso = violent and sexual offences
    #o = other crime
    asTally = 0
    tTally = 0
    bTally = 0
    cdaTally = 0
    dTally = 0
    pwTally = 0
    poTally = 0
    rTally = 0
    sTally = 0
    vcTally = 0
    vsoTally = 0
    oTally = 0
    crimes = api.get_crimes_area(n.boundary, date='2020-01')
    for x in crimes:
        type = str(x.category)
        if type == '<CrimeCategory> Anti-social behaviour':
            asTally += 1
        elif type == '<CrimeCategory> Bicycle theft' or type == '<CrimeCategory> Other theft' or type == '<CrimeCategory> Theft from the person':
            tTally += 1
        elif type == '<CrimeCategory> Burglary':
            bTally += 1
        elif type == '<CrimeCategory> Criminal damage and arson':
            cdaTally += 1
        elif type == '<CrimeCategory> Drugs':
            dTally += 1
        elif type == '<CrimeCategory> Possession of weapons':
            pwTally += 1
        elif type == '<CrimeCategory> Public order':
            poTally += 1
        elif type == '<CrimeCategory> Robbery':
            rTally += 1
        elif type == '<CrimeCategory> Shoplifting':
            sTally += 1
        elif type == '<CrimeCategory> Vehicle crime':
            vcTally += 1
        elif type == '<CrimeCategory> Violence and sexual offences':
            vsoTally += 1
        elif type == '<CrimeCategory> Other crime':
            oTally += 1
        array = [
            asTally, tTally, bTally, cdaTally, dTally, pwTally, poTally,
            rTally, sTally, vcTally, vsoTally, oTally
        ]
        array.sort(reverse=True)
        mostCrimeNumber = int(array[0])

    if array[0] == bTally:
        mostCrime = 'Burglary'
    elif array[0] == cdaTally:
        mostCrime = 'Criminal damage and arson'
    elif array[0] == dTally:
        mostCrime = 'Drugs'
    elif array[0] == pwTally:
        mostCrime = 'Possession of weapons'
    elif array[0] == poTally:
        mostCrime = 'Public order'
    elif array[0] == rTally:
        mostCrime = 'Robbery'
    elif array[0] == sTally:
        mostCrime = 'Shoplifting'
    elif array[0] == vcTally:
        mostCrime = 'Vehicle crime'
    elif array[0] == vsoTally:
        mostCrime = 'Violence and sexual offences'
    elif array[0] == oTally:
        mostCrime = 'Other crime'
    elif array[0] == asTally:
        mostCrime = 'Antisocial Behaviour'

    #these are the percentages that the clock needs:
    asTotal = (asTally / ncrimes) * 100
    tTotal = (tTally / ncrimes) * 100
    bTotal = (bTally / ncrimes) * 100
    cdaTotal = (cdaTally / ncrimes) * 100
    dTotal = (dTally / ncrimes) * 100
    pwTotal = (pwTally / ncrimes) * 100
    poTotal = (poTally / ncrimes) * 100
    rTotal = (rTally / ncrimes) * 100
    sTotal = (sTally / ncrimes) * 100
    vcTotal = (vcTally / ncrimes) * 100
    vsoTotal = (vsoTally / ncrimes) * 100
    oTotal = (oTally / ncrimes) * 100

    return render_template(
        'clock.html',
        lng=lng,
        lat=lat,
        ncrimes=ncrimes,
        n=n,
        mostCrime=mostCrime,
        mostCrimeNumber=mostCrimeNumber,
        Mth=Mth,
        highRisk=highRisk,
        population=population,
        asTotal=asTotal,
        tTotal=tTotal,
        bTotal=bTotal,
        cdaTotal=cdaTotal,
        dTotal=dTotal,
        pwTotal=pwTotal,
        poTotal=poTotal,
        rTotal=rTotal,
        sTotal=sTotal,
        vcTotal=vcTotal,
        vsoTotal=vsoTotal,
        oTotal=oTotal,
    )
示例#7
0
#!/usr/bin/env python2
import csv
import json
from police_api import PoliceAPI
from police_api.forces import Force

api = PoliceAPI()
forces = api.get_forces()

# creating new csv file with structure.
with open("forces.csv", "w") as file:
    writer = csv.writer(file)
    writer.writerow([
        "force id",
        "facebook page",
    ])

for dep in forces:
    # opening forces.csv in append mode.
    f = open("forces.csv", "a")
    force = Force(api, id=dep.id)
    # getting engagements methods
    json_engagements = force.engagement_methods
    for data in json_engagements:
        # searching for those who has facebook type of engagement
        if data["type"] == "Facebook":
            force_facebook = data["url"]
            csv_data = [dep.id, force_facebook]
            # appending to csv file.
            with f:
                writer = csv.writer(f)
示例#8
0
"""
form = cgi.FieldStorage()
Userpc = form["command"].value
if command != "" :
     print "<p> Finding Data For Postcode" + Userpc + "</p>" 
pcr = pc.get(Userpc)
pcr2 = pcr["geo"]
UserLat = pcr2["lat"]
UserLong = pcr2["lng"]
location = g_m.search(location=Userpc)
#locate = location.first()
#print locate.city
print location
from police_api import PoliceAPI 
papi = PoliceAPI()
locate = papi.locate_neighbourhood(UserLat, UserLong) 
print "Police Data for" + Userpc
#print "<h2>" + locate + "</h2>"
print "<h2> Force </h2<"
print "<h2> Contact details </h2> "
print  
print "<h3>" + locate.force + "</h3>"
print "<h3>" + papi.get.crimes.area + "</h3>"
#OSM = OsmApi()
#print "       "
#print "       "
#print "OSM Data"
#print OSM.NodeGet(123)

示例#9
0
    'Burglary': 'Red',
    'Violence and sexual offences': 'Magenta',
    'Drugs': 'Blue',
    'Bicycle theft': 'Green',
    'Criminal damage and arson': 'light yellow',
    'Other theft': 'light green',
    'Possession of weapons': 'cyan',
    'Public order': 'white',
    'Shoplifting': 'grey',
    'Theft from the person': 'light orange',
    'Vehicle crime': 'brown',
    'Other crime': 'light blue',
    'Robbery': 'Yellow'
}

police = PoliceAPI()
# Get the date range of data
dt_range = police.get_dates()


def format_date_range(date_range):
    month_dict = {
        1: 'Jan',
        2: 'Feb',
        3: 'Mar',
        4: 'Apr',
        5: 'May',
        6: 'Jun',
        7: 'Jul',
        8: 'Aug',
        9: 'Sep',
def get_crime_counts(coord):
    api = PoliceAPI()
    crimes = api.get_crimes_point(*coord)
    catgories = pd.Series([c.category.id for c in crimes])
    counts = catgories.value_counts().to_dict()
    return counts
示例#11
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" Collect the infromation from the https://data.police.uk/docs/method/crime-street/ API
    Using https://github.com/rkhleics/police-api-client-python/
"""

from police_api import PoliceAPI

from matchingClosestPoint import closest
from scipy.stats import zscore
import numpy as np

api = PoliceAPI()
# forces = api.get_forces()


def get_closest_street_id(streets_location, closest_street):
    """
    """
    for k in streets_location:
        if float(streets_location[k]['lat']) == float(closest_street['lat']):
            if streets_location[k]['lon'] == closest_street['lon']:
                return k

def aggregate_crime_per_street(crime_location):
    """
    """
    crime_count = dict()
    streets_location = dict()
    for crime in crime_location: