Skip to content

Commit 0400292

Browse files
authored
port timezone fixes for time utils (#1)
* port timezone fixes for time utils MycroftAI#209 add to_system utility fix extract_datetime_fr timezone bug MycroftAI#218 fix farsi tests (ignoring timezone due to not being rebased before merge) remove unimplemented farsi code (is_fractional and normalize) split english tests into their own files like the other languages + remove solved TODO comment authored-by: jarbasai <[email protected]>
1 parent 7c3d416 commit 0400292

File tree

8 files changed

+1789
-1624
lines changed

8 files changed

+1789
-1624
lines changed

lingua_franca/lang/parse_fa.py

+16-45
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,11 @@
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
1515
#
16-
import json
17-
from datetime import timedelta
16+
from datetime import datetime, timedelta
1817

19-
from lingua_franca.internal import resolve_resource_file
2018
from lingua_franca.lang.common_data_fa import (_FARSI_BIG, _FARSI_HUNDREDS,
2119
_FARSI_ONES, _FARSI_TENS,
2220
_FORMAL_VARIANT)
23-
from lingua_franca.lang.parse_common import Normalizer
2421
from lingua_franca.time import now_local
2522

2623

@@ -31,6 +28,7 @@ def _is_number(s):
3128
except ValueError:
3229
return False
3330

31+
3432
def _parse_sentence(text):
3533
for key, value in _FORMAL_VARIANT.items():
3634
text = text.replace(key, value)
@@ -39,8 +37,8 @@ def _parse_sentence(text):
3937
current_number = 0
4038
current_words = []
4139
s = 0
42-
step = 10
4340
mode = 'init'
41+
4442
def finish_num():
4543
nonlocal current_number
4644
nonlocal s
@@ -54,13 +52,14 @@ def finish_num():
5452
current_number = 0
5553
current_words = []
5654
mode = 'init'
55+
5756
for x in ar:
5857
if x == "و":
5958
if mode == 'num_ten' or mode == 'num_hundred' or mode == 'num_one':
6059
mode += '_va'
6160
current_words.append(x)
6261
elif mode == 'num':
63-
current_words.append(x)
62+
current_words.append(x)
6463
else:
6564
finish_num()
6665
result.append(x)
@@ -71,7 +70,7 @@ def finish_num():
7170
elif x in _FARSI_ONES:
7271
t = _FARSI_ONES.index(x)
7372
if mode != 'init' and mode != 'num_hundred_va' and mode != 'num':
74-
if not(t < 10 and mode == 'num_ten_va'):
73+
if not (t < 10 and mode == 'num_ten_va'):
7574
finish_num()
7675
current_words.append(x)
7776
s += t
@@ -80,20 +79,20 @@ def finish_num():
8079
if mode != 'init' and mode != 'num_hundred_va' and mode != 'num':
8180
finish_num()
8281
current_words.append(x)
83-
s += _FARSI_TENS.index(x)*10
82+
s += _FARSI_TENS.index(x) * 10
8483
mode = 'num_ten'
8584
elif x in _FARSI_HUNDREDS:
8685
if mode != 'init' and mode != 'num':
8786
finish_num()
8887
current_words.append(x)
89-
s += _FARSI_HUNDREDS.index(x)*100
88+
s += _FARSI_HUNDREDS.index(x) * 100
9089
mode = 'num_hundred'
9190
elif x in _FARSI_BIG:
9291
current_words.append(x)
9392
d = _FARSI_BIG.index(x)
9493
if mode == 'init' and d == 1:
9594
s = 1
96-
s *= 10**(3*d)
95+
s *= 10 ** (3 * d)
9796
current_number += s
9897
s = 0
9998
mode = 'num'
@@ -120,6 +119,7 @@ def finish_num():
120119
'هفته': timedelta(weeks=1),
121120
}
122121

