-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphone_formats.py
More file actions
447 lines (371 loc) · 18.4 KB
/
phone_formats.py
File metadata and controls
447 lines (371 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# -*- encoding: utf-8 -*-
##################################
#
# phone_formats.py
# contains phone formats
# and creates appropriate regexes
#
##################################
import re
GENERAL_SEPARATOR = r'[^\d\s,]{0,2}'
OBLIGATED_SEPARATOR = r'[^\d\t\r\n,]{1,2}'
def _stronger_value(original, replacement):
"""
Fight between original value and replacement.
Return replacement if it isn't null, else return original
"""
if replacement is None:
return original
return replacement
class FormatList(list):
"""
Custom class for containing phone regexes.
Allows exporting to many different formats
"""
def __init__(self, format_list=list(), country_code='', is_strict=True, is_canonized=True):
super(FormatList, self).__init__(format_list)
self._is_canonized = is_canonized
self._is_strict = is_strict
self.country_code = country_code
def copy(self):
return FormatList(self, country_code=self.country_code, is_strict=self._is_strict,
is_canonized=self._is_canonized)
def to_find_regex(self, is_strict=False, country_code='', optional_country=False, is_canonized=True, stuck_zero=False):
"""
Creates a final compiled regex that will find phone numbers
"""
return self._create_full_regex(absolute_anchors=False, is_strict=is_strict, country_code=country_code,
optional_country=optional_country,
is_canonized=is_canonized, stuck_zero=stuck_zero)
def to_exact_regex(self, is_strict=False, country_code='', optional_country=False, is_canonized=True, stuck_zero=False):
"""
Creates a final compiled regex that will exactly match phone number (between anchors)
if strict or country_code are given as params, replace they are used instead of self.country_code and self._is_strict
"""
return self._create_full_regex(absolute_anchors=True, is_strict=is_strict, country_code=country_code,
optional_country=optional_country,
is_canonized=is_canonized, stuck_zero=stuck_zero)
def _create_full_regex(self, absolute_anchors=True, is_strict=None, country_code='', optional_country=False,
is_canonized=None, stuck_zero=False):
"""
create full regex based on anchors.
absolute_anchors True: ^ and $
absolute_anchors False: normal anchors
stuck_zero: allow zeroes between country and prefix
"""
is_strict = _stronger_value(self._is_strict, is_strict)
country_code = _stronger_value(self.country_code, country_code)
is_canonized = _stronger_value(self._is_canonized, is_canonized)
orred_regexes = self._create_orred_regexes(is_canonized=is_canonized)
if absolute_anchors:
start_anchor = '^'
end_anchor = '$'
else:
start_anchor = '(?:\\b|\\D)'
end_anchor = '(?:\\b|\\D)'
if is_canonized:
separator = ''
else:
separator = GENERAL_SEPARATOR
if stuck_zero:
optional_zero = '0*'
else:
optional_zero = ''
if is_strict and country_code: # with country code
if is_canonized:
final_regex = "{start_anchor}(?P<phone>0*{country}{alt}){end_anchor}".format(start_anchor=start_anchor,
end_anchor=end_anchor,
country=country_code,
alt=orred_regexes)
else:
if not optional_country:
final_regex = "{start_anchor}(?P<phone>{country}{sep}{zero}{alt}){end_anchor}".format(
start_anchor=start_anchor,
end_anchor=end_anchor,
sep=separator,
country=country_code,
alt=orred_regexes,
zero=optional_zero)
else:
final_regex = "{start_anchor}(?P<phone>0*({country}{sep})?{zero}{alt}){end_anchor}".format(
start_anchor=start_anchor,
end_anchor=end_anchor,
sep=separator,
country=country_code,
alt=orred_regexes,
zero=optional_zero)
elif not country_code:
# No Country code given
final_regex = "{start_anchor}(?P<phone>0*({alt})){end_anchor}".format(start_anchor=start_anchor,
end_anchor=end_anchor,
country=country_code,
alt=orred_regexes)
elif country_code:
# Country code given, but optional
final_regex = "{start_anchor}(?P<phone>0*({country}{sep})?{zero}{alt}){end_anchor}".format(
start_anchor=start_anchor,
end_anchor=end_anchor,
country=country_code,
sep=separator,
alt=orred_regexes,
zero=optional_zero)
else:
final_regex = "{start_anchor}(?P<phone>(0*{country}{sep})?{zero}{alt}){end_anchor}".format(
start_anchor=start_anchor,
end_anchor=end_anchor,
sep=separator,
country=country_code,
alt=orred_regexes,
zero=optional_zero)
return re.compile(final_regex)
def _create_reversed_regex(self):
"""
creates reversed regex. first alternative and then prefix.
for example: 794565-03
"""
basic_regexes = []
for index, phone_format in enumerate(self):
current_regex = "(?P<num{i}>\\d{{{min},{max}}})0*{sep}(?P<pre{i}>{prefix})".format(
prefix=phone_format.prefix, sep=OBLIGATED_SEPARATOR,
min=phone_format.min_length, max=phone_format.max_length, i=len(basic_regexes))
basic_regexes.append(current_regex)
return basic_regexes
def _create_regexes(self, is_canonized=True):
"""
Create a regex for every phone format in the list
"""
basic_regexes = []
for phone_format in self:
if is_canonized:
current_regex = "{prefix}\\d{{{min},{max}}}".format(prefix=phone_format.prefix,
min=phone_format.min_length,
max=phone_format.max_length)
else:
current_regex = "{prefix}{sep}(\\d{sep}){{{min},{max}}}\\d".format(prefix=phone_format.prefix,
sep=GENERAL_SEPARATOR,
min=phone_format.min_length - 1,
max=phone_format.max_length - 1)
basic_regexes.append(current_regex)
return basic_regexes
def _or_regexes(self, regexes):
"""
Creates a big regex or-ing between smaller regexes
"""
with_bracks = map(lambda x: "({0})".format(x), regexes) # Add brackets #Only add brackets
regexes_orred = '|'.join(with_bracks)
return "({0})".format(regexes_orred)
def _create_orred_regexes(self, is_canonized=True):
"""
create regexes for all phone formats, and OR them in a big regex
"""
regexes = self._create_regexes(is_canonized)
orred_regexes = self._or_regexes(regexes)
return orred_regexes
def _create_orred_reversed_regexes(self):
"""
create regexes for all reversed phone formats (prefix at end), and OR them in big regex
"""
reversed_regex = self._create_reversed_regex()
orred_regexes = self._or_regexes(reversed_regex)
return orred_regexes
class Phone(object):
def __init__(self, comment='', is_strict=True, is_canonized=True):
self.formats = FormatList(is_strict=is_strict, is_canonized=is_canonized)
self.comment = comment
def add_format(self, phone_format):
"""
Adds PhoneFormat instance
"""
self.formats.append(phone_format)
def _get_abs_min_max(self):
"""
:return: tuple of minimal and maximal length of all formats
"""
min_lengths = [item.min_length for item in self.formats]
max_lengths = [item.max_length for item in self.formats]
return min(min_lengths), max(max_lengths)
def is_valid(self, phone_number, country_code=''):
"""
Checks if phone_number matches any of the current formats.
if no country code is given, it doesnt look for any
"""
phone_regex = self.formats.to_exact_regex(country_code=country_code)
print phone_regex.pattern
match = re.search(phone_regex, phone_number)
if match:
return True
return False
def __unicode__(self):
return unicode(self.comment)
def __repr__(self):
return self.__unicode__()
class CountryPhone(object):
def __init__(self, country='', country_code='', mobile_phone=Phone(), line_phone=Phone(),
is_strict=True, is_canonized=True, phones_dict=None):
self.country = country
self.country_code = country_code
self._is_strict = is_strict
self._is_canonized = is_canonized
if phones_dict:
# init with dict
self.mobile_phone, self.line_phone = self._parse_phones_dict(phones_dict,
is_strict=is_strict,
is_canonized=is_canonized)
else:
# init with each Phone instance
self.mobile_phone = mobile_phone
self.line_phone = line_phone
self.min_length, self.max_length = self._abs_min_max()
def _abs_min_max(self):
"""
:return: absolute min and max lengths
"""
mobile_min, mobile_max = self.mobile_phone._get_abs_min_max()
line_min, line_max = self.line_phone._get_abs_min_max()
return min(mobile_min, line_min), max(mobile_max, line_max)
def is_valid_mobile(self, phone_number, is_strict=True):
"""
checks if phone_number is a valid mobile. strict flag adds mobile country code
"""
if is_strict:
return self.mobile_phone.is_valid(phone_number=phone_number, country_code=self.country_code)
return self.mobile_phone.is_valid(phone_number)
def is_valid_line(self, phone_number, is_strict=True):
"""
checks if phone_number is a valid line. strict flag adds line country code
"""
if is_strict:
return self.line_phone.is_valid(phone_number=phone_number, country_code=self.country_code)
return self.line_phone.is_valid(phone_number)
def is_valid(self, phone_number, is_strict=True):
"""
checks if phone_number is a valid mobile or line number
"""
return self.is_valid_line(phone_number, is_strict) or self.is_valid_mobile(phone_number, is_strict)
def get_phone_formats(self):
formats = self.mobile_phone.formats.copy()
formats.extend(self.line_phone.formats)
return formats
def to_find_regex(self, is_strict=None, is_canonized=None, with_country=True, optional_country=False, stuck_zero=False):
"""
Creates a final compiled regex that will find phone numbers
"""
return self._create_full_regex(absolute_anchors=False, is_strict=is_strict, with_country=with_country,
optional_country=optional_country,
is_canonized=is_canonized, stuck_zero=stuck_zero)
def to_exact_regex(self, is_strict=None, is_canonized=None, with_country=True, optional_country=False, stuck_zero=False):
"""
Creates a final compiled regex that will exactly match phone number (between anchors)
if strict or country_code are given as params, replace they are used instead of self.country_code and self._is_strict
"""
return self._create_full_regex(absolute_anchors=True, is_strict=is_strict, with_country=with_country,
optional_country=optional_country,
is_canonized=is_canonized, stuck_zero=stuck_zero)
def _create_full_regex(self, absolute_anchors=True, is_strict=None, is_canonized=None, with_country=True,
optional_country=False, stuck_zero=False):
"""
:param absolute_anchors: Phone numbers are part of text
:param is_strict: Must have country code
:param with_country: flag to add country code or nor
:param is_canonized: with or without separators
:return: regex of country phone
"""
is_canonized = _stronger_value(self._is_canonized, is_canonized)
is_strict = _stronger_value(self._is_strict, is_strict)
format_list = FormatList(self.get_phone_formats(), country_code=self.country_code,
is_strict=is_strict, is_canonized=is_canonized)
if with_country:
return format_list._create_full_regex(absolute_anchors=absolute_anchors,
is_strict=is_strict,
country_code=self.country_code,
optional_country=optional_country,
is_canonized=is_canonized,
stuck_zero=stuck_zero)
return format_list._create_full_regex(absolute_anchors=absolute_anchors,
is_strict=is_strict,
optional_country=optional_country,
is_canonized=is_canonized,
stuck_zero=stuck_zero)
def _parse_phones_dict(self, phones_dict, is_strict=True, is_canonized=True):
"""
Gets a dict of PhoneFormat instances. parses it to mobile and line phones_dict
return: tuple (mobile_phone, line_phone)
"""
mobile_phone = Phone(comment="{country} - {kind} number".format(country=self.country, kind="mobile"),
is_strict=is_strict,
is_canonized=is_canonized)
line_phone = Phone(comment="{country} - {kind} number".format(country=self.country, kind="line"),
is_strict = is_strict,
is_canonized=is_canonized)
for kind, phone_formats in phones_dict.iteritems():
for phone_format in phone_formats:
if 'mobile' in kind:
mobile_phone.add_format(phone_format)
elif 'line' in kind:
line_phone.add_format(phone_format)
return mobile_phone, line_phone
def __unicode__(self):
return unicode(self.country)
def __repr__(self):
return self.__unicode__()
class PhoneFormat(object):
def __init__(self, prefix, min_length, max_length, comment=''):
"""
Creates a phone format.
prefix: any regex
min_length and max_length: integers
"""
self.prefix = prefix
self.min_length = min_length
self.max_length = max_length
self.comment = comment
def create_israeli_phone(is_strict=True, is_canonized=True):
"""
:return: Instance of israeli phone number
"""
israeli_formats = {
'line': [
PhoneFormat(prefix='[23489]', min_length=7, max_length=7, comment=r'geographic prefixes'),
PhoneFormat(prefix='7', min_length=8, max_length=8, comment=r'non geographic Landline and VoIP')
],
'mobile': [PhoneFormat(prefix='5[^\\D]', min_length=7, max_length=7,
comment=r'55 prefix is for virtual network operators')]
}
return CountryPhone(country='israel', country_code='972', is_strict=is_strict,
is_canonized=is_canonized, phones_dict=israeli_formats)
def create_belgian_phone(is_strict=True, is_canonized=True):
"""
:return: Create instance of belgian phone number
"""
belgian_formats = {
'line': [
PhoneFormat(prefix='[^\\D0]', min_length=7, max_length=7, comment=r'geographic prefixes'),
PhoneFormat(prefix='(70|78|90)', min_length=6, max_length=6,
comment=r'non geographic, mostly services'),
PhoneFormat(prefix='800', min_length=7, max_length=7, comment=r'non geographic, mostly services')
],
'mobile': [PhoneFormat(prefix='4[6789]', min_length=7, max_length=7)]
}
return CountryPhone(country='belgium', country_code='32', is_strict=is_strict,
is_canonized=is_canonized, phones_dict=belgian_formats)
def create_holland_phone(is_strict=True, is_canonized=True):
"""
:return: Create instance of dutch phone number
"""
france_formats = {
'line': [
PhoneFormat(prefix='[12345]', min_length=8, max_length=8, comment=r'geographic prefixes'),
PhoneFormat(prefix='[89]', min_length=6, max_length=6, comment=r'non geographic, mostly services')
],
'mobile': [PhoneFormat(prefix='[67]', min_length=8, max_length=8)]
}
return CountryPhone(country='france', country_code='33', is_strict=is_strict,
is_canonized=is_canonized, phones_dict=france_formats)
def create_all_phones(is_strict=True, is_canonized=True):
"""
:return: dict of all phone formats
"""
phone_formats = {'israel': create_israeli_phone(is_strict, is_canonized),
'belgium': create_belgian_phone(is_strict, is_canonized),
'holland': create_holland_phone(is_strict, is_canonized)}
return phone_formats