Пример #1
0
 def testGetDescriptionForNumber_en_US(self):
     self.assertEqual("CA",
                       geocoder.description_for_number(US_NUMBER1, _ENGLISH, region=_USA))
     self.assertEqual("Mountain View, CA",
                       geocoder.description_for_number(US_NUMBER2, _ENGLISH, region=_USA))
     self.assertEqual("New York, NY",
                       geocoder.description_for_number(US_NUMBER3, _ENGLISH, region=_USA))
Пример #2
0
 def testGetDescriptionForNumber_en_US(self):
     self.assertEquals(
         "CA",
         geocoder.description_for_number(US_NUMBER1, _ENGLISH, region=_USA))
     self.assertEquals(
         "Mountain View, CA",
         geocoder.description_for_number(US_NUMBER2, _ENGLISH, region=_USA))
     self.assertEquals(
         "New York, NY",
         geocoder.description_for_number(US_NUMBER3, _ENGLISH, region=_USA))
Пример #3
0
def localScan(InputNumber):
    global number
    global localNumber
    global internationalNumber
    global numberCountryCode
    global numberCountry

    print code_info + 'Running local scan...'

    FormattedPhoneNumber = "+" + formatNumber(InputNumber)

    try:
        PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None)
    except:
        return False
    else:
        if not phonenumbers.is_valid_number(PhoneNumberObject):
            return False

        number = phonenumbers.format_number(
            PhoneNumberObject,
            phonenumbers.PhoneNumberFormat.E164).replace('+', '')
        numberCountryCode = phonenumbers.format_number(
            PhoneNumberObject,
            phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(' ')[0]

        countryRequest = json.loads(
            requests.request(
                'GET', 'https://restcountries.eu/rest/v2/callingcode/%s' %
                numberCountryCode.replace('+', '')).content)
        numberCountry = countryRequest[0]['alpha2Code']

        localNumber = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace(
                numberCountryCode, '')
        internationalNumber = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL)

        print code_result + 'International format: %s' % internationalNumber
        print code_result + 'Local format: 0%s' % localNumber
        print code_result + 'Country code: %s' % numberCountryCode
        print code_result + 'Location: %s' % geocoder.description_for_number(
            PhoneNumberObject, "en")
        print code_result + 'Carrier: %s' % carrier.name_for_number(
            PhoneNumberObject, 'en')
        print code_result + 'Area: %s' % geocoder.description_for_number(
            PhoneNumberObject, 'en')
        for timezoneResult in timezone.time_zones_for_number(
                PhoneNumberObject):
            print code_result + 'Timezone: %s' % (timezoneResult)

        if phonenumbers.is_possible_number(PhoneNumberObject):
            print code_info + 'The number is valid and possible.'
        else:
            print code_warning + 'The number is valid but might not be possible.'
Пример #4
0
 def testGetDescriptionForKoreanNumber(self):
     self.assertEqual("Seoul",
                       geocoder.description_for_number(KO_NUMBER1, _ENGLISH))
     self.assertEqual("Incheon",
                       geocoder.description_for_number(KO_NUMBER2, _ENGLISH))
     self.assertEqual("Jeju",
                       geocoder.description_for_number(KO_NUMBER3, _ENGLISH))
     self.assertEqual(u"\uC11C\uC6B8",
                       geocoder.description_for_number(KO_NUMBER1, _KOREAN))
     self.assertEqual(u"\uC778\uCC9C",
                       geocoder.description_for_number(KO_NUMBER2, _KOREAN))
Пример #5
0
 def testGetDescriptionForKoreanNumber(self):
     self.assertEqual("Seoul",
                      geocoder.description_for_number(KO_NUMBER1, _ENGLISH))
     self.assertEqual("Incheon",
                      geocoder.description_for_number(KO_NUMBER2, _ENGLISH))
     self.assertEqual("Jeju",
                      geocoder.description_for_number(KO_NUMBER3, _ENGLISH))
     self.assertEqual(u"\uC11C\uC6B8",
                      geocoder.description_for_number(KO_NUMBER1, _KOREAN))
     self.assertEqual(u"\uC778\uCC9C",
                      geocoder.description_for_number(KO_NUMBER2, _KOREAN))
 def testGetDescriptionForFallBack(self):
     # No fallback, as the location name for the given phone number is
     # available in the requested language.
     self.assertEqual("Kalifornien",
                      description_for_number(US_NUMBER1, _GERMAN))
     # German falls back to English.
     self.assertEqual("New York, NY",
                      description_for_number(US_NUMBER3, _GERMAN))
     # Italian falls back to English.
     self.assertEqual("CA", description_for_number(US_NUMBER1, _ITALIAN))
     # Korean doesn't fall back to English.
     self.assertEqual(u"\uB300\uD55C\uBBFC\uAD6D",
                      description_for_number(KO_NUMBER3, _KOREAN))
Пример #7
0
 def testGetDescriptionForNumberWithNoDataFile(self):
     # No data file containing mappings for US numbers is available in Chinese for the unittests. As
     # a result, the country name of United States in simplified Chinese is returned.
     self.assertEqual(u("\u7F8E\u56FD"),
                      description_for_number(US_NUMBER1, _CHINESE, region=_CHINA))
     self.assertEqual("Bahamas",
                      description_for_number(BS_NUMBER1, _ENGLISH, region=_USA))
     self.assertEqual("Australia",
                      description_for_number(AU_NUMBER, _ENGLISH, region=_USA))
     self.assertEqual("",
                      description_for_number(NUMBER_WITH_INVALID_COUNTRY_CODE, _ENGLISH, region=_USA))
     self.assertEqual("",
                      description_for_number(INTERNATIONAL_TOLL_FREE, _ENGLISH, region=_USA))
