def dist_answer_for_loc(matches, query): """ Generate response to distance query. """ locname = matches.group(1) loc_nf = _addr2nom(locname[0].upper() + locname[1:]) res = query_geocode_api_addr(loc_nf) # Verify sanity of API response if (not res or not "status" in res or res["status"] != "OK" or not res.get("results")): return None # Try to avoid answering bus queries here loc_lower = locname.lower() if any(s in loc_lower for s in ( "strætó", "stoppistöð", "strætisvagn", "biðstöð", "stoppustöð", "stræto", "strædo", )): return None # Extract location coordinates from API result topres = res["results"][0] coords = topres["geometry"]["location"] loc = (coords["lat"], coords["lng"]) # Calculate distance, round it intelligently and format num string km_dist = distance(query.location, loc) # Generate answer answer = distance_desc(km_dist, abbr=True) response = dict(answer=answer) loc_nf = loc_nf[0].upper() + loc_nf[1:] dist = distance_desc(km_dist, case="þf") voice = "{0} er {1} í burtu".format(loc_nf, dist) query.set_key(capitalize_placename(loc_nf)) # Beautify by capitalizing remote loc name uc = capitalize_placename(locname) bq = query.beautified_query.replace(locname, uc) query.set_beautified_query(bq) query.set_context(dict(subject=loc_nf)) return response, answer, voice
def test_query_utility_functions(): """ Tests for various utility functions used by query modules. """ from queries import ( natlang_seq, nom2dat, numbers_to_neutral, is_plural, sing_or_plur, country_desc, cap_first, time_period_desc, distance_desc, krona_desc, strip_trailing_zeros, iceformat_float, icequote, timezone4loc, # parse_num, ) assert natlang_seq(["Jón", "Gunna"]) == "Jón og Gunna" assert natlang_seq(["Jón", "Gunna", "Siggi"]) == "Jón, Gunna og Siggi" assert ( natlang_seq(["Jón", "Gunna", "Siggi"], oxford_comma=True) == "Jón, Gunna, og Siggi" ) assert nom2dat("hestur") == "hesti" assert nom2dat("Hvolsvöllur") == "Hvolsvelli" # assert parse_num("11") == 11 # assert parse_num("17,33") == 17.33 assert numbers_to_neutral("Öldugötu 4") == "Öldugötu fjögur" assert numbers_to_neutral("Fiskislóð 31") == "Fiskislóð þrjátíu og eitt" assert is_plural(22) assert is_plural(11) assert is_plural("76,3") assert is_plural(27.6) assert is_plural("19,11") assert not is_plural("276,1") assert not is_plural(22.1) assert not is_plural(22.41) assert sing_or_plur(21, "maður", "menn") == "21 maður" assert sing_or_plur(11, "köttur", "kettir") == "11 kettir" assert sing_or_plur(2.11, "króna", "krónur") == "2,11 krónur" assert sing_or_plur(172, "einstaklingur", "einstaklingar") == "172 einstaklingar" assert sing_or_plur(72.1, "gráða", "gráður") == "72,1 gráða" assert country_desc("DE") == "í Þýskalandi" assert country_desc("es") == "á Spáni" assert country_desc("IS") == "á Íslandi" assert country_desc("us") == "í Bandaríkjunum" assert cap_first("yolo") == "Yolo" assert cap_first("YOLO") == "YOLO" assert cap_first("Yolo") == "Yolo" assert time_period_desc(3751) == "1 klukkustund og 3 mínútur" assert ( time_period_desc(3751, omit_seconds=False) == "1 klukkustund, 2 mínútur og 31 sekúnda" ) assert time_period_desc(601) == "10 mínútur" assert time_period_desc(610, omit_seconds=False) == "10 mínútur og 10 sekúndur" assert time_period_desc(61, omit_seconds=False) == "1 mínúta og 1 sekúnda" assert ( time_period_desc(121, omit_seconds=False, case="þgf") == "2 mínútum og 1 sekúndu" ) assert distance_desc(1.1) == "1,1 kílómetri" assert distance_desc(1.2) == "1,2 kílómetrar" assert distance_desc(0.7) == "700 metrar" assert distance_desc(0.021) == "20 metrar" assert distance_desc(41, case="þf") == "41 kílómetra" assert distance_desc(0.215, case="þgf") == "220 metrum" assert krona_desc(361) == "361 króna" assert krona_desc(28) == "28 krónur" assert krona_desc(4264.2) == "4.264,2 krónur" assert krona_desc(2443681.1) == "2.443.681,1 króna" assert strip_trailing_zeros("17,0") == "17" assert strip_trailing_zeros("219.117,0000") == "219.117" assert strip_trailing_zeros("170") == "170" assert strip_trailing_zeros("170,0") == "170" assert iceformat_float(666.0) == "666" assert iceformat_float(666, strip_zeros=False) == "666,00" assert iceformat_float(217.296) == "217,3" assert iceformat_float(2528963.9) == "2.528.963,9" assert iceformat_float(123.12341, decimal_places=4) == "123,1234" assert iceformat_float(123.1000, strip_zeros=True) == "123,1" assert iceformat_float(123.0, decimal_places=4, strip_zeros=False) == "123,0000" assert icequote("sæll") == "„sæll“" assert icequote(" Góðan daginn ") == "„Góðan daginn“" assert timezone4loc((64.157202, -21.948536)) == "Atlantic/Reykjavik" assert timezone4loc((40.093368, 57.000067)) == "Asia/Ashgabat"
def dist_answer_for_loc(matches, query: Query): """Generate response to distance query, e.g. "Hvað er ég langt frá X?" """ locname = matches.group(1) loc_nf = _addr2nom(locname) or locname # Try to avoid answering certain queries here loc_lower = locname.lower() # TODO: Solve this by configuring qmodule priority if any(s in loc_lower for s in ( "strætó", "stoppistöð", "strætisvagn", "biðstöð", "stoppustöð", "stræto", "strædo", "jólin", "jól", "páska", )): return None # Check if user is asking about distance from home address is_home = False loc: Tuple[float, float] if loc_lower in _HOME_LOC: ad = query.client_data("address") if not ad: return gen_answer( "Ég veit ekki hvar þú átt heima, en þú getur sagt mér það.") elif "lat" not in ad or "lon" not in ad: return gen_answer("Ég veit ekki hvar heimili þitt er.") else: is_home = True loc = (cast(float, ad["lat"]), cast(float, ad["lon"])) loc_nf = "{0} {1}".format(ad["street"], ad["number"]) else: # Talk to geocode API res = query_geocode_api_addr(loc_nf) # Verify sanity of API response if (not res or "status" not in res or res["status"] != "OK" or not res.get("results")): return None # Extract location coordinates from result coords = res["results"][0]["geometry"]["location"] loc = (coords["lat"], coords["lng"]) # Calculate distance, round it intelligently and format num string if query.location is None: km_dist = 0.0 else: km_dist = distance(query.location, loc) # Generate answer answer = distance_desc(km_dist, abbr=True) response = dict(answer=answer, distance=km_dist) loc_nf = capitalize_placename(loc_nf) dist = distance_desc(km_dist, case="þf") voice = "{0} er {1} í burtu".format(numbers_to_neutral(loc_nf), dist) query.set_key(loc_nf) # Beautify by capitalizing remote loc name uc = locname if is_home else capitalize_placename(locname) bq = query.beautified_query.replace(locname, uc) # Hack to fix the fact that the voice recognition often misses "ég" prefix_fix = "Hvað er langt frá" if bq.startswith(prefix_fix): bq = bq.replace(prefix_fix, "Hvað er ég langt frá") query.set_beautified_query(bq) query.set_context(dict(subject=loc_nf)) return response, answer, voice