Пример #1
0
def locinfo():
    """ Return info about a location as JSON """
    resp = dict(found=False)

    name = request.args.get("name")
    kind = request.args.get("kind")

    if name and kind and kind in LOCATION_TAXONOMY:
        loc = location_info(name, kind)
        if loc:
            resp["found"] = True
            resp["country"] = loc.get("country")
            resp["continent"] = loc.get("continent")
            resp["desc"] = location_description(loc)
            lat, lon = loc.get("latitude"), loc.get("longitude")
            if lat and lon:
                z = ZOOM_FOR_LOC_KIND.get(loc.get("kind"))
                # We want a slightly lower zoom level for foreign placenames
                if resp["country"] != ICELAND_ISOCODE and kind == "placename":
                    z -= 1
                resp["map"] = STATIC_MAP_URL.format(lat, lon, z)
            elif name in ICE_REGIONS:
                resp["map"] = "/static/img/maps/regions/" + name + ".png"
            elif kind == "continent" and resp["continent"] and resp[
                    "continent"] in ISO_TO_CONTINENT:
                resp["map"] = ("/static/img/maps/continents/" +
                               resp["continent"] + ".png")

    return better_jsonify(**resp)
Пример #2
0
def _which_continent_query(subject, q):
    """ Generate answer to question concerning the continent on which
        a given country name or placename is located. """

    # Get country code
    cc = isocode_for_country_name(subject)
    is_city = False
    if not cc:
        # OK, the subject is not a country
        # Let's see if it's a city
        info = location_info(subject, "placename")
        if not info:
            return False  # We don't know where it is
        cc = info.get("country")
        is_city = True

    contcode = continent_for_country(cc)
    continent = ISO_TO_CONTINENT[contcode]
    continent_dat = nom2dat(continent)

    # Format answer
    answer = continent_dat
    response = dict(answer=answer)
    if is_city:
        voice = "Borgin {0} er {1}, sem er land í {2}".format(
            subject, country_desc(cc), continent_dat)
    else:
        voice = "Landið {0} er í {1}".format(subject, continent_dat)

    q.set_answer(response, answer, voice)
    q.set_key(subject)
    q.set_context(dict(subject=continent))

    return True
Пример #3
0
def locinfo():
    """ Return info about a location as JSON """
    resp = dict(found=False)

    name = request.args.get("name")
    kind = request.args.get("kind")

    if name and kind and kind in LOCATION_TAXONOMY:
        loc = location_info(name, kind)
        if loc:
            resp["found"] = True
            resp["country"] = loc.get("country")
            resp["continent"] = loc.get("continent")
            resp["desc"] = location_description(loc)
            lat, lon = loc.get("latitude"), loc.get("longitude")
            if lat and lon:
                z = ZOOM_FOR_LOC_KIND.get(loc.get("kind"))
                # We want a slightly lower zoom level for foreign placenames
                if resp["country"] != ICELAND_ISOCODE and kind == "placename":
                    z -= 1
                resp["map"] = STATIC_MAP_URL.format(lat, lon, z)
            elif name in ICE_REGIONS:
                resp["map"] = "/static/img/maps/regions/" + name + ".png"
            elif resp["continent"] and name in ISO_TO_CONTINENT.values():
                resp["map"] = "/static/img/maps/continents/" + resp["continent"] + ".png"

    return better_jsonify(**resp)
Пример #4
0
def article_end(state):
    """ Called at the end of article processing """

    locs = state.get("locations")
    if not locs:
        return

    url = state["url"]
    session = state["session"]

    # Find all placenames mentioned in article
    # We can use them to disambiguate addresses and street names
    # TODO: Perhaps do this in a more fine-grained manner, at a
    # sentence or paragraph level.
    placenames = [p.name for p in locs if p.kind == "placename"]

    # Get info about each location and save to database
    for name, kind in locs:
        loc = location_info(name=name, kind=kind, placename_hints=placenames)

        loc["article_url"] = url
        loc["timestamp"] = datetime.utcnow()

        print("Location '{0}' is a {1}".format(loc["name"], loc["kind"]))

        locmodel = Location(**loc)
        session.add(locmodel)
Пример #5
0
def article_end(state):
    """ Called at the end of article processing """

    locs = state.get("locations")
    if not locs:
        return

    url = state["url"]
    session = state["session"]

    # Find all placenames mentioned in article
    # We can use them to disambiguate addresses and street names
    # TODO: Perhaps do this in a more fine-grained manner, at a
    # sentence or paragraph level.
    placenames = [p.name for p in locs if p.kind == "placename"]

    # Get info about each location and save to database
    for name, kind in locs:
        loc = location_info(name=name, kind=kind, placename_hints=placenames)

        loc["article_url"] = url
        loc["timestamp"] = datetime.utcnow()

        print("Location '{0}' is a {1}".format(loc["name"], loc["kind"]))

        locmodel = Location(**loc)
        session.add(locmodel)