Пример #8
0
 def testGetDescriptionForNumberWithNoDataFile(self):
     # No data file containing mappings for US numbers is available in Chinese for the unittests. As
     # a result, the country name of United States in simplified Chinese is returned.
     self.assertEqual(u"\u7F8E\u56FD",
                       geocoder.description_for_number(US_NUMBER1, _CHINESE, region=_CHINA))
     self.assertEqual("Bahamas",
                       geocoder.description_for_number(BS_NUMBER1, _ENGLISH, region=_USA))
     self.assertEqual("Australia",
                       geocoder.description_for_number(AU_NUMBER, _ENGLISH, region=_USA))
     self.assertEqual("",
                       geocoder.description_for_number(NUMBER_WITH_INVALID_COUNTRY_CODE, _ENGLISH, region=_USA))
     self.assertEqual("",
                       geocoder.description_for_number(INTERNATIONAL_TOLL_FREE, _ENGLISH, region=_USA))
Пример #9
0
 def testGetDescriptionForFallBack(self):
     # No fallback, as the location name for the given phone number is
     # available in the requested language.
     self.assertEqual("Kalifornien",
                       geocoder.description_for_number(US_NUMBER1, _GERMAN))
     # German falls back to English.
     self.assertEqual("New York, NY",
                       geocoder.description_for_number(US_NUMBER3, _GERMAN))
     # Italian falls back to English.
     self.assertEqual("CA",
                       geocoder.description_for_number(US_NUMBER1, _ITALIAN))
     # Korean doesn't fall back to English.
     self.assertEqual(u"\uB300\uD55C\uBBFC\uAD6D",
                       geocoder.description_for_number(KO_NUMBER3, _KOREAN))
Пример #10
0
def phonenumber_lookup(ph):
    try:
        number = phonenumbers.parse(ph)
        phonenumbers.is_possible_number(number)
        print("Country: " + geocoder.region_code_for_number(number))
        if geocoder.description_for_number(number, "en").lstrip() != "":
            print("City: " + geocoder.description_for_number(number, "en"))
        print(
            "Timezone: " +
            re.sub("[()'',]", "", str(timezone.time_zones_for_number(number))))
        print("Carrier: " + carrier.name_for_number(number, "en"))
    except phonenumbers.phonenumberutil.NumberParseException:
        cprint(error, "Invalid or malformed number.")
        return
Пример #11
0
 def get_number_location_description(self):
     """
     return a text description of a PhoneNumber object, return empty string is not found.
     :return: string
     """
     from phonenumbers import geocoder, parse
     return geocoder.description_for_number(parse(str(self.number)), "en")
Пример #12
0
def url_fetch(query=""):
    if not query:
        last_query = session.get('last_query', None)
        if last_query is not None:
            query = session['last_query']['query']
    stopset = set(stopwords.words('english'))
    q = {
        "fields": ["file"],
        "query": {
            "term": {"file": query}
        }
    }
    r = es.search(body=q, index=es_index)
    data = r['hits']['hits']
    urls = []
    pn = []
    for doc in data:
        urls.append(re.findall(r'(https?://[^\s]+)', doc['fields']['file'][0]))
        try:
            for match in phonenumbers.PhoneNumberMatcher(doc['fields']['file'][0], region=None):
                pn.append({'number': phonenumbers.format_number(match.number, phonenumbers.PhoneNumberFormat.E164),
                           'location': geocoder.description_for_number(match.number, "en")})
        except KeyError:
            pass
    urls = filter(lambda x: x != [], urls)
    # urls_flat=reduce(lambda x,y: x.extend(y),urls)
    urls_flat = [item for sublist in urls for item in sublist]
    return json.dumps({'urls': dict(Counter(urls_flat)), 'pn': pn})
Пример #13
0
def number_phone_function():
    print(" ")
    print("ATTENTION DONT FORGET => +48... <= OR SOMETHING LIKE THAT...")

    y = input("write phonenumber => ")
    x = phonenumbers.parse(y, None)
    print(x)

    x2 = phonenumbers.is_possible_number(x)
    print("is possible number? =>", x2)

    x3 = phonenumbers.is_valid_number(x)
    print("is valid number? =>", x3)

    #country..
    print("from where is use the number? =>",
          geocoder.description_for_number(x, 'pl'))

    #services..
    print("services of phonenumber? =>", carrier.name_for_number(x, 'pl'))

    #timezone..
    print("timezone =>", timezone.time_zones_for_number(x))

    print(" ")
Пример #14
0
def locate_numbers():
    if request.method == 'POST':
        if 'numbers' not in request.files:
            return redirect(url_for('index'))

        numbers = request.files['numbers'].readlines()
        numbers_results = []

        for line in numbers:
            line = line.rstrip().decode()
            number = format_phonenumber(line)

            if number == 'numbers':
                number_result = [line, 'valid', 'location']
            else:
                try:
                    parsed_number = phonenumbers.parse(number, PHONE_REGION)
                    if phonenumbers.is_valid_number(parsed_number):
                        location = geocoder.description_for_number(
                            parsed_number, "en")
                        number_result = [line, 'true', location]
                    else:
                        number_result = [line, 'false', 'n/a']
                except:
                    number_result = [line, 'false', 'n/a']

            numbers_results.append(number_result)

        return '\n'.join(', '.join(elems) for elems in numbers_results), 200, {
            'Content-Type': 'text/plain'
        }

    else:  # request.method == 'GET'
        msg = "HTTP 501: Not implemented"
        return msg, 501, {'Content-Type': 'text/plain'}
