def test_geo(): """ Test geography and location-related functions in geo.py """ assert continent_for_country("IS") == "EU" assert coords_for_country("DE") != None assert coords_for_street_name("Austurstræti") != None assert country_name_for_isocode("DE", lang="is") == "Þýskaland" assert isocode_for_country_name("Danmörk", lang="is") == "DK" addr_info = icelandic_addr_info("Fiskislóð 31") assert addr_info and addr_info["stadur_tgf"] == "Reykjavík" city_info = lookup_city_info("Kaupmannahöfn") assert city_info and len(city_info) == 1 and city_info[0]["country"] == "DK" assert parse_address_string("Fiskislóð 31") == { "street": "Fiskislóð", "number": 31, "letter": None, } assert parse_address_string("Öldugata 19c") == { "street": "Öldugata", "number": 19, "letter": "c", }
def handle_plain_text(q): """ Handle a plain text query, contained in the q parameter which is an instance of the query.Query class. Returns True if the query was handled, and in that case the appropriate properties on the Query instance have been set, such as the answer and the query type (qtype). If the query is not recognized, returns False. """ ql = q.query_lower.rstrip("?") # Timezone being asked about tz = None # Whether user asked for the time in a particular location specific_desc = None if ql in _TIME_QUERIES: # Use location to determine time zone tz = timezone4loc(q.location, fallback="IS") elif ql.startswith("hvað er klukkan á ") or ql.startswith( "hvað er klukkan í "): # Query about the time in a particular location, i.e. country or city loc = ql[18:] # Cut away question prefix, leaving only placename # Capitalize each word in country/city name loc = capitalize_placename(loc) # Look up nominative # This only works for single-word city/country names found # in BÍN and could be improved (e.g. fails for "Nýju Jórvík") bin_res = BIN_Db().lookup_nominative(loc) words = [m.stofn for m in bin_res] words.append( loc) # In case it's not in BÍN (e.g. "New York", "San José") # Check if any word is a recognised country or city name for w in words: cc = isocode_for_country_name(w) if cc and cc in country_timezones: # Look up country timezone # Use the first timezone although some countries have more than one # The timezone list returned by pytz is ordered by "dominance" tz = country_timezones[cc][0] else: # It's not a country name, look up in city database info = lookup_city_info(w) if info: top = info[0] location = (top.get("lat_wgs84"), top.get("long_wgs84")) tz = timezone4loc(location) if tz: # We have a timezone break # "Klukkan í Lundúnum er" - Used for voice answer specific_desc = "{0} er".format(ql[8:]) # Beautify query by capitalizing the country/city name q.set_beautified_query("{0}{1}?".format(q.beautified_query[:18], loc)) # We have a timezone. Return formatted answer. if tz: now = datetime.now(timezone(tz)) desc = specific_desc or "Klukkan er" # Create displayable answer answer = "{0:02}:{1:02}".format(now.hour, now.minute) # A detailed response object is usually a list or a dict response = dict(answer=answer) # A voice answer is a plain string that will be # passed as-is to a voice synthesizer voice = "{0} {1}:{2:02}.".format(desc, now.hour, now.minute) q.set_qtype(_TIME_QTYPE) q.set_key(tz) # Query key is the timezone q.set_answer(response, answer, voice) return True return False
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"
def handle_plain_text(q: Query) -> bool: """Handle a plain text query, contained in the q parameter which is an instance of the query.Query class. Returns True if the query was handled, and in that case the appropriate properties on the Query instance have been set, such as the answer and the query type (qtype). If the query is not recognized, returns False.""" ql = q.query_lower.rstrip("?") # Timezone being asked about tz = None # Whether user asked for the time in a particular location specific_desc = None if ql in _TIME_QUERIES: # Use location to determine time zone tz = timezone4loc(q.location, fallback="IS") else: locq = [x for x in _TIME_IN_LOC_QUERIES if ql.startswith(x.lower())] if not locq: return False # Not matching any time queries # This is a query about the time in a particular location, i.e. country or city # Cut away question prefix, leaving only loc name loc = ql[len(locq[0]):].strip() if not loc: return False # No location string # Intelligently capitalize country/city/location name loc = capitalize_placename(loc) # Look up nominative loc_nom = NounPhrase(loc).nominative or loc prep = "í" # Check if loc is a recognised country or city name cc = isocode_for_country_name(loc_nom) if cc and cc in country_timezones: # Look up country timezone # Use the first timezone although some countries have more than one # The timezone list returned by pytz is ordered by "dominance" tz = country_timezones[cc][0] prep = iceprep_for_cc(cc) else: # It's not a country name, look up in city database info = lookup_city_info(loc_nom) if info: top = info[0] location = ( cast(float, top.get("lat_wgs84")), cast(float, top.get("long_wgs84")), ) tz = timezone4loc(location) prep = iceprep_for_placename(loc_nom) if tz: # "Klukkan í Lundúnum er" - Used for voice answer dat = NounPhrase(loc_nom).dative or loc specific_desc = "Klukkan {0} {1} er".format(prep, dat) else: # Unable to find the specified location q.set_qtype(_TIME_QTYPE) q.set_key(loc) q.set_answer( *gen_answer("Ég gat ekki flett upp staðsetningunni {0}".format( icequote(loc)))) return True # We have a timezone. Return formatted answer. if tz: now = datetime.now(timezone(tz)) desc = specific_desc or "Klukkan er" # Create displayable answer answer = "{0:02}:{1:02}".format(now.hour, now.minute) # A detailed response object is usually a list or a dict response = dict(answer=answer) # A voice answer is a plain string that will be # passed as-is to a voice synthesizer voice = "{0} {1}:{2:02}.".format(desc, now.hour, now.minute) q.set_qtype(_TIME_QTYPE) q.set_key(tz) # Query key is the timezone q.set_answer(response, answer, voice) return True return False