Пример #6
0
def _which_country_query(subject: str, q: Query):
    """ Generate answer to question concerning the country in which
        a given placename is located. """
    info = location_info(subject, "placename")
    if not info:
        return False

    cc = info.get("country")
    if not cc:
        return False

    # Get country name w. preposition ("í Þýskalandi")
    desc = country_desc(cc)

    # Format answer
    answer = cap_first(desc)
    response = dict(answer=answer)
    voice = "{0} er {1}".format(subject, desc)

    q.set_answer(response, answer, voice)
    q.set_key(subject)
    cname = country_name_for_isocode(cc)
    if cname is not None:
        q.set_context(dict(subject=cname))

    return True
Пример #7
0
def _which_continent_query(subject: str, q: Query):
    """ Generate answer to question concerning the continent on which
        a given country name or placename is located. """

    # Get country code
    cc = isocode_for_country_name(subject)
    is_placename = False
    if not cc:
        # OK, the subject is not a country
        # Let's see if it's a placename
        info = location_info(subject, "placename")
        if not info:
            return False  # We don't know where it is
        cc = info.get("country")
        is_placename = True

    if not cc:
        return False

    contcode = continent_for_country(cc)
    if contcode is None:
        continent = "óþekkt heimsálfa"
        continent_dat = "óþekktri heimsálfu"
    else:
        continent = ISO_TO_CONTINENT[contcode]
        continent_dat = nom2dat(continent)

    # Format answer
    answer = continent_dat
    response = dict(answer=answer)
    if is_placename:
        cd = country_desc(cc)
        voice = "Staðurinn {0} er {1}, sem er land í {2}".format(
            subject, cd, continent_dat)
        answer = "{0}, {1}".format(cap_first(cd), continent_dat)
    else:
        voice = "Landið {0} er í {1}".format(subject, continent_dat)

    q.set_answer(response, answer, voice)
    q.set_key(subject)
    q.set_context(dict(subject=continent))

    return True
Пример #8
0
def locinfo():
    """ Return info about a location as JSON. """
    resp = dict(found=False)

    name = request.args.get("name")
    kind = request.args.get("kind")

    # Bail if we don't have the args
    if not (name and kind and kind in LOCATION_TAXONOMY):
        return better_jsonify(**resp)

    # Try to find some info on loc
    loc = location_info(name, kind)
    if not loc:
        return better_jsonify(**resp)

    # We've found it
    resp["found"] = True
    resp["country"] = loc.get("country")
    resp["continent"] = loc.get("continent")
    resp["desc"] = location_description(loc)
    lat, lon = loc.get("latitude"), loc.get("longitude")
    # We have coords
    if lat and lon:
        z = ZOOM_FOR_LOC_KIND.get(loc.get("kind"))
        # We want a slightly lower zoom level for foreign placenames
        if resp["country"] != ICELAND_ISOCODE and kind == "placename":
            z -= 1
        resp["map"] = STATIC_MAP_URL.format(lat, lon, z)
    # Icelandic region
    elif name in ICE_REGIONS:
        resp["map"] = "/static/img/maps/regions/" + name + ".png"
    # Continent
    elif resp["country"] is None and resp["continent"] in ISO_TO_CONTINENT:
        resp["map"] = "/static/img/maps/continents/" + resp[
            "continent"] + ".png"

    return better_jsonify(**resp)
Пример #9
0
def _which_country_query(subject, q):
    """ Generate answer to question concerning the country in which
        a given placename is located. """
    info = location_info(subject, "placename")
    if not info:
        return False

    cc = info.get("country")
    if not cc:
        return False

    # Get country name w. preposition ("í Þýskalandi")
    desc = country_desc(cc)

    # Format answer
    answer = desc[0].upper() + desc[1:]
    response = dict(answer=answer)
    voice = "{0} er {1}".format(subject, desc)

    q.set_answer(response, answer, voice)
    q.set_key(subject)

    return True