Пример #15
0
 def testGetDescriptionForArgentinianMobileNumber(self):
     self.assertEqual("La Plata", description_for_number(AR_MOBILE_NUMBER, _ENGLISH))
     # Python version extra test
     # Put an invalid number after the mobile token ("9") and lie about
     # this being a valid number
     arInvalidMobileNumber = PhoneNumber(country_code=54, national_number=91)
     self.assertEqual("Argentina", description_for_valid_number(arInvalidMobileNumber, _ENGLISH))
 def testGetDescriptionForArgentinianMobileNumber(self):
     self.assertEqual("La Plata", description_for_number(AR_MOBILE_NUMBER, _ENGLISH))
     # Python version extra test
     # Put an invalid number after the mobile token ("9") and lie about
     # this being a valid number
     arInvalidMobileNumber = PhoneNumber(country_code=54, national_number=91)
     self.assertEqual("Argentina", description_for_valid_number(arInvalidMobileNumber, _ENGLISH))
Пример #17
0
    def get(self, number):
        code = 0
        message = 'success'
        data = {'number': number, 'isValid': None}

        try:
            if not number.startswith("+"):
                number = "+" + number
            logger.info('valid number:{0}'.format(number))
            x = phonenumbers.parse(number, None)
            data['countryCode'] = x.country_code
            data['nationalNumber'] = x.national_number
            # a = phonenumbers.is_possible_number(x)
            # 验证是否是可用的
            b = phonenumbers.is_valid_number(x)
            data['isValid'] = b
            # 本国格式化
            rx = phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.NATIONAL)
            data['nationalFormat'] = rx
            # 国际格式化
            rx = phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
            data['internationalFormat'] = rx
            # 地区
            c = geocoder.description_for_number(x, "en")
            data['region'] = c
            # 运营商
            d = carrier.name_for_number(x, "en")
            data['carrier'] = d
            logger.info('valid result:{0}'.format(data))
        except Exception as err:
            logger.error(err, exc_info=True)
            code = 1000
            message = 'valid fail'
        return {'code': code, 'message': message, 'data': data}
Пример #18
0
def phone_anonymizer(phone): #return a phone number anonymized
	"Anonymizes a phone number in order to respect privacy in the PoC"

	#the phone number must have a '+' to be in E.164 format
	#in order to be parseable by phonenumbers
	if phone[0] is not '+':
		phone = str('+')+phone
	
	try:
		phone_number = phonenumbers.parse(phone, None)

		phone_format = phonenumbers.format_number(phone_number, phonenumbers.PhoneNumberFormat.INTERNATIONAL)

		phone_geo = str(geocoder.description_for_number(phone_number, "en"))

		if phone_geo is None: #idk if needed, just in case some city/country is not in the mapping table
			phone_geo = 'Unknown'

		tokens = phone_format.split()

		pre_anonym = ''
		for i in range(0,len(tokens)):
			pre_anonym = pre_anonym+str(tokens[i])+phone_geo

		###### hash of the recently generated string. I chose the less demanding algorithm, without collisions, in term of
		###### computing load among the supported ones ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
		hash_object = hashlib.sha224(pre_anonym)
		return hash_object.hexdigest()

	except NumberParseException as err:
		logging.warning('Error ocurred while processing in phone_anonymizer: %s', str(err))
Пример #19
0
def info():

    while True:
        b = input(colored("   Enter number: ", 'blue'))
        inp = input(colored("Continue ? Y/n: ", 'red'))
        if inp == "n":
            sys.exit("\n Shutting down... ")
        if inp == "y":
            print(colored("\n Target Number... \n", 'blue'))
        else:
            print(colored(f"\n  Invalid '{inp}'  Try again ! \n", 'red'))
            break
        ex = phonenumbers.parse(b)
        #	ex=phonenumbers.PhoneMetadata.load_all(inp)
        #		exp=timezone.time_zones_for_number(ex, "GB")
        exp = geocoder.description_for_number(ex, "en")

        print(colored("Country: ", 'green'), exp)

        #if inp=="y" or "Y":
        #	sys.exit("\n Shutting down... ")

        def isp():
            i = phonenumbers.parse(b)
            s = carrier.name_for_number(i, "en")
            print(colored("ISP: ", 'green'), s)

        isp()

        def time():
            p = phonenumbers.parse(b)
            e = timezone.time_zones_for_number(p)
            print(colored("Timezone: ", 'green'), e, "\n")

        time()