122+
123123
def extract_duration_fa(text):
124124
"""
125125
Convert an english phrase into a number of seconds
@@ -208,9 +208,8 @@ def extract_datetime_fa(text, anchorDate=None, default_time=None):
208208
.replace('سه شنبه', 'سهشنبه') \
209209
.replace('چهار شنبه', 'چهارشنبه') \
210210
.replace('پنج شنبه', 'پنجشنبه') \
211-
.replace('بعد از ظهر', 'بعدازظهر') \
212-
213-
211+
.replace('بعد از ظهر', 'بعدازظهر')
212+
214213
if not anchorDate:
215214
anchorDate = now_local()
216215
today = anchorDate.replace(hour=0, minute=0, second=0, microsecond=0)
@@ -225,11 +224,11 @@ def extract_datetime_fa(text, anchorDate=None, default_time=None):
225224
'یکشنبه',
226225
]
227226
daysDict = {
228-
'پریروز': today + timedelta(days= -2),
229-
'دیروز': today + timedelta(days= -1),
227+
'پریروز': today + timedelta(days=-2),
228+
'دیروز': today + timedelta(days=-1),
230229
'امروز': today,
231-
'فردا': today + timedelta(days= 1),
232-
'پسفردا': today + timedelta(days= 2),
230+
'فردا': today + timedelta(days=1),
231+
'پسفردا': today + timedelta(days=2),
233232
}
234233
timesDict = {
235234
'صبح': timedelta(hours=8),
@@ -307,34 +306,6 @@ def extract_datetime_fa(text, anchorDate=None, default_time=None):
307306
remainder.append(x)
308307
return (result, " ".join(remainder))
309308

310-
def is_fractional_fa(input_str, short_scale=True):
311-
"""
312-
This function takes the given text and checks if it is a fraction.
313-
314-
Args:
315-
input_str (str): the string to check if fractional
316-
short_scale (bool): use short scale if True, long scale if False
317-
Returns:
318-
(bool) or (float): False if not a fraction, otherwise the fraction
319-
320-
"""
321-
if input_str.endswith('s', -1):
322-
input_str = input_str[:len(input_str) - 1] # e.g. "fifths"
323-
324-
fracts = {"whole": 1, "half": 2, "halve": 2, "quarter": 4}
325-
if short_scale:
326-
for num in _SHORT_ORDINAL_FA:
327-
if num > 2:
328-
fracts[_SHORT_ORDINAL_FA[num]] = num
329-
else:
330-
for num in _LONG_ORDINAL_FA:
331-
if num > 2:
332-
fracts[_LONG_ORDINAL_FA[num]] = num
333-
334-
if input_str.lower() in fracts:
335-
return 1.0 / fracts[input_str.lower()]
336-
return False
337-
338309

339310
def extract_numbers_fa(text, short_scale=True, ordinals=False):
340311
"""

lingua_franca/lang/parse_fr.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -944,8 +944,7 @@ def date_found():
944944
if not hasYear:
945945
temp = datetime.strptime(datestr, "%B %d")
946946
if extractedDate.tzinfo:
947-
temp = temp.replace(tzinfo=gettz("UTC"))
948-
temp = temp.astimezone(extractedDate.tzinfo)
947+
temp = temp.replace(tzinfo=extractedDate.tzinfo)
949948
temp = temp.replace(year=extractedDate.year)
950949
if extractedDate < temp:
951950
extractedDate = extractedDate.replace(year=int(currentYear),

lingua_franca/time.py

+22-12
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def now_utc():
4646
Returns:
4747
(datetime): The current time in Universal Time, aka GMT
4848
"""
49-
return to_utc(datetime.utcnow())
49+
return datetime.utcnow().replace(tzinfo=gettz("UTC"))
5050

5151

5252
def now_local(tz=None):
@@ -58,8 +58,7 @@ def now_local(tz=None):
5858
Returns:
5959
(datetime): The current time
6060
"""
61-
if not tz:
62-
tz = default_timezone()
61+
tz = tz or default_timezone()
6362
return datetime.now(tz)
6463

6564

@@ -71,11 +70,10 @@ def to_utc(dt):
7170
Returns:
7271
(datetime): time converted to UTC
7372
"""
74-
tzUTC = gettz("UTC")
75-
if dt.tzinfo:
76-
return dt.astimezone(tzUTC)
77-
else:
78-
return dt.replace(tzinfo=gettz("UTC")).astimezone(tzUTC)
73+
tz = gettz("UTC")
74+
if not dt.tzinfo:
75+
dt = dt.replace(tzinfo=default_timezone())
76+
return dt.astimezone(tz)
7977

8078

8179
def to_local(dt):
@@ -87,8 +85,20 @@ def to_local(dt):
8785
(datetime): time converted to the local timezone
8886
"""
8987
tz = default_timezone()
90-
if dt.tzinfo:
91-
return dt.astimezone(tz)
92-
else:
93-
return dt.replace(tzinfo=gettz("UTC")).astimezone(tz)
88+
if not dt.tzinfo:
89+
dt = dt.replace(tzinfo=default_timezone())
90+
return dt.astimezone(tz)
9491

92+
93+
def to_system(dt):
94+
"""Convert a datetime to the system's local timezone
95+
96+
Args:
97+
dt (datetime): A datetime (if no timezone, assumed to be UTC)
98+
Returns:
99+
(datetime): time converted to the operation system's timezone
100+
"""
101+
tz = tzlocal()
102+
if not dt.tzinfo:
103+
dt = dt.replace(tzinfo=default_timezone())
104+
return dt.astimezone(tz)

0 commit comments

Comments
 (0)