Пример #10
0
def test_geo():
    """ Test geography and location-related functions in geo.py """
    from geo import (
        icelandic_city_name,
        continent_for_country,
        coords_for_country,
        coords_for_street_name,
        country_name_for_isocode,
        isocode_for_country_name,
        icelandic_addr_info,
        lookup_city_info,
        parse_address_string,
        iceprep_for_street,
        iceprep_for_placename,
        iceprep_for_country,
        iceprep_for_cc,
        capitalize_placename,
        distance,
        in_iceland,
        code_for_us_state,
        coords_for_us_state_code,
        location_info,
    )

    assert icelandic_city_name("London") == "Lundúnir"
    assert icelandic_city_name("Rome") == "Róm"

    assert continent_for_country("IS") == "EU"
    assert continent_for_country("no") == "EU"
    assert continent_for_country("MX") == "NA"

    assert coords_for_country("DE") is not None
    assert coords_for_country("it") is not None

    assert coords_for_street_name("Austurstræti") is not None
    assert coords_for_street_name("Háaleitisbraut") is not None

    assert country_name_for_isocode("DE", lang="is") == "Þýskaland"
    assert country_name_for_isocode("DE") == "Þýskaland"

    assert isocode_for_country_name("Danmörk", lang="is") == "DK"
    assert isocode_for_country_name("Danmörk", lang="IS") == "DK"
    assert isocode_for_country_name("Noregur") == "NO"

    addr_info = icelandic_addr_info("Fiskislóð 31")
    assert addr_info and addr_info["stadur_tgf"] == "Reykjavík"

    # Test city info lookup
    city_info = lookup_city_info("Kænugarður")
    assert city_info and len(
        city_info) == 1 and city_info[0]["country"] == "UA"

    city_info = lookup_city_info("Kaupmannahöfn")
    assert city_info and len(
        city_info) == 1 and city_info[0]["country"] == "DK"

    city_info = lookup_city_info("Pjongjang")
    assert city_info and len(
        city_info) == 1 and city_info[0]["country"] == "KP"

    city_info = lookup_city_info("Pyongyang")
    assert city_info and len(
        city_info) == 1 and city_info[0]["country"] == "KP"

    # Test address string parsing
    assert parse_address_string("   Fiskislóð  31") == {
        "street": "Fiskislóð",
        "number": 31,
        "letter": "",
    }
    assert parse_address_string("Öldugata 19c ") == {
        "street": "Öldugata",
        "number": 19,
        "letter": "c",
    }
    assert parse_address_string("    Dúfnahólar   10   ") == {
        "street": "Dúfnahólar",
        "number": 10,
        "letter": "",
    }

    # Test prepositions for street names
    assert iceprep_for_street("Öldugata") == "á"
    assert iceprep_for_street("Fiskislóð") == "á"
    assert iceprep_for_street("Austurstræti") == "í"
    assert iceprep_for_street("Hamrahlíð") == "í"

    # Test prepositions for placenames
    assert iceprep_for_placename("Dalvík") == "á"
    assert iceprep_for_placename("Akureyri") == "á"
    assert iceprep_for_placename("Ísafjörður") == "á"
    assert iceprep_for_placename("Reykjavík") == "í"
    assert iceprep_for_placename("Hafnarfjörður") == "í"
    assert iceprep_for_placename("London") == "í"
    assert iceprep_for_placename("Dyflinni") == "í"

    # Test prepositions for countries
    assert iceprep_for_country("Ítalía") == "á"
    assert iceprep_for_country("Ísland") == "á"
    assert iceprep_for_country("Þýskaland") == "í"
    assert iceprep_for_country("Japan") == "í"
    assert iceprep_for_country("spánn") == "á"

    # Test prepositions for countries, queried by CC
    assert iceprep_for_cc("IS") == "á"
    assert iceprep_for_cc("US") == "í"
    assert iceprep_for_cc("ES") == "á"
    assert iceprep_for_cc("es") == "á"

    # Test placename capitalization
    assert capitalize_placename("ríó de janeiro") == "Ríó de Janeiro"
    assert capitalize_placename("vík í mýrdal") == "Vík í Mýrdal"
    assert capitalize_placename("Vík í mýrdal") == "Vík í Mýrdal"
    assert capitalize_placename("frankfúrt am main") == "Frankfúrt am Main"
    assert capitalize_placename("mið-afríkulýðveldið") == "Mið-Afríkulýðveldið"
    assert capitalize_placename("Norður-kórea") == "Norður-Kórea"
    assert capitalize_placename("norður-Kórea") == "Norður-Kórea"
    assert capitalize_placename(
        "bosnía og hersegóvína") == "Bosnía og Hersegóvína"
    assert capitalize_placename("Norður-Makedónía") == "Norður-Makedónía"

    # Distance
    assert int(distance((64.141439, -21.943944),
                        (65.688131, -18.102528))) == 249
    assert in_iceland((66.462205, -15.968417))
    assert not in_iceland((62.010846, -6.776709))
    assert not in_iceland((62.031342, -18.539553))

    # US States
    assert code_for_us_state("Flórída") == "FL"
    assert code_for_us_state("Norður-Karólína") == "NC"
    assert code_for_us_state("Kalifornía") == "CA"
    assert coords_for_us_state_code("CA") == [36.778261, -119.417932]

    # Generic location info lookup functions
    assert "country" in location_info("Reykjavík", "placename")
    assert "continent" in location_info("Minsk", "placename")
    assert location_info("Japan", "country")["continent"] == "AS"
    assert location_info("Danmörk", "country")["continent"] == "EU"
    assert location_info("Mexíkó", "country")["continent"] == "NA"
    assert location_info("ísafjörður", "placename")["continent"] == "EU"
    assert location_info("Meðalfellsvatn", "placename")["country"] == "IS"
    assert location_info("Georgía", "country")["country"] != "US"
    assert location_info("Virginía", "placename")["country"] == "US"
    assert location_info("Norður-Dakóta", "country")["country"] == "US"
    assert location_info("Kænugarður", "placename")["continent"] == "EU"
    assert location_info("Fiskislóð 31", "address")["country"] == "IS"