Пример #20
0
def formatNumber(number):
    '''
    number 必须是带区号的
    '''

    code = 0
    message = 'success'
    data = {'number': number, 'isValid': None}

    print "number:", number
    x = phonenumbers.parse(number, None)
    print x
    data['countryCode'] = x.country_code
    data['nationalNumber'] = x.national_number
    # a = phonenumbers.is_possible_number(x)
    # 验证是否是可用的
    b = phonenumbers.is_valid_number(x)
    print b
    data['isValid'] = b
    # 格式化
    rx = phonenumbers.format_number(
        x, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
    print rx
    data['format'] = rx
    # 地区
    c = geocoder.description_for_number(x, "en")
    print c
    data['region'] = c
    #运营商
    d = carrier.name_for_number(x, "en")
    print(d)
    data['carrier'] = d

    print data
Пример #21
0
def test_getCountryMax():
  countryCount = {}
  countryWithMaxCount = None
  finalDic = {}
  reader = io.StringIO("""History trip always room. c369e42170409b5a250f5ec8a86fa5bf +61353386215
   +447733795449 Bag show white artist town message field catch. 6d:a6:0f:0b:94:17
   Continue address throw difference discover. 43,221,224 +40756809984
   Continue address throw difference discover. 43,221,224 +40756809984
   Davidside, NY 84689
   +61786844803 
   +61211549558 
   +61303024775""")
  for line in reader.readlines():
    m = re.search(r"\+[\d]+", line)
    if m != None:
      ch_number = phonenumbers.parse(m.group(0), "US")
      country = geocoder.description_for_number(ch_number, "en")
      print(country == "")
      if country in countryCount.keys():
        countryCount[country] += 1
      elif country == "":
        countryCount["notfound in {}".format(m.group(0))] = 1
      else:
        countryCount[country] = 1
  countryWithMaxCount = max(countryCount, key=countryCount.get)
  assert countryWithMaxCount == "Australia"
  assert countryCount[countryWithMaxCount] == 3
Пример #22
0
def number_scanner(phone_number):
    number = phonenumbers.parse(phone_number)
    description = geocoder.description_for_number(number, "en")
    supplier = carrier.name_for_number(number, "en")
    info = [["Country", "Supplier"], [description, supplier]]
    data = str(tabulate(info, headers="firstrow", tablefmt="github"))
    return data
Пример #23
0
def validate_number(number,
                    country,
                    include_description=True) -> Optional[Number]:
    try:
        p = parse_number(number, country)
    except NumberParseException:
        return

    if not is_valid_number(p):
        return

    is_mobile = number_type(p) in MOBILE_NUMBER_TYPES
    descr = None
    if include_description:
        country = country_name_for_number(p, 'en')
        region = description_for_number(p, 'en')
        descr = country if country == region else f'{region}, {country}'

    return Number(
        number=format_number(p, PhoneNumberFormat.E164),
        country_code=f'{p.country_code}',
        number_formatted=format_number(p, PhoneNumberFormat.INTERNATIONAL),
        descr=descr,
        is_mobile=is_mobile,
    )
Пример #24
0
 def simple_scan(self, working=True):
     # function to get the basic info about a number (phonenumbers module)
     phone = phonenumbers.parse(self.phonenumber)
     if not phonenumbers.is_valid_number(phone):
         return False
     if phonenumbers.is_possible_number(phone):
         print(f"{b}{plus} The number is valid and possible.")
     else:
         print(f"{b}{warn} The number is valid but not possible.")
     international = phonenumbers.format_number(
         phone, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
     countrycode = phonenumbers.format_number(
         phone, phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(" ")[0]
     country = geocoder.country_name_for_number(phone, 'en')
     location = geocoder.description_for_number(phone, 'en')
     carrierr = carrier.name_for_number(phone, 'en')
     # ------------------------------------------------------------------------
     if working:
         print(f'{b}{plus} International Format : {international}')
         print(
             f'{b}{plus} Country name         : {country} ({countrycode})')
         print(f'{b}{plus} City/Province        : {location}')
         print(f'{b}{plus} Carrier              : {carrierr}')
         for time in timezone.time_zones_for_number(phone):
             print(f'{b}{plus} Timezone             : {time}')
Пример #25
0
def getCountry(phone):
    try:
        query = parse("+" + phone, None)
        country = repr(geocoder.description_for_number(query, 'en'))
    except:
        country = "Unknown"
    return country
Пример #26
0
def info():

    while True:
        b = input("    টুনির মার নম্বার: ")
        inp = input(" ভরতে চাস ? Y/n: ")
        if inp == "n":
            sys.exit("\n  বিদাই পিতিবি... ")
        if inp == "y":
            print("\n ভরে দেওয়া নম্বার... \n")
        else:
            print(f"\n   কানাষুদা '{inp}' দেখে লেখ \n")
            break
        ex = phonenumbers.parse(b)
        #       ex=phonenumbers.PhoneMetadata.load_all(inp)
        #               exp=timezone.time_zones_for_number(ex, "GB")
        exp = geocoder.description_for_number(ex, "en")

        print("দেশ =", exp)

        def time():
            p = phonenumbers.parse(b)
            e = timezone.time_zones_for_number(p)
            print("সময়যাত্রা=", e)

        time()
Пример #27
0
def numberScanner(number):
    number = phonenumbers.parse(number)
    description = geocoder.description_for_number(number, 'en')
    supplier = carrier.name_for_number(number, 'en')
    info = [['Country', 'Supplier'], [description, supplier]]
    data = str(tabulate(info, headers="firstrow", tablefmt="github"))
    return data
Пример #28
0
def phone():
    os.system('figlet phone number')
    print(colored('================================', 'cyan'))
    # Parsing String to Phone number
    a = str(input(colored('enter number: ', 'green')))
    print(
        colored(
            '''=======================
[      TIME ZONE      ]
======================= ''', 'green'))
    phoneNumber = phonenumbers.parse(a)
    # Pass the parsed phone number in below function
    timeZone = timezone.time_zones_for_number(phoneNumber)
    time.sleep(1)

    # It print the timezone of a phonenumber
    print(colored(timeZone, 'yellow'))
    print(
        colored(
            '''=======================
[      NETWORK        ]
======================= ''', 'green'))
    ro_number = phonenumbers.parse(a, "RO")
    time.sleep(1)

    print(colored(carrier.name_for_number(ro_number, "en"), 'yellow'))
    print(
        colored(
            '''=======================
[      GEOLOCATION    ]
======================= ''', 'green'))
    ch_number = phonenumbers.parse(a, "CH")
    time.sleep(1)
    print(colored(geocoder.description_for_number(ch_number, "en"), 'yellow'))
Пример #29
0
def url_fetch(query=""):
    if not query:
        last_query = session.get('last_query', None)
        if last_query is not None:
            query = session['last_query']['query']
    stopset = set(stopwords.words('english'))
    q = {"fields": ["file"], "query": {"term": {"file": query}}}
    r = es.search(body=q, index=es_index)
    data = r['hits']['hits']
    urls = []
    pn = []
    for doc in data:
        urls.append(re.findall(r'(https?://[^\s]+)', doc['fields']['file'][0]))
        try:
            for match in phonenumbers.PhoneNumberMatcher(
                    doc['fields']['file'][0], region=None):
                pn.append({
                    'number':
                    phonenumbers.format_number(
                        match.number, phonenumbers.PhoneNumberFormat.E164),
                    'location':
                    geocoder.description_for_number(match.number, "en")
                })
        except KeyError:
            pass
    urls = filter(lambda x: x != [], urls)
    # urls_flat=reduce(lambda x,y: x.extend(y),urls)
    urls_flat = [item for sublist in urls for item in sublist]
    return json.dumps({'urls': dict(Counter(urls_flat)), 'pn': pn})
Пример #30
0
def localScan(InputNumber, print_results=True):
    print("Running local scan...")

    FormattedPhoneNumber = "+" + formatNumber(InputNumber)

    try:
        PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None)
    except Exception as e:
        print(e)
    else:
        if not phonenumbers.is_valid_number(PhoneNumberObject):
            return False

        number = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164
        ).replace("+", "")
        numberCountryCode = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL
        ).split(" ")[0]
        numberCountry = phonenumbers.region_code_for_country_code(
            int(numberCountryCode)
        )

        localNumber = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164
        ).replace(numberCountryCode, "")
        internationalNumber = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL
        )

        country = geocoder.country_name_for_number(PhoneNumberObject, "en")
        location = geocoder.description_for_number(PhoneNumberObject, "en")
        carrierName = carrier.name_for_number(PhoneNumberObject, "en")

        if print_results:
            print("International format: {}".format(internationalNumber))
            print("Local format: {}".format(localNumber))
            print("Country found: {} ({})".format(country, numberCountryCode))
            print("City/Area: {}".format(location))
            print("Carrier: {}".format(carrierName))
            for timezoneResult in timezone.time_zones_for_number(PhoneNumberObject):
                print("Timezone: {}".format(timezoneResult))

            if phonenumbers.is_possible_number(PhoneNumberObject):
                print("The number is valid and possible.")
            else:
                print("The number is valid but might not be possible.")

    numberObj = {}
    numberObj["input"] = InputNumber
    numberObj["default"] = number
    numberObj["local"] = localNumber
    numberObj["international"] = internationalNumber
    numberObj["country"] = country
    numberObj["countryCode"] = numberCountryCode
    numberObj["countryIsoCode"] = numberCountry
    numberObj["location"] = location
    numberObj["carrier"] = carrierName

    return numberObj
Пример #31
0
def numberScan():
    global phoneNumberGET, phoneNumber, numberNSCAN, numberCC, numberC, numberLOCAL, numberINTER, countryNSCAN, locationNSCAN, carrierNameNSCAN
    phoneNumberGET = numberSCANentryVar.get()
    #GET INFORMATIONS - PHONE NUMBER SCANNER FRAME
    phoneNumber = phonenumbers.parse(phoneNumberGET, None)
    numberNSCAN = phonenumbers.format_number(
        phoneNumber, phonenumbers.PhoneNumberFormat.E164).replace('+', '')
    numberCC = phonenumbers.format_number(
        phoneNumber,
        phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(' ')[0]
    numberC = phonenumbers.region_code_for_country_code(int(numberCC))
    numberLOCAL = phonenumbers.format_number(
        phoneNumber,
        phonenumbers.PhoneNumberFormat.E164).replace(numberCC, '')
    numberINTER = phonenumbers.format_number(
        phoneNumber, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
    countryNSCAN = geocoder.country_name_for_number(phoneNumber, 'en')
    locationNSCAN = geocoder.description_for_number(phoneNumber, 'en')
    carrierNameNSCAN = carrier.name_for_number(phoneNumber, 'en')
    #APPLY RESULTS - PHONE NUMBER SCANNER FRAME
    numberReset()
    numberSCANentryVar.set(phoneNumberGET)
    localNSCANentryVar.set(numberLOCAL)
    interNSCANentryVar.set(numberINTER)
    countryNSCANentryVar.set("{} ({})".format(countryNSCAN, numberCC))
    areaNSCANentryVar.set(locationNSCAN)
    carrierNSCANentryVar.set(carrierNameNSCAN)
    for timezoneResult in timezone.time_zones_for_number(phoneNumber):
        timezoneNSCANentryVar.set(timezoneResult)
    if phonenumbers.is_possible_number(phoneNumber):
        validNSCANentryVar.set("VALID+POSSIBLE")
    else:
        validNSCANentryVar.set("INVALID")
Пример #32
0
def test_getCountryTest():
  ch_number = phonenumbers.parse("+447733795449", "US")
  # requires E164 format
  # E.164 numbers are formatted [+] [country code] [subscriber number including area code] and can have a maximum of fifteen digits
  # @see https://www.twilio.com/docs/glossary/what-e164
  geo = geocoder.description_for_number(ch_number, "en")
  assert geo ==  "United Kingdom"
Пример #33
0
def number_check(Phone_number):
    number = phonenumbers.parse(Phone_number)
    description = geocoder.description_for_number(number, "en")
    supplier = carrier.name_for_number(number, "en")
    info = [["country", "supplier"], [description, supplier]]

    return tabulate(info, headers="firstrow", tablefmt="github")
Пример #34
0
def lambda_handler(event, context=None):
    phone_number = event["params"]["querystring"]["phone"]
    phone_number = '+' + phone_number
    print phone_number
    try:
        v = phonenumbers.parse(phone_number, None)
    except:
        v = None
    if v and v.country_code == 1:
        # This is a US number, so lets do the geocoder

        state = geocoder.description_for_number(v, "en")
        country_code = "US"
        return {"country_code": country_code, "state": state}
    if v and v.country_code == 91:
        # This is India, so we may get some more info about this guy
        country_code = "IN"
        phone_without = str(v.national_number)
        url = 'https://avneesh-indian-phone-number-info-v1.p.mashape.com/getphoneinfo'
        params = {'mobile_number': phone_without[:4]}
        headers = {
            'X-Mashape-Key':
            'gi7WK8GMREmshSQcmqWtPalrLYrap1D3t32jsnMgtJqq0NafUR',
            'Accept': 'application/json'
        }
        r = requests.get(url, params=params, headers=headers)

        if r.status_code == 200 and 'location' in r.json().keys():
            state = r.json()['location']
            if state == 'Kolkatta':
                state = 'Kolkata'
            if state == 'Andra Pradesh':
                state = 'Andhra Pradesh'
            if state == 'Maharastra':
                state = 'Maharashtra'
            if state == 'Gujarat':
                state = 'Gujrat'
            if state == 'Goa&Maharashtra':
                state = 'Maharashtra'
            if state == 'Uttar Pradesh(East)':
                state = 'Uttar Pradesh East'
            if state == 'Uttar Pradesh(West)':
                state = 'Uttar Pradesh West'
            if state == 'Madhya Pradesh & Chhattisgarh':
                state = 'Madhya Pradesh'
            if state == 'karnataka':
                state = 'Karnataka'
            if state == 'Bihar & Jharkhand':
                state = 'Bihar'
            if state == 'Orissa':
                state = 'Odisha'
            if state == 'Uttar Pradesh(west) & Uttarakhand':
                state = 'Uttar Pradesh West'
            if state == 'Uttar Pradesh(west) & Uttarkhand':
                state = 'Uttar Pradesh West'
            if state == 'Tata Docomo':
                return None
            return {'country_code': country_code, "state": state}
    return None
Пример #35
0
def scan(InputNumber, print_results=True):
    test('Running local scan...')

    FormattedPhoneNumber = "+" + formatNumber(InputNumber)

    try:
        PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None)
    except Exception as e:
        throw(e)
    else:
        if not phonenumbers.is_valid_number(PhoneNumberObject):
            return False

        number = phonenumbers.format_number(
            PhoneNumberObject,
            phonenumbers.PhoneNumberFormat.E164).replace('+', '')
        numberCountryCode = phonenumbers.format_number(
            PhoneNumberObject,
            phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(' ')[0]
        numberCountry = phonenumbers.region_code_for_country_code(
            int(numberCountryCode))

        localNumber = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace(
                numberCountryCode, '')
        internationalNumber = phonenumbers.format_number(
            PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL)

        country = geocoder.country_name_for_number(PhoneNumberObject, "en")
        location = geocoder.description_for_number(PhoneNumberObject, "en")
        carrierName = carrier.name_for_number(PhoneNumberObject, 'en')

        if print_results:
            plus('International format: {}'.format(internationalNumber))
            plus('Local format: {}'.format(localNumber))
            plus('Country found: {} ({})'.format(country, numberCountryCode))
            plus('City/Area: {}'.format(location))
            plus('Carrier: {}'.format(carrierName))
            for timezoneResult in timezone.time_zones_for_number(
                    PhoneNumberObject):
                plus('Timezone: {}'.format(timezoneResult))

            if phonenumbers.is_possible_number(PhoneNumberObject):
                plus('The number is valid and possible!')
            else:
                warn('The number is valid but might not be possible.')

    numberObj = {}
    numberObj['input'] = InputNumber
    numberObj['default'] = number
    numberObj['local'] = localNumber
    numberObj['international'] = internationalNumber
    numberObj['country'] = country
    numberObj['countryCode'] = numberCountryCode
    numberObj['countryIsoCode'] = numberCountry
    numberObj['location'] = location
    numberObj['carrier'] = carrierName

    return numberObj
Пример #36
0
 def testGetDescriptionForNumberWithUserRegion(self):
     # User in Italy, American number. We should just show United States, in
     # Spanish, and not more detailed information.
     self.assertEqual("Estados Unidos",
                      description_for_number(US_NUMBER1, _SPANISH, region="IT"))
     # Unknown region - should just show country name.
     self.assertEqual("Estados Unidos",
                      description_for_number(US_NUMBER1, _SPANISH, region="ZZ"))
     # User in the States, language German, should show detailed data.
     self.assertEqual("Kalifornien",
                      description_for_number(US_NUMBER1, _GERMAN, region="US"))
     # User in the States, language French, no data for French, so we fallback
     # to English detailed data.
     self.assertEqual("CA",
                      description_for_number(US_NUMBER1, _FRENCH, region="US"))
     # Invalid number - return an empty string.
     self.assertEqual("", description_for_number(US_INVALID_NUMBER, _ENGLISH, region="US"))
Пример #37
0
 def testGetDescriptionForNumberWithUserRegion(self):
     # User in Italy, American number. We should just show United States, in
     # Spanish, and not more detailed information.
     self.assertEqual("Estados Unidos",
                      geocoder.description_for_number(US_NUMBER1, _SPANISH, region="IT"))
     # Unknown region - should just show country name.
     self.assertEqual("Estados Unidos",
                      geocoder.description_for_number(US_NUMBER1, _SPANISH, region="ZZ"))
     # User in the States, language German, should show detailed data.
     self.assertEqual("Kalifornien",
                      geocoder.description_for_number(US_NUMBER1, _GERMAN, region="US"))
     # User in the States, language French, no data for French, so we fallback
     # to English detailed data.
     self.assertEqual("CA",
                      geocoder.description_for_number(US_NUMBER1, _FRENCH, region="US"))
     # Invalid number - return an empty string.
     self.assertEqual("", geocoder.description_for_number(US_INVALID_NUMBER, _ENGLISH, region="US"))
Пример #38
0
def tz_ids_for_phone(phone, country='US'):
    """ Get the TZ identifiers that a phone number might be related to, e.g.

    >>> tztrout.tz_ids_for_phone('+16503334444')
    [u'America/Los_Angeles']
    >>> tztrout.tz_ids_for_phone('+49 (0)711 400 40990')
    [u'Europe/Berlin', u'Europe/Busingen']
    """

    from phonenumbers.geocoder import description_for_number

    try:
        phone = phonenumbers.parse(phone, country)
    except:
        pass
    else:
        country_iso = phonenumbers.region_code_for_number(phone)
        if not country_iso:
            country_iso = phonenumbers.region_code_for_country_code(phone.country_code)

        if country_iso == 'US':

            # check if we have a specific exception for a given area code first
            exception_key = 'areacode:%s' % str(phone.national_number)[:3]
            if exception_key in data_exceptions:
                return data_exceptions[exception_key]['include']

            state = city = None
            area = description_for_number(phone, 'en').split(',')
            if len(area) == 2:
                city = area[0].strip()
                state = area[1].strip()
            elif len(area) == 1 and area[0]:
                state = area[0].lower().strip()
                state = td.normalized_states['US'].get(state, None)

            return tz_ids_for_address(country_iso, state=state, city=city)

        elif country_iso == 'CA':
            area_code = str(phone.national_number)[:3]
            state = td.ca_area_code_to_state.get(area_code)
            return td.ca_state_to_tz_ids.get(state)

        elif country_iso == 'AU':
            area_code = str(phone.national_number)[:2]
            state = td.au_area_code_to_state.get(area_code)

            # Some Australian number prefixes (e.g. 04) are country-wide - fall
            # back to all the AU tz ids
            if state:
                return td.au_state_to_tz_ids.get(state)
            return pytz.country_timezones.get(country_iso)

        elif country_iso:
            return pytz.country_timezones.get(country_iso)

    return []
Пример #39
0
 def testCoverage(self):
     # Python version extra tests
     invalid_number = PhoneNumber(country_code=210, national_number=123456L)
     self.assertEqual("", geocoder.country_name_for_number(invalid_number, "en"))
     # Add in some script and region specific fictional names
     TEST_GEOCODE_DATA['1650960'] = {'en': u'Mountain View, CA',
                                     "en_GB": u'Mountain View California',
                                     "en_US": u'Mountain View, Sunny California',
                                     "en_Latn": u'MountainView'}
     # The following test might one day return "Mountain View California"
     self.assertEqual("United States",
                      geocoder.description_for_number(US_NUMBER2, _ENGLISH, region="GB"))
     self.assertEqual("Mountain View, Sunny California",
                      geocoder.description_for_number(US_NUMBER2, _ENGLISH, region="US"))
     self.assertEqual("MountainView",
                      geocoder.description_for_number(US_NUMBER2, _ENGLISH, script="Latn"))
     self.assertEqual("United States",
                      geocoder.description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="GB"))
     # Get a different result when there is a script-specific variant
     self.assertEqual("MountainView",
                      geocoder.description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="US"))
     TEST_GEOCODE_DATA['1650960'] = {'en': u'Mountain View, CA'}
Пример #40
0
def run(node):
    """ This returns any US phone numbers in the text.

        :param node:    a python dictionary with the 'text' field
    """
    results = []
    for match in phonenumbers.PhoneNumberMatcher(node['text'], "US"):
        results.append({
            "number"    : phonenumbers.format_number(match.number, phonenumbers.PhoneNumberFormat.E164),
            "location"  : geocoder.description_for_number(match.number, "en"),
            "carrier"   : carrier.name_for_number(match.number, "en"),
            "time_zone" : timezone.time_zones_for_number(match.number)
        })
    # http://stackoverflow.com/questions/11092511/python-list-of-unique-dictionaries
    return {"phonenumbers": uniq_lod(results, 'number')}
    def testCoverage(self):
        # Python version extra tests
        invalid_number = PhoneNumber(country_code=210, national_number=123456)
        self.assertEqual("", country_name_for_number(invalid_number, "en"))
        # Ensure we exercise all public entrypoints directly
        self.assertEqual("CA", _prefix_description_for_number(TEST_GEOCODE_DATA, TEST_GEOCODE_LONGEST_PREFIX, US_NUMBER1, "en"))
        self.assertEqual("CA", description_for_valid_number(US_NUMBER1, "en"))
        self.assertEqual("", description_for_valid_number(US_INVALID_NUMBER, "en"))
        # Add in some script and region specific fictional names
        TEST_GEOCODE_DATA['1650960'] = {'en': u("Mountain View, CA"),
                                        "en_GB": u("Mountain View California"),
                                        "en_US": u("Mountain View, Sunny California"),
                                        "en_Xyzz_US": u("MTV - xyzz"),
                                        "en_Latn": u("MountainView")}
        # The following test might one day return "Mountain View California"
        self.assertEqual("United States",
                         description_for_number(US_NUMBER2, _ENGLISH, region="GB"))
        self.assertEqual("Mountain View, Sunny California",
                         description_for_number(US_NUMBER2, _ENGLISH, region="US"))
        self.assertEqual("MountainView",
                         description_for_number(US_NUMBER2, _ENGLISH, script="Latn"))
        self.assertEqual("United States",
                         description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="GB"))
        self.assertEqual("MTV - xyzz",
                         description_for_number(US_NUMBER2, _ENGLISH, script="Xyzz", region="US"))
        self.assertEqual("Mountain View, Sunny California",
                         description_for_number(US_NUMBER2, _ENGLISH, script="Zazz", region="US"))
        # Get a different result when there is a script-specific variant
        self.assertEqual("MountainView",
                         description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="US"))
        TEST_GEOCODE_DATA['1650960'] = {'en': u("Mountain View, CA")}

        # Test the locale mapping
        TEST_GEOCODE_DATA['8868'] = {'zh': u("Chinese"), 'zh_Hant': u("Hant-specific")}
        tw_number = FrozenPhoneNumber(country_code=886, national_number=810080123)
        self.assertEqual("Hant-specific",
                         description_for_number(tw_number, "zh", region="TW"))
        del TEST_GEOCODE_DATA['8868']
Пример #42
0
 def testGetDescriptionForNumberWithMissingPrefix(self):
     # Test that the name of the country is returned when the number passed in
     # is valid but not covered by the geocoding data file.
     self.assertEqual("United States",
                       geocoder.description_for_number(US_NUMBER4, _ENGLISH, region=_USA))
 def testGetDescriptionForNumberBelongingToMultipleCountriesIsEmpty(self):
     # Test that nothing is returned when the number passed in is valid but
     # not covered by the geocoding data file and belongs to multiple
     # countries
     self.assertEqual("", description_for_number(NANPA_TOLL_FREE, _ENGLISH, region=_USA))
Пример #44
0
def description(number):
    n = phonenumbers.parse(number, 'US')
    return description_for_number(n, 'en', region='US')
Пример #45
0
phonenumbers.is_valid_number(z)

print dir(phonenumbers.PhoneNumberFormat)
print
print x.country_code
print x
print str(x)
p = z
resp = {
    "countryCode": p.country_code,
    "nationalNumber": p.national_number,
    "isPossible": phonenumbers.is_possible_number(p),
    "isValid": phonenumbers.is_valid_number(p),
    "e164": phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.E164),
    "international": phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.INTERNATIONAL),
    "national": phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.NATIONAL),
    "rfc3966": phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.RFC3966),
    "location": geocoder.description_for_number(p, "en"),
    "country": geocoder.country_name_for_number(p, "en"),
}

print json.dumps(resp, indent=2)
exit()
print y
print z

print repr(carrier.name_for_number(x, "en"))
print repr(carrier.name_for_number(y, "en"))
print repr(carrier.name_for_number(z, "en"))
Пример #46
0
 def testGetDescriptionForInvalidNumber(self):
     self.assertEqual("", geocoder.description_for_number(KO_INVALID_NUMBER, _ENGLISH))
     self.assertEqual("", geocoder.description_for_number(US_INVALID_NUMBER, _ENGLISH))
Пример #47
0
def find_phone_numbers(source_txt):
    # logger = get_logger()
    tagged_phone_entities = []

    for match in re.finditer(phonenum_candidate_regex_str, source_txt, re.MULTILINE):
        # Extract the full-text value and the "normalized" value (i.e., digits only)
        value = source_txt[match.start() : match.end()]
        value_normalized = re.sub(u'[^\d]', u'', value)

        # Extract an excerpt of text that precedes the match
        excerpt_start = match.start() - EXCERPT_CHAR_BUFFER
        if excerpt_start < 0:
            excerpt_start = 0
        excerpt_prefix = source_txt[ excerpt_start : match.start() ]

        phone_number_obj = None

        try:
            # print "phone guess: %s"%value_normalized
            # Try using the 'phonenumbers' module to parse the number. Note that we need to prefix
            # the phone number string with "+" for parse() to work properly. If the number can't
            # be parsed it will throw a NumberParseException.
            phone_number_obj = phonenumbers.parse(u'+'+value_normalized, None)

            # More lenient than valid_num
            possible_num = phonenumbers.is_possible_number(phone_number_obj)
            valid_num= phonenumbers.is_valid_number(phone_number_obj)

            # print "possible=%s valid=%s"%(str(possible_num), str(valid_num))
            # If the phonenumbers module thinks the number is invalid BUT it is preceded by text
            # with a phone-related keyword, we'll accept the number. If the number is invalid and
            # doesn't have a phone-related keyword, however, skip it.
            if (not possible_num or not valid_num) and not contains_tel_keyword(excerpt_prefix[-15:]):
                continue

        except phonenumbers.phonenumberutil.NumberParseException as err:

            # The phonenumbers modules couldn't parse the number; however, if it's preceded by text
            # with a phone-related keyword we'll still accept it. Or put another way, if it is NOT
            # preceded by a phone keyword, skip it.
            if not contains_tel_keyword(excerpt_prefix[-15:]):
                continue

        #There seems to be a bug with some strings that cause partial numbers to be returned
        if len(value_normalized) < 7:
            continue

        # If we got this far, it means we're accepting the number as a phone number. Extract a snippet
        # of text that follows the match.
        excerpt_stop = match.end() + EXCERPT_CHAR_BUFFER
        if excerpt_stop > len(source_txt):
            excerpt_stop = len(source_txt)

        excerpt = source_txt[excerpt_start:excerpt_stop]
        excerpt_value_start = match.start() - excerpt_start
        excerpt_value_stop = excerpt_stop - match.end()

        # Remove carriage returns replace multiple, consecutive whitespace with a single space
        # so the excerpt will be compact and one line.
        excerpt = re.sub('\r+', u'', excerpt)
        excerpt = re.sub('\n+', u' ', excerpt)
        excerpt = re.sub(u'\s+', u' ', excerpt)

        print(u"Phone #: %s, \"%s\"" % (value_normalized, excerpt))

        entity_dict = {
            u"type": u"phone_number",
            u"value": value,
            u"value_normalized": value_normalized,
            u"note": None,
            u"body_offset_start": match.start(),
            u"body_offset_stop": match.end(),
            u"excerpt": excerpt,
            u"excerpt_value_start": excerpt_value_start,
            u"excerpt_value_stop": excerpt_value_stop,
            u"possible_area": None,
            u"possible_carrier": None
        }

        # If the phonenumbers module was able to construct an actual phone number object, attempt to
        # add some notes about the possible geographic region and telco carrier.
        if phone_number_obj is not None:
            area_name = geocoder.description_for_number(phone_number_obj, "en")
            if area_name:
                entity_dict[u'possible_area'] = u"Possible area: %s. " % area_name

            carrier_name = carrier.name_for_number(phone_number_obj, "en")
            if carrier_name:
                entity_dict[u'possible_carrier'] = u"Possible carrier: %s." % carrier_name

        tagged_phone_entities.append(entity_dict)

    return tagged_phone_entities