repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
awkman/pywifi
pywifi/iface.py
Interface.connect
python
def connect(self, params): self._logger.info("iface '%s' connects to AP: '%s'", self.name(), params.ssid) self._wifi_ctrl.connect(self._raw_obj, params)
Connect to the specified AP.
train
https://github.com/awkman/pywifi/blob/719baf73d8d32c623dbaf5e9de5d973face152a4/pywifi/iface.py#L95-L101
[ "def name(self):\n \"\"\"\"Get the name of the wifi interfacce.\"\"\"\n\n return self._raw_obj['name']\n" ]
class Interface: """Interface provides methods for manipulating wifi devices.""" """ For encapsulating OS dependent behavior, we declare _raw_obj here for storing some common attribute (e.g. name) and os attributes (e.g. dbus objects for linux) """ _raw_obj = {} _wifi_ctrl = {} _logger = None def __init__(self, raw_obj): self._raw_obj = raw_obj self._wifi_ctrl = wifiutil.WifiUtil() self._logger = logging.getLogger('pywifi') def name(self): """"Get the name of the wifi interfacce.""" return self._raw_obj['name'] def scan(self): """Trigger the wifi interface to scan.""" self._logger.info("iface '%s' scans", self.name()) self._wifi_ctrl.scan(self._raw_obj) def scan_results(self): """Return the scan result.""" bsses = self._wifi_ctrl.scan_results(self._raw_obj) if self._logger.isEnabledFor(logging.INFO): for bss in bsses: self._logger.info("Find bss:") self._logger.info("\tbssid: %s", bss.bssid) self._logger.info("\tssid: %s", bss.ssid) self._logger.info("\tfreq: %d", bss.freq) self._logger.info("\tauth: %s", bss.auth) self._logger.info("\takm: %s", bss.akm) self._logger.info("\tsignal: %d", bss.signal) return bsses def add_network_profile(self, params): """Add the info of the AP for connecting afterward.""" return self._wifi_ctrl.add_network_profile(self._raw_obj, params) def remove_network_profile(self, params): """Remove the specified AP settings.""" self._wifi_ctrl.remove_network_profile(self._raw_obj, params) def remove_all_network_profiles(self): """Remove all the AP settings.""" self._wifi_ctrl.remove_all_network_profiles(self._raw_obj) def network_profiles(self): """Get all the AP profiles.""" profiles = self._wifi_ctrl.network_profiles(self._raw_obj) if self._logger.isEnabledFor(logging.INFO): for profile in profiles: self._logger.info("Get profile:") self._logger.info("\tssid: %s", profile.ssid) self._logger.info("\tauth: %s", profile.auth) self._logger.info("\takm: %s", profile.akm) self._logger.info("\tcipher: %s", profile.cipher) return profiles def disconnect(self): """Disconnect from the specified AP.""" self._logger.info("iface '%s' disconnects", self.name()) self._wifi_ctrl.disconnect(self._raw_obj) def status(self): """Get the status of the wifi interface.""" return self._wifi_ctrl.status(self._raw_obj)
awkman/pywifi
pywifi/iface.py
Interface.disconnect
python
def disconnect(self): self._logger.info("iface '%s' disconnects", self.name()) self._wifi_ctrl.disconnect(self._raw_obj)
Disconnect from the specified AP.
train
https://github.com/awkman/pywifi/blob/719baf73d8d32c623dbaf5e9de5d973face152a4/pywifi/iface.py#L103-L108
[ "def name(self):\n \"\"\"\"Get the name of the wifi interfacce.\"\"\"\n\n return self._raw_obj['name']\n" ]
class Interface: """Interface provides methods for manipulating wifi devices.""" """ For encapsulating OS dependent behavior, we declare _raw_obj here for storing some common attribute (e.g. name) and os attributes (e.g. dbus objects for linux) """ _raw_obj = {} _wifi_ctrl = {} _logger = None def __init__(self, raw_obj): self._raw_obj = raw_obj self._wifi_ctrl = wifiutil.WifiUtil() self._logger = logging.getLogger('pywifi') def name(self): """"Get the name of the wifi interfacce.""" return self._raw_obj['name'] def scan(self): """Trigger the wifi interface to scan.""" self._logger.info("iface '%s' scans", self.name()) self._wifi_ctrl.scan(self._raw_obj) def scan_results(self): """Return the scan result.""" bsses = self._wifi_ctrl.scan_results(self._raw_obj) if self._logger.isEnabledFor(logging.INFO): for bss in bsses: self._logger.info("Find bss:") self._logger.info("\tbssid: %s", bss.bssid) self._logger.info("\tssid: %s", bss.ssid) self._logger.info("\tfreq: %d", bss.freq) self._logger.info("\tauth: %s", bss.auth) self._logger.info("\takm: %s", bss.akm) self._logger.info("\tsignal: %d", bss.signal) return bsses def add_network_profile(self, params): """Add the info of the AP for connecting afterward.""" return self._wifi_ctrl.add_network_profile(self._raw_obj, params) def remove_network_profile(self, params): """Remove the specified AP settings.""" self._wifi_ctrl.remove_network_profile(self._raw_obj, params) def remove_all_network_profiles(self): """Remove all the AP settings.""" self._wifi_ctrl.remove_all_network_profiles(self._raw_obj) def network_profiles(self): """Get all the AP profiles.""" profiles = self._wifi_ctrl.network_profiles(self._raw_obj) if self._logger.isEnabledFor(logging.INFO): for profile in profiles: self._logger.info("Get profile:") self._logger.info("\tssid: %s", profile.ssid) self._logger.info("\tauth: %s", profile.auth) self._logger.info("\takm: %s", profile.akm) self._logger.info("\tcipher: %s", profile.cipher) return profiles def connect(self, params): """Connect to the specified AP.""" self._logger.info("iface '%s' connects to AP: '%s'", self.name(), params.ssid) self._wifi_ctrl.connect(self._raw_obj, params) def status(self): """Get the status of the wifi interface.""" return self._wifi_ctrl.status(self._raw_obj)
MacHu-GWU/rolex-project
rolex/math.py
add_seconds
python
def add_seconds(datetime_like_object, n, return_date=False): a_datetime = parser.parse_datetime(datetime_like_object) a_datetime = a_datetime + timedelta(seconds=n) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime
Returns a time that n seconds after a time. :param datetimestr: a datetime object or a datetime str :param n: number of seconds, value can be negative **中文文档** 返回给定日期N秒之后的时间。
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/math.py#L12-L28
[ "def parse_datetime(self, value):\n \"\"\"\n A lazy method to parse anything to datetime.\n\n If input data type is:\n\n - string: parse datetime from it\n - integer: use from ordinal\n - date: use date part and set hour, minute, second to zero\n - datetime: just return it\n \"\"\"\n if i...
# -*- coding: utf-8 -*- from collections import OrderedDict from datetime import datetime, timedelta try: from .parse import parser except: # pragma: no cover from rolex.parse import parser # --- Calculator --- def add_minutes(datetime_like_object, n, return_date=False): """ Returns a time that n minutes after a time. :param datetimestr: a datetime object or a datetime str :param n: number of minutes, value can be negative **中文文档** 返回给定日期N分钟之后的时间。 """ return add_seconds(datetime_like_object, n * 60, return_date) def add_hours(datetime_like_object, n, return_date=False): """ Returns a time that n hours after a time. :param datetimestr: a datetime object or a datetime str :param n: number of hours, value can be negative **中文文档** 返回给定日期N小时之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60, return_date) def add_days(datetime_like_object, n, return_date=False): """ Returns a time that n days after a time. :param datetimestr: a datetime object or a datetime str :param n: number of days, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N天之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60 * 24, return_date) def add_weeks(datetime_like_object, n, return_date=False): """ Returns a time that n weeks after a time. :param datetimestr: a datetime object or a datetime str :param n: number of weeks, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N周之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60 * 24 * 7, return_date) def add_months(datetime_like_object, n, return_date=False): """ Returns a time that n months after a time. Notice: for example, the date that one month after 2015-01-31 supposed to be 2015-02-31. But there's no 31th in Feb, so we fix that value to 2015-02-28. :param datetimestr: a datetime object or a datetime str :param n: number of months, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N月之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) month_from_ordinary = a_datetime.year * 12 + a_datetime.month month_from_ordinary += n year, month = divmod(month_from_ordinary, 12) # try assign year, month, day try: a_datetime = datetime( year, month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) # 肯定是由于新的月份的日子不够, 所以肯定是月底, # 那么直接跳到下一个月的第一天, 再回退一天 except ValueError: month_from_ordinary += 1 year, month = divmod(month_from_ordinary, 12) a_datetime = datetime( year, month, 1, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) a_datetime = add_days(a_datetime, -1) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime def add_years(datetime_like_object, n, return_date=False): """ Returns a time that n years after a time. :param datetimestr: a datetime object or a datetime str :param n: number of years, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N年之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) # try assign year, month, day try: a_datetime = datetime( a_datetime.year + n, a_datetime.month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) except ValueError: # Must be xxxx-02-29 a_datetime = datetime( a_datetime.year + n, 2, 28, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime def _floor_to(dt, hour, minute, second): """ Route the given datetime to the latest time with the hour, minute, second before it. """ new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt <= dt: return new_dt else: return new_dt - timedelta(days=1) def _ceiling_to(dt, hour, minute, second): """ Route the given datetime to the earliest time with the hour, minute, second after it. """ new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt >= dt: return new_dt else: return new_dt + timedelta(days=1) def _round_to(dt, hour, minute, second): """ Route the given datetime to the latest time with the hour, minute, second before it. """ new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt == dt: return new_dt elif new_dt < dt: before = new_dt after = new_dt + timedelta(days=1) elif new_dt > dt: before = new_dt - timedelta(days=1) after = new_dt d1 = dt - before d2 = after - dt if d1 < d2: return before elif d1 > d2: return after else: return before _round_to_options = OrderedDict([ ("floor", _floor_to), ("ceiling", _ceiling_to), ("round", _round_to), ]) def round_to(dt, hour, minute, second, mode="round"): """ Round the given datetime to specified hour, minute and second. :param mode: 'floor' or 'ceiling' .. versionadded:: 0.0.5 message **中文文档** 将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。 """ mode = mode.lower() if mode not in _round_to_options: raise ValueError( "'mode' has to be one of %r!" % list(_round_to_options.keys())) return _round_to_options[mode](dt, hour, minute, second)
MacHu-GWU/rolex-project
rolex/math.py
add_months
python
def add_months(datetime_like_object, n, return_date=False): a_datetime = parser.parse_datetime(datetime_like_object) month_from_ordinary = a_datetime.year * 12 + a_datetime.month month_from_ordinary += n year, month = divmod(month_from_ordinary, 12) # try assign year, month, day try: a_datetime = datetime( year, month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) # 肯定是由于新的月份的日子不够, 所以肯定是月底, # 那么直接跳到下一个月的第一天, 再回退一天 except ValueError: month_from_ordinary += 1 year, month = divmod(month_from_ordinary, 12) a_datetime = datetime( year, month, 1, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) a_datetime = add_days(a_datetime, -1) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime
Returns a time that n months after a time. Notice: for example, the date that one month after 2015-01-31 supposed to be 2015-02-31. But there's no 31th in Feb, so we fix that value to 2015-02-28. :param datetimestr: a datetime object or a datetime str :param n: number of months, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N月之后的时间。
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/math.py#L89-L132
[ "def add_days(datetime_like_object, n, return_date=False):\n \"\"\"\n Returns a time that n days after a time.\n\n :param datetimestr: a datetime object or a datetime str\n :param n: number of days, value can be negative\n :param return_date: returns a date object instead of datetime\n\n **中文文档**\...
# -*- coding: utf-8 -*- from collections import OrderedDict from datetime import datetime, timedelta try: from .parse import parser except: # pragma: no cover from rolex.parse import parser # --- Calculator --- def add_seconds(datetime_like_object, n, return_date=False): """ Returns a time that n seconds after a time. :param datetimestr: a datetime object or a datetime str :param n: number of seconds, value can be negative **中文文档** 返回给定日期N秒之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) a_datetime = a_datetime + timedelta(seconds=n) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime def add_minutes(datetime_like_object, n, return_date=False): """ Returns a time that n minutes after a time. :param datetimestr: a datetime object or a datetime str :param n: number of minutes, value can be negative **中文文档** 返回给定日期N分钟之后的时间。 """ return add_seconds(datetime_like_object, n * 60, return_date) def add_hours(datetime_like_object, n, return_date=False): """ Returns a time that n hours after a time. :param datetimestr: a datetime object or a datetime str :param n: number of hours, value can be negative **中文文档** 返回给定日期N小时之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60, return_date) def add_days(datetime_like_object, n, return_date=False): """ Returns a time that n days after a time. :param datetimestr: a datetime object or a datetime str :param n: number of days, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N天之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60 * 24, return_date) def add_weeks(datetime_like_object, n, return_date=False): """ Returns a time that n weeks after a time. :param datetimestr: a datetime object or a datetime str :param n: number of weeks, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N周之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60 * 24 * 7, return_date) def add_years(datetime_like_object, n, return_date=False): """ Returns a time that n years after a time. :param datetimestr: a datetime object or a datetime str :param n: number of years, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N年之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) # try assign year, month, day try: a_datetime = datetime( a_datetime.year + n, a_datetime.month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) except ValueError: # Must be xxxx-02-29 a_datetime = datetime( a_datetime.year + n, 2, 28, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime def _floor_to(dt, hour, minute, second): """ Route the given datetime to the latest time with the hour, minute, second before it. """ new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt <= dt: return new_dt else: return new_dt - timedelta(days=1) def _ceiling_to(dt, hour, minute, second): """ Route the given datetime to the earliest time with the hour, minute, second after it. """ new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt >= dt: return new_dt else: return new_dt + timedelta(days=1) def _round_to(dt, hour, minute, second): """ Route the given datetime to the latest time with the hour, minute, second before it. """ new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt == dt: return new_dt elif new_dt < dt: before = new_dt after = new_dt + timedelta(days=1) elif new_dt > dt: before = new_dt - timedelta(days=1) after = new_dt d1 = dt - before d2 = after - dt if d1 < d2: return before elif d1 > d2: return after else: return before _round_to_options = OrderedDict([ ("floor", _floor_to), ("ceiling", _ceiling_to), ("round", _round_to), ]) def round_to(dt, hour, minute, second, mode="round"): """ Round the given datetime to specified hour, minute and second. :param mode: 'floor' or 'ceiling' .. versionadded:: 0.0.5 message **中文文档** 将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。 """ mode = mode.lower() if mode not in _round_to_options: raise ValueError( "'mode' has to be one of %r!" % list(_round_to_options.keys())) return _round_to_options[mode](dt, hour, minute, second)
MacHu-GWU/rolex-project
rolex/math.py
add_years
python
def add_years(datetime_like_object, n, return_date=False): a_datetime = parser.parse_datetime(datetime_like_object) # try assign year, month, day try: a_datetime = datetime( a_datetime.year + n, a_datetime.month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) except ValueError: # Must be xxxx-02-29 a_datetime = datetime( a_datetime.year + n, 2, 28, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime
Returns a time that n years after a time. :param datetimestr: a datetime object or a datetime str :param n: number of years, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N年之后的时间。
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/math.py#L135-L165
[ "def parse_datetime(self, value):\n \"\"\"\n A lazy method to parse anything to datetime.\n\n If input data type is:\n\n - string: parse datetime from it\n - integer: use from ordinal\n - date: use date part and set hour, minute, second to zero\n - datetime: just return it\n \"\"\"\n if i...
# -*- coding: utf-8 -*- from collections import OrderedDict from datetime import datetime, timedelta try: from .parse import parser except: # pragma: no cover from rolex.parse import parser # --- Calculator --- def add_seconds(datetime_like_object, n, return_date=False): """ Returns a time that n seconds after a time. :param datetimestr: a datetime object or a datetime str :param n: number of seconds, value can be negative **中文文档** 返回给定日期N秒之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) a_datetime = a_datetime + timedelta(seconds=n) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime def add_minutes(datetime_like_object, n, return_date=False): """ Returns a time that n minutes after a time. :param datetimestr: a datetime object or a datetime str :param n: number of minutes, value can be negative **中文文档** 返回给定日期N分钟之后的时间。 """ return add_seconds(datetime_like_object, n * 60, return_date) def add_hours(datetime_like_object, n, return_date=False): """ Returns a time that n hours after a time. :param datetimestr: a datetime object or a datetime str :param n: number of hours, value can be negative **中文文档** 返回给定日期N小时之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60, return_date) def add_days(datetime_like_object, n, return_date=False): """ Returns a time that n days after a time. :param datetimestr: a datetime object or a datetime str :param n: number of days, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N天之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60 * 24, return_date) def add_weeks(datetime_like_object, n, return_date=False): """ Returns a time that n weeks after a time. :param datetimestr: a datetime object or a datetime str :param n: number of weeks, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N周之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60 * 24 * 7, return_date) def add_months(datetime_like_object, n, return_date=False): """ Returns a time that n months after a time. Notice: for example, the date that one month after 2015-01-31 supposed to be 2015-02-31. But there's no 31th in Feb, so we fix that value to 2015-02-28. :param datetimestr: a datetime object or a datetime str :param n: number of months, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N月之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) month_from_ordinary = a_datetime.year * 12 + a_datetime.month month_from_ordinary += n year, month = divmod(month_from_ordinary, 12) # try assign year, month, day try: a_datetime = datetime( year, month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) # 肯定是由于新的月份的日子不够, 所以肯定是月底, # 那么直接跳到下一个月的第一天, 再回退一天 except ValueError: month_from_ordinary += 1 year, month = divmod(month_from_ordinary, 12) a_datetime = datetime( year, month, 1, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) a_datetime = add_days(a_datetime, -1) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime def _floor_to(dt, hour, minute, second): """ Route the given datetime to the latest time with the hour, minute, second before it. """ new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt <= dt: return new_dt else: return new_dt - timedelta(days=1) def _ceiling_to(dt, hour, minute, second): """ Route the given datetime to the earliest time with the hour, minute, second after it. """ new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt >= dt: return new_dt else: return new_dt + timedelta(days=1) def _round_to(dt, hour, minute, second): """ Route the given datetime to the latest time with the hour, minute, second before it. """ new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt == dt: return new_dt elif new_dt < dt: before = new_dt after = new_dt + timedelta(days=1) elif new_dt > dt: before = new_dt - timedelta(days=1) after = new_dt d1 = dt - before d2 = after - dt if d1 < d2: return before elif d1 > d2: return after else: return before _round_to_options = OrderedDict([ ("floor", _floor_to), ("ceiling", _ceiling_to), ("round", _round_to), ]) def round_to(dt, hour, minute, second, mode="round"): """ Round the given datetime to specified hour, minute and second. :param mode: 'floor' or 'ceiling' .. versionadded:: 0.0.5 message **中文文档** 将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。 """ mode = mode.lower() if mode not in _round_to_options: raise ValueError( "'mode' has to be one of %r!" % list(_round_to_options.keys())) return _round_to_options[mode](dt, hour, minute, second)
MacHu-GWU/rolex-project
rolex/math.py
_floor_to
python
def _floor_to(dt, hour, minute, second): new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt <= dt: return new_dt else: return new_dt - timedelta(days=1)
Route the given datetime to the latest time with the hour, minute, second before it.
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/math.py#L168-L177
null
# -*- coding: utf-8 -*- from collections import OrderedDict from datetime import datetime, timedelta try: from .parse import parser except: # pragma: no cover from rolex.parse import parser # --- Calculator --- def add_seconds(datetime_like_object, n, return_date=False): """ Returns a time that n seconds after a time. :param datetimestr: a datetime object or a datetime str :param n: number of seconds, value can be negative **中文文档** 返回给定日期N秒之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) a_datetime = a_datetime + timedelta(seconds=n) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime def add_minutes(datetime_like_object, n, return_date=False): """ Returns a time that n minutes after a time. :param datetimestr: a datetime object or a datetime str :param n: number of minutes, value can be negative **中文文档** 返回给定日期N分钟之后的时间。 """ return add_seconds(datetime_like_object, n * 60, return_date) def add_hours(datetime_like_object, n, return_date=False): """ Returns a time that n hours after a time. :param datetimestr: a datetime object or a datetime str :param n: number of hours, value can be negative **中文文档** 返回给定日期N小时之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60, return_date) def add_days(datetime_like_object, n, return_date=False): """ Returns a time that n days after a time. :param datetimestr: a datetime object or a datetime str :param n: number of days, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N天之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60 * 24, return_date) def add_weeks(datetime_like_object, n, return_date=False): """ Returns a time that n weeks after a time. :param datetimestr: a datetime object or a datetime str :param n: number of weeks, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N周之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60 * 24 * 7, return_date) def add_months(datetime_like_object, n, return_date=False): """ Returns a time that n months after a time. Notice: for example, the date that one month after 2015-01-31 supposed to be 2015-02-31. But there's no 31th in Feb, so we fix that value to 2015-02-28. :param datetimestr: a datetime object or a datetime str :param n: number of months, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N月之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) month_from_ordinary = a_datetime.year * 12 + a_datetime.month month_from_ordinary += n year, month = divmod(month_from_ordinary, 12) # try assign year, month, day try: a_datetime = datetime( year, month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) # 肯定是由于新的月份的日子不够, 所以肯定是月底, # 那么直接跳到下一个月的第一天, 再回退一天 except ValueError: month_from_ordinary += 1 year, month = divmod(month_from_ordinary, 12) a_datetime = datetime( year, month, 1, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) a_datetime = add_days(a_datetime, -1) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime def add_years(datetime_like_object, n, return_date=False): """ Returns a time that n years after a time. :param datetimestr: a datetime object or a datetime str :param n: number of years, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N年之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) # try assign year, month, day try: a_datetime = datetime( a_datetime.year + n, a_datetime.month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) except ValueError: # Must be xxxx-02-29 a_datetime = datetime( a_datetime.year + n, 2, 28, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime def _ceiling_to(dt, hour, minute, second): """ Route the given datetime to the earliest time with the hour, minute, second after it. """ new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt >= dt: return new_dt else: return new_dt + timedelta(days=1) def _round_to(dt, hour, minute, second): """ Route the given datetime to the latest time with the hour, minute, second before it. """ new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt == dt: return new_dt elif new_dt < dt: before = new_dt after = new_dt + timedelta(days=1) elif new_dt > dt: before = new_dt - timedelta(days=1) after = new_dt d1 = dt - before d2 = after - dt if d1 < d2: return before elif d1 > d2: return after else: return before _round_to_options = OrderedDict([ ("floor", _floor_to), ("ceiling", _ceiling_to), ("round", _round_to), ]) def round_to(dt, hour, minute, second, mode="round"): """ Round the given datetime to specified hour, minute and second. :param mode: 'floor' or 'ceiling' .. versionadded:: 0.0.5 message **中文文档** 将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。 """ mode = mode.lower() if mode not in _round_to_options: raise ValueError( "'mode' has to be one of %r!" % list(_round_to_options.keys())) return _round_to_options[mode](dt, hour, minute, second)
MacHu-GWU/rolex-project
rolex/math.py
_round_to
python
def _round_to(dt, hour, minute, second): new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt == dt: return new_dt elif new_dt < dt: before = new_dt after = new_dt + timedelta(days=1) elif new_dt > dt: before = new_dt - timedelta(days=1) after = new_dt d1 = dt - before d2 = after - dt if d1 < d2: return before elif d1 > d2: return after else: return before
Route the given datetime to the latest time with the hour, minute, second before it.
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/math.py#L192-L215
null
# -*- coding: utf-8 -*- from collections import OrderedDict from datetime import datetime, timedelta try: from .parse import parser except: # pragma: no cover from rolex.parse import parser # --- Calculator --- def add_seconds(datetime_like_object, n, return_date=False): """ Returns a time that n seconds after a time. :param datetimestr: a datetime object or a datetime str :param n: number of seconds, value can be negative **中文文档** 返回给定日期N秒之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) a_datetime = a_datetime + timedelta(seconds=n) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime def add_minutes(datetime_like_object, n, return_date=False): """ Returns a time that n minutes after a time. :param datetimestr: a datetime object or a datetime str :param n: number of minutes, value can be negative **中文文档** 返回给定日期N分钟之后的时间。 """ return add_seconds(datetime_like_object, n * 60, return_date) def add_hours(datetime_like_object, n, return_date=False): """ Returns a time that n hours after a time. :param datetimestr: a datetime object or a datetime str :param n: number of hours, value can be negative **中文文档** 返回给定日期N小时之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60, return_date) def add_days(datetime_like_object, n, return_date=False): """ Returns a time that n days after a time. :param datetimestr: a datetime object or a datetime str :param n: number of days, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N天之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60 * 24, return_date) def add_weeks(datetime_like_object, n, return_date=False): """ Returns a time that n weeks after a time. :param datetimestr: a datetime object or a datetime str :param n: number of weeks, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N周之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60 * 24 * 7, return_date) def add_months(datetime_like_object, n, return_date=False): """ Returns a time that n months after a time. Notice: for example, the date that one month after 2015-01-31 supposed to be 2015-02-31. But there's no 31th in Feb, so we fix that value to 2015-02-28. :param datetimestr: a datetime object or a datetime str :param n: number of months, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N月之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) month_from_ordinary = a_datetime.year * 12 + a_datetime.month month_from_ordinary += n year, month = divmod(month_from_ordinary, 12) # try assign year, month, day try: a_datetime = datetime( year, month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) # 肯定是由于新的月份的日子不够, 所以肯定是月底, # 那么直接跳到下一个月的第一天, 再回退一天 except ValueError: month_from_ordinary += 1 year, month = divmod(month_from_ordinary, 12) a_datetime = datetime( year, month, 1, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) a_datetime = add_days(a_datetime, -1) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime def add_years(datetime_like_object, n, return_date=False): """ Returns a time that n years after a time. :param datetimestr: a datetime object or a datetime str :param n: number of years, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N年之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) # try assign year, month, day try: a_datetime = datetime( a_datetime.year + n, a_datetime.month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) except ValueError: # Must be xxxx-02-29 a_datetime = datetime( a_datetime.year + n, 2, 28, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime def _floor_to(dt, hour, minute, second): """ Route the given datetime to the latest time with the hour, minute, second before it. """ new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt <= dt: return new_dt else: return new_dt - timedelta(days=1) def _ceiling_to(dt, hour, minute, second): """ Route the given datetime to the earliest time with the hour, minute, second after it. """ new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt >= dt: return new_dt else: return new_dt + timedelta(days=1) _round_to_options = OrderedDict([ ("floor", _floor_to), ("ceiling", _ceiling_to), ("round", _round_to), ]) def round_to(dt, hour, minute, second, mode="round"): """ Round the given datetime to specified hour, minute and second. :param mode: 'floor' or 'ceiling' .. versionadded:: 0.0.5 message **中文文档** 将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。 """ mode = mode.lower() if mode not in _round_to_options: raise ValueError( "'mode' has to be one of %r!" % list(_round_to_options.keys())) return _round_to_options[mode](dt, hour, minute, second)
MacHu-GWU/rolex-project
rolex/math.py
round_to
python
def round_to(dt, hour, minute, second, mode="round"): mode = mode.lower() if mode not in _round_to_options: raise ValueError( "'mode' has to be one of %r!" % list(_round_to_options.keys())) return _round_to_options[mode](dt, hour, minute, second)
Round the given datetime to specified hour, minute and second. :param mode: 'floor' or 'ceiling' .. versionadded:: 0.0.5 message **中文文档** 将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/math.py#L225-L244
null
# -*- coding: utf-8 -*- from collections import OrderedDict from datetime import datetime, timedelta try: from .parse import parser except: # pragma: no cover from rolex.parse import parser # --- Calculator --- def add_seconds(datetime_like_object, n, return_date=False): """ Returns a time that n seconds after a time. :param datetimestr: a datetime object or a datetime str :param n: number of seconds, value can be negative **中文文档** 返回给定日期N秒之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) a_datetime = a_datetime + timedelta(seconds=n) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime def add_minutes(datetime_like_object, n, return_date=False): """ Returns a time that n minutes after a time. :param datetimestr: a datetime object or a datetime str :param n: number of minutes, value can be negative **中文文档** 返回给定日期N分钟之后的时间。 """ return add_seconds(datetime_like_object, n * 60, return_date) def add_hours(datetime_like_object, n, return_date=False): """ Returns a time that n hours after a time. :param datetimestr: a datetime object or a datetime str :param n: number of hours, value can be negative **中文文档** 返回给定日期N小时之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60, return_date) def add_days(datetime_like_object, n, return_date=False): """ Returns a time that n days after a time. :param datetimestr: a datetime object or a datetime str :param n: number of days, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N天之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60 * 24, return_date) def add_weeks(datetime_like_object, n, return_date=False): """ Returns a time that n weeks after a time. :param datetimestr: a datetime object or a datetime str :param n: number of weeks, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N周之后的时间。 """ return add_seconds(datetime_like_object, n * 60 * 60 * 24 * 7, return_date) def add_months(datetime_like_object, n, return_date=False): """ Returns a time that n months after a time. Notice: for example, the date that one month after 2015-01-31 supposed to be 2015-02-31. But there's no 31th in Feb, so we fix that value to 2015-02-28. :param datetimestr: a datetime object or a datetime str :param n: number of months, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N月之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) month_from_ordinary = a_datetime.year * 12 + a_datetime.month month_from_ordinary += n year, month = divmod(month_from_ordinary, 12) # try assign year, month, day try: a_datetime = datetime( year, month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) # 肯定是由于新的月份的日子不够, 所以肯定是月底, # 那么直接跳到下一个月的第一天, 再回退一天 except ValueError: month_from_ordinary += 1 year, month = divmod(month_from_ordinary, 12) a_datetime = datetime( year, month, 1, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) a_datetime = add_days(a_datetime, -1) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime def add_years(datetime_like_object, n, return_date=False): """ Returns a time that n years after a time. :param datetimestr: a datetime object or a datetime str :param n: number of years, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N年之后的时间。 """ a_datetime = parser.parse_datetime(datetime_like_object) # try assign year, month, day try: a_datetime = datetime( a_datetime.year + n, a_datetime.month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) except ValueError: # Must be xxxx-02-29 a_datetime = datetime( a_datetime.year + n, 2, 28, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime def _floor_to(dt, hour, minute, second): """ Route the given datetime to the latest time with the hour, minute, second before it. """ new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt <= dt: return new_dt else: return new_dt - timedelta(days=1) def _ceiling_to(dt, hour, minute, second): """ Route the given datetime to the earliest time with the hour, minute, second after it. """ new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt >= dt: return new_dt else: return new_dt + timedelta(days=1) def _round_to(dt, hour, minute, second): """ Route the given datetime to the latest time with the hour, minute, second before it. """ new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt == dt: return new_dt elif new_dt < dt: before = new_dt after = new_dt + timedelta(days=1) elif new_dt > dt: before = new_dt - timedelta(days=1) after = new_dt d1 = dt - before d2 = after - dt if d1 < d2: return before elif d1 > d2: return after else: return before _round_to_options = OrderedDict([ ("floor", _floor_to), ("ceiling", _ceiling_to), ("round", _round_to), ])
MacHu-GWU/rolex-project
rolex/parse.py
Parser.str2date
python
def str2date(self, date_str): # try default date template try: a_datetime = datetime.strptime( date_str, self._default_date_template) return a_datetime.date() except: pass # try every date templates for template in date_template_list: try: a_datetime = datetime.strptime(date_str, template) self._default_date_template = template return a_datetime.date() except: pass # raise error raise ValueError("Unable to parse date from: %r!" % date_str)
Parse date from string. If there's no template matches your string, Please go https://github.com/MacHu-GWU/rolex-project/issues submit your datetime string. I 'll update templates ASAP. This method is faster than :meth:`dateutil.parser.parse`. :param date_str: a string represent a date :type date_str: str :return: a date object **中文文档** 从string解析date。首先尝试默认模板, 如果失败了, 则尝试所有的模板。 一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的 字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。 该方法要快过 :meth:`dateutil.parser.parse` 方法。
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/parse.py#L129-L168
null
class Parser(object): """ datetime string parser. """ _default_date_template = date_template_list[0] _default_datetime_template = datetime_template_list[0] # --- Parse datetime --- def _str2datetime(self, datetime_str): """ Parse datetime from string. If there's no template matches your string, Please go https://github.com/MacHu-GWU/rolex-project/issues submit your datetime string. I 'll update templates ASAP. This method is faster than :meth:`dateutil.parser.parse`. :param datetime_str: a string represent a datetime :type datetime_str: str :return: a datetime object **中文文档** 从string解析datetime。首先尝试默认模板, 如果失败了, 则尝试所有的模板。 一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的 字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。 该方法要快过 :meth:`dateutil.parser.parse` 方法。 为了防止模板库失败的情况, 程序设定在失败后自动一直启用 :meth:`dateutil.parser.parse` 进行解析。你可以调用 :meth:`Parser.reset()` 方法恢复默认设定。 """ # try default datetime template try: a_datetime = datetime.strptime( datetime_str, self._default_datetime_template) return a_datetime except: pass # try every datetime templates for template in datetime_template_list: try: a_datetime = datetime.strptime(datetime_str, template) self._default_datetime_template = template return a_datetime except: pass # raise error a_datetime = parse(datetime_str) self.str2datetime = parse return a_datetime str2datetime = _str2datetime def reset(self): """ Reset :class:`Parser` behavior to default. """ self.str2datetime = self._str2datetime def parse_date(self, value): """ A lazy method to parse anything to date. If input data type is: - string: parse date from it - integer: use from ordinal - datetime: use date part - date: just return it """ if isinstance(value, sixmini.string_types): return self.str2date(value) elif value is None: raise TypeError("Unable to parse date from %r" % value) elif isinstance(value, sixmini.integer_types): return date.fromordinal(value) elif isinstance(value, datetime): return value.date() elif isinstance(value, date): return value else: raise ValueError("Unable to parse date from %r" % value) def parse_datetime(self, value): """ A lazy method to parse anything to datetime. If input data type is: - string: parse datetime from it - integer: use from ordinal - date: use date part and set hour, minute, second to zero - datetime: just return it """ if isinstance(value, sixmini.string_types): return self.str2datetime(value) elif value is None: raise TypeError("Unable to parse datetime from %r" % value) elif isinstance(value, sixmini.integer_types): return from_utctimestamp(value) elif isinstance(value, float): return from_utctimestamp(value) elif isinstance(value, datetime): return value elif isinstance(value, date): return datetime(value.year, value.month, value.day) else: raise ValueError("Unable to parse datetime from %r" % value)
MacHu-GWU/rolex-project
rolex/parse.py
Parser._str2datetime
python
def _str2datetime(self, datetime_str): # try default datetime template try: a_datetime = datetime.strptime( datetime_str, self._default_datetime_template) return a_datetime except: pass # try every datetime templates for template in datetime_template_list: try: a_datetime = datetime.strptime(datetime_str, template) self._default_datetime_template = template return a_datetime except: pass # raise error a_datetime = parse(datetime_str) self.str2datetime = parse return a_datetime
Parse datetime from string. If there's no template matches your string, Please go https://github.com/MacHu-GWU/rolex-project/issues submit your datetime string. I 'll update templates ASAP. This method is faster than :meth:`dateutil.parser.parse`. :param datetime_str: a string represent a datetime :type datetime_str: str :return: a datetime object **中文文档** 从string解析datetime。首先尝试默认模板, 如果失败了, 则尝试所有的模板。 一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的 字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。 该方法要快过 :meth:`dateutil.parser.parse` 方法。 为了防止模板库失败的情况, 程序设定在失败后自动一直启用 :meth:`dateutil.parser.parse` 进行解析。你可以调用 :meth:`Parser.reset()` 方法恢复默认设定。
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/parse.py#L170-L216
null
class Parser(object): """ datetime string parser. """ _default_date_template = date_template_list[0] _default_datetime_template = datetime_template_list[0] # --- Parse datetime --- def str2date(self, date_str): """ Parse date from string. If there's no template matches your string, Please go https://github.com/MacHu-GWU/rolex-project/issues submit your datetime string. I 'll update templates ASAP. This method is faster than :meth:`dateutil.parser.parse`. :param date_str: a string represent a date :type date_str: str :return: a date object **中文文档** 从string解析date。首先尝试默认模板, 如果失败了, 则尝试所有的模板。 一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的 字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。 该方法要快过 :meth:`dateutil.parser.parse` 方法。 """ # try default date template try: a_datetime = datetime.strptime( date_str, self._default_date_template) return a_datetime.date() except: pass # try every date templates for template in date_template_list: try: a_datetime = datetime.strptime(date_str, template) self._default_date_template = template return a_datetime.date() except: pass # raise error raise ValueError("Unable to parse date from: %r!" % date_str) str2datetime = _str2datetime def reset(self): """ Reset :class:`Parser` behavior to default. """ self.str2datetime = self._str2datetime def parse_date(self, value): """ A lazy method to parse anything to date. If input data type is: - string: parse date from it - integer: use from ordinal - datetime: use date part - date: just return it """ if isinstance(value, sixmini.string_types): return self.str2date(value) elif value is None: raise TypeError("Unable to parse date from %r" % value) elif isinstance(value, sixmini.integer_types): return date.fromordinal(value) elif isinstance(value, datetime): return value.date() elif isinstance(value, date): return value else: raise ValueError("Unable to parse date from %r" % value) def parse_datetime(self, value): """ A lazy method to parse anything to datetime. If input data type is: - string: parse datetime from it - integer: use from ordinal - date: use date part and set hour, minute, second to zero - datetime: just return it """ if isinstance(value, sixmini.string_types): return self.str2datetime(value) elif value is None: raise TypeError("Unable to parse datetime from %r" % value) elif isinstance(value, sixmini.integer_types): return from_utctimestamp(value) elif isinstance(value, float): return from_utctimestamp(value) elif isinstance(value, datetime): return value elif isinstance(value, date): return datetime(value.year, value.month, value.day) else: raise ValueError("Unable to parse datetime from %r" % value)
MacHu-GWU/rolex-project
rolex/parse.py
Parser.parse_date
python
def parse_date(self, value): if isinstance(value, sixmini.string_types): return self.str2date(value) elif value is None: raise TypeError("Unable to parse date from %r" % value) elif isinstance(value, sixmini.integer_types): return date.fromordinal(value) elif isinstance(value, datetime): return value.date() elif isinstance(value, date): return value else: raise ValueError("Unable to parse date from %r" % value)
A lazy method to parse anything to date. If input data type is: - string: parse date from it - integer: use from ordinal - datetime: use date part - date: just return it
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/parse.py#L226-L248
[ "def str2date(self, date_str):\n \"\"\"\n Parse date from string.\n\n If there's no template matches your string, Please go\n https://github.com/MacHu-GWU/rolex-project/issues\n submit your datetime string. I 'll update templates ASAP.\n\n This method is faster than :meth:`dateutil.parser.parse`.\...
class Parser(object): """ datetime string parser. """ _default_date_template = date_template_list[0] _default_datetime_template = datetime_template_list[0] # --- Parse datetime --- def str2date(self, date_str): """ Parse date from string. If there's no template matches your string, Please go https://github.com/MacHu-GWU/rolex-project/issues submit your datetime string. I 'll update templates ASAP. This method is faster than :meth:`dateutil.parser.parse`. :param date_str: a string represent a date :type date_str: str :return: a date object **中文文档** 从string解析date。首先尝试默认模板, 如果失败了, 则尝试所有的模板。 一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的 字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。 该方法要快过 :meth:`dateutil.parser.parse` 方法。 """ # try default date template try: a_datetime = datetime.strptime( date_str, self._default_date_template) return a_datetime.date() except: pass # try every date templates for template in date_template_list: try: a_datetime = datetime.strptime(date_str, template) self._default_date_template = template return a_datetime.date() except: pass # raise error raise ValueError("Unable to parse date from: %r!" % date_str) def _str2datetime(self, datetime_str): """ Parse datetime from string. If there's no template matches your string, Please go https://github.com/MacHu-GWU/rolex-project/issues submit your datetime string. I 'll update templates ASAP. This method is faster than :meth:`dateutil.parser.parse`. :param datetime_str: a string represent a datetime :type datetime_str: str :return: a datetime object **中文文档** 从string解析datetime。首先尝试默认模板, 如果失败了, 则尝试所有的模板。 一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的 字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。 该方法要快过 :meth:`dateutil.parser.parse` 方法。 为了防止模板库失败的情况, 程序设定在失败后自动一直启用 :meth:`dateutil.parser.parse` 进行解析。你可以调用 :meth:`Parser.reset()` 方法恢复默认设定。 """ # try default datetime template try: a_datetime = datetime.strptime( datetime_str, self._default_datetime_template) return a_datetime except: pass # try every datetime templates for template in datetime_template_list: try: a_datetime = datetime.strptime(datetime_str, template) self._default_datetime_template = template return a_datetime except: pass # raise error a_datetime = parse(datetime_str) self.str2datetime = parse return a_datetime str2datetime = _str2datetime def reset(self): """ Reset :class:`Parser` behavior to default. """ self.str2datetime = self._str2datetime def parse_datetime(self, value): """ A lazy method to parse anything to datetime. If input data type is: - string: parse datetime from it - integer: use from ordinal - date: use date part and set hour, minute, second to zero - datetime: just return it """ if isinstance(value, sixmini.string_types): return self.str2datetime(value) elif value is None: raise TypeError("Unable to parse datetime from %r" % value) elif isinstance(value, sixmini.integer_types): return from_utctimestamp(value) elif isinstance(value, float): return from_utctimestamp(value) elif isinstance(value, datetime): return value elif isinstance(value, date): return datetime(value.year, value.month, value.day) else: raise ValueError("Unable to parse datetime from %r" % value)
MacHu-GWU/rolex-project
rolex/parse.py
Parser.parse_datetime
python
def parse_datetime(self, value): if isinstance(value, sixmini.string_types): return self.str2datetime(value) elif value is None: raise TypeError("Unable to parse datetime from %r" % value) elif isinstance(value, sixmini.integer_types): return from_utctimestamp(value) elif isinstance(value, float): return from_utctimestamp(value) elif isinstance(value, datetime): return value elif isinstance(value, date): return datetime(value.year, value.month, value.day) else: raise ValueError("Unable to parse datetime from %r" % value)
A lazy method to parse anything to datetime. If input data type is: - string: parse datetime from it - integer: use from ordinal - date: use date part and set hour, minute, second to zero - datetime: just return it
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/parse.py#L250-L274
[ "def _str2datetime(self, datetime_str):\n \"\"\"\n Parse datetime from string.\n\n If there's no template matches your string, Please go\n https://github.com/MacHu-GWU/rolex-project/issues\n submit your datetime string. I 'll update templates ASAP.\n\n This method is faster than :meth:`dateutil.pa...
class Parser(object): """ datetime string parser. """ _default_date_template = date_template_list[0] _default_datetime_template = datetime_template_list[0] # --- Parse datetime --- def str2date(self, date_str): """ Parse date from string. If there's no template matches your string, Please go https://github.com/MacHu-GWU/rolex-project/issues submit your datetime string. I 'll update templates ASAP. This method is faster than :meth:`dateutil.parser.parse`. :param date_str: a string represent a date :type date_str: str :return: a date object **中文文档** 从string解析date。首先尝试默认模板, 如果失败了, 则尝试所有的模板。 一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的 字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。 该方法要快过 :meth:`dateutil.parser.parse` 方法。 """ # try default date template try: a_datetime = datetime.strptime( date_str, self._default_date_template) return a_datetime.date() except: pass # try every date templates for template in date_template_list: try: a_datetime = datetime.strptime(date_str, template) self._default_date_template = template return a_datetime.date() except: pass # raise error raise ValueError("Unable to parse date from: %r!" % date_str) def _str2datetime(self, datetime_str): """ Parse datetime from string. If there's no template matches your string, Please go https://github.com/MacHu-GWU/rolex-project/issues submit your datetime string. I 'll update templates ASAP. This method is faster than :meth:`dateutil.parser.parse`. :param datetime_str: a string represent a datetime :type datetime_str: str :return: a datetime object **中文文档** 从string解析datetime。首先尝试默认模板, 如果失败了, 则尝试所有的模板。 一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的 字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。 该方法要快过 :meth:`dateutil.parser.parse` 方法。 为了防止模板库失败的情况, 程序设定在失败后自动一直启用 :meth:`dateutil.parser.parse` 进行解析。你可以调用 :meth:`Parser.reset()` 方法恢复默认设定。 """ # try default datetime template try: a_datetime = datetime.strptime( datetime_str, self._default_datetime_template) return a_datetime except: pass # try every datetime templates for template in datetime_template_list: try: a_datetime = datetime.strptime(datetime_str, template) self._default_datetime_template = template return a_datetime except: pass # raise error a_datetime = parse(datetime_str) self.str2datetime = parse return a_datetime str2datetime = _str2datetime def reset(self): """ Reset :class:`Parser` behavior to default. """ self.str2datetime = self._str2datetime def parse_date(self, value): """ A lazy method to parse anything to date. If input data type is: - string: parse date from it - integer: use from ordinal - datetime: use date part - date: just return it """ if isinstance(value, sixmini.string_types): return self.str2date(value) elif value is None: raise TypeError("Unable to parse date from %r" % value) elif isinstance(value, sixmini.integer_types): return date.fromordinal(value) elif isinstance(value, datetime): return value.date() elif isinstance(value, date): return value else: raise ValueError("Unable to parse date from %r" % value)
MacHu-GWU/rolex-project
rolex/util.py
to_utctimestamp
python
def to_utctimestamp(a_datetime): if a_datetime.tzinfo is None: delta = a_datetime - datetime(1970, 1, 1) else: delta = a_datetime - datetime(1970, 1, 1, tzinfo=utc) return delta.total_seconds()
Calculate number of seconds from UTC 1970-01-01 00:00:00. When: - dt doesn't have tzinfo: assume it's a utc time. - dt has tzinfo: use tzinfo. WARNING, if your datetime object doens't have ``tzinfo``, make sure it's a UTC time, but **NOT a LOCAL TIME**. **中文文档** 计算时间戳, 若: - 不带tzinfo: 则默认为是UTC time。 - 带tzinfo: 则使用tzinfo。
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/util.py#L30-L53
null
# -*- coding: utf-8 -*- """ time math calculation. """ from datetime import date, datetime, timedelta try: from .tz import utc, local except: # pragma: no cover from rolex.tz import utc, local def to_ordinal(a_date): """ Calculate number of days from 0000-00-00. """ return a_date.toordinal() def from_ordinal(days): """ Create a date object that number ``days`` of days after 0000-00-00. """ return date.fromordinal(days) def from_utctimestamp(timestamp): """ Create a **datetime** object that number of seconds after UTC 1970-01-01 00:00:00. If you want local time, use :meth:`from_timestamp` This method support negative timestamp. :returns: non-timezone awared UTC datetime. **中文文档** 返回一个在UTC 1970-01-01 00:00:00 之后 #timestamp 秒后的时间。默认为 UTC时间。即返回的datetime不带tzinfo """ return datetime(1970, 1, 1) + timedelta(seconds=timestamp) def to_utc(a_datetime, keep_utc_tzinfo=False): """ Convert a time awared datetime to utc datetime. :param a_datetime: a timezone awared datetime. (If not, then just returns) :param keep_utc_tzinfo: whether to retain the utc time zone information. **中文文档** 将一个带时区的时间转化成UTC时间。而对于UTC时间而言, 有没有时区信息都无所谓了。 """ if a_datetime.tzinfo: utc_datetime = a_datetime.astimezone(utc) # convert to utc time if keep_utc_tzinfo is False: utc_datetime = utc_datetime.replace(tzinfo=None) return utc_datetime else: return a_datetime def utc_to_tz(utc_datetime, tzinfo, keep_tzinfo=False): """ Convert a UTC datetime to a time awared local time :param utc_datetime: :param tzinfo: :param keep_tzinfo: """ tz_awared_datetime = utc_datetime.replace(tzinfo=utc).astimezone(tzinfo) if keep_tzinfo is False: tz_awared_datetime = tz_awared_datetime.replace(tzinfo=None) return tz_awared_datetime def utc_to_local(utc_datetime, keep_tzinfo=False): """ Convert a UTC datetime to current machine local timezone datetime. :param utc_datetime: :param keep_tzinfo: """ return utc_to_tz(utc_datetime, local, keep_tzinfo) def is_weekend(d_or_dt): """Check if a datetime is weekend. """ return d_or_dt.isoweekday() in [6, 7] def is_weekday(d_or_dt): """Check if a datetime is weekday. """ return d_or_dt.isoweekday() not in [6, 7]
MacHu-GWU/rolex-project
rolex/util.py
to_utc
python
def to_utc(a_datetime, keep_utc_tzinfo=False): if a_datetime.tzinfo: utc_datetime = a_datetime.astimezone(utc) # convert to utc time if keep_utc_tzinfo is False: utc_datetime = utc_datetime.replace(tzinfo=None) return utc_datetime else: return a_datetime
Convert a time awared datetime to utc datetime. :param a_datetime: a timezone awared datetime. (If not, then just returns) :param keep_utc_tzinfo: whether to retain the utc time zone information. **中文文档** 将一个带时区的时间转化成UTC时间。而对于UTC时间而言, 有没有时区信息都无所谓了。
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/util.py#L74-L91
null
# -*- coding: utf-8 -*- """ time math calculation. """ from datetime import date, datetime, timedelta try: from .tz import utc, local except: # pragma: no cover from rolex.tz import utc, local def to_ordinal(a_date): """ Calculate number of days from 0000-00-00. """ return a_date.toordinal() def from_ordinal(days): """ Create a date object that number ``days`` of days after 0000-00-00. """ return date.fromordinal(days) def to_utctimestamp(a_datetime): """ Calculate number of seconds from UTC 1970-01-01 00:00:00. When: - dt doesn't have tzinfo: assume it's a utc time. - dt has tzinfo: use tzinfo. WARNING, if your datetime object doens't have ``tzinfo``, make sure it's a UTC time, but **NOT a LOCAL TIME**. **中文文档** 计算时间戳, 若: - 不带tzinfo: 则默认为是UTC time。 - 带tzinfo: 则使用tzinfo。 """ if a_datetime.tzinfo is None: delta = a_datetime - datetime(1970, 1, 1) else: delta = a_datetime - datetime(1970, 1, 1, tzinfo=utc) return delta.total_seconds() def from_utctimestamp(timestamp): """ Create a **datetime** object that number of seconds after UTC 1970-01-01 00:00:00. If you want local time, use :meth:`from_timestamp` This method support negative timestamp. :returns: non-timezone awared UTC datetime. **中文文档** 返回一个在UTC 1970-01-01 00:00:00 之后 #timestamp 秒后的时间。默认为 UTC时间。即返回的datetime不带tzinfo """ return datetime(1970, 1, 1) + timedelta(seconds=timestamp) def utc_to_tz(utc_datetime, tzinfo, keep_tzinfo=False): """ Convert a UTC datetime to a time awared local time :param utc_datetime: :param tzinfo: :param keep_tzinfo: """ tz_awared_datetime = utc_datetime.replace(tzinfo=utc).astimezone(tzinfo) if keep_tzinfo is False: tz_awared_datetime = tz_awared_datetime.replace(tzinfo=None) return tz_awared_datetime def utc_to_local(utc_datetime, keep_tzinfo=False): """ Convert a UTC datetime to current machine local timezone datetime. :param utc_datetime: :param keep_tzinfo: """ return utc_to_tz(utc_datetime, local, keep_tzinfo) def is_weekend(d_or_dt): """Check if a datetime is weekend. """ return d_or_dt.isoweekday() in [6, 7] def is_weekday(d_or_dt): """Check if a datetime is weekday. """ return d_or_dt.isoweekday() not in [6, 7]
MacHu-GWU/rolex-project
rolex/util.py
utc_to_tz
python
def utc_to_tz(utc_datetime, tzinfo, keep_tzinfo=False): tz_awared_datetime = utc_datetime.replace(tzinfo=utc).astimezone(tzinfo) if keep_tzinfo is False: tz_awared_datetime = tz_awared_datetime.replace(tzinfo=None) return tz_awared_datetime
Convert a UTC datetime to a time awared local time :param utc_datetime: :param tzinfo: :param keep_tzinfo:
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/util.py#L94-L105
null
# -*- coding: utf-8 -*- """ time math calculation. """ from datetime import date, datetime, timedelta try: from .tz import utc, local except: # pragma: no cover from rolex.tz import utc, local def to_ordinal(a_date): """ Calculate number of days from 0000-00-00. """ return a_date.toordinal() def from_ordinal(days): """ Create a date object that number ``days`` of days after 0000-00-00. """ return date.fromordinal(days) def to_utctimestamp(a_datetime): """ Calculate number of seconds from UTC 1970-01-01 00:00:00. When: - dt doesn't have tzinfo: assume it's a utc time. - dt has tzinfo: use tzinfo. WARNING, if your datetime object doens't have ``tzinfo``, make sure it's a UTC time, but **NOT a LOCAL TIME**. **中文文档** 计算时间戳, 若: - 不带tzinfo: 则默认为是UTC time。 - 带tzinfo: 则使用tzinfo。 """ if a_datetime.tzinfo is None: delta = a_datetime - datetime(1970, 1, 1) else: delta = a_datetime - datetime(1970, 1, 1, tzinfo=utc) return delta.total_seconds() def from_utctimestamp(timestamp): """ Create a **datetime** object that number of seconds after UTC 1970-01-01 00:00:00. If you want local time, use :meth:`from_timestamp` This method support negative timestamp. :returns: non-timezone awared UTC datetime. **中文文档** 返回一个在UTC 1970-01-01 00:00:00 之后 #timestamp 秒后的时间。默认为 UTC时间。即返回的datetime不带tzinfo """ return datetime(1970, 1, 1) + timedelta(seconds=timestamp) def to_utc(a_datetime, keep_utc_tzinfo=False): """ Convert a time awared datetime to utc datetime. :param a_datetime: a timezone awared datetime. (If not, then just returns) :param keep_utc_tzinfo: whether to retain the utc time zone information. **中文文档** 将一个带时区的时间转化成UTC时间。而对于UTC时间而言, 有没有时区信息都无所谓了。 """ if a_datetime.tzinfo: utc_datetime = a_datetime.astimezone(utc) # convert to utc time if keep_utc_tzinfo is False: utc_datetime = utc_datetime.replace(tzinfo=None) return utc_datetime else: return a_datetime def utc_to_local(utc_datetime, keep_tzinfo=False): """ Convert a UTC datetime to current machine local timezone datetime. :param utc_datetime: :param keep_tzinfo: """ return utc_to_tz(utc_datetime, local, keep_tzinfo) def is_weekend(d_or_dt): """Check if a datetime is weekend. """ return d_or_dt.isoweekday() in [6, 7] def is_weekday(d_or_dt): """Check if a datetime is weekday. """ return d_or_dt.isoweekday() not in [6, 7]
MacHu-GWU/rolex-project
rolex/generator.py
_rnd_date
python
def _rnd_date(start, end): return date.fromordinal(random.randint(start.toordinal(), end.toordinal()))
Internal random date generator.
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/generator.py#L253-L256
null
# -*- coding: utf-8 -*- import random from datetime import date, datetime, timedelta try: # pragma: no cover import numpy as np has_np = True except: # pragma: no cover has_np = False from .pkg.sixmini import integer_types, string_types from .parse import parser from .util import ( from_utctimestamp, to_utctimestamp, from_ordinal, to_ordinal, ) _valid_freq = [ "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", ] def _freq_parser(freq): # pragma: no cover """ Parse frequency to timedelta. Valid keywords "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", """ freq = freq.lower().strip() error_message = "'%s' is invalid, use one of %s" % (freq, _valid_freq) try: # day for surfix in ["days", "day", "d"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq)) # hour for surfix in ["hours", "hour", "h"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(hours=int(freq)) # minute for surfix in ["minutes", "minute", "min", "m"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(minutes=int(freq)) # second for surfix in ["seconds", "second", "sec", "s"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(seconds=int(freq)) # week for surfix in ["weeks", "week", "w"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq) * 7) except: pass raise ValueError(error_message) def time_series(start=None, end=None, periods=None, freq="1day", normalize=False, return_date=False): """ A pure Python implementation of pandas.date_range(). Given 2 of start, end, periods and freq, generate a series of datetime object. :param start: Left bound for generating dates :type start: str or datetime.datetime (default None) :param end: Right bound for generating dates :type end: str or datetime.datetime (default None) :param periods: Number of date points. If None, must specify start and end :type periods: integer (default None) :param freq: string, default '1day' (calendar daily) Available mode are day, hour, min, sec Frequency strings can have multiples. e.g. '7day', '6hour', '5min', '4sec', '3week` :type freq: string (default '1day' calendar daily) :param normalize: Trigger that normalize start/end dates to midnight :type normalize: boolean (default False) :param return_date: Trigger that only return date object. :type return_date: boolean (default False) :return: A list of datetime.datetime object. An evenly sampled time series. Usage:: >>> from __future__ import print_function >>> for dt in rolex.time_series("2014-1-1", "2014-1-7"): ... print(dt) 2014-01-01 00:00:00 2014-01-02 00:00:00 2014-01-03 00:00:00 2014-01-04 00:00:00 2014-01-05 00:00:00 2014-01-06 00:00:00 2014-01-07 00:00:00 **中文文档** 生成等间隔的时间序列。 需要给出, "起始", "结束", "数量" 中的任意两个。以及指定"频率"。以此唯一 确定一个等间隔时间序列。"频率"项所支持的命令字符有"7day", "6hour", "5min", "4sec", "3week" (可以改变数字). """ def normalize_datetime_to_midnight(dt): """Normalize a datetime %Y-%m-%d %H:%M:%S to %Y-%m-%d 00:00:00. """ return datetime(dt.year, dt.month, dt.day) def not_normalize(dt): """Do not normalize. """ return dt series = list() # if two of start, end, or periods exist if (bool(start) + bool(end) + bool(periods)) != 2: raise ValueError( "Must specify two of 'start', 'end', or 'periods'.") if normalize: converter = normalize_datetime_to_midnight else: converter = not_normalize interval = _freq_parser(freq) if (bool(start) & bool(end)): # start and end start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) start = start - interval while 1: start += interval if start <= end: series.append(converter(start)) else: break elif (bool(start) & bool(periods)): # start and periods start = parser.parse_datetime(start) start = start - interval for _ in range(periods): start += interval series.append(converter(start)) elif (bool(end) & bool(periods)): # end and periods end = parser.parse_datetime(end) start = end - interval * periods for _ in range(periods): start += interval series.append(converter(start)) if return_date: # pragma: no cover series = [i.date() for i in series] return series def weekday_series(start, end, weekday, return_date=False): """Generate a datetime series with same weekday number. ISO weekday number: Mon to Sun = 1 to 7 Usage:: >>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25" >>> rolex.weekday_series(start, end, weekday=2) # All Tuesday [ datetime(2014, 1, 7, 6, 30, 25), datetime(2014, 1, 14, 6, 30, 25), datetime(2014, 1, 21, 6, 30, 25), datetime(2014, 1, 28, 6, 30, 25), ] :param weekday: int or list of int :returns: list of datetime **中文文档** 生成星期数一致的时间序列。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) if isinstance(weekday, integer_types): weekday = [weekday, ] series = list() for i in time_series(start, end, freq="1day", return_date=return_date): if i.isoweekday() in weekday: series.append(i) return series # --- Random Generator --- def _randn(size, rnd_generator, *args, **kwargs): if isinstance(size, integer_types): if size < 0: raise ValueError("'size' can't smaller than zero") return [rnd_generator(*args, **kwargs) for _ in range(size)] else: try: m, n = size[0], size[1] if ((m < 0) or (n < 0)): raise ValueError("'size' can't smaller than zero") return [[rnd_generator(*args, **kwargs) for _ in range(n)] for _ in range(m)] except: raise ValueError("'size' has to be int or tuple. " "e.g. 6 or (2, 3)") def _assert_correct_start_end(start, end): if start > end: # pragma: no cover raise ValueError("start time has to be earlier than end time!") def rnd_date(start=date(1970, 1, 1), end=None, **kwargs): """ Generate a random date between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.date, (default date(1970, 1, 1)) :param end: Right bound :type end: string or datetime.date, (default date.today()) :return: a datetime.date object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的日期。 """ if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _rnd_date(start, end) def rnd_date_array(size, start=date(1970, 1, 1), end=None, **kwargs): """ Array or Matrix of random date generator. :returns: 1d or 2d array of datetime.date """ if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_date, start, end) def rnd_date_list_high_performance(size, start=date(1970, 1, 1), end=None, **kwargs): """ Generate mass random date. :param size: int, number of :param start: date similar object, int / str / date / datetime :param end: date similar object, int / str / date / datetime, default today's date :param kwargs: args placeholder :return: list of datetime.date """ if end is None: end = date.today() start_days = to_ordinal(parser.parse_datetime(start)) end_days = to_ordinal(parser.parse_datetime(end)) _assert_correct_start_end(start_days, end_days) if has_np: # pragma: no cover return [ from_ordinal(days) for days in np.random.randint(start_days, end_days, size) ] else: return [ from_ordinal(random.randint(start_days, end_days)) for _ in range(size) ] def _rnd_datetime(start, end): """ Internal random datetime generator. """ return from_utctimestamp( random.randint( int(to_utctimestamp(start)), int(to_utctimestamp(end)), ) ) def rnd_datetime(start=datetime(1970, 1, 1), end=datetime.now()): """ Generate a random datetime between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.datetime, (default datetime(1970, 1, 1)) :param end: Right bound :type end: string or datetime.datetime, (default datetime.now()) :return: a datetime.datetime object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的时间。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _rnd_datetime(start, end) def rnd_datetime_array(size, start=datetime(1970, 1, 1), end=None): """ Array or Matrix of random datetime generator. :returns: 1d or 2d array of datetime.date """ if end is None: end = datetime.now() start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_datetime, start, end) def rnd_datetime_list_high_performance(size, start=datetime(1970, 1, 1), end=None): if end is None: end = datetime.now() start_ts = to_utctimestamp(parser.parse_datetime(start)) end_ts = to_utctimestamp(parser.parse_datetime(end)) _assert_correct_start_end(start, end) interval_range = end_ts - start_ts if has_np: # pragma: no cover return [ from_utctimestamp(v * interval_range + start_ts) for v in np.random.random(size) ] else: return [ from_utctimestamp(random.random() * interval_range + start_ts) for _ in range(size) ] def day_interval(year, month, day, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a day. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.day_interval(2014, 6, 17) >>> start datetime(2014, 6, 17, 0, 0, 0) >>> end datetime(2014, 6, 17, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, month, day) end = datetime(year, month, day) + timedelta(days=1) - delta if not return_string: return start, end else: return str(start), str(end) def month_interval(year, month, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a month. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.month_interval(2000, 2) >>> start datetime(2000, 2, 1, 0, 0, 0) >>> end datetime(2000, 2, 29, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) if month == 12: start = datetime(year, month, 1) end = datetime(year + 1, 1, 1) - delta else: start = datetime(year, month, 1) end = datetime(year, month + 1, 1) - delta if not return_string: return start, end else: return str(start), str(end) def year_interval(year, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a year. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.year_interval(2007) >>> start datetime(2007, 1, 1, 0, 0, 0) >>> end datetime(2007, 12, 31, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, 1, 1) end = datetime(year + 1, 1, 1) - delta if not return_string: return start, end else: return str(start), str(end)
MacHu-GWU/rolex-project
rolex/generator.py
rnd_date
python
def rnd_date(start=date(1970, 1, 1), end=None, **kwargs): if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _rnd_date(start, end)
Generate a random date between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.date, (default date(1970, 1, 1)) :param end: Right bound :type end: string or datetime.date, (default date.today()) :return: a datetime.date object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的日期。
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/generator.py#L259-L278
[ "def _assert_correct_start_end(start, end):\n if start > end: # pragma: no cover\n raise ValueError(\"start time has to be earlier than end time!\")\n", "def _rnd_date(start, end):\n \"\"\"Internal random date generator.\n \"\"\"\n return date.fromordinal(random.randint(start.toordinal(), end....
# -*- coding: utf-8 -*- import random from datetime import date, datetime, timedelta try: # pragma: no cover import numpy as np has_np = True except: # pragma: no cover has_np = False from .pkg.sixmini import integer_types, string_types from .parse import parser from .util import ( from_utctimestamp, to_utctimestamp, from_ordinal, to_ordinal, ) _valid_freq = [ "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", ] def _freq_parser(freq): # pragma: no cover """ Parse frequency to timedelta. Valid keywords "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", """ freq = freq.lower().strip() error_message = "'%s' is invalid, use one of %s" % (freq, _valid_freq) try: # day for surfix in ["days", "day", "d"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq)) # hour for surfix in ["hours", "hour", "h"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(hours=int(freq)) # minute for surfix in ["minutes", "minute", "min", "m"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(minutes=int(freq)) # second for surfix in ["seconds", "second", "sec", "s"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(seconds=int(freq)) # week for surfix in ["weeks", "week", "w"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq) * 7) except: pass raise ValueError(error_message) def time_series(start=None, end=None, periods=None, freq="1day", normalize=False, return_date=False): """ A pure Python implementation of pandas.date_range(). Given 2 of start, end, periods and freq, generate a series of datetime object. :param start: Left bound for generating dates :type start: str or datetime.datetime (default None) :param end: Right bound for generating dates :type end: str or datetime.datetime (default None) :param periods: Number of date points. If None, must specify start and end :type periods: integer (default None) :param freq: string, default '1day' (calendar daily) Available mode are day, hour, min, sec Frequency strings can have multiples. e.g. '7day', '6hour', '5min', '4sec', '3week` :type freq: string (default '1day' calendar daily) :param normalize: Trigger that normalize start/end dates to midnight :type normalize: boolean (default False) :param return_date: Trigger that only return date object. :type return_date: boolean (default False) :return: A list of datetime.datetime object. An evenly sampled time series. Usage:: >>> from __future__ import print_function >>> for dt in rolex.time_series("2014-1-1", "2014-1-7"): ... print(dt) 2014-01-01 00:00:00 2014-01-02 00:00:00 2014-01-03 00:00:00 2014-01-04 00:00:00 2014-01-05 00:00:00 2014-01-06 00:00:00 2014-01-07 00:00:00 **中文文档** 生成等间隔的时间序列。 需要给出, "起始", "结束", "数量" 中的任意两个。以及指定"频率"。以此唯一 确定一个等间隔时间序列。"频率"项所支持的命令字符有"7day", "6hour", "5min", "4sec", "3week" (可以改变数字). """ def normalize_datetime_to_midnight(dt): """Normalize a datetime %Y-%m-%d %H:%M:%S to %Y-%m-%d 00:00:00. """ return datetime(dt.year, dt.month, dt.day) def not_normalize(dt): """Do not normalize. """ return dt series = list() # if two of start, end, or periods exist if (bool(start) + bool(end) + bool(periods)) != 2: raise ValueError( "Must specify two of 'start', 'end', or 'periods'.") if normalize: converter = normalize_datetime_to_midnight else: converter = not_normalize interval = _freq_parser(freq) if (bool(start) & bool(end)): # start and end start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) start = start - interval while 1: start += interval if start <= end: series.append(converter(start)) else: break elif (bool(start) & bool(periods)): # start and periods start = parser.parse_datetime(start) start = start - interval for _ in range(periods): start += interval series.append(converter(start)) elif (bool(end) & bool(periods)): # end and periods end = parser.parse_datetime(end) start = end - interval * periods for _ in range(periods): start += interval series.append(converter(start)) if return_date: # pragma: no cover series = [i.date() for i in series] return series def weekday_series(start, end, weekday, return_date=False): """Generate a datetime series with same weekday number. ISO weekday number: Mon to Sun = 1 to 7 Usage:: >>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25" >>> rolex.weekday_series(start, end, weekday=2) # All Tuesday [ datetime(2014, 1, 7, 6, 30, 25), datetime(2014, 1, 14, 6, 30, 25), datetime(2014, 1, 21, 6, 30, 25), datetime(2014, 1, 28, 6, 30, 25), ] :param weekday: int or list of int :returns: list of datetime **中文文档** 生成星期数一致的时间序列。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) if isinstance(weekday, integer_types): weekday = [weekday, ] series = list() for i in time_series(start, end, freq="1day", return_date=return_date): if i.isoweekday() in weekday: series.append(i) return series # --- Random Generator --- def _randn(size, rnd_generator, *args, **kwargs): if isinstance(size, integer_types): if size < 0: raise ValueError("'size' can't smaller than zero") return [rnd_generator(*args, **kwargs) for _ in range(size)] else: try: m, n = size[0], size[1] if ((m < 0) or (n < 0)): raise ValueError("'size' can't smaller than zero") return [[rnd_generator(*args, **kwargs) for _ in range(n)] for _ in range(m)] except: raise ValueError("'size' has to be int or tuple. " "e.g. 6 or (2, 3)") def _assert_correct_start_end(start, end): if start > end: # pragma: no cover raise ValueError("start time has to be earlier than end time!") def _rnd_date(start, end): """Internal random date generator. """ return date.fromordinal(random.randint(start.toordinal(), end.toordinal())) def rnd_date_array(size, start=date(1970, 1, 1), end=None, **kwargs): """ Array or Matrix of random date generator. :returns: 1d or 2d array of datetime.date """ if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_date, start, end) def rnd_date_list_high_performance(size, start=date(1970, 1, 1), end=None, **kwargs): """ Generate mass random date. :param size: int, number of :param start: date similar object, int / str / date / datetime :param end: date similar object, int / str / date / datetime, default today's date :param kwargs: args placeholder :return: list of datetime.date """ if end is None: end = date.today() start_days = to_ordinal(parser.parse_datetime(start)) end_days = to_ordinal(parser.parse_datetime(end)) _assert_correct_start_end(start_days, end_days) if has_np: # pragma: no cover return [ from_ordinal(days) for days in np.random.randint(start_days, end_days, size) ] else: return [ from_ordinal(random.randint(start_days, end_days)) for _ in range(size) ] def _rnd_datetime(start, end): """ Internal random datetime generator. """ return from_utctimestamp( random.randint( int(to_utctimestamp(start)), int(to_utctimestamp(end)), ) ) def rnd_datetime(start=datetime(1970, 1, 1), end=datetime.now()): """ Generate a random datetime between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.datetime, (default datetime(1970, 1, 1)) :param end: Right bound :type end: string or datetime.datetime, (default datetime.now()) :return: a datetime.datetime object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的时间。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _rnd_datetime(start, end) def rnd_datetime_array(size, start=datetime(1970, 1, 1), end=None): """ Array or Matrix of random datetime generator. :returns: 1d or 2d array of datetime.date """ if end is None: end = datetime.now() start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_datetime, start, end) def rnd_datetime_list_high_performance(size, start=datetime(1970, 1, 1), end=None): if end is None: end = datetime.now() start_ts = to_utctimestamp(parser.parse_datetime(start)) end_ts = to_utctimestamp(parser.parse_datetime(end)) _assert_correct_start_end(start, end) interval_range = end_ts - start_ts if has_np: # pragma: no cover return [ from_utctimestamp(v * interval_range + start_ts) for v in np.random.random(size) ] else: return [ from_utctimestamp(random.random() * interval_range + start_ts) for _ in range(size) ] def day_interval(year, month, day, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a day. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.day_interval(2014, 6, 17) >>> start datetime(2014, 6, 17, 0, 0, 0) >>> end datetime(2014, 6, 17, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, month, day) end = datetime(year, month, day) + timedelta(days=1) - delta if not return_string: return start, end else: return str(start), str(end) def month_interval(year, month, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a month. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.month_interval(2000, 2) >>> start datetime(2000, 2, 1, 0, 0, 0) >>> end datetime(2000, 2, 29, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) if month == 12: start = datetime(year, month, 1) end = datetime(year + 1, 1, 1) - delta else: start = datetime(year, month, 1) end = datetime(year, month + 1, 1) - delta if not return_string: return start, end else: return str(start), str(end) def year_interval(year, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a year. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.year_interval(2007) >>> start datetime(2007, 1, 1, 0, 0, 0) >>> end datetime(2007, 12, 31, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, 1, 1) end = datetime(year + 1, 1, 1) - delta if not return_string: return start, end else: return str(start), str(end)
MacHu-GWU/rolex-project
rolex/generator.py
rnd_date_array
python
def rnd_date_array(size, start=date(1970, 1, 1), end=None, **kwargs): if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_date, start, end)
Array or Matrix of random date generator. :returns: 1d or 2d array of datetime.date
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/generator.py#L281-L292
[ "def _assert_correct_start_end(start, end):\n if start > end: # pragma: no cover\n raise ValueError(\"start time has to be earlier than end time!\")\n", "def _randn(size, rnd_generator, *args, **kwargs):\n if isinstance(size, integer_types):\n if size < 0:\n raise ValueError(\"'siz...
# -*- coding: utf-8 -*- import random from datetime import date, datetime, timedelta try: # pragma: no cover import numpy as np has_np = True except: # pragma: no cover has_np = False from .pkg.sixmini import integer_types, string_types from .parse import parser from .util import ( from_utctimestamp, to_utctimestamp, from_ordinal, to_ordinal, ) _valid_freq = [ "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", ] def _freq_parser(freq): # pragma: no cover """ Parse frequency to timedelta. Valid keywords "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", """ freq = freq.lower().strip() error_message = "'%s' is invalid, use one of %s" % (freq, _valid_freq) try: # day for surfix in ["days", "day", "d"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq)) # hour for surfix in ["hours", "hour", "h"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(hours=int(freq)) # minute for surfix in ["minutes", "minute", "min", "m"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(minutes=int(freq)) # second for surfix in ["seconds", "second", "sec", "s"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(seconds=int(freq)) # week for surfix in ["weeks", "week", "w"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq) * 7) except: pass raise ValueError(error_message) def time_series(start=None, end=None, periods=None, freq="1day", normalize=False, return_date=False): """ A pure Python implementation of pandas.date_range(). Given 2 of start, end, periods and freq, generate a series of datetime object. :param start: Left bound for generating dates :type start: str or datetime.datetime (default None) :param end: Right bound for generating dates :type end: str or datetime.datetime (default None) :param periods: Number of date points. If None, must specify start and end :type periods: integer (default None) :param freq: string, default '1day' (calendar daily) Available mode are day, hour, min, sec Frequency strings can have multiples. e.g. '7day', '6hour', '5min', '4sec', '3week` :type freq: string (default '1day' calendar daily) :param normalize: Trigger that normalize start/end dates to midnight :type normalize: boolean (default False) :param return_date: Trigger that only return date object. :type return_date: boolean (default False) :return: A list of datetime.datetime object. An evenly sampled time series. Usage:: >>> from __future__ import print_function >>> for dt in rolex.time_series("2014-1-1", "2014-1-7"): ... print(dt) 2014-01-01 00:00:00 2014-01-02 00:00:00 2014-01-03 00:00:00 2014-01-04 00:00:00 2014-01-05 00:00:00 2014-01-06 00:00:00 2014-01-07 00:00:00 **中文文档** 生成等间隔的时间序列。 需要给出, "起始", "结束", "数量" 中的任意两个。以及指定"频率"。以此唯一 确定一个等间隔时间序列。"频率"项所支持的命令字符有"7day", "6hour", "5min", "4sec", "3week" (可以改变数字). """ def normalize_datetime_to_midnight(dt): """Normalize a datetime %Y-%m-%d %H:%M:%S to %Y-%m-%d 00:00:00. """ return datetime(dt.year, dt.month, dt.day) def not_normalize(dt): """Do not normalize. """ return dt series = list() # if two of start, end, or periods exist if (bool(start) + bool(end) + bool(periods)) != 2: raise ValueError( "Must specify two of 'start', 'end', or 'periods'.") if normalize: converter = normalize_datetime_to_midnight else: converter = not_normalize interval = _freq_parser(freq) if (bool(start) & bool(end)): # start and end start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) start = start - interval while 1: start += interval if start <= end: series.append(converter(start)) else: break elif (bool(start) & bool(periods)): # start and periods start = parser.parse_datetime(start) start = start - interval for _ in range(periods): start += interval series.append(converter(start)) elif (bool(end) & bool(periods)): # end and periods end = parser.parse_datetime(end) start = end - interval * periods for _ in range(periods): start += interval series.append(converter(start)) if return_date: # pragma: no cover series = [i.date() for i in series] return series def weekday_series(start, end, weekday, return_date=False): """Generate a datetime series with same weekday number. ISO weekday number: Mon to Sun = 1 to 7 Usage:: >>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25" >>> rolex.weekday_series(start, end, weekday=2) # All Tuesday [ datetime(2014, 1, 7, 6, 30, 25), datetime(2014, 1, 14, 6, 30, 25), datetime(2014, 1, 21, 6, 30, 25), datetime(2014, 1, 28, 6, 30, 25), ] :param weekday: int or list of int :returns: list of datetime **中文文档** 生成星期数一致的时间序列。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) if isinstance(weekday, integer_types): weekday = [weekday, ] series = list() for i in time_series(start, end, freq="1day", return_date=return_date): if i.isoweekday() in weekday: series.append(i) return series # --- Random Generator --- def _randn(size, rnd_generator, *args, **kwargs): if isinstance(size, integer_types): if size < 0: raise ValueError("'size' can't smaller than zero") return [rnd_generator(*args, **kwargs) for _ in range(size)] else: try: m, n = size[0], size[1] if ((m < 0) or (n < 0)): raise ValueError("'size' can't smaller than zero") return [[rnd_generator(*args, **kwargs) for _ in range(n)] for _ in range(m)] except: raise ValueError("'size' has to be int or tuple. " "e.g. 6 or (2, 3)") def _assert_correct_start_end(start, end): if start > end: # pragma: no cover raise ValueError("start time has to be earlier than end time!") def _rnd_date(start, end): """Internal random date generator. """ return date.fromordinal(random.randint(start.toordinal(), end.toordinal())) def rnd_date(start=date(1970, 1, 1), end=None, **kwargs): """ Generate a random date between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.date, (default date(1970, 1, 1)) :param end: Right bound :type end: string or datetime.date, (default date.today()) :return: a datetime.date object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的日期。 """ if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _rnd_date(start, end) def rnd_date_list_high_performance(size, start=date(1970, 1, 1), end=None, **kwargs): """ Generate mass random date. :param size: int, number of :param start: date similar object, int / str / date / datetime :param end: date similar object, int / str / date / datetime, default today's date :param kwargs: args placeholder :return: list of datetime.date """ if end is None: end = date.today() start_days = to_ordinal(parser.parse_datetime(start)) end_days = to_ordinal(parser.parse_datetime(end)) _assert_correct_start_end(start_days, end_days) if has_np: # pragma: no cover return [ from_ordinal(days) for days in np.random.randint(start_days, end_days, size) ] else: return [ from_ordinal(random.randint(start_days, end_days)) for _ in range(size) ] def _rnd_datetime(start, end): """ Internal random datetime generator. """ return from_utctimestamp( random.randint( int(to_utctimestamp(start)), int(to_utctimestamp(end)), ) ) def rnd_datetime(start=datetime(1970, 1, 1), end=datetime.now()): """ Generate a random datetime between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.datetime, (default datetime(1970, 1, 1)) :param end: Right bound :type end: string or datetime.datetime, (default datetime.now()) :return: a datetime.datetime object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的时间。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _rnd_datetime(start, end) def rnd_datetime_array(size, start=datetime(1970, 1, 1), end=None): """ Array or Matrix of random datetime generator. :returns: 1d or 2d array of datetime.date """ if end is None: end = datetime.now() start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_datetime, start, end) def rnd_datetime_list_high_performance(size, start=datetime(1970, 1, 1), end=None): if end is None: end = datetime.now() start_ts = to_utctimestamp(parser.parse_datetime(start)) end_ts = to_utctimestamp(parser.parse_datetime(end)) _assert_correct_start_end(start, end) interval_range = end_ts - start_ts if has_np: # pragma: no cover return [ from_utctimestamp(v * interval_range + start_ts) for v in np.random.random(size) ] else: return [ from_utctimestamp(random.random() * interval_range + start_ts) for _ in range(size) ] def day_interval(year, month, day, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a day. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.day_interval(2014, 6, 17) >>> start datetime(2014, 6, 17, 0, 0, 0) >>> end datetime(2014, 6, 17, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, month, day) end = datetime(year, month, day) + timedelta(days=1) - delta if not return_string: return start, end else: return str(start), str(end) def month_interval(year, month, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a month. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.month_interval(2000, 2) >>> start datetime(2000, 2, 1, 0, 0, 0) >>> end datetime(2000, 2, 29, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) if month == 12: start = datetime(year, month, 1) end = datetime(year + 1, 1, 1) - delta else: start = datetime(year, month, 1) end = datetime(year, month + 1, 1) - delta if not return_string: return start, end else: return str(start), str(end) def year_interval(year, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a year. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.year_interval(2007) >>> start datetime(2007, 1, 1, 0, 0, 0) >>> end datetime(2007, 12, 31, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, 1, 1) end = datetime(year + 1, 1, 1) - delta if not return_string: return start, end else: return str(start), str(end)
MacHu-GWU/rolex-project
rolex/generator.py
rnd_date_list_high_performance
python
def rnd_date_list_high_performance(size, start=date(1970, 1, 1), end=None, **kwargs): if end is None: end = date.today() start_days = to_ordinal(parser.parse_datetime(start)) end_days = to_ordinal(parser.parse_datetime(end)) _assert_correct_start_end(start_days, end_days) if has_np: # pragma: no cover return [ from_ordinal(days) for days in np.random.randint(start_days, end_days, size) ] else: return [ from_ordinal(random.randint(start_days, end_days)) for _ in range(size) ]
Generate mass random date. :param size: int, number of :param start: date similar object, int / str / date / datetime :param end: date similar object, int / str / date / datetime, default today's date :param kwargs: args placeholder :return: list of datetime.date
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/generator.py#L295-L319
[ "def to_ordinal(a_date):\n \"\"\"\n Calculate number of days from 0000-00-00.\n \"\"\"\n return a_date.toordinal()\n", "def _assert_correct_start_end(start, end):\n if start > end: # pragma: no cover\n raise ValueError(\"start time has to be earlier than end time!\")\n", "def parse_dateti...
# -*- coding: utf-8 -*- import random from datetime import date, datetime, timedelta try: # pragma: no cover import numpy as np has_np = True except: # pragma: no cover has_np = False from .pkg.sixmini import integer_types, string_types from .parse import parser from .util import ( from_utctimestamp, to_utctimestamp, from_ordinal, to_ordinal, ) _valid_freq = [ "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", ] def _freq_parser(freq): # pragma: no cover """ Parse frequency to timedelta. Valid keywords "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", """ freq = freq.lower().strip() error_message = "'%s' is invalid, use one of %s" % (freq, _valid_freq) try: # day for surfix in ["days", "day", "d"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq)) # hour for surfix in ["hours", "hour", "h"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(hours=int(freq)) # minute for surfix in ["minutes", "minute", "min", "m"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(minutes=int(freq)) # second for surfix in ["seconds", "second", "sec", "s"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(seconds=int(freq)) # week for surfix in ["weeks", "week", "w"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq) * 7) except: pass raise ValueError(error_message) def time_series(start=None, end=None, periods=None, freq="1day", normalize=False, return_date=False): """ A pure Python implementation of pandas.date_range(). Given 2 of start, end, periods and freq, generate a series of datetime object. :param start: Left bound for generating dates :type start: str or datetime.datetime (default None) :param end: Right bound for generating dates :type end: str or datetime.datetime (default None) :param periods: Number of date points. If None, must specify start and end :type periods: integer (default None) :param freq: string, default '1day' (calendar daily) Available mode are day, hour, min, sec Frequency strings can have multiples. e.g. '7day', '6hour', '5min', '4sec', '3week` :type freq: string (default '1day' calendar daily) :param normalize: Trigger that normalize start/end dates to midnight :type normalize: boolean (default False) :param return_date: Trigger that only return date object. :type return_date: boolean (default False) :return: A list of datetime.datetime object. An evenly sampled time series. Usage:: >>> from __future__ import print_function >>> for dt in rolex.time_series("2014-1-1", "2014-1-7"): ... print(dt) 2014-01-01 00:00:00 2014-01-02 00:00:00 2014-01-03 00:00:00 2014-01-04 00:00:00 2014-01-05 00:00:00 2014-01-06 00:00:00 2014-01-07 00:00:00 **中文文档** 生成等间隔的时间序列。 需要给出, "起始", "结束", "数量" 中的任意两个。以及指定"频率"。以此唯一 确定一个等间隔时间序列。"频率"项所支持的命令字符有"7day", "6hour", "5min", "4sec", "3week" (可以改变数字). """ def normalize_datetime_to_midnight(dt): """Normalize a datetime %Y-%m-%d %H:%M:%S to %Y-%m-%d 00:00:00. """ return datetime(dt.year, dt.month, dt.day) def not_normalize(dt): """Do not normalize. """ return dt series = list() # if two of start, end, or periods exist if (bool(start) + bool(end) + bool(periods)) != 2: raise ValueError( "Must specify two of 'start', 'end', or 'periods'.") if normalize: converter = normalize_datetime_to_midnight else: converter = not_normalize interval = _freq_parser(freq) if (bool(start) & bool(end)): # start and end start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) start = start - interval while 1: start += interval if start <= end: series.append(converter(start)) else: break elif (bool(start) & bool(periods)): # start and periods start = parser.parse_datetime(start) start = start - interval for _ in range(periods): start += interval series.append(converter(start)) elif (bool(end) & bool(periods)): # end and periods end = parser.parse_datetime(end) start = end - interval * periods for _ in range(periods): start += interval series.append(converter(start)) if return_date: # pragma: no cover series = [i.date() for i in series] return series def weekday_series(start, end, weekday, return_date=False): """Generate a datetime series with same weekday number. ISO weekday number: Mon to Sun = 1 to 7 Usage:: >>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25" >>> rolex.weekday_series(start, end, weekday=2) # All Tuesday [ datetime(2014, 1, 7, 6, 30, 25), datetime(2014, 1, 14, 6, 30, 25), datetime(2014, 1, 21, 6, 30, 25), datetime(2014, 1, 28, 6, 30, 25), ] :param weekday: int or list of int :returns: list of datetime **中文文档** 生成星期数一致的时间序列。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) if isinstance(weekday, integer_types): weekday = [weekday, ] series = list() for i in time_series(start, end, freq="1day", return_date=return_date): if i.isoweekday() in weekday: series.append(i) return series # --- Random Generator --- def _randn(size, rnd_generator, *args, **kwargs): if isinstance(size, integer_types): if size < 0: raise ValueError("'size' can't smaller than zero") return [rnd_generator(*args, **kwargs) for _ in range(size)] else: try: m, n = size[0], size[1] if ((m < 0) or (n < 0)): raise ValueError("'size' can't smaller than zero") return [[rnd_generator(*args, **kwargs) for _ in range(n)] for _ in range(m)] except: raise ValueError("'size' has to be int or tuple. " "e.g. 6 or (2, 3)") def _assert_correct_start_end(start, end): if start > end: # pragma: no cover raise ValueError("start time has to be earlier than end time!") def _rnd_date(start, end): """Internal random date generator. """ return date.fromordinal(random.randint(start.toordinal(), end.toordinal())) def rnd_date(start=date(1970, 1, 1), end=None, **kwargs): """ Generate a random date between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.date, (default date(1970, 1, 1)) :param end: Right bound :type end: string or datetime.date, (default date.today()) :return: a datetime.date object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的日期。 """ if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _rnd_date(start, end) def rnd_date_array(size, start=date(1970, 1, 1), end=None, **kwargs): """ Array or Matrix of random date generator. :returns: 1d or 2d array of datetime.date """ if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_date, start, end) def _rnd_datetime(start, end): """ Internal random datetime generator. """ return from_utctimestamp( random.randint( int(to_utctimestamp(start)), int(to_utctimestamp(end)), ) ) def rnd_datetime(start=datetime(1970, 1, 1), end=datetime.now()): """ Generate a random datetime between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.datetime, (default datetime(1970, 1, 1)) :param end: Right bound :type end: string or datetime.datetime, (default datetime.now()) :return: a datetime.datetime object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的时间。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _rnd_datetime(start, end) def rnd_datetime_array(size, start=datetime(1970, 1, 1), end=None): """ Array or Matrix of random datetime generator. :returns: 1d or 2d array of datetime.date """ if end is None: end = datetime.now() start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_datetime, start, end) def rnd_datetime_list_high_performance(size, start=datetime(1970, 1, 1), end=None): if end is None: end = datetime.now() start_ts = to_utctimestamp(parser.parse_datetime(start)) end_ts = to_utctimestamp(parser.parse_datetime(end)) _assert_correct_start_end(start, end) interval_range = end_ts - start_ts if has_np: # pragma: no cover return [ from_utctimestamp(v * interval_range + start_ts) for v in np.random.random(size) ] else: return [ from_utctimestamp(random.random() * interval_range + start_ts) for _ in range(size) ] def day_interval(year, month, day, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a day. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.day_interval(2014, 6, 17) >>> start datetime(2014, 6, 17, 0, 0, 0) >>> end datetime(2014, 6, 17, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, month, day) end = datetime(year, month, day) + timedelta(days=1) - delta if not return_string: return start, end else: return str(start), str(end) def month_interval(year, month, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a month. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.month_interval(2000, 2) >>> start datetime(2000, 2, 1, 0, 0, 0) >>> end datetime(2000, 2, 29, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) if month == 12: start = datetime(year, month, 1) end = datetime(year + 1, 1, 1) - delta else: start = datetime(year, month, 1) end = datetime(year, month + 1, 1) - delta if not return_string: return start, end else: return str(start), str(end) def year_interval(year, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a year. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.year_interval(2007) >>> start datetime(2007, 1, 1, 0, 0, 0) >>> end datetime(2007, 12, 31, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, 1, 1) end = datetime(year + 1, 1, 1) - delta if not return_string: return start, end else: return str(start), str(end)
MacHu-GWU/rolex-project
rolex/generator.py
rnd_datetime
python
def rnd_datetime(start=datetime(1970, 1, 1), end=datetime.now()): start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _rnd_datetime(start, end)
Generate a random datetime between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.datetime, (default datetime(1970, 1, 1)) :param end: Right bound :type end: string or datetime.datetime, (default datetime.now()) :return: a datetime.datetime object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的时间。
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/generator.py#L334-L351
[ "def _assert_correct_start_end(start, end):\n if start > end: # pragma: no cover\n raise ValueError(\"start time has to be earlier than end time!\")\n", "def _rnd_datetime(start, end):\n \"\"\"\n Internal random datetime generator.\n \"\"\"\n return from_utctimestamp(\n random.randin...
# -*- coding: utf-8 -*- import random from datetime import date, datetime, timedelta try: # pragma: no cover import numpy as np has_np = True except: # pragma: no cover has_np = False from .pkg.sixmini import integer_types, string_types from .parse import parser from .util import ( from_utctimestamp, to_utctimestamp, from_ordinal, to_ordinal, ) _valid_freq = [ "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", ] def _freq_parser(freq): # pragma: no cover """ Parse frequency to timedelta. Valid keywords "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", """ freq = freq.lower().strip() error_message = "'%s' is invalid, use one of %s" % (freq, _valid_freq) try: # day for surfix in ["days", "day", "d"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq)) # hour for surfix in ["hours", "hour", "h"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(hours=int(freq)) # minute for surfix in ["minutes", "minute", "min", "m"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(minutes=int(freq)) # second for surfix in ["seconds", "second", "sec", "s"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(seconds=int(freq)) # week for surfix in ["weeks", "week", "w"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq) * 7) except: pass raise ValueError(error_message) def time_series(start=None, end=None, periods=None, freq="1day", normalize=False, return_date=False): """ A pure Python implementation of pandas.date_range(). Given 2 of start, end, periods and freq, generate a series of datetime object. :param start: Left bound for generating dates :type start: str or datetime.datetime (default None) :param end: Right bound for generating dates :type end: str or datetime.datetime (default None) :param periods: Number of date points. If None, must specify start and end :type periods: integer (default None) :param freq: string, default '1day' (calendar daily) Available mode are day, hour, min, sec Frequency strings can have multiples. e.g. '7day', '6hour', '5min', '4sec', '3week` :type freq: string (default '1day' calendar daily) :param normalize: Trigger that normalize start/end dates to midnight :type normalize: boolean (default False) :param return_date: Trigger that only return date object. :type return_date: boolean (default False) :return: A list of datetime.datetime object. An evenly sampled time series. Usage:: >>> from __future__ import print_function >>> for dt in rolex.time_series("2014-1-1", "2014-1-7"): ... print(dt) 2014-01-01 00:00:00 2014-01-02 00:00:00 2014-01-03 00:00:00 2014-01-04 00:00:00 2014-01-05 00:00:00 2014-01-06 00:00:00 2014-01-07 00:00:00 **中文文档** 生成等间隔的时间序列。 需要给出, "起始", "结束", "数量" 中的任意两个。以及指定"频率"。以此唯一 确定一个等间隔时间序列。"频率"项所支持的命令字符有"7day", "6hour", "5min", "4sec", "3week" (可以改变数字). """ def normalize_datetime_to_midnight(dt): """Normalize a datetime %Y-%m-%d %H:%M:%S to %Y-%m-%d 00:00:00. """ return datetime(dt.year, dt.month, dt.day) def not_normalize(dt): """Do not normalize. """ return dt series = list() # if two of start, end, or periods exist if (bool(start) + bool(end) + bool(periods)) != 2: raise ValueError( "Must specify two of 'start', 'end', or 'periods'.") if normalize: converter = normalize_datetime_to_midnight else: converter = not_normalize interval = _freq_parser(freq) if (bool(start) & bool(end)): # start and end start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) start = start - interval while 1: start += interval if start <= end: series.append(converter(start)) else: break elif (bool(start) & bool(periods)): # start and periods start = parser.parse_datetime(start) start = start - interval for _ in range(periods): start += interval series.append(converter(start)) elif (bool(end) & bool(periods)): # end and periods end = parser.parse_datetime(end) start = end - interval * periods for _ in range(periods): start += interval series.append(converter(start)) if return_date: # pragma: no cover series = [i.date() for i in series] return series def weekday_series(start, end, weekday, return_date=False): """Generate a datetime series with same weekday number. ISO weekday number: Mon to Sun = 1 to 7 Usage:: >>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25" >>> rolex.weekday_series(start, end, weekday=2) # All Tuesday [ datetime(2014, 1, 7, 6, 30, 25), datetime(2014, 1, 14, 6, 30, 25), datetime(2014, 1, 21, 6, 30, 25), datetime(2014, 1, 28, 6, 30, 25), ] :param weekday: int or list of int :returns: list of datetime **中文文档** 生成星期数一致的时间序列。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) if isinstance(weekday, integer_types): weekday = [weekday, ] series = list() for i in time_series(start, end, freq="1day", return_date=return_date): if i.isoweekday() in weekday: series.append(i) return series # --- Random Generator --- def _randn(size, rnd_generator, *args, **kwargs): if isinstance(size, integer_types): if size < 0: raise ValueError("'size' can't smaller than zero") return [rnd_generator(*args, **kwargs) for _ in range(size)] else: try: m, n = size[0], size[1] if ((m < 0) or (n < 0)): raise ValueError("'size' can't smaller than zero") return [[rnd_generator(*args, **kwargs) for _ in range(n)] for _ in range(m)] except: raise ValueError("'size' has to be int or tuple. " "e.g. 6 or (2, 3)") def _assert_correct_start_end(start, end): if start > end: # pragma: no cover raise ValueError("start time has to be earlier than end time!") def _rnd_date(start, end): """Internal random date generator. """ return date.fromordinal(random.randint(start.toordinal(), end.toordinal())) def rnd_date(start=date(1970, 1, 1), end=None, **kwargs): """ Generate a random date between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.date, (default date(1970, 1, 1)) :param end: Right bound :type end: string or datetime.date, (default date.today()) :return: a datetime.date object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的日期。 """ if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _rnd_date(start, end) def rnd_date_array(size, start=date(1970, 1, 1), end=None, **kwargs): """ Array or Matrix of random date generator. :returns: 1d or 2d array of datetime.date """ if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_date, start, end) def rnd_date_list_high_performance(size, start=date(1970, 1, 1), end=None, **kwargs): """ Generate mass random date. :param size: int, number of :param start: date similar object, int / str / date / datetime :param end: date similar object, int / str / date / datetime, default today's date :param kwargs: args placeholder :return: list of datetime.date """ if end is None: end = date.today() start_days = to_ordinal(parser.parse_datetime(start)) end_days = to_ordinal(parser.parse_datetime(end)) _assert_correct_start_end(start_days, end_days) if has_np: # pragma: no cover return [ from_ordinal(days) for days in np.random.randint(start_days, end_days, size) ] else: return [ from_ordinal(random.randint(start_days, end_days)) for _ in range(size) ] def _rnd_datetime(start, end): """ Internal random datetime generator. """ return from_utctimestamp( random.randint( int(to_utctimestamp(start)), int(to_utctimestamp(end)), ) ) def rnd_datetime_array(size, start=datetime(1970, 1, 1), end=None): """ Array or Matrix of random datetime generator. :returns: 1d or 2d array of datetime.date """ if end is None: end = datetime.now() start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_datetime, start, end) def rnd_datetime_list_high_performance(size, start=datetime(1970, 1, 1), end=None): if end is None: end = datetime.now() start_ts = to_utctimestamp(parser.parse_datetime(start)) end_ts = to_utctimestamp(parser.parse_datetime(end)) _assert_correct_start_end(start, end) interval_range = end_ts - start_ts if has_np: # pragma: no cover return [ from_utctimestamp(v * interval_range + start_ts) for v in np.random.random(size) ] else: return [ from_utctimestamp(random.random() * interval_range + start_ts) for _ in range(size) ] def day_interval(year, month, day, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a day. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.day_interval(2014, 6, 17) >>> start datetime(2014, 6, 17, 0, 0, 0) >>> end datetime(2014, 6, 17, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, month, day) end = datetime(year, month, day) + timedelta(days=1) - delta if not return_string: return start, end else: return str(start), str(end) def month_interval(year, month, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a month. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.month_interval(2000, 2) >>> start datetime(2000, 2, 1, 0, 0, 0) >>> end datetime(2000, 2, 29, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) if month == 12: start = datetime(year, month, 1) end = datetime(year + 1, 1, 1) - delta else: start = datetime(year, month, 1) end = datetime(year, month + 1, 1) - delta if not return_string: return start, end else: return str(start), str(end) def year_interval(year, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a year. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.year_interval(2007) >>> start datetime(2007, 1, 1, 0, 0, 0) >>> end datetime(2007, 12, 31, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, 1, 1) end = datetime(year + 1, 1, 1) - delta if not return_string: return start, end else: return str(start), str(end)
MacHu-GWU/rolex-project
rolex/generator.py
rnd_datetime_array
python
def rnd_datetime_array(size, start=datetime(1970, 1, 1), end=None): if end is None: end = datetime.now() start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_datetime, start, end)
Array or Matrix of random datetime generator. :returns: 1d or 2d array of datetime.date
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/generator.py#L354-L365
[ "def _assert_correct_start_end(start, end):\n if start > end: # pragma: no cover\n raise ValueError(\"start time has to be earlier than end time!\")\n", "def _randn(size, rnd_generator, *args, **kwargs):\n if isinstance(size, integer_types):\n if size < 0:\n raise ValueError(\"'siz...
# -*- coding: utf-8 -*- import random from datetime import date, datetime, timedelta try: # pragma: no cover import numpy as np has_np = True except: # pragma: no cover has_np = False from .pkg.sixmini import integer_types, string_types from .parse import parser from .util import ( from_utctimestamp, to_utctimestamp, from_ordinal, to_ordinal, ) _valid_freq = [ "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", ] def _freq_parser(freq): # pragma: no cover """ Parse frequency to timedelta. Valid keywords "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", """ freq = freq.lower().strip() error_message = "'%s' is invalid, use one of %s" % (freq, _valid_freq) try: # day for surfix in ["days", "day", "d"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq)) # hour for surfix in ["hours", "hour", "h"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(hours=int(freq)) # minute for surfix in ["minutes", "minute", "min", "m"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(minutes=int(freq)) # second for surfix in ["seconds", "second", "sec", "s"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(seconds=int(freq)) # week for surfix in ["weeks", "week", "w"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq) * 7) except: pass raise ValueError(error_message) def time_series(start=None, end=None, periods=None, freq="1day", normalize=False, return_date=False): """ A pure Python implementation of pandas.date_range(). Given 2 of start, end, periods and freq, generate a series of datetime object. :param start: Left bound for generating dates :type start: str or datetime.datetime (default None) :param end: Right bound for generating dates :type end: str or datetime.datetime (default None) :param periods: Number of date points. If None, must specify start and end :type periods: integer (default None) :param freq: string, default '1day' (calendar daily) Available mode are day, hour, min, sec Frequency strings can have multiples. e.g. '7day', '6hour', '5min', '4sec', '3week` :type freq: string (default '1day' calendar daily) :param normalize: Trigger that normalize start/end dates to midnight :type normalize: boolean (default False) :param return_date: Trigger that only return date object. :type return_date: boolean (default False) :return: A list of datetime.datetime object. An evenly sampled time series. Usage:: >>> from __future__ import print_function >>> for dt in rolex.time_series("2014-1-1", "2014-1-7"): ... print(dt) 2014-01-01 00:00:00 2014-01-02 00:00:00 2014-01-03 00:00:00 2014-01-04 00:00:00 2014-01-05 00:00:00 2014-01-06 00:00:00 2014-01-07 00:00:00 **中文文档** 生成等间隔的时间序列。 需要给出, "起始", "结束", "数量" 中的任意两个。以及指定"频率"。以此唯一 确定一个等间隔时间序列。"频率"项所支持的命令字符有"7day", "6hour", "5min", "4sec", "3week" (可以改变数字). """ def normalize_datetime_to_midnight(dt): """Normalize a datetime %Y-%m-%d %H:%M:%S to %Y-%m-%d 00:00:00. """ return datetime(dt.year, dt.month, dt.day) def not_normalize(dt): """Do not normalize. """ return dt series = list() # if two of start, end, or periods exist if (bool(start) + bool(end) + bool(periods)) != 2: raise ValueError( "Must specify two of 'start', 'end', or 'periods'.") if normalize: converter = normalize_datetime_to_midnight else: converter = not_normalize interval = _freq_parser(freq) if (bool(start) & bool(end)): # start and end start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) start = start - interval while 1: start += interval if start <= end: series.append(converter(start)) else: break elif (bool(start) & bool(periods)): # start and periods start = parser.parse_datetime(start) start = start - interval for _ in range(periods): start += interval series.append(converter(start)) elif (bool(end) & bool(periods)): # end and periods end = parser.parse_datetime(end) start = end - interval * periods for _ in range(periods): start += interval series.append(converter(start)) if return_date: # pragma: no cover series = [i.date() for i in series] return series def weekday_series(start, end, weekday, return_date=False): """Generate a datetime series with same weekday number. ISO weekday number: Mon to Sun = 1 to 7 Usage:: >>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25" >>> rolex.weekday_series(start, end, weekday=2) # All Tuesday [ datetime(2014, 1, 7, 6, 30, 25), datetime(2014, 1, 14, 6, 30, 25), datetime(2014, 1, 21, 6, 30, 25), datetime(2014, 1, 28, 6, 30, 25), ] :param weekday: int or list of int :returns: list of datetime **中文文档** 生成星期数一致的时间序列。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) if isinstance(weekday, integer_types): weekday = [weekday, ] series = list() for i in time_series(start, end, freq="1day", return_date=return_date): if i.isoweekday() in weekday: series.append(i) return series # --- Random Generator --- def _randn(size, rnd_generator, *args, **kwargs): if isinstance(size, integer_types): if size < 0: raise ValueError("'size' can't smaller than zero") return [rnd_generator(*args, **kwargs) for _ in range(size)] else: try: m, n = size[0], size[1] if ((m < 0) or (n < 0)): raise ValueError("'size' can't smaller than zero") return [[rnd_generator(*args, **kwargs) for _ in range(n)] for _ in range(m)] except: raise ValueError("'size' has to be int or tuple. " "e.g. 6 or (2, 3)") def _assert_correct_start_end(start, end): if start > end: # pragma: no cover raise ValueError("start time has to be earlier than end time!") def _rnd_date(start, end): """Internal random date generator. """ return date.fromordinal(random.randint(start.toordinal(), end.toordinal())) def rnd_date(start=date(1970, 1, 1), end=None, **kwargs): """ Generate a random date between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.date, (default date(1970, 1, 1)) :param end: Right bound :type end: string or datetime.date, (default date.today()) :return: a datetime.date object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的日期。 """ if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _rnd_date(start, end) def rnd_date_array(size, start=date(1970, 1, 1), end=None, **kwargs): """ Array or Matrix of random date generator. :returns: 1d or 2d array of datetime.date """ if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_date, start, end) def rnd_date_list_high_performance(size, start=date(1970, 1, 1), end=None, **kwargs): """ Generate mass random date. :param size: int, number of :param start: date similar object, int / str / date / datetime :param end: date similar object, int / str / date / datetime, default today's date :param kwargs: args placeholder :return: list of datetime.date """ if end is None: end = date.today() start_days = to_ordinal(parser.parse_datetime(start)) end_days = to_ordinal(parser.parse_datetime(end)) _assert_correct_start_end(start_days, end_days) if has_np: # pragma: no cover return [ from_ordinal(days) for days in np.random.randint(start_days, end_days, size) ] else: return [ from_ordinal(random.randint(start_days, end_days)) for _ in range(size) ] def _rnd_datetime(start, end): """ Internal random datetime generator. """ return from_utctimestamp( random.randint( int(to_utctimestamp(start)), int(to_utctimestamp(end)), ) ) def rnd_datetime(start=datetime(1970, 1, 1), end=datetime.now()): """ Generate a random datetime between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.datetime, (default datetime(1970, 1, 1)) :param end: Right bound :type end: string or datetime.datetime, (default datetime.now()) :return: a datetime.datetime object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的时间。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _rnd_datetime(start, end) def rnd_datetime_list_high_performance(size, start=datetime(1970, 1, 1), end=None): if end is None: end = datetime.now() start_ts = to_utctimestamp(parser.parse_datetime(start)) end_ts = to_utctimestamp(parser.parse_datetime(end)) _assert_correct_start_end(start, end) interval_range = end_ts - start_ts if has_np: # pragma: no cover return [ from_utctimestamp(v * interval_range + start_ts) for v in np.random.random(size) ] else: return [ from_utctimestamp(random.random() * interval_range + start_ts) for _ in range(size) ] def day_interval(year, month, day, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a day. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.day_interval(2014, 6, 17) >>> start datetime(2014, 6, 17, 0, 0, 0) >>> end datetime(2014, 6, 17, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, month, day) end = datetime(year, month, day) + timedelta(days=1) - delta if not return_string: return start, end else: return str(start), str(end) def month_interval(year, month, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a month. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.month_interval(2000, 2) >>> start datetime(2000, 2, 1, 0, 0, 0) >>> end datetime(2000, 2, 29, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) if month == 12: start = datetime(year, month, 1) end = datetime(year + 1, 1, 1) - delta else: start = datetime(year, month, 1) end = datetime(year, month + 1, 1) - delta if not return_string: return start, end else: return str(start), str(end) def year_interval(year, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a year. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.year_interval(2007) >>> start datetime(2007, 1, 1, 0, 0, 0) >>> end datetime(2007, 12, 31, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, 1, 1) end = datetime(year + 1, 1, 1) - delta if not return_string: return start, end else: return str(start), str(end)
MacHu-GWU/rolex-project
rolex/generator.py
day_interval
python
def day_interval(year, month, day, milliseconds=False, return_string=False): if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, month, day) end = datetime(year, month, day) + timedelta(days=1) - delta if not return_string: return start, end else: return str(start), str(end)
Return a start datetime and end datetime of a day. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.day_interval(2014, 6, 17) >>> start datetime(2014, 6, 17, 0, 0, 0) >>> end datetime(2014, 6, 17, 23, 59, 59)
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/generator.py#L387-L414
null
# -*- coding: utf-8 -*- import random from datetime import date, datetime, timedelta try: # pragma: no cover import numpy as np has_np = True except: # pragma: no cover has_np = False from .pkg.sixmini import integer_types, string_types from .parse import parser from .util import ( from_utctimestamp, to_utctimestamp, from_ordinal, to_ordinal, ) _valid_freq = [ "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", ] def _freq_parser(freq): # pragma: no cover """ Parse frequency to timedelta. Valid keywords "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", """ freq = freq.lower().strip() error_message = "'%s' is invalid, use one of %s" % (freq, _valid_freq) try: # day for surfix in ["days", "day", "d"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq)) # hour for surfix in ["hours", "hour", "h"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(hours=int(freq)) # minute for surfix in ["minutes", "minute", "min", "m"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(minutes=int(freq)) # second for surfix in ["seconds", "second", "sec", "s"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(seconds=int(freq)) # week for surfix in ["weeks", "week", "w"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq) * 7) except: pass raise ValueError(error_message) def time_series(start=None, end=None, periods=None, freq="1day", normalize=False, return_date=False): """ A pure Python implementation of pandas.date_range(). Given 2 of start, end, periods and freq, generate a series of datetime object. :param start: Left bound for generating dates :type start: str or datetime.datetime (default None) :param end: Right bound for generating dates :type end: str or datetime.datetime (default None) :param periods: Number of date points. If None, must specify start and end :type periods: integer (default None) :param freq: string, default '1day' (calendar daily) Available mode are day, hour, min, sec Frequency strings can have multiples. e.g. '7day', '6hour', '5min', '4sec', '3week` :type freq: string (default '1day' calendar daily) :param normalize: Trigger that normalize start/end dates to midnight :type normalize: boolean (default False) :param return_date: Trigger that only return date object. :type return_date: boolean (default False) :return: A list of datetime.datetime object. An evenly sampled time series. Usage:: >>> from __future__ import print_function >>> for dt in rolex.time_series("2014-1-1", "2014-1-7"): ... print(dt) 2014-01-01 00:00:00 2014-01-02 00:00:00 2014-01-03 00:00:00 2014-01-04 00:00:00 2014-01-05 00:00:00 2014-01-06 00:00:00 2014-01-07 00:00:00 **中文文档** 生成等间隔的时间序列。 需要给出, "起始", "结束", "数量" 中的任意两个。以及指定"频率"。以此唯一 确定一个等间隔时间序列。"频率"项所支持的命令字符有"7day", "6hour", "5min", "4sec", "3week" (可以改变数字). """ def normalize_datetime_to_midnight(dt): """Normalize a datetime %Y-%m-%d %H:%M:%S to %Y-%m-%d 00:00:00. """ return datetime(dt.year, dt.month, dt.day) def not_normalize(dt): """Do not normalize. """ return dt series = list() # if two of start, end, or periods exist if (bool(start) + bool(end) + bool(periods)) != 2: raise ValueError( "Must specify two of 'start', 'end', or 'periods'.") if normalize: converter = normalize_datetime_to_midnight else: converter = not_normalize interval = _freq_parser(freq) if (bool(start) & bool(end)): # start and end start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) start = start - interval while 1: start += interval if start <= end: series.append(converter(start)) else: break elif (bool(start) & bool(periods)): # start and periods start = parser.parse_datetime(start) start = start - interval for _ in range(periods): start += interval series.append(converter(start)) elif (bool(end) & bool(periods)): # end and periods end = parser.parse_datetime(end) start = end - interval * periods for _ in range(periods): start += interval series.append(converter(start)) if return_date: # pragma: no cover series = [i.date() for i in series] return series def weekday_series(start, end, weekday, return_date=False): """Generate a datetime series with same weekday number. ISO weekday number: Mon to Sun = 1 to 7 Usage:: >>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25" >>> rolex.weekday_series(start, end, weekday=2) # All Tuesday [ datetime(2014, 1, 7, 6, 30, 25), datetime(2014, 1, 14, 6, 30, 25), datetime(2014, 1, 21, 6, 30, 25), datetime(2014, 1, 28, 6, 30, 25), ] :param weekday: int or list of int :returns: list of datetime **中文文档** 生成星期数一致的时间序列。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) if isinstance(weekday, integer_types): weekday = [weekday, ] series = list() for i in time_series(start, end, freq="1day", return_date=return_date): if i.isoweekday() in weekday: series.append(i) return series # --- Random Generator --- def _randn(size, rnd_generator, *args, **kwargs): if isinstance(size, integer_types): if size < 0: raise ValueError("'size' can't smaller than zero") return [rnd_generator(*args, **kwargs) for _ in range(size)] else: try: m, n = size[0], size[1] if ((m < 0) or (n < 0)): raise ValueError("'size' can't smaller than zero") return [[rnd_generator(*args, **kwargs) for _ in range(n)] for _ in range(m)] except: raise ValueError("'size' has to be int or tuple. " "e.g. 6 or (2, 3)") def _assert_correct_start_end(start, end): if start > end: # pragma: no cover raise ValueError("start time has to be earlier than end time!") def _rnd_date(start, end): """Internal random date generator. """ return date.fromordinal(random.randint(start.toordinal(), end.toordinal())) def rnd_date(start=date(1970, 1, 1), end=None, **kwargs): """ Generate a random date between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.date, (default date(1970, 1, 1)) :param end: Right bound :type end: string or datetime.date, (default date.today()) :return: a datetime.date object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的日期。 """ if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _rnd_date(start, end) def rnd_date_array(size, start=date(1970, 1, 1), end=None, **kwargs): """ Array or Matrix of random date generator. :returns: 1d or 2d array of datetime.date """ if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_date, start, end) def rnd_date_list_high_performance(size, start=date(1970, 1, 1), end=None, **kwargs): """ Generate mass random date. :param size: int, number of :param start: date similar object, int / str / date / datetime :param end: date similar object, int / str / date / datetime, default today's date :param kwargs: args placeholder :return: list of datetime.date """ if end is None: end = date.today() start_days = to_ordinal(parser.parse_datetime(start)) end_days = to_ordinal(parser.parse_datetime(end)) _assert_correct_start_end(start_days, end_days) if has_np: # pragma: no cover return [ from_ordinal(days) for days in np.random.randint(start_days, end_days, size) ] else: return [ from_ordinal(random.randint(start_days, end_days)) for _ in range(size) ] def _rnd_datetime(start, end): """ Internal random datetime generator. """ return from_utctimestamp( random.randint( int(to_utctimestamp(start)), int(to_utctimestamp(end)), ) ) def rnd_datetime(start=datetime(1970, 1, 1), end=datetime.now()): """ Generate a random datetime between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.datetime, (default datetime(1970, 1, 1)) :param end: Right bound :type end: string or datetime.datetime, (default datetime.now()) :return: a datetime.datetime object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的时间。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _rnd_datetime(start, end) def rnd_datetime_array(size, start=datetime(1970, 1, 1), end=None): """ Array or Matrix of random datetime generator. :returns: 1d or 2d array of datetime.date """ if end is None: end = datetime.now() start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_datetime, start, end) def rnd_datetime_list_high_performance(size, start=datetime(1970, 1, 1), end=None): if end is None: end = datetime.now() start_ts = to_utctimestamp(parser.parse_datetime(start)) end_ts = to_utctimestamp(parser.parse_datetime(end)) _assert_correct_start_end(start, end) interval_range = end_ts - start_ts if has_np: # pragma: no cover return [ from_utctimestamp(v * interval_range + start_ts) for v in np.random.random(size) ] else: return [ from_utctimestamp(random.random() * interval_range + start_ts) for _ in range(size) ] def month_interval(year, month, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a month. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.month_interval(2000, 2) >>> start datetime(2000, 2, 1, 0, 0, 0) >>> end datetime(2000, 2, 29, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) if month == 12: start = datetime(year, month, 1) end = datetime(year + 1, 1, 1) - delta else: start = datetime(year, month, 1) end = datetime(year, month + 1, 1) - delta if not return_string: return start, end else: return str(start), str(end) def year_interval(year, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a year. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.year_interval(2007) >>> start datetime(2007, 1, 1, 0, 0, 0) >>> end datetime(2007, 12, 31, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, 1, 1) end = datetime(year + 1, 1, 1) - delta if not return_string: return start, end else: return str(start), str(end)
MacHu-GWU/rolex-project
rolex/generator.py
month_interval
python
def month_interval(year, month, milliseconds=False, return_string=False): if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) if month == 12: start = datetime(year, month, 1) end = datetime(year + 1, 1, 1) - delta else: start = datetime(year, month, 1) end = datetime(year, month + 1, 1) - delta if not return_string: return start, end else: return str(start), str(end)
Return a start datetime and end datetime of a month. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.month_interval(2000, 2) >>> start datetime(2000, 2, 1, 0, 0, 0) >>> end datetime(2000, 2, 29, 23, 59, 59)
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/generator.py#L417-L448
null
# -*- coding: utf-8 -*- import random from datetime import date, datetime, timedelta try: # pragma: no cover import numpy as np has_np = True except: # pragma: no cover has_np = False from .pkg.sixmini import integer_types, string_types from .parse import parser from .util import ( from_utctimestamp, to_utctimestamp, from_ordinal, to_ordinal, ) _valid_freq = [ "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", ] def _freq_parser(freq): # pragma: no cover """ Parse frequency to timedelta. Valid keywords "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", """ freq = freq.lower().strip() error_message = "'%s' is invalid, use one of %s" % (freq, _valid_freq) try: # day for surfix in ["days", "day", "d"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq)) # hour for surfix in ["hours", "hour", "h"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(hours=int(freq)) # minute for surfix in ["minutes", "minute", "min", "m"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(minutes=int(freq)) # second for surfix in ["seconds", "second", "sec", "s"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(seconds=int(freq)) # week for surfix in ["weeks", "week", "w"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq) * 7) except: pass raise ValueError(error_message) def time_series(start=None, end=None, periods=None, freq="1day", normalize=False, return_date=False): """ A pure Python implementation of pandas.date_range(). Given 2 of start, end, periods and freq, generate a series of datetime object. :param start: Left bound for generating dates :type start: str or datetime.datetime (default None) :param end: Right bound for generating dates :type end: str or datetime.datetime (default None) :param periods: Number of date points. If None, must specify start and end :type periods: integer (default None) :param freq: string, default '1day' (calendar daily) Available mode are day, hour, min, sec Frequency strings can have multiples. e.g. '7day', '6hour', '5min', '4sec', '3week` :type freq: string (default '1day' calendar daily) :param normalize: Trigger that normalize start/end dates to midnight :type normalize: boolean (default False) :param return_date: Trigger that only return date object. :type return_date: boolean (default False) :return: A list of datetime.datetime object. An evenly sampled time series. Usage:: >>> from __future__ import print_function >>> for dt in rolex.time_series("2014-1-1", "2014-1-7"): ... print(dt) 2014-01-01 00:00:00 2014-01-02 00:00:00 2014-01-03 00:00:00 2014-01-04 00:00:00 2014-01-05 00:00:00 2014-01-06 00:00:00 2014-01-07 00:00:00 **中文文档** 生成等间隔的时间序列。 需要给出, "起始", "结束", "数量" 中的任意两个。以及指定"频率"。以此唯一 确定一个等间隔时间序列。"频率"项所支持的命令字符有"7day", "6hour", "5min", "4sec", "3week" (可以改变数字). """ def normalize_datetime_to_midnight(dt): """Normalize a datetime %Y-%m-%d %H:%M:%S to %Y-%m-%d 00:00:00. """ return datetime(dt.year, dt.month, dt.day) def not_normalize(dt): """Do not normalize. """ return dt series = list() # if two of start, end, or periods exist if (bool(start) + bool(end) + bool(periods)) != 2: raise ValueError( "Must specify two of 'start', 'end', or 'periods'.") if normalize: converter = normalize_datetime_to_midnight else: converter = not_normalize interval = _freq_parser(freq) if (bool(start) & bool(end)): # start and end start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) start = start - interval while 1: start += interval if start <= end: series.append(converter(start)) else: break elif (bool(start) & bool(periods)): # start and periods start = parser.parse_datetime(start) start = start - interval for _ in range(periods): start += interval series.append(converter(start)) elif (bool(end) & bool(periods)): # end and periods end = parser.parse_datetime(end) start = end - interval * periods for _ in range(periods): start += interval series.append(converter(start)) if return_date: # pragma: no cover series = [i.date() for i in series] return series def weekday_series(start, end, weekday, return_date=False): """Generate a datetime series with same weekday number. ISO weekday number: Mon to Sun = 1 to 7 Usage:: >>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25" >>> rolex.weekday_series(start, end, weekday=2) # All Tuesday [ datetime(2014, 1, 7, 6, 30, 25), datetime(2014, 1, 14, 6, 30, 25), datetime(2014, 1, 21, 6, 30, 25), datetime(2014, 1, 28, 6, 30, 25), ] :param weekday: int or list of int :returns: list of datetime **中文文档** 生成星期数一致的时间序列。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) if isinstance(weekday, integer_types): weekday = [weekday, ] series = list() for i in time_series(start, end, freq="1day", return_date=return_date): if i.isoweekday() in weekday: series.append(i) return series # --- Random Generator --- def _randn(size, rnd_generator, *args, **kwargs): if isinstance(size, integer_types): if size < 0: raise ValueError("'size' can't smaller than zero") return [rnd_generator(*args, **kwargs) for _ in range(size)] else: try: m, n = size[0], size[1] if ((m < 0) or (n < 0)): raise ValueError("'size' can't smaller than zero") return [[rnd_generator(*args, **kwargs) for _ in range(n)] for _ in range(m)] except: raise ValueError("'size' has to be int or tuple. " "e.g. 6 or (2, 3)") def _assert_correct_start_end(start, end): if start > end: # pragma: no cover raise ValueError("start time has to be earlier than end time!") def _rnd_date(start, end): """Internal random date generator. """ return date.fromordinal(random.randint(start.toordinal(), end.toordinal())) def rnd_date(start=date(1970, 1, 1), end=None, **kwargs): """ Generate a random date between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.date, (default date(1970, 1, 1)) :param end: Right bound :type end: string or datetime.date, (default date.today()) :return: a datetime.date object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的日期。 """ if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _rnd_date(start, end) def rnd_date_array(size, start=date(1970, 1, 1), end=None, **kwargs): """ Array or Matrix of random date generator. :returns: 1d or 2d array of datetime.date """ if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_date, start, end) def rnd_date_list_high_performance(size, start=date(1970, 1, 1), end=None, **kwargs): """ Generate mass random date. :param size: int, number of :param start: date similar object, int / str / date / datetime :param end: date similar object, int / str / date / datetime, default today's date :param kwargs: args placeholder :return: list of datetime.date """ if end is None: end = date.today() start_days = to_ordinal(parser.parse_datetime(start)) end_days = to_ordinal(parser.parse_datetime(end)) _assert_correct_start_end(start_days, end_days) if has_np: # pragma: no cover return [ from_ordinal(days) for days in np.random.randint(start_days, end_days, size) ] else: return [ from_ordinal(random.randint(start_days, end_days)) for _ in range(size) ] def _rnd_datetime(start, end): """ Internal random datetime generator. """ return from_utctimestamp( random.randint( int(to_utctimestamp(start)), int(to_utctimestamp(end)), ) ) def rnd_datetime(start=datetime(1970, 1, 1), end=datetime.now()): """ Generate a random datetime between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.datetime, (default datetime(1970, 1, 1)) :param end: Right bound :type end: string or datetime.datetime, (default datetime.now()) :return: a datetime.datetime object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的时间。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _rnd_datetime(start, end) def rnd_datetime_array(size, start=datetime(1970, 1, 1), end=None): """ Array or Matrix of random datetime generator. :returns: 1d or 2d array of datetime.date """ if end is None: end = datetime.now() start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_datetime, start, end) def rnd_datetime_list_high_performance(size, start=datetime(1970, 1, 1), end=None): if end is None: end = datetime.now() start_ts = to_utctimestamp(parser.parse_datetime(start)) end_ts = to_utctimestamp(parser.parse_datetime(end)) _assert_correct_start_end(start, end) interval_range = end_ts - start_ts if has_np: # pragma: no cover return [ from_utctimestamp(v * interval_range + start_ts) for v in np.random.random(size) ] else: return [ from_utctimestamp(random.random() * interval_range + start_ts) for _ in range(size) ] def day_interval(year, month, day, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a day. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.day_interval(2014, 6, 17) >>> start datetime(2014, 6, 17, 0, 0, 0) >>> end datetime(2014, 6, 17, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, month, day) end = datetime(year, month, day) + timedelta(days=1) - delta if not return_string: return start, end else: return str(start), str(end) def year_interval(year, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a year. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.year_interval(2007) >>> start datetime(2007, 1, 1, 0, 0, 0) >>> end datetime(2007, 12, 31, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, 1, 1) end = datetime(year + 1, 1, 1) - delta if not return_string: return start, end else: return str(start), str(end)
MacHu-GWU/rolex-project
rolex/generator.py
year_interval
python
def year_interval(year, milliseconds=False, return_string=False): if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, 1, 1) end = datetime(year + 1, 1, 1) - delta if not return_string: return start, end else: return str(start), str(end)
Return a start datetime and end datetime of a year. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.year_interval(2007) >>> start datetime(2007, 1, 1, 0, 0, 0) >>> end datetime(2007, 12, 31, 23, 59, 59)
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/generator.py#L451-L478
null
# -*- coding: utf-8 -*- import random from datetime import date, datetime, timedelta try: # pragma: no cover import numpy as np has_np = True except: # pragma: no cover has_np = False from .pkg.sixmini import integer_types, string_types from .parse import parser from .util import ( from_utctimestamp, to_utctimestamp, from_ordinal, to_ordinal, ) _valid_freq = [ "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", ] def _freq_parser(freq): # pragma: no cover """ Parse frequency to timedelta. Valid keywords "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", """ freq = freq.lower().strip() error_message = "'%s' is invalid, use one of %s" % (freq, _valid_freq) try: # day for surfix in ["days", "day", "d"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq)) # hour for surfix in ["hours", "hour", "h"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(hours=int(freq)) # minute for surfix in ["minutes", "minute", "min", "m"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(minutes=int(freq)) # second for surfix in ["seconds", "second", "sec", "s"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(seconds=int(freq)) # week for surfix in ["weeks", "week", "w"]: if freq.endswith(surfix): freq = freq.replace(surfix, "") return timedelta(days=int(freq) * 7) except: pass raise ValueError(error_message) def time_series(start=None, end=None, periods=None, freq="1day", normalize=False, return_date=False): """ A pure Python implementation of pandas.date_range(). Given 2 of start, end, periods and freq, generate a series of datetime object. :param start: Left bound for generating dates :type start: str or datetime.datetime (default None) :param end: Right bound for generating dates :type end: str or datetime.datetime (default None) :param periods: Number of date points. If None, must specify start and end :type periods: integer (default None) :param freq: string, default '1day' (calendar daily) Available mode are day, hour, min, sec Frequency strings can have multiples. e.g. '7day', '6hour', '5min', '4sec', '3week` :type freq: string (default '1day' calendar daily) :param normalize: Trigger that normalize start/end dates to midnight :type normalize: boolean (default False) :param return_date: Trigger that only return date object. :type return_date: boolean (default False) :return: A list of datetime.datetime object. An evenly sampled time series. Usage:: >>> from __future__ import print_function >>> for dt in rolex.time_series("2014-1-1", "2014-1-7"): ... print(dt) 2014-01-01 00:00:00 2014-01-02 00:00:00 2014-01-03 00:00:00 2014-01-04 00:00:00 2014-01-05 00:00:00 2014-01-06 00:00:00 2014-01-07 00:00:00 **中文文档** 生成等间隔的时间序列。 需要给出, "起始", "结束", "数量" 中的任意两个。以及指定"频率"。以此唯一 确定一个等间隔时间序列。"频率"项所支持的命令字符有"7day", "6hour", "5min", "4sec", "3week" (可以改变数字). """ def normalize_datetime_to_midnight(dt): """Normalize a datetime %Y-%m-%d %H:%M:%S to %Y-%m-%d 00:00:00. """ return datetime(dt.year, dt.month, dt.day) def not_normalize(dt): """Do not normalize. """ return dt series = list() # if two of start, end, or periods exist if (bool(start) + bool(end) + bool(periods)) != 2: raise ValueError( "Must specify two of 'start', 'end', or 'periods'.") if normalize: converter = normalize_datetime_to_midnight else: converter = not_normalize interval = _freq_parser(freq) if (bool(start) & bool(end)): # start and end start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) start = start - interval while 1: start += interval if start <= end: series.append(converter(start)) else: break elif (bool(start) & bool(periods)): # start and periods start = parser.parse_datetime(start) start = start - interval for _ in range(periods): start += interval series.append(converter(start)) elif (bool(end) & bool(periods)): # end and periods end = parser.parse_datetime(end) start = end - interval * periods for _ in range(periods): start += interval series.append(converter(start)) if return_date: # pragma: no cover series = [i.date() for i in series] return series def weekday_series(start, end, weekday, return_date=False): """Generate a datetime series with same weekday number. ISO weekday number: Mon to Sun = 1 to 7 Usage:: >>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25" >>> rolex.weekday_series(start, end, weekday=2) # All Tuesday [ datetime(2014, 1, 7, 6, 30, 25), datetime(2014, 1, 14, 6, 30, 25), datetime(2014, 1, 21, 6, 30, 25), datetime(2014, 1, 28, 6, 30, 25), ] :param weekday: int or list of int :returns: list of datetime **中文文档** 生成星期数一致的时间序列。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) if isinstance(weekday, integer_types): weekday = [weekday, ] series = list() for i in time_series(start, end, freq="1day", return_date=return_date): if i.isoweekday() in weekday: series.append(i) return series # --- Random Generator --- def _randn(size, rnd_generator, *args, **kwargs): if isinstance(size, integer_types): if size < 0: raise ValueError("'size' can't smaller than zero") return [rnd_generator(*args, **kwargs) for _ in range(size)] else: try: m, n = size[0], size[1] if ((m < 0) or (n < 0)): raise ValueError("'size' can't smaller than zero") return [[rnd_generator(*args, **kwargs) for _ in range(n)] for _ in range(m)] except: raise ValueError("'size' has to be int or tuple. " "e.g. 6 or (2, 3)") def _assert_correct_start_end(start, end): if start > end: # pragma: no cover raise ValueError("start time has to be earlier than end time!") def _rnd_date(start, end): """Internal random date generator. """ return date.fromordinal(random.randint(start.toordinal(), end.toordinal())) def rnd_date(start=date(1970, 1, 1), end=None, **kwargs): """ Generate a random date between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.date, (default date(1970, 1, 1)) :param end: Right bound :type end: string or datetime.date, (default date.today()) :return: a datetime.date object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的日期。 """ if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _rnd_date(start, end) def rnd_date_array(size, start=date(1970, 1, 1), end=None, **kwargs): """ Array or Matrix of random date generator. :returns: 1d or 2d array of datetime.date """ if end is None: end = date.today() start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_date, start, end) def rnd_date_list_high_performance(size, start=date(1970, 1, 1), end=None, **kwargs): """ Generate mass random date. :param size: int, number of :param start: date similar object, int / str / date / datetime :param end: date similar object, int / str / date / datetime, default today's date :param kwargs: args placeholder :return: list of datetime.date """ if end is None: end = date.today() start_days = to_ordinal(parser.parse_datetime(start)) end_days = to_ordinal(parser.parse_datetime(end)) _assert_correct_start_end(start_days, end_days) if has_np: # pragma: no cover return [ from_ordinal(days) for days in np.random.randint(start_days, end_days, size) ] else: return [ from_ordinal(random.randint(start_days, end_days)) for _ in range(size) ] def _rnd_datetime(start, end): """ Internal random datetime generator. """ return from_utctimestamp( random.randint( int(to_utctimestamp(start)), int(to_utctimestamp(end)), ) ) def rnd_datetime(start=datetime(1970, 1, 1), end=datetime.now()): """ Generate a random datetime between ``start`` to ``end``. :param start: Left bound :type start: string or datetime.datetime, (default datetime(1970, 1, 1)) :param end: Right bound :type end: string or datetime.datetime, (default datetime.now()) :return: a datetime.datetime object **中文文档** 随机生成一个位于 ``start`` 和 ``end`` 之间的时间。 """ start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _rnd_datetime(start, end) def rnd_datetime_array(size, start=datetime(1970, 1, 1), end=None): """ Array or Matrix of random datetime generator. :returns: 1d or 2d array of datetime.date """ if end is None: end = datetime.now() start = parser.parse_datetime(start) end = parser.parse_datetime(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_datetime, start, end) def rnd_datetime_list_high_performance(size, start=datetime(1970, 1, 1), end=None): if end is None: end = datetime.now() start_ts = to_utctimestamp(parser.parse_datetime(start)) end_ts = to_utctimestamp(parser.parse_datetime(end)) _assert_correct_start_end(start, end) interval_range = end_ts - start_ts if has_np: # pragma: no cover return [ from_utctimestamp(v * interval_range + start_ts) for v in np.random.random(size) ] else: return [ from_utctimestamp(random.random() * interval_range + start_ts) for _ in range(size) ] def day_interval(year, month, day, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a day. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.day_interval(2014, 6, 17) >>> start datetime(2014, 6, 17, 0, 0, 0) >>> end datetime(2014, 6, 17, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) start = datetime(year, month, day) end = datetime(year, month, day) + timedelta(days=1) - delta if not return_string: return start, end else: return str(start), str(end) def month_interval(year, month, milliseconds=False, return_string=False): """ Return a start datetime and end datetime of a month. :param milliseconds: Minimum time resolution. :param return_string: If you want string instead of datetime, set True Usage Example:: >>> start, end = rolex.month_interval(2000, 2) >>> start datetime(2000, 2, 1, 0, 0, 0) >>> end datetime(2000, 2, 29, 23, 59, 59) """ if milliseconds: # pragma: no cover delta = timedelta(milliseconds=1) else: delta = timedelta(seconds=1) if month == 12: start = datetime(year, month, 1) end = datetime(year + 1, 1, 1) - delta else: start = datetime(year, month, 1) end = datetime(year, month + 1, 1) - delta if not return_string: return start, end else: return str(start), str(end)
rosshamish/catanlog
catanlog.py
CatanLog._log
python
def _log(self, content): self._buffer += content if self._auto_flush: self.flush()
Write a string to the log
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L51-L57
[ "def flush(self):\n \"\"\"\n Append the latest updates to file, or optionally to stdout instead. See the constructor\n for logging options.\n \"\"\"\n latest = self._latest()\n self._chars_flushed += len(latest)\n if self._use_stdout:\n file = sys.stdout\n else:\n file = open(s...
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog.reset
python
def reset(self): self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now()
Erase the log and reset the timestamp
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L71-L77
null
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog.logpath
python
def logpath(self): name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path
Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively.
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L91-L106
[ "def timestamp_str(self):\n return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S')\n" ]
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog.flush
python
def flush(self): latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close()
Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options.
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L111-L126
[ "def _latest(self):\n \"\"\"\n Get all characters written to _log since the last flush()\n \"\"\"\n return self._buffer[self._chars_flushed:]\n", "def logpath(self):\n \"\"\"\n Return the logfile path and filename as a string.\n\n The file with name self.logpath() is written to on flush().\n\...
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog.log_game_start
python
def log_game_start(self, players, terrain, numbers, ports): self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!')
Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects.
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L128-L149
[ "def _logln(self, content):\n \"\"\"\n Write a string to the log, appending a newline\n \"\"\"\n self._log('{0}\\n'.format(content))\n", "def reset(self):\n \"\"\"\n Erase the log and reset the timestamp\n \"\"\"\n self._buffer = ''\n self._chars_flushed = 0\n self._game_start_timest...
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog.log_player_roll
python
def log_player_roll(self, player, roll): self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else ''))
:param player: catan.game.Player :param roll: integer or string, the sum of the dice
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L151-L156
[ "def _logln(self, content):\n \"\"\"\n Write a string to the log, appending a newline\n \"\"\"\n self._log('{0}\\n'.format(content))\n" ]
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog.log_player_buys_road
python
def log_player_buys_road(self, player, location): self._logln('{0} buys road, builds at {1}'.format( player.color, location ))
:param player: catan.game.Player :param location: string, see hexgrid.location()
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L170-L178
[ "def _logln(self, content):\n \"\"\"\n Write a string to the log, appending a newline\n \"\"\"\n self._log('{0}\\n'.format(content))\n" ]
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog.log_player_buys_settlement
python
def log_player_buys_settlement(self, player, location): self._logln('{0} buys settlement, builds at {1}'.format( player.color, location ))
:param player: catan.game.Player :param location: string, see hexgrid.location()
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L180-L188
[ "def _logln(self, content):\n \"\"\"\n Write a string to the log, appending a newline\n \"\"\"\n self._log('{0}\\n'.format(content))\n" ]
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog.log_player_buys_city
python
def log_player_buys_city(self, player, location): self._logln('{0} buys city, builds at {1}'.format( player.color, location ))
:param player: catan.game.Player :param location: string, see hexgrid.location()
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L190-L198
[ "def _logln(self, content):\n \"\"\"\n Write a string to the log, appending a newline\n \"\"\"\n self._log('{0}\\n'.format(content))\n" ]
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog.log_player_trades_with_port
python
def log_player_trades_with_port(self, player, to_port, port, to_player): self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n')
:param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)]
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L208-L235
[ "def _log(self, content):\n \"\"\"\n Write a string to the log\n \"\"\"\n self._buffer += content\n if self._auto_flush:\n self.flush()\n" ]
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog.log_player_trades_with_other_player
python
def log_player_trades_with_other_player(self, player, to_other, other, to_player): self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n')
:param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)]
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L237-L264
[ "def _log(self, content):\n \"\"\"\n Write a string to the log\n \"\"\"\n self._buffer += content\n if self._auto_flush:\n self.flush()\n" ]
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog.log_player_plays_knight
python
def log_player_plays_knight(self, player, location, victim): self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim)
:param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L266-L273
[ "def _logln(self, content):\n \"\"\"\n Write a string to the log, appending a newline\n \"\"\"\n self._log('{0}\\n'.format(content))\n", "def log_player_moves_robber_and_steals(self, player, location, victim):\n \"\"\"\n :param player: catan.game.Player\n :param location: string, see hexgrid....
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog.log_player_plays_road_builder
python
def log_player_plays_road_builder(self, player, location1, location2): self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 ))
:param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location()
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L275-L285
[ "def _logln(self, content):\n \"\"\"\n Write a string to the log, appending a newline\n \"\"\"\n self._log('{0}\\n'.format(content))\n" ]
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog.log_player_plays_year_of_plenty
python
def log_player_plays_year_of_plenty(self, player, resource1, resource2): self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value ))
:param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L287-L297
[ "def _logln(self, content):\n \"\"\"\n Write a string to the log, appending a newline\n \"\"\"\n self._log('{0}\\n'.format(content))\n" ]
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog.log_player_plays_monopoly
python
def log_player_plays_monopoly(self, player, resource): self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value ))
:param player: catan.game.Player :param resource: catan.board.Terrain
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L299-L307
[ "def _logln(self, content):\n \"\"\"\n Write a string to the log, appending a newline\n \"\"\"\n self._log('{0}\\n'.format(content))\n" ]
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog.log_player_ends_turn
python
def log_player_ends_turn(self, player): seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now()
:param player: catan.game.Player
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L315-L321
[ "def _logln(self, content):\n \"\"\"\n Write a string to the log, appending a newline\n \"\"\"\n self._log('{0}\\n'.format(content))\n" ]
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog._log_board_terrain
python
def _log_board_terrain(self, terrain): self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain)))
Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L329-L336
[ "def _logln(self, content):\n \"\"\"\n Write a string to the log, appending a newline\n \"\"\"\n self._log('{0}\\n'.format(content))\n" ]
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog._log_board_numbers
python
def _log_board_numbers(self, numbers): self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers)))
Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects.
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L338-L345
[ "def _logln(self, content):\n \"\"\"\n Write a string to the log, appending a newline\n \"\"\"\n self._log('{0}\\n'.format(content))\n" ]
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog._log_board_ports
python
def _log_board_ports(self, ports): ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports)))
A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L347-L359
[ "def _logln(self, content):\n \"\"\"\n Write a string to the log, appending a newline\n \"\"\"\n self._log('{0}\\n'.format(content))\n" ]
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog._log_players
python
def _log_players(self, players): self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat))
:param players: list of catan.game.Player objects
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L361-L367
[ "def _logln(self, content):\n \"\"\"\n Write a string to the log, appending a newline\n \"\"\"\n self._log('{0}\\n'.format(content))\n" ]
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _set_players(self, _players): """ Players will always be set in seat order (1,2,3,4) """ self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
rosshamish/catanlog
catanlog.py
CatanLog._set_players
python
def _set_players(self, _players): self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
Players will always be set in seat order (1,2,3,4)
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/catanlog.py#L369-L377
null
class CatanLog(object): """ class CatanLog introduces a machine-parsable, human-readable log of all actions made in a game of Catan. Each log contains all publicly known information in the game. Each log is sufficient to 'replay' a game from a spectator's point of view. This logger is for raw game actions only. No derivable or inferrable information will be logged. - e.g. players discarding cards on a 7 is not logged, because it is derivable from previous rolls, purchases, etc. The files are explicitly versioned by the class variable version, and versioning follows semver. Use #dump to get the log as a string. Use #flush to write the log to a file. TODO maybe log private information as well (which dev card picked up, which card stolen) """ def __init__(self, auto_flush=True, log_dir='log', use_stdout=False): """ Create a CatanLog object using the given options. The defaults are fine. :param auto_flush: flush the log to file after every log() call, bool :param log_dir: directory to write the log to, str :param use_stdout: if True, flush() will write to stdout instead of to file """ self._buffer = str() self._chars_flushed = 0 self._auto_flush = auto_flush self._log_dir = log_dir self._use_stdout = use_stdout self._game_start_timestamp = datetime.datetime.now() self._latest_timestamp = copy.deepcopy(self._game_start_timestamp) self._players = list() def _log(self, content): """ Write a string to the log """ self._buffer += content if self._auto_flush: self.flush() def _logln(self, content): """ Write a string to the log, appending a newline """ self._log('{0}\n'.format(content)) def eraseln(self): """ Erase the latest line from the log """ self._buffer = '\n'.join(self._buffer.split('\n')[:-2]) def reset(self): """ Erase the log and reset the timestamp """ self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now() def dump(self): """ Dump the entire log to a string, and return it """ return self._buffer def _latest(self): """ Get all characters written to _log since the last flush() """ return self._buffer[self._chars_flushed:] def logpath(self): """ Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively. """ name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path def timestamp_str(self): return self._game_start_timestamp.strftime('%Y-%m-%d %H:%M:%S') def flush(self): """ Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options. """ latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close() def log_game_start(self, players, terrain, numbers, ports): """ Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects. """ self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!') def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) def log_player_moves_robber_and_steals(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} moves robber to {1}, steals from {2}'.format( player.color, location, victim.color )) def log_player_buys_road(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys road, builds at {1}'.format( player.color, location )) def log_player_buys_settlement(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys settlement, builds at {1}'.format( player.color, location )) def log_player_buys_city(self, player, location): """ :param player: catan.game.Player :param location: string, see hexgrid.location() """ self._logln('{0} buys city, builds at {1}'.format( player.color, location )) def log_player_buys_dev_card(self, player): """ :param player: catan.game.Player """ self._logln('{0} buys dev card'.format( player.color )) def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_trades_with_other_player(self, player, to_other, other, to_player): """ :param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] """ self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n') def log_player_plays_knight(self, player, location, victim): """ :param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player """ self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim) def log_player_plays_road_builder(self, player, location1, location2): """ :param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location() """ self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 )) def log_player_plays_year_of_plenty(self, player, resource1, resource2): """ :param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain """ self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value )) def log_player_plays_monopoly(self, player, resource): """ :param player: catan.game.Player :param resource: catan.board.Terrain """ self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value )) def log_player_plays_victory_point(self, player): """ :param player: catan.game.Player """ self._logln('{0} plays victory point'.format(player.color)) def log_player_ends_turn(self, player): """ :param player: catan.game.Player """ seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now() def log_player_wins(self, player): """ :param player: catan.game.Player """ self._logln('{0} wins'.format(player.color)) def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain))) def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers))) def _log_board_ports(self, ports): """ A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects """ ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports))) def _log_players(self, players): """ :param players: list of catan.game.Player objects """ self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat))
rosshamish/catanlog
spec/steps/thens.py
step_impl
python
def step_impl(context): expected_lines = context.text.split('\n') assert len(expected_lines) == len(context.output) for expected, actual in zip(expected_lines, context.output): print('--\n\texpected: {}\n\tactual: {}'.format(expected, actual)) assert expected == actual
Compares text as written to the log output
train
https://github.com/rosshamish/catanlog/blob/6f204920d9b67fd53fc6ff6a1c7b6a756b009bf0/spec/steps/thens.py#L13-L19
null
from behave import * import re @then('it should look exactly like "{text}"') def step_impl(context, text): print(context.output) assert len(context.output) == 1 assert text == context.output[0] @then('it should look exactly like') @then('it should look like "{regex}"') def step_impl(context, regex): print(context.output) assert len(context.output) == 1 assert re.fullmatch(regex, context.output[0]) @then('it should look like') def step_impl(context): """Compares text as regex to the log output""" expected_lines = context.text.split('\n') assert len(expected_lines) == len(context.output) for expected, actual in zip(expected_lines, context.output): print('--\n\texpected: {}\n\tactual: {}'.format(expected, actual)) assert re.match(expected, actual) @then('print output') def step_impl(context): print(context.output) assert False
XRDX/pyleap
pyleap/event.py
on_mouse_motion
python
def on_mouse_motion(x, y, dx, dy): mouse.x, mouse.y = x, y mouse.move() window.update_caption(mouse)
当鼠标没有按下时移动的时候触发
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/event.py#L9-L13
[ "def move(self):\n \"\"\" 触发鼠标移动事件 \"\"\"\n self._move()\n" ]
from pyleap.window import window from pyleap.mouse import mouse from pyleap.collision import shape_clicked from pyleap.util import all_shapes from pyleap.key import key @window.event @window.event def on_mouse_drag(x, y, dx, dy, buttons, modifiers): """ 当鼠标按下并且移动的时候触发 """ mouse.x, mouse.y = x, y mouse.move() class MouseKeyCode: """ button 1 - 左键 2 - 滚轮 4 - 右键 """ LEFT = 1 MIDDLE = 2 RIGHT = 4 @window.event def on_mouse_press(x, y, button, modifiers): """ 按下鼠标时 """ if button == MouseKeyCode.LEFT: mouse.press() elif button == MouseKeyCode.RIGHT: mouse.right_press() # 判断是否有图形的点击事件被触发了 shapes = list(all_shapes) while shapes: shape = shapes.pop() if(shape._press and shape_clicked(shape)): shape._press() @window.event def on_mouse_release(x, y, button, modifiers): """ 松开鼠标时 """ if button == MouseKeyCode.LEFT: mouse.release() elif button == MouseKeyCode.RIGHT: mouse.right_release() @window.event def on_key_press(symbol, modifiers): """ 当键盘按键按下时触发 """ try: key[symbol].press() except: pass @window.event def on_key_release(symbol, modifiers): """ 当键盘按键松开时触发 """ try: key[symbol].release() except: pass @window.event def on_move(x, y): import configparser config = configparser.ConfigParser() config['location'] = { 'x': str(x), 'y': str(y)} try: with open('download/config.ini', 'w') as configfile: config.write(configfile) except: pass
XRDX/pyleap
pyleap/event.py
on_mouse_drag
python
def on_mouse_drag(x, y, dx, dy, buttons, modifiers): mouse.x, mouse.y = x, y mouse.move()
当鼠标按下并且移动的时候触发
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/event.py#L17-L20
[ "def move(self):\n \"\"\" 触发鼠标移动事件 \"\"\"\n self._move()\n" ]
from pyleap.window import window from pyleap.mouse import mouse from pyleap.collision import shape_clicked from pyleap.util import all_shapes from pyleap.key import key @window.event def on_mouse_motion(x, y, dx, dy): """ 当鼠标没有按下时移动的时候触发 """ mouse.x, mouse.y = x, y mouse.move() window.update_caption(mouse) @window.event class MouseKeyCode: """ button 1 - 左键 2 - 滚轮 4 - 右键 """ LEFT = 1 MIDDLE = 2 RIGHT = 4 @window.event def on_mouse_press(x, y, button, modifiers): """ 按下鼠标时 """ if button == MouseKeyCode.LEFT: mouse.press() elif button == MouseKeyCode.RIGHT: mouse.right_press() # 判断是否有图形的点击事件被触发了 shapes = list(all_shapes) while shapes: shape = shapes.pop() if(shape._press and shape_clicked(shape)): shape._press() @window.event def on_mouse_release(x, y, button, modifiers): """ 松开鼠标时 """ if button == MouseKeyCode.LEFT: mouse.release() elif button == MouseKeyCode.RIGHT: mouse.right_release() @window.event def on_key_press(symbol, modifiers): """ 当键盘按键按下时触发 """ try: key[symbol].press() except: pass @window.event def on_key_release(symbol, modifiers): """ 当键盘按键松开时触发 """ try: key[symbol].release() except: pass @window.event def on_move(x, y): import configparser config = configparser.ConfigParser() config['location'] = { 'x': str(x), 'y': str(y)} try: with open('download/config.ini', 'w') as configfile: config.write(configfile) except: pass
XRDX/pyleap
pyleap/event.py
on_mouse_press
python
def on_mouse_press(x, y, button, modifiers): """ 按下鼠标时 """ if button == MouseKeyCode.LEFT: mouse.press() elif button == MouseKeyCode.RIGHT: mouse.right_press() # 判断是否有图形的点击事件被触发了 shapes = list(all_shapes) while shapes: shape = shapes.pop() if(shape._press and shape_clicked(shape)): shape._press()
按下鼠标时
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/event.py#L35-L49
[ "def shape_clicked(shape):\n shape.transform.update_points(shape.points)\n return point_in_points((mouse.x, mouse.y), shape.transform)\n", "def press(self):\n \"\"\" 触发鼠标左键点击事件 \"\"\"\n self.LEFT = True\n self._press()\n", "def right_press(self):\n \"\"\" 触发鼠标右击事件 \"\"\"\n self.RIGHT = True...
from pyleap.window import window from pyleap.mouse import mouse from pyleap.collision import shape_clicked from pyleap.util import all_shapes from pyleap.key import key @window.event def on_mouse_motion(x, y, dx, dy): """ 当鼠标没有按下时移动的时候触发 """ mouse.x, mouse.y = x, y mouse.move() window.update_caption(mouse) @window.event def on_mouse_drag(x, y, dx, dy, buttons, modifiers): """ 当鼠标按下并且移动的时候触发 """ mouse.x, mouse.y = x, y mouse.move() class MouseKeyCode: """ button 1 - 左键 2 - 滚轮 4 - 右键 """ LEFT = 1 MIDDLE = 2 RIGHT = 4 @window.event @window.event def on_mouse_release(x, y, button, modifiers): """ 松开鼠标时 """ if button == MouseKeyCode.LEFT: mouse.release() elif button == MouseKeyCode.RIGHT: mouse.right_release() @window.event def on_key_press(symbol, modifiers): """ 当键盘按键按下时触发 """ try: key[symbol].press() except: pass @window.event def on_key_release(symbol, modifiers): """ 当键盘按键松开时触发 """ try: key[symbol].release() except: pass @window.event def on_move(x, y): import configparser config = configparser.ConfigParser() config['location'] = { 'x': str(x), 'y': str(y)} try: with open('download/config.ini', 'w') as configfile: config.write(configfile) except: pass
XRDX/pyleap
pyleap/event.py
on_mouse_release
python
def on_mouse_release(x, y, button, modifiers): """ 松开鼠标时 """ if button == MouseKeyCode.LEFT: mouse.release() elif button == MouseKeyCode.RIGHT: mouse.right_release()
松开鼠标时
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/event.py#L53-L58
[ "def release(self):\n \"\"\" 触发鼠标左键松开事件 \"\"\"\n self.LEFT = False\n self._release()\n", "def right_release(self):\n \"\"\" 触发鼠标右键松开事件 \"\"\"\n self.RIGHT = False\n self._right_release()\n" ]
from pyleap.window import window from pyleap.mouse import mouse from pyleap.collision import shape_clicked from pyleap.util import all_shapes from pyleap.key import key @window.event def on_mouse_motion(x, y, dx, dy): """ 当鼠标没有按下时移动的时候触发 """ mouse.x, mouse.y = x, y mouse.move() window.update_caption(mouse) @window.event def on_mouse_drag(x, y, dx, dy, buttons, modifiers): """ 当鼠标按下并且移动的时候触发 """ mouse.x, mouse.y = x, y mouse.move() class MouseKeyCode: """ button 1 - 左键 2 - 滚轮 4 - 右键 """ LEFT = 1 MIDDLE = 2 RIGHT = 4 @window.event def on_mouse_press(x, y, button, modifiers): """ 按下鼠标时 """ if button == MouseKeyCode.LEFT: mouse.press() elif button == MouseKeyCode.RIGHT: mouse.right_press() # 判断是否有图形的点击事件被触发了 shapes = list(all_shapes) while shapes: shape = shapes.pop() if(shape._press and shape_clicked(shape)): shape._press() @window.event @window.event def on_key_press(symbol, modifiers): """ 当键盘按键按下时触发 """ try: key[symbol].press() except: pass @window.event def on_key_release(symbol, modifiers): """ 当键盘按键松开时触发 """ try: key[symbol].release() except: pass @window.event def on_move(x, y): import configparser config = configparser.ConfigParser() config['location'] = { 'x': str(x), 'y': str(y)} try: with open('download/config.ini', 'w') as configfile: config.write(configfile) except: pass
XRDX/pyleap
pyleap/collision.py
line_cross
python
def line_cross(x1, y1, x2, y2, x3, y3, x4, y4): # out of the rect if min(x1, x2) > max(x3, x4) or max(x1, x2) < min(x3, x4) or \ min(y1, y2) > max(y3, y4) or max(y1, y2) < min(y3, y4): return False # same slope rate if ((y1 - y2) * (x3 - x4) == (x1 - x2) * (y3 - y4)): return False if cross_product(x3, y3, x2, y2, x4, y4) * cross_product(x3, y3, x4, y4, x1, y1) < 0 or \ cross_product(x1, y1, x4, y4, x2, y2) * cross_product(x1, y1, x2, y2, x3, y3) < 0: return False # get collide point b1 = (y2 - y1) * x1 + (x1 - x2) * y1 b2 = (y4 - y3) * x3 + (x3 - x4) * y3 D = (x2 - x1) * (y4 - y3) - (x4 - x3) * (y2 - y1) D1 = b2 * (x2 - x1) - b1 * (x4 - x3) D2 = b2 * (y2 - y1) - b1 * (y4 - y3) return P(D1 / D, D2 / D)
判断两条线段是否交叉
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/collision.py#L66-L88
[ "def cross_product (x1, y1, x2, y2, x3, y3):\n \"\"\" 叉乘\n vector 1: x1, y1, x2, y2\n vector 2: x1, y1, x3, y3\n \"\"\"\n return (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)\n" ]
""" 判断2个基本图形是否发生碰撞, 如果没有碰撞,则返回False 如果碰撞,则返回其中一个碰撞的坐标点,如 {'x': 100, 'y': 200} """ from pyleap.mouse import mouse from pyleap.util import P __all__ = ['shape_clicked', 'CollisionMixin' ] def shape_clicked(shape): shape.transform.update_points(shape.points) return point_in_points((mouse.x, mouse.y), shape.transform) def point_in_points(p, s2): x = p[0] y = p[1] cross_count = 0 for i in range(0, len(s2.points), 2): x1 = s2.points[i-2] y1 = s2.points[i-1] x2 = s2.points[i] y2 = s2.points[i+1] if (x1 < x and x2 < x) or (y1-y)*(y2-y) > 0 or (y1==y2) or (y2==y): continue cross_x = x1 - (x1-x2)*(y1-y)/(y1-y2) if(cross_x >= x): cross_count += 1 return cross_count % 2 def points_in_points(s1, s2): for i in range(0, len(s1.points), 2): x = s1.points[i] y = s1.points[i+1] # outside the collide rect if(x < s2.min_x or x > s2.max_x or y < s2.min_y or y > s2.max_y): continue if(point_in_points((x, y), s2)): return P(x, y) return False def lines_cross(s1, s2): for i in range(0, len(s1.points), 2): x1 = s1.points[i-2] y1 = s1.points[i-1] x2 = s1.points[i] y2 = s1.points[i+1] for i in range(0, len(s2.points), 2): x3 = s2.points[i-2] y3 = s2.points[i-1] x4 = s2.points[i] y4 = s2.points[i+1] p = line_cross(x1, y1, x2, y2, x3, y3, x4, y4) if p: return p return False def cross_product (x1, y1, x2, y2, x3, y3): """ 叉乘 vector 1: x1, y1, x2, y2 vector 2: x1, y1, x3, y3 """ return (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1) class CollisionMixin(): """ 碰撞图形 将任意图形转换为多边形进行判断,图形需要拥有points属性 按照以下步骤进行判断 1. 如果图形的外接矩形没有碰撞,返回False 2. 如果图形的点在目标图形内,返回这个点 3. 如果图形的边和目标图形的边相交,返回相交点 4. 返回False """ def update_collision_rect(self): """ 获取外接矩形 """ self.min_x = min(self.points[::2]) self.max_x = max(self.points[::2]) self.min_y = min(self.points[1::2]) self.max_y = max(self.points[1::2]) def collide(self, s2): """ 判断图形是否碰到了另外一个图形 """ s1 = self s1.update_points() s2.update_points() if not (s1.points and s2.points): return False t1 = s1.transform t2 = s2.transform t1.update_points(s1.points) t2.update_points(s2.points) # 更新外接矩形 t1.update_collision_rect() t2.update_collision_rect() # simple collide rect if not (t1.min_x < t2.max_x and t1.max_x > t2.min_x \ and t1.min_y < t2.max_y and t1.max_y > t2.min_y): return False return points_in_points(t1, t2) or \ points_in_points(t2, t1) or \ lines_cross(t1, t2) def on_press(self, f): """ 注册on_press函数,当图形被点击时,触发func函数 """ self._press = f
XRDX/pyleap
pyleap/collision.py
cross_product
python
def cross_product (x1, y1, x2, y2, x3, y3): return (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)
叉乘 vector 1: x1, y1, x2, y2 vector 2: x1, y1, x3, y3
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/collision.py#L91-L96
null
""" 判断2个基本图形是否发生碰撞, 如果没有碰撞,则返回False 如果碰撞,则返回其中一个碰撞的坐标点,如 {'x': 100, 'y': 200} """ from pyleap.mouse import mouse from pyleap.util import P __all__ = ['shape_clicked', 'CollisionMixin' ] def shape_clicked(shape): shape.transform.update_points(shape.points) return point_in_points((mouse.x, mouse.y), shape.transform) def point_in_points(p, s2): x = p[0] y = p[1] cross_count = 0 for i in range(0, len(s2.points), 2): x1 = s2.points[i-2] y1 = s2.points[i-1] x2 = s2.points[i] y2 = s2.points[i+1] if (x1 < x and x2 < x) or (y1-y)*(y2-y) > 0 or (y1==y2) or (y2==y): continue cross_x = x1 - (x1-x2)*(y1-y)/(y1-y2) if(cross_x >= x): cross_count += 1 return cross_count % 2 def points_in_points(s1, s2): for i in range(0, len(s1.points), 2): x = s1.points[i] y = s1.points[i+1] # outside the collide rect if(x < s2.min_x or x > s2.max_x or y < s2.min_y or y > s2.max_y): continue if(point_in_points((x, y), s2)): return P(x, y) return False def lines_cross(s1, s2): for i in range(0, len(s1.points), 2): x1 = s1.points[i-2] y1 = s1.points[i-1] x2 = s1.points[i] y2 = s1.points[i+1] for i in range(0, len(s2.points), 2): x3 = s2.points[i-2] y3 = s2.points[i-1] x4 = s2.points[i] y4 = s2.points[i+1] p = line_cross(x1, y1, x2, y2, x3, y3, x4, y4) if p: return p return False def line_cross(x1, y1, x2, y2, x3, y3, x4, y4): """ 判断两条线段是否交叉 """ # out of the rect if min(x1, x2) > max(x3, x4) or max(x1, x2) < min(x3, x4) or \ min(y1, y2) > max(y3, y4) or max(y1, y2) < min(y3, y4): return False # same slope rate if ((y1 - y2) * (x3 - x4) == (x1 - x2) * (y3 - y4)): return False if cross_product(x3, y3, x2, y2, x4, y4) * cross_product(x3, y3, x4, y4, x1, y1) < 0 or \ cross_product(x1, y1, x4, y4, x2, y2) * cross_product(x1, y1, x2, y2, x3, y3) < 0: return False # get collide point b1 = (y2 - y1) * x1 + (x1 - x2) * y1 b2 = (y4 - y3) * x3 + (x3 - x4) * y3 D = (x2 - x1) * (y4 - y3) - (x4 - x3) * (y2 - y1) D1 = b2 * (x2 - x1) - b1 * (x4 - x3) D2 = b2 * (y2 - y1) - b1 * (y4 - y3) return P(D1 / D, D2 / D) class CollisionMixin(): """ 碰撞图形 将任意图形转换为多边形进行判断,图形需要拥有points属性 按照以下步骤进行判断 1. 如果图形的外接矩形没有碰撞,返回False 2. 如果图形的点在目标图形内,返回这个点 3. 如果图形的边和目标图形的边相交,返回相交点 4. 返回False """ def update_collision_rect(self): """ 获取外接矩形 """ self.min_x = min(self.points[::2]) self.max_x = max(self.points[::2]) self.min_y = min(self.points[1::2]) self.max_y = max(self.points[1::2]) def collide(self, s2): """ 判断图形是否碰到了另外一个图形 """ s1 = self s1.update_points() s2.update_points() if not (s1.points and s2.points): return False t1 = s1.transform t2 = s2.transform t1.update_points(s1.points) t2.update_points(s2.points) # 更新外接矩形 t1.update_collision_rect() t2.update_collision_rect() # simple collide rect if not (t1.min_x < t2.max_x and t1.max_x > t2.min_x \ and t1.min_y < t2.max_y and t1.max_y > t2.min_y): return False return points_in_points(t1, t2) or \ points_in_points(t2, t1) or \ lines_cross(t1, t2) def on_press(self, f): """ 注册on_press函数,当图形被点击时,触发func函数 """ self._press = f
XRDX/pyleap
pyleap/collision.py
CollisionMixin.update_collision_rect
python
def update_collision_rect(self): self.min_x = min(self.points[::2]) self.max_x = max(self.points[::2]) self.min_y = min(self.points[1::2]) self.max_y = max(self.points[1::2])
获取外接矩形
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/collision.py#L111-L116
null
class CollisionMixin(): """ 碰撞图形 将任意图形转换为多边形进行判断,图形需要拥有points属性 按照以下步骤进行判断 1. 如果图形的外接矩形没有碰撞,返回False 2. 如果图形的点在目标图形内,返回这个点 3. 如果图形的边和目标图形的边相交,返回相交点 4. 返回False """ def collide(self, s2): """ 判断图形是否碰到了另外一个图形 """ s1 = self s1.update_points() s2.update_points() if not (s1.points and s2.points): return False t1 = s1.transform t2 = s2.transform t1.update_points(s1.points) t2.update_points(s2.points) # 更新外接矩形 t1.update_collision_rect() t2.update_collision_rect() # simple collide rect if not (t1.min_x < t2.max_x and t1.max_x > t2.min_x \ and t1.min_y < t2.max_y and t1.max_y > t2.min_y): return False return points_in_points(t1, t2) or \ points_in_points(t2, t1) or \ lines_cross(t1, t2) def on_press(self, f): """ 注册on_press函数,当图形被点击时,触发func函数 """ self._press = f
XRDX/pyleap
pyleap/collision.py
CollisionMixin.collide
python
def collide(self, s2): s1 = self s1.update_points() s2.update_points() if not (s1.points and s2.points): return False t1 = s1.transform t2 = s2.transform t1.update_points(s1.points) t2.update_points(s2.points) # 更新外接矩形 t1.update_collision_rect() t2.update_collision_rect() # simple collide rect if not (t1.min_x < t2.max_x and t1.max_x > t2.min_x \ and t1.min_y < t2.max_y and t1.max_y > t2.min_y): return False return points_in_points(t1, t2) or \ points_in_points(t2, t1) or \ lines_cross(t1, t2)
判断图形是否碰到了另外一个图形
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/collision.py#L118-L145
[ "def points_in_points(s1, s2):\n for i in range(0, len(s1.points), 2):\n x = s1.points[i]\n y = s1.points[i+1]\n\n # outside the collide rect\n if(x < s2.min_x or x > s2.max_x or y < s2.min_y or y > s2.max_y):\n continue\n\n if(point_in_points((x, y), s2)):\n ...
class CollisionMixin(): """ 碰撞图形 将任意图形转换为多边形进行判断,图形需要拥有points属性 按照以下步骤进行判断 1. 如果图形的外接矩形没有碰撞,返回False 2. 如果图形的点在目标图形内,返回这个点 3. 如果图形的边和目标图形的边相交,返回相交点 4. 返回False """ def update_collision_rect(self): """ 获取外接矩形 """ self.min_x = min(self.points[::2]) self.max_x = max(self.points[::2]) self.min_y = min(self.points[1::2]) self.max_y = max(self.points[1::2]) def collide(self, s2): """ 判断图形是否碰到了另外一个图形 """ s1 = self s1.update_points() s2.update_points() if not (s1.points and s2.points): return False t1 = s1.transform t2 = s2.transform t1.update_points(s1.points) t2.update_points(s2.points) # 更新外接矩形 t1.update_collision_rect() t2.update_collision_rect() # simple collide rect if not (t1.min_x < t2.max_x and t1.max_x > t2.min_x \ and t1.min_y < t2.max_y and t1.max_y > t2.min_y): return False return points_in_points(t1, t2) or \ points_in_points(t2, t1) or \ lines_cross(t1, t2) def on_press(self, f): """ 注册on_press函数,当图形被点击时,触发func函数 """ self._press = f
XRDX/pyleap
pyleap/window.py
Window.update_caption
python
def update_caption(self, mouse): caption = "{} x: {}, y: {}".format(self._title, mouse.x, mouse.y) super().set_caption(caption)
添加坐标显示
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/window.py#L104-L107
null
class Window(pyglet.window.Window): """ 属性 Attributes caption str,窗口标题,只读. width/w 窗口宽度,单位像素点,只读。 height/h 窗口高度,单位像素点,只读。 方法 Methods clear() 清除窗口里的内容 set_caption(caption) 设置窗口标题 Parameters: caption (str or unicode) set_size(width, height) 设置窗口大小 """ def __init__(self): """ 初始化,创建一个窗口 """ if platform.system() =="Windows": template = pyglet.gl.Config(alpha_size=8, sample_buffers=1, samples=4) configs = screen.get_matching_configs(template) if not configs: super().__init__() else: try: super().__init__(config=configs[0]) except Exception: super().__init__() else: # Mac or Linux super().__init__() self.set_caption("LeapLearner") self.set_location(location_x, location_y) self.axis_batch = None @property def w(self): """ width """ return self.width @property def h(self): """ height """ return self.height @property def center_x(self): return self.width // 2 @property def center_y(self): return self.height // 2 @property def caption(self): return self._title def set_caption(self, caption): self._title = caption def clear(self): all_shapes.clear() super().clear() def show_axis(self): if self.axis_batch is None: self.create_axis_batch() self.axis_batch.draw() def create_axis_batch(self): self.axis_batch = pyglet.graphics.Batch() for x in range(0, self.w, 100): self.axis_batch.add( 2, pyglet.gl.GL_LINES, None, ('v2i', (x, 0, x, self.h)), ('c3B', (240, 160, 0) * 2)) pyglet.text.Label(str(x), x=x+2, y=2, color=(240, 160, 0, 255), batch=self.axis_batch) for y in range(0, self.h, 100): self.axis_batch.add( 2, pyglet.gl.GL_LINES, None, ('v2i', (0, y, self.w, y)), ('c3B', (240, 160, 0) * 2)) pyglet.text.Label(str(y), x=2, y=y+2, color=(240, 160, 0, 255), batch=self.axis_batch) def show_fps(self): fps = int(get_fps()) if fps>100: s = "fps: >100" else: s = "fps: {}".format(fps) pyglet.text.Label(s, x=2, y=window.h-15, color=(240, 160, 0, 255)).draw() def keep_on_top(self): # keep window on top if platform.system()=="Windows": try: import win32gui import win32con win32gui.SetWindowPos(self._hwnd, win32con.HWND_TOPMOST, 0,0,0,0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE) except: print("Please install pywin32 first to use keep_on_top()") # Mac elif "Darwin" in platform.system(): import os script = 'tell application "System Events" \ to set frontmost of the first process whose unix id is {pid} to true'.format(pid=os.getpid()) os.system("/usr/bin/osascript -e '{script}'".format(script=script)) else: print("keep on top only support on windows")
XRDX/pyleap
pyleap/util.py
repeat
python
def repeat(f, dt=1/60): stop(f) pyglet.clock.schedule_interval(f, dt)
重复执行函数f,时间间隔dt
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/util.py#L13-L16
null
import pyglet import sys __all__ = ['null', 'run', 'stop', 'repeat', 'run_after', 'all_shapes', 'P', 'get_fps', 'Batch'] def null(): """ 空函数 """ pass stop = pyglet.clock.unschedule def run_after(f, dt=1/60): """ 在一定时间之后执行 """ pyglet.clock.schedule_once(f, dt) def run(): """ 在程序的最后运行,进入循环阻塞 """ pyglet.app.run() # all_shapes, use for track all the shapes draw on the windows all_shapes = set() class P: """ P for point """ def __init__(self, x, y): self.x = x self.y = y get_fps = pyglet.clock.get_fps gl = pyglet.gl Batch = pyglet.graphics.Batch
XRDX/pyleap
pyleap/shape/sprite.py
Sprite.center_image
python
def center_image(self, img): img.anchor_x = img.width // 2 # int img.anchor_y = img.height // 2
Sets an image's anchor point to its center
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/shape/sprite.py#L84-L87
null
class Sprite(Rectangle): """ Sprite """ def __init__(self, src, x=300, y=200, w=None, h=None, batch=None): """ 默认位置: 300, 200 """ self.batch = batch self.src = src w = w or self._sprite.width h = h or self._sprite.height super().__init__(x, y, w, h) self.collision_scale = 0.8 @property def w(self): return self.img.width * self._sprite.scale_x @w.setter def w(self, w): self._sprite.scale_x = w / self.img.width @property def h(self): return self.img.height * self._sprite.scale_y @h.setter def h(self, h): self._sprite.scale_y = h / self.img.height @property def src(self): return self._src @src.setter def src(self, src): if src not in cache_images: img = pyglet.image.load(rss.get(src)) self.center_image(img) cache_images[src] = img self._src = src self.img = cache_images[src] try: self._sprite.image = self.img except Exception: self._sprite = pyglet.sprite.Sprite(img=self.img, batch=self.batch) @property def x(self): return self._sprite.x @x.setter def x(self, x): self._sprite.x = x @property def y(self): return self._sprite.y @y.setter def y(self, y): self._sprite.y = y @property def opacity(self): return self._sprite.opacity / 255 @opacity.setter def opacity(self, opacity): self._sprite.opacity = int(opacity * 255) # int def update_points(self): min_x = self.x - self.w/2 * self.collision_scale min_y = self.y - self.h/2 * self.collision_scale max_x = self.x + self.w/2 * self.collision_scale max_y = self.y + self.h/2 * self.collision_scale self.points = (min_x, min_y, max_x, min_y, max_x, max_y, min_x, max_y) def draw(self): self.update_all() self._sprite.draw() pyglet.gl.glLoadIdentity() # reset gl def delete(self): self._sprite.delete()
XRDX/pyleap
pyleap/shape/rectangle.py
Rectangle.update_points
python
def update_points(self): x, y, w, h = self.x, self.y, self.w, self.h self.points = (x, y, x + w, y, x + w, y + h, x, y + h)
统一变为多个点组成的多边形,用于处理碰撞
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/shape/rectangle.py#L19-L22
null
class Rectangle(Shape): """ 长方形: Rectangle """ def __init__(self, x=100, y=100, w=100, h=50, color="orange"): """ 长方形 左下角顶点的位置: x, y 宽度: w 高度: h 颜色: color 默认为 "orange" """ super().__init__(color, gl=pyglet.gl.GL_QUADS) self.x, self.y, self.w, self.h = x, y, w, h
XRDX/pyleap
pyleap/shape/ellipse.py
Ellipse.update_points
python
def update_points(self): n = max(8, min(72, int(2*sqrt(self.r_x+self.r_y)))) d = pi * 2 / n x, y, r_x, r_y = self.x, self.y, self.r_x, self.r_y ps = [] for i in range(n): ps += [(x + r_x * sin(d * i)), (y + r_y * cos(d * i))] self.points = tuple(ps)
椭圆的近似图形:72边形
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/shape/ellipse.py#L25-L34
null
class Ellipse(Shape): """ 基本图形:椭圆 Ellipse """ def __init__(self, x=100, y=100, r_x=50, r_y=30, color="orange"): """ 圆心: x、y, 默认为100, 100 半径: r_x, r_y 默认为50, 30 颜色: color, 默认为 "orange" """ super().__init__(color, gl=gl.GL_POLYGON) self.x, self.y, self.r_x, self.r_y = x, y, r_x, r_y
XRDX/pyleap
pyleap/resource.py
Resource.md5_8_name
python
def md5_8_name(self, url): m = hashlib.md5() m.update(url.encode('utf-8')) return m.hexdigest()[:8] + os.path.splitext(url)[1]
把下载的文件重命名为地址的md5前8位
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/resource.py#L37-L41
null
class Resource(): def __init__(self, path="download"): """ 设置保存路径 """ self.path = path self.ctx = ssl.create_default_context() self.ctx.check_hostname = False self.ctx.verify_mode = ssl.CERT_NONE def get(self, url): if not self.is_url(url): return url filename = self.md5_8_name(url) fullname = '{}{}{}'.format(self.path, os.sep, filename) if not os.path.exists(fullname): self.download(url, fullname) return fullname def download(self, url, fullname): if not os.path.exists(self.path): os.makedirs(self.path) print("Downloading: " + url) # urllib.request.urlretrieve(url, filename=fullname) with urllib.request.urlopen(url, context=self.ctx) as u, \ open(fullname, 'wb') as f: f.write(u.read()) def is_url(self, url): regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... r'localhost|' #localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip r'(?::\d+)?' # optional port r'(?:/?|[/?]\S+)$', re.IGNORECASE) return re.match(regex, url) is not None
XRDX/pyleap
pyleap/color.py
color_to_tuple
python
def color_to_tuple(color, opacity=1): if(type(color) == str and color[0] == "#"): color = hex_color_to_tuple(color) elif type(color) == str: if color in color_dict: color = color_dict[color.lower()] else: print("无法解析颜色:" + color) color = (255, 125, 0, int(255*opacity)) while len(color) < 4: color += (int(255*opacity),) return color
convert any color to standard () "red" -> 'c3B', (255, 125, 0) "#ffffff" -> 'c3B', (255, 255, 255) "#ffffffff" -> 'c4B', (255, 255, 255, 255)
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/color.py#L4-L23
[ "def hex_color_to_tuple(hex):\n \"\"\" convent hex color to tuple\n \"#ffffff\" -> (255, 255, 255)\n \"#ffff00ff\" -> (255, 255, 0, 255)\n \"\"\"\n hex = hex[1:]\n length = len(hex) // 2\n return tuple(int(hex[i*2:i*2+2], 16) for i in range(length))\n" ]
from pyleap.constant_colors import color_dict def hex_color_to_tuple(hex): """ convent hex color to tuple "#ffffff" -> (255, 255, 255) "#ffff00ff" -> (255, 255, 0, 255) """ hex = hex[1:] length = len(hex) // 2 return tuple(int(hex[i*2:i*2+2], 16) for i in range(length)) def hsl(h, s=0.5, l=0.5): return hsla_to_rgba(h, s, l, 1) def hsla(h, s=0.5, l=0.5, a=1): return hsla_to_rgba(h, s, l, a) def hsla_to_rgba(h, s, l, a): """ 0 <= H < 360, 0 <= s,l,a < 1 """ h = h % 360 s = max(0, min(1, s)) l = max(0, min(1, l)) a = max(0, min(1, a)) c = (1 - abs(2*l - 1)) * s x = c * (1 - abs(h/60%2 - 1)) m = l - c/2 if h<60: r, g, b = c, x, 0 elif h<120: r, g, b = x, c, 0 elif h<180: r, g, b = 0, c, x elif h<240: r, g, b = 0, x, c elif h<300: r, g, b = x, 0, c else: r, g, b = c, 0, x return (int((r+m)*255), int((g+m)*255), int((b+m)*255), int(a*255))
XRDX/pyleap
pyleap/color.py
hex_color_to_tuple
python
def hex_color_to_tuple(hex): hex = hex[1:] length = len(hex) // 2 return tuple(int(hex[i*2:i*2+2], 16) for i in range(length))
convent hex color to tuple "#ffffff" -> (255, 255, 255) "#ffff00ff" -> (255, 255, 0, 255)
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/color.py#L25-L32
null
from pyleap.constant_colors import color_dict def color_to_tuple(color, opacity=1): """ convert any color to standard () "red" -> 'c3B', (255, 125, 0) "#ffffff" -> 'c3B', (255, 255, 255) "#ffffffff" -> 'c4B', (255, 255, 255, 255) """ if(type(color) == str and color[0] == "#"): color = hex_color_to_tuple(color) elif type(color) == str: if color in color_dict: color = color_dict[color.lower()] else: print("无法解析颜色:" + color) color = (255, 125, 0, int(255*opacity)) while len(color) < 4: color += (int(255*opacity),) return color def hsl(h, s=0.5, l=0.5): return hsla_to_rgba(h, s, l, 1) def hsla(h, s=0.5, l=0.5, a=1): return hsla_to_rgba(h, s, l, a) def hsla_to_rgba(h, s, l, a): """ 0 <= H < 360, 0 <= s,l,a < 1 """ h = h % 360 s = max(0, min(1, s)) l = max(0, min(1, l)) a = max(0, min(1, a)) c = (1 - abs(2*l - 1)) * s x = c * (1 - abs(h/60%2 - 1)) m = l - c/2 if h<60: r, g, b = c, x, 0 elif h<120: r, g, b = x, c, 0 elif h<180: r, g, b = 0, c, x elif h<240: r, g, b = 0, x, c elif h<300: r, g, b = x, 0, c else: r, g, b = c, 0, x return (int((r+m)*255), int((g+m)*255), int((b+m)*255), int(a*255))
XRDX/pyleap
pyleap/color.py
hsla_to_rgba
python
def hsla_to_rgba(h, s, l, a): h = h % 360 s = max(0, min(1, s)) l = max(0, min(1, l)) a = max(0, min(1, a)) c = (1 - abs(2*l - 1)) * s x = c * (1 - abs(h/60%2 - 1)) m = l - c/2 if h<60: r, g, b = c, x, 0 elif h<120: r, g, b = x, c, 0 elif h<180: r, g, b = 0, c, x elif h<240: r, g, b = 0, x, c elif h<300: r, g, b = x, 0, c else: r, g, b = c, 0, x return (int((r+m)*255), int((g+m)*255), int((b+m)*255), int(a*255))
0 <= H < 360, 0 <= s,l,a < 1
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/color.py#L40-L66
null
from pyleap.constant_colors import color_dict def color_to_tuple(color, opacity=1): """ convert any color to standard () "red" -> 'c3B', (255, 125, 0) "#ffffff" -> 'c3B', (255, 255, 255) "#ffffffff" -> 'c4B', (255, 255, 255, 255) """ if(type(color) == str and color[0] == "#"): color = hex_color_to_tuple(color) elif type(color) == str: if color in color_dict: color = color_dict[color.lower()] else: print("无法解析颜色:" + color) color = (255, 125, 0, int(255*opacity)) while len(color) < 4: color += (int(255*opacity),) return color def hex_color_to_tuple(hex): """ convent hex color to tuple "#ffffff" -> (255, 255, 255) "#ffff00ff" -> (255, 255, 0, 255) """ hex = hex[1:] length = len(hex) // 2 return tuple(int(hex[i*2:i*2+2], 16) for i in range(length)) def hsl(h, s=0.5, l=0.5): return hsla_to_rgba(h, s, l, 1) def hsla(h, s=0.5, l=0.5, a=1): return hsla_to_rgba(h, s, l, a)
XRDX/pyleap
pyleap/shape/shape.py
Shape.draw
python
def draw(self): self.update_all() self.vertex_list.draw(self.gl) pyglet.gl.glLoadIdentity()
使用draw方法将图形绘制在窗口里
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/shape/shape.py#L47-L51
[ "def update_all(self):\n \"\"\" 在绘制之前,针对形变进行计算,通过设置openGL的属性来达到绘制出变形的图形 \"\"\"\n self.update_points()\n self.update_vertex_list()\n self.update_anchor()\n\n pyglet.gl.glLoadIdentity() # reset gl\n pyglet.gl.glLineWidth(self.line_width)\n pyglet.gl.glPointSize(self.point_size)\n self.transfo...
class Shape(CollisionMixin, TransformMixin): """ base shape class """ def __init__(self, color="orange", gl=pyglet.gl.GL_LINE_LOOP, line_width=1): """ 默认参数 颜色 color: "orange" 线条粗细 line_width: 1 """ self.color = color self.gl = gl self.transform = Transform() # 图形的线条宽度,默认为1 self.line_width = line_width # 图形的顶点 (Point1, Point2, ...) self.points = () # 用于记录press事件函数 self._press = null # 仅Point类point_size属性有效 self.point_size = 1 # 透明度 opacity self.opacity = 1 # reset gl def stroke(self): """ 使用stroke方法将图形绘制在窗口里,仅对基本的几何图形有效 """ self.update_all() length = len(self.points) # thick lines if self.line_width <= 3: if length==4: self.vertex_list.draw(pyglet.gl.GL_LINES) elif length > 4: self.vertex_list.draw(pyglet.gl.GL_LINE_LOOP) return # color = color_to_tuple(self.color, self.opacity) if length == 4: x, y, x1, y1 = self.points[0:4] l = max(1, math.sqrt((x1-x)*(x1-x)+(y1-y)*(y1-y))) ly = (x1-x) / l * self.line_width / 2 lx = - (y1-y) / l * self.line_width / 2 points = [x-lx, y-ly, x+lx, y+ly, x1+lx, y1+ly, x1-lx, y1-ly] vertex_list = pyglet.graphics.vertex_list( 4, ('v2f', points), ('c4B', color * 4)) vertex_list.draw(pyglet.gl.GL_QUADS) elif length > 4: points = [] for i in range(0, length, 2): x, y = self.points[i], self.points[i+1] x1, y1 = self.points[i-2], self.points[i-1] x2, y2 = self.points[(i+2) % length], self.points[(i+3) % length] l1 = max(1, math.sqrt((x1-x)*(x1-x)+(y1-y)*(y1-y))) l2 = max(1, math.sqrt((x2-x)*(x2-x)+(y2-y)*(y2-y))) nx1, ny1 = (x - x1) / l1, (y - y1) / l1 nx2, ny2 = (x - x2) / l2, (y - y2) / l2 nx, ny = nx1 + nx2, ny1 + ny2 vx, vy = -ny1, nx1 t = nx1*nx2 + ny1*ny2 if t > 0.99: lx = vx * self.line_width / 2 ly = vy * self.line_width / 2 points += [x-lx, y-ly, x+lx, y+ly, x+lx, y+ly, x-lx, y-ly] elif t < -0.99: lx = vx * self.line_width / 2 ly = vy * self.line_width / 2 points += [x+lx, y+ly, x-lx, y-ly] else: radio = 1/(vx*nx + vy*ny) if radio < 0: radio = -radio lx = (nx1+nx2) * self.line_width / 2 * radio ly = (ny1+ny2) * self.line_width / 2 * radio points += [x+lx, y+ly, x-lx, y-ly] batch = pyglet.graphics.Batch() for i in range(0, len(points), 4): batch.add(4, pyglet.gl.GL_QUADS, None, ('v2f', (points[i-4], points[i-3], points[i-2], points[i-1], points[i+2], points[i+3], points[i], points[i+1])), ('c4B', color * 4)) batch.draw() pyglet.gl.glLoadIdentity() # reset gl def update_all(self): """ 在绘制之前,针对形变进行计算,通过设置openGL的属性来达到绘制出变形的图形 """ self.update_points() self.update_vertex_list() self.update_anchor() pyglet.gl.glLoadIdentity() # reset gl pyglet.gl.glLineWidth(self.line_width) pyglet.gl.glPointSize(self.point_size) self.transform.update_gl() # handle shapes click envets all_shapes.discard(self) if(self._press != None): all_shapes.add(self) def update_points(self): """ translate shapes to points,在子类中实现 """ pass def update_vertex_list(self): """ 使用pyglet来绘制基本图形之前,转为pyglet识别的属性 """ color = color_to_tuple(self.color, self.opacity) length = len(self.points) // 2 self.vertex_list = pyglet.graphics.vertex_list( length, ('v2f', self.points), ('c4B', color * length)) def update_anchor(self): """ 如果是使用set_anchor_rate来设定锚点,那么就需要不停的更新锚点的位置 """ t = self.transform self.update_collision_rect() if t.anchor_x_r and t.anchor_y_r: t.anchor_x = self.min_x + (self.max_x - self.min_x) * t.anchor_x_r t.anchor_y = self.min_y + (self.max_y - self.min_y) * t.anchor_y_r
XRDX/pyleap
pyleap/shape/shape.py
Shape.stroke
python
def stroke(self): self.update_all() length = len(self.points) # thick lines if self.line_width <= 3: if length==4: self.vertex_list.draw(pyglet.gl.GL_LINES) elif length > 4: self.vertex_list.draw(pyglet.gl.GL_LINE_LOOP) return # color = color_to_tuple(self.color, self.opacity) if length == 4: x, y, x1, y1 = self.points[0:4] l = max(1, math.sqrt((x1-x)*(x1-x)+(y1-y)*(y1-y))) ly = (x1-x) / l * self.line_width / 2 lx = - (y1-y) / l * self.line_width / 2 points = [x-lx, y-ly, x+lx, y+ly, x1+lx, y1+ly, x1-lx, y1-ly] vertex_list = pyglet.graphics.vertex_list( 4, ('v2f', points), ('c4B', color * 4)) vertex_list.draw(pyglet.gl.GL_QUADS) elif length > 4: points = [] for i in range(0, length, 2): x, y = self.points[i], self.points[i+1] x1, y1 = self.points[i-2], self.points[i-1] x2, y2 = self.points[(i+2) % length], self.points[(i+3) % length] l1 = max(1, math.sqrt((x1-x)*(x1-x)+(y1-y)*(y1-y))) l2 = max(1, math.sqrt((x2-x)*(x2-x)+(y2-y)*(y2-y))) nx1, ny1 = (x - x1) / l1, (y - y1) / l1 nx2, ny2 = (x - x2) / l2, (y - y2) / l2 nx, ny = nx1 + nx2, ny1 + ny2 vx, vy = -ny1, nx1 t = nx1*nx2 + ny1*ny2 if t > 0.99: lx = vx * self.line_width / 2 ly = vy * self.line_width / 2 points += [x-lx, y-ly, x+lx, y+ly, x+lx, y+ly, x-lx, y-ly] elif t < -0.99: lx = vx * self.line_width / 2 ly = vy * self.line_width / 2 points += [x+lx, y+ly, x-lx, y-ly] else: radio = 1/(vx*nx + vy*ny) if radio < 0: radio = -radio lx = (nx1+nx2) * self.line_width / 2 * radio ly = (ny1+ny2) * self.line_width / 2 * radio points += [x+lx, y+ly, x-lx, y-ly] batch = pyglet.graphics.Batch() for i in range(0, len(points), 4): batch.add(4, pyglet.gl.GL_QUADS, None, ('v2f', (points[i-4], points[i-3], points[i-2], points[i-1], points[i+2], points[i+3], points[i], points[i+1])), ('c4B', color * 4)) batch.draw() pyglet.gl.glLoadIdentity()
使用stroke方法将图形绘制在窗口里,仅对基本的几何图形有效
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/shape/shape.py#L53-L125
[ "def color_to_tuple(color, opacity=1):\n \"\"\" convert any color to standard ()\n \"red\" -> 'c3B', (255, 125, 0)\n \"#ffffff\" -> 'c3B', (255, 255, 255)\n \"#ffffffff\" -> 'c4B', (255, 255, 255, 255)\n \"\"\"\n if(type(color) == str and color[0] == \"#\"):\n color = hex_color_t...
class Shape(CollisionMixin, TransformMixin): """ base shape class """ def __init__(self, color="orange", gl=pyglet.gl.GL_LINE_LOOP, line_width=1): """ 默认参数 颜色 color: "orange" 线条粗细 line_width: 1 """ self.color = color self.gl = gl self.transform = Transform() # 图形的线条宽度,默认为1 self.line_width = line_width # 图形的顶点 (Point1, Point2, ...) self.points = () # 用于记录press事件函数 self._press = null # 仅Point类point_size属性有效 self.point_size = 1 # 透明度 opacity self.opacity = 1 def draw(self): """ 使用draw方法将图形绘制在窗口里 """ self.update_all() self.vertex_list.draw(self.gl) pyglet.gl.glLoadIdentity() # reset gl def stroke(self): """ 使用stroke方法将图形绘制在窗口里,仅对基本的几何图形有效 """ self.update_all() length = len(self.points) # thick lines if self.line_width <= 3: if length==4: self.vertex_list.draw(pyglet.gl.GL_LINES) elif length > 4: self.vertex_list.draw(pyglet.gl.GL_LINE_LOOP) return # color = color_to_tuple(self.color, self.opacity) if length == 4: x, y, x1, y1 = self.points[0:4] l = max(1, math.sqrt((x1-x)*(x1-x)+(y1-y)*(y1-y))) ly = (x1-x) / l * self.line_width / 2 lx = - (y1-y) / l * self.line_width / 2 points = [x-lx, y-ly, x+lx, y+ly, x1+lx, y1+ly, x1-lx, y1-ly] vertex_list = pyglet.graphics.vertex_list( 4, ('v2f', points), ('c4B', color * 4)) vertex_list.draw(pyglet.gl.GL_QUADS) elif length > 4: points = [] for i in range(0, length, 2): x, y = self.points[i], self.points[i+1] x1, y1 = self.points[i-2], self.points[i-1] x2, y2 = self.points[(i+2) % length], self.points[(i+3) % length] l1 = max(1, math.sqrt((x1-x)*(x1-x)+(y1-y)*(y1-y))) l2 = max(1, math.sqrt((x2-x)*(x2-x)+(y2-y)*(y2-y))) nx1, ny1 = (x - x1) / l1, (y - y1) / l1 nx2, ny2 = (x - x2) / l2, (y - y2) / l2 nx, ny = nx1 + nx2, ny1 + ny2 vx, vy = -ny1, nx1 t = nx1*nx2 + ny1*ny2 if t > 0.99: lx = vx * self.line_width / 2 ly = vy * self.line_width / 2 points += [x-lx, y-ly, x+lx, y+ly, x+lx, y+ly, x-lx, y-ly] elif t < -0.99: lx = vx * self.line_width / 2 ly = vy * self.line_width / 2 points += [x+lx, y+ly, x-lx, y-ly] else: radio = 1/(vx*nx + vy*ny) if radio < 0: radio = -radio lx = (nx1+nx2) * self.line_width / 2 * radio ly = (ny1+ny2) * self.line_width / 2 * radio points += [x+lx, y+ly, x-lx, y-ly] batch = pyglet.graphics.Batch() for i in range(0, len(points), 4): batch.add(4, pyglet.gl.GL_QUADS, None, ('v2f', (points[i-4], points[i-3], points[i-2], points[i-1], points[i+2], points[i+3], points[i], points[i+1])), ('c4B', color * 4)) batch.draw() pyglet.gl.glLoadIdentity() # reset gl def update_all(self): """ 在绘制之前,针对形变进行计算,通过设置openGL的属性来达到绘制出变形的图形 """ self.update_points() self.update_vertex_list() self.update_anchor() pyglet.gl.glLoadIdentity() # reset gl pyglet.gl.glLineWidth(self.line_width) pyglet.gl.glPointSize(self.point_size) self.transform.update_gl() # handle shapes click envets all_shapes.discard(self) if(self._press != None): all_shapes.add(self) def update_points(self): """ translate shapes to points,在子类中实现 """ pass def update_vertex_list(self): """ 使用pyglet来绘制基本图形之前,转为pyglet识别的属性 """ color = color_to_tuple(self.color, self.opacity) length = len(self.points) // 2 self.vertex_list = pyglet.graphics.vertex_list( length, ('v2f', self.points), ('c4B', color * length)) def update_anchor(self): """ 如果是使用set_anchor_rate来设定锚点,那么就需要不停的更新锚点的位置 """ t = self.transform self.update_collision_rect() if t.anchor_x_r and t.anchor_y_r: t.anchor_x = self.min_x + (self.max_x - self.min_x) * t.anchor_x_r t.anchor_y = self.min_y + (self.max_y - self.min_y) * t.anchor_y_r
XRDX/pyleap
pyleap/shape/shape.py
Shape.update_all
python
def update_all(self): self.update_points() self.update_vertex_list() self.update_anchor() pyglet.gl.glLoadIdentity() # reset gl pyglet.gl.glLineWidth(self.line_width) pyglet.gl.glPointSize(self.point_size) self.transform.update_gl() # handle shapes click envets all_shapes.discard(self) if(self._press != None): all_shapes.add(self)
在绘制之前,针对形变进行计算,通过设置openGL的属性来达到绘制出变形的图形
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/shape/shape.py#L127-L141
[ "def update_points(self):\n \"\"\" 统一变为多个点组成的多边形,用于处理碰撞 \"\"\"\n x, y, w, h = self.x, self.y, self.w, self.h\n self.points = (x, y, x + w, y, x + w, y + h, x, y + h)\n", "def update_points(self):\n \"\"\" translate shapes to points,在子类中实现 \"\"\"\n pass\n", "def update_vertex_list(self):\n \"\"...
class Shape(CollisionMixin, TransformMixin): """ base shape class """ def __init__(self, color="orange", gl=pyglet.gl.GL_LINE_LOOP, line_width=1): """ 默认参数 颜色 color: "orange" 线条粗细 line_width: 1 """ self.color = color self.gl = gl self.transform = Transform() # 图形的线条宽度,默认为1 self.line_width = line_width # 图形的顶点 (Point1, Point2, ...) self.points = () # 用于记录press事件函数 self._press = null # 仅Point类point_size属性有效 self.point_size = 1 # 透明度 opacity self.opacity = 1 def draw(self): """ 使用draw方法将图形绘制在窗口里 """ self.update_all() self.vertex_list.draw(self.gl) pyglet.gl.glLoadIdentity() # reset gl def stroke(self): """ 使用stroke方法将图形绘制在窗口里,仅对基本的几何图形有效 """ self.update_all() length = len(self.points) # thick lines if self.line_width <= 3: if length==4: self.vertex_list.draw(pyglet.gl.GL_LINES) elif length > 4: self.vertex_list.draw(pyglet.gl.GL_LINE_LOOP) return # color = color_to_tuple(self.color, self.opacity) if length == 4: x, y, x1, y1 = self.points[0:4] l = max(1, math.sqrt((x1-x)*(x1-x)+(y1-y)*(y1-y))) ly = (x1-x) / l * self.line_width / 2 lx = - (y1-y) / l * self.line_width / 2 points = [x-lx, y-ly, x+lx, y+ly, x1+lx, y1+ly, x1-lx, y1-ly] vertex_list = pyglet.graphics.vertex_list( 4, ('v2f', points), ('c4B', color * 4)) vertex_list.draw(pyglet.gl.GL_QUADS) elif length > 4: points = [] for i in range(0, length, 2): x, y = self.points[i], self.points[i+1] x1, y1 = self.points[i-2], self.points[i-1] x2, y2 = self.points[(i+2) % length], self.points[(i+3) % length] l1 = max(1, math.sqrt((x1-x)*(x1-x)+(y1-y)*(y1-y))) l2 = max(1, math.sqrt((x2-x)*(x2-x)+(y2-y)*(y2-y))) nx1, ny1 = (x - x1) / l1, (y - y1) / l1 nx2, ny2 = (x - x2) / l2, (y - y2) / l2 nx, ny = nx1 + nx2, ny1 + ny2 vx, vy = -ny1, nx1 t = nx1*nx2 + ny1*ny2 if t > 0.99: lx = vx * self.line_width / 2 ly = vy * self.line_width / 2 points += [x-lx, y-ly, x+lx, y+ly, x+lx, y+ly, x-lx, y-ly] elif t < -0.99: lx = vx * self.line_width / 2 ly = vy * self.line_width / 2 points += [x+lx, y+ly, x-lx, y-ly] else: radio = 1/(vx*nx + vy*ny) if radio < 0: radio = -radio lx = (nx1+nx2) * self.line_width / 2 * radio ly = (ny1+ny2) * self.line_width / 2 * radio points += [x+lx, y+ly, x-lx, y-ly] batch = pyglet.graphics.Batch() for i in range(0, len(points), 4): batch.add(4, pyglet.gl.GL_QUADS, None, ('v2f', (points[i-4], points[i-3], points[i-2], points[i-1], points[i+2], points[i+3], points[i], points[i+1])), ('c4B', color * 4)) batch.draw() pyglet.gl.glLoadIdentity() # reset gl def update_points(self): """ translate shapes to points,在子类中实现 """ pass def update_vertex_list(self): """ 使用pyglet来绘制基本图形之前,转为pyglet识别的属性 """ color = color_to_tuple(self.color, self.opacity) length = len(self.points) // 2 self.vertex_list = pyglet.graphics.vertex_list( length, ('v2f', self.points), ('c4B', color * length)) def update_anchor(self): """ 如果是使用set_anchor_rate来设定锚点,那么就需要不停的更新锚点的位置 """ t = self.transform self.update_collision_rect() if t.anchor_x_r and t.anchor_y_r: t.anchor_x = self.min_x + (self.max_x - self.min_x) * t.anchor_x_r t.anchor_y = self.min_y + (self.max_y - self.min_y) * t.anchor_y_r
XRDX/pyleap
pyleap/shape/shape.py
Shape.update_vertex_list
python
def update_vertex_list(self): color = color_to_tuple(self.color, self.opacity) length = len(self.points) // 2 self.vertex_list = pyglet.graphics.vertex_list( length, ('v2f', self.points), ('c4B', color * length))
使用pyglet来绘制基本图形之前,转为pyglet识别的属性
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/shape/shape.py#L147-L154
[ "def color_to_tuple(color, opacity=1):\n \"\"\" convert any color to standard ()\n \"red\" -> 'c3B', (255, 125, 0)\n \"#ffffff\" -> 'c3B', (255, 255, 255)\n \"#ffffffff\" -> 'c4B', (255, 255, 255, 255)\n \"\"\"\n if(type(color) == str and color[0] == \"#\"):\n color = hex_color_t...
class Shape(CollisionMixin, TransformMixin): """ base shape class """ def __init__(self, color="orange", gl=pyglet.gl.GL_LINE_LOOP, line_width=1): """ 默认参数 颜色 color: "orange" 线条粗细 line_width: 1 """ self.color = color self.gl = gl self.transform = Transform() # 图形的线条宽度,默认为1 self.line_width = line_width # 图形的顶点 (Point1, Point2, ...) self.points = () # 用于记录press事件函数 self._press = null # 仅Point类point_size属性有效 self.point_size = 1 # 透明度 opacity self.opacity = 1 def draw(self): """ 使用draw方法将图形绘制在窗口里 """ self.update_all() self.vertex_list.draw(self.gl) pyglet.gl.glLoadIdentity() # reset gl def stroke(self): """ 使用stroke方法将图形绘制在窗口里,仅对基本的几何图形有效 """ self.update_all() length = len(self.points) # thick lines if self.line_width <= 3: if length==4: self.vertex_list.draw(pyglet.gl.GL_LINES) elif length > 4: self.vertex_list.draw(pyglet.gl.GL_LINE_LOOP) return # color = color_to_tuple(self.color, self.opacity) if length == 4: x, y, x1, y1 = self.points[0:4] l = max(1, math.sqrt((x1-x)*(x1-x)+(y1-y)*(y1-y))) ly = (x1-x) / l * self.line_width / 2 lx = - (y1-y) / l * self.line_width / 2 points = [x-lx, y-ly, x+lx, y+ly, x1+lx, y1+ly, x1-lx, y1-ly] vertex_list = pyglet.graphics.vertex_list( 4, ('v2f', points), ('c4B', color * 4)) vertex_list.draw(pyglet.gl.GL_QUADS) elif length > 4: points = [] for i in range(0, length, 2): x, y = self.points[i], self.points[i+1] x1, y1 = self.points[i-2], self.points[i-1] x2, y2 = self.points[(i+2) % length], self.points[(i+3) % length] l1 = max(1, math.sqrt((x1-x)*(x1-x)+(y1-y)*(y1-y))) l2 = max(1, math.sqrt((x2-x)*(x2-x)+(y2-y)*(y2-y))) nx1, ny1 = (x - x1) / l1, (y - y1) / l1 nx2, ny2 = (x - x2) / l2, (y - y2) / l2 nx, ny = nx1 + nx2, ny1 + ny2 vx, vy = -ny1, nx1 t = nx1*nx2 + ny1*ny2 if t > 0.99: lx = vx * self.line_width / 2 ly = vy * self.line_width / 2 points += [x-lx, y-ly, x+lx, y+ly, x+lx, y+ly, x-lx, y-ly] elif t < -0.99: lx = vx * self.line_width / 2 ly = vy * self.line_width / 2 points += [x+lx, y+ly, x-lx, y-ly] else: radio = 1/(vx*nx + vy*ny) if radio < 0: radio = -radio lx = (nx1+nx2) * self.line_width / 2 * radio ly = (ny1+ny2) * self.line_width / 2 * radio points += [x+lx, y+ly, x-lx, y-ly] batch = pyglet.graphics.Batch() for i in range(0, len(points), 4): batch.add(4, pyglet.gl.GL_QUADS, None, ('v2f', (points[i-4], points[i-3], points[i-2], points[i-1], points[i+2], points[i+3], points[i], points[i+1])), ('c4B', color * 4)) batch.draw() pyglet.gl.glLoadIdentity() # reset gl def update_all(self): """ 在绘制之前,针对形变进行计算,通过设置openGL的属性来达到绘制出变形的图形 """ self.update_points() self.update_vertex_list() self.update_anchor() pyglet.gl.glLoadIdentity() # reset gl pyglet.gl.glLineWidth(self.line_width) pyglet.gl.glPointSize(self.point_size) self.transform.update_gl() # handle shapes click envets all_shapes.discard(self) if(self._press != None): all_shapes.add(self) def update_points(self): """ translate shapes to points,在子类中实现 """ pass def update_anchor(self): """ 如果是使用set_anchor_rate来设定锚点,那么就需要不停的更新锚点的位置 """ t = self.transform self.update_collision_rect() if t.anchor_x_r and t.anchor_y_r: t.anchor_x = self.min_x + (self.max_x - self.min_x) * t.anchor_x_r t.anchor_y = self.min_y + (self.max_y - self.min_y) * t.anchor_y_r
XRDX/pyleap
pyleap/shape/shape.py
Shape.update_anchor
python
def update_anchor(self): t = self.transform self.update_collision_rect() if t.anchor_x_r and t.anchor_y_r: t.anchor_x = self.min_x + (self.max_x - self.min_x) * t.anchor_x_r t.anchor_y = self.min_y + (self.max_y - self.min_y) * t.anchor_y_r
如果是使用set_anchor_rate来设定锚点,那么就需要不停的更新锚点的位置
train
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/shape/shape.py#L156-L162
[ "def update_collision_rect(self):\n \"\"\" 获取外接矩形 \"\"\"\n self.min_x = min(self.points[::2])\n self.max_x = max(self.points[::2])\n self.min_y = min(self.points[1::2])\n self.max_y = max(self.points[1::2])\n" ]
class Shape(CollisionMixin, TransformMixin): """ base shape class """ def __init__(self, color="orange", gl=pyglet.gl.GL_LINE_LOOP, line_width=1): """ 默认参数 颜色 color: "orange" 线条粗细 line_width: 1 """ self.color = color self.gl = gl self.transform = Transform() # 图形的线条宽度,默认为1 self.line_width = line_width # 图形的顶点 (Point1, Point2, ...) self.points = () # 用于记录press事件函数 self._press = null # 仅Point类point_size属性有效 self.point_size = 1 # 透明度 opacity self.opacity = 1 def draw(self): """ 使用draw方法将图形绘制在窗口里 """ self.update_all() self.vertex_list.draw(self.gl) pyglet.gl.glLoadIdentity() # reset gl def stroke(self): """ 使用stroke方法将图形绘制在窗口里,仅对基本的几何图形有效 """ self.update_all() length = len(self.points) # thick lines if self.line_width <= 3: if length==4: self.vertex_list.draw(pyglet.gl.GL_LINES) elif length > 4: self.vertex_list.draw(pyglet.gl.GL_LINE_LOOP) return # color = color_to_tuple(self.color, self.opacity) if length == 4: x, y, x1, y1 = self.points[0:4] l = max(1, math.sqrt((x1-x)*(x1-x)+(y1-y)*(y1-y))) ly = (x1-x) / l * self.line_width / 2 lx = - (y1-y) / l * self.line_width / 2 points = [x-lx, y-ly, x+lx, y+ly, x1+lx, y1+ly, x1-lx, y1-ly] vertex_list = pyglet.graphics.vertex_list( 4, ('v2f', points), ('c4B', color * 4)) vertex_list.draw(pyglet.gl.GL_QUADS) elif length > 4: points = [] for i in range(0, length, 2): x, y = self.points[i], self.points[i+1] x1, y1 = self.points[i-2], self.points[i-1] x2, y2 = self.points[(i+2) % length], self.points[(i+3) % length] l1 = max(1, math.sqrt((x1-x)*(x1-x)+(y1-y)*(y1-y))) l2 = max(1, math.sqrt((x2-x)*(x2-x)+(y2-y)*(y2-y))) nx1, ny1 = (x - x1) / l1, (y - y1) / l1 nx2, ny2 = (x - x2) / l2, (y - y2) / l2 nx, ny = nx1 + nx2, ny1 + ny2 vx, vy = -ny1, nx1 t = nx1*nx2 + ny1*ny2 if t > 0.99: lx = vx * self.line_width / 2 ly = vy * self.line_width / 2 points += [x-lx, y-ly, x+lx, y+ly, x+lx, y+ly, x-lx, y-ly] elif t < -0.99: lx = vx * self.line_width / 2 ly = vy * self.line_width / 2 points += [x+lx, y+ly, x-lx, y-ly] else: radio = 1/(vx*nx + vy*ny) if radio < 0: radio = -radio lx = (nx1+nx2) * self.line_width / 2 * radio ly = (ny1+ny2) * self.line_width / 2 * radio points += [x+lx, y+ly, x-lx, y-ly] batch = pyglet.graphics.Batch() for i in range(0, len(points), 4): batch.add(4, pyglet.gl.GL_QUADS, None, ('v2f', (points[i-4], points[i-3], points[i-2], points[i-1], points[i+2], points[i+3], points[i], points[i+1])), ('c4B', color * 4)) batch.draw() pyglet.gl.glLoadIdentity() # reset gl def update_all(self): """ 在绘制之前,针对形变进行计算,通过设置openGL的属性来达到绘制出变形的图形 """ self.update_points() self.update_vertex_list() self.update_anchor() pyglet.gl.glLoadIdentity() # reset gl pyglet.gl.glLineWidth(self.line_width) pyglet.gl.glPointSize(self.point_size) self.transform.update_gl() # handle shapes click envets all_shapes.discard(self) if(self._press != None): all_shapes.add(self) def update_points(self): """ translate shapes to points,在子类中实现 """ pass def update_vertex_list(self): """ 使用pyglet来绘制基本图形之前,转为pyglet识别的属性 """ color = color_to_tuple(self.color, self.opacity) length = len(self.points) // 2 self.vertex_list = pyglet.graphics.vertex_list( length, ('v2f', self.points), ('c4B', color * length))
liminspace/dju-image
dju_image/image.py
image_get_format
python
def image_get_format(f): f.seek(0) try: img = Image.open(f) t = img.format.lower() except IOError: t = None return t
Return image format for file-object f. (jpeg, png, gif etc.) All formats: http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html Example: if image_get_format(request.FILES['image']) == 'jpeg': print 'Image is JPEG' if image_get_format(open('/tmp/image.png', 'rb')) == 'png': print 'File is PNG'
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/image.py#L12-L29
null
# coding=utf-8 import os import subprocess from cStringIO import StringIO from PIL import Image, ImageFile from contextlib import contextmanager from django.core.files.uploadedfile import UploadedFile from dju_common.file import truncate_file from . import settings as dju_settings def set_uploaded_file_content_type_and_file_ext(f, img_format): assert isinstance(img_format, basestring) img_format = img_format.lower() if img_format not in dju_settings.DJU_IMG_UPLOAD_IMG_EXTS: raise RuntimeError if isinstance(f, UploadedFile): f.content_type = 'image/{}'.format(img_format) f.name = os.path.splitext(f.name)[0] + '.' + img_format def is_image(f, types=('png', 'jpeg', 'gif'), set_content_type=True): """ Return True if file f is image (types type) and set its correct content_type and filename extension. Example: if is_image(request.FILES['file']): print 'File is image' if is_image(open('/tmp/image.jpeg', 'rb')): print 'File is image' """ assert isinstance(types, (list, tuple)) t = image_get_format(f) if t not in [t.lower() for t in types]: return False if set_content_type: set_uploaded_file_content_type_and_file_ext(f, t) return True @contextmanager def image_save_buffer_fix(maxblock=1048576): """ Contextmanager that change MAXBLOCK in ImageFile. """ before = ImageFile.MAXBLOCK ImageFile.MAXBLOCK = maxblock try: yield finally: ImageFile.MAXBLOCK = before def _save_img(img, f, img_format, **kwargs): if isinstance(f, UploadedFile): f = f.file modes = ({}, {'mb_x': 5}, {'mb_x': 10}, {'mb_x': 10, 'disable_optimize': True}, {'mb_x': 10, 'disable_optimize': True, 'disable_progressive': True}) maxblock = max(ImageFile.MAXBLOCK, img.size[0] * img.size[1]) last_error = None if img_format.upper() == 'JPEG' and img.mode != 'RGB': current_format = img.format img = img.convert('RGB') img.format = current_format for mode in modes: try: kw = kwargs.copy() if mode.get('disable_optimize'): kw.pop('optimize') if mode.get('disable_progressive'): kw.pop('progressive') with image_save_buffer_fix(maxblock * mode.get('mb_x', 1)): img.save(f, format=img_format, **kw) last_error = None break except IOError, e: last_error = e if last_error: raise last_error if image_get_format(f) == 'jpeg' and dju_settings.DJU_IMG_USE_JPEGTRAN: f.seek(0) try: p = subprocess.Popen(['jpegtran', '-copy', 'none', '-optimize', '-progressive'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) r = p.communicate(f.read())[0] except IOError: r = None if r: truncate_file(f) f.write(r) def get_image_as_rgb(f): f.seek(0) try: p = subprocess.Popen(['convert', '-colorspace', 'rgb', '-', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) r = p.communicate(f.read())[0] except IOError: r = None if r: return Image.open(StringIO(r)) def optimize_png_file(f, o=None): """ Use pngquant for optimize PNG-image. f - path to input image file or file-object. o - path to output image file or file-object for save result. NOTICE: f and o can not be of different type """ if isinstance(f, basestring): if o is None: o = f else: assert isinstance(o, basestring) try: subprocess.check_call(['pngquant', '--force', '--output', o, f]) except subprocess.CalledProcessError: return False return True if not hasattr(f, 'read'): raise RuntimeError if o is None: o = f else: if not hasattr(f, 'write'): raise RuntimeError f.seek(0) try: p = subprocess.Popen(['pngquant', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) r = p.communicate(f.read())[0] except IOError: r = None if r: truncate_file(o) o.write(r) return True return False def adjust_image(f, max_size=(800, 800), new_format=None, jpeg_quality=90, fill=False, stretch=False, return_new_image=False, force_jpeg_save=True): """ Підганяє зображення під параметри. max_size - максимальний розмір картинки. один з розмірів може бути None (авто) new_format - формат файлу (jpeg, png, gif). якщо None, тоді буде використаний формат оригіналу jpeg_quality - якість JPEG fill - чи зображення має бути заповненим при обрізці (інакше буде вписане) stretch - чи розтягувати, якщо картинка замаленька return_new_image - якщо True, тоді буде повертатись новий об'єкт StringIO картинки. Інакше bool, чи файл змінювався. force_jpeg_save - якщо True, тоді якщо файл JPEG, то він буде перезбережений в будь-якому випадку """ assert isinstance(max_size, (list, tuple)) and len(max_size) == 2 assert 0 < jpeg_quality <= 100 if new_format: new_format = new_format.lower() if new_format not in ('jpeg', 'png', 'gif'): raise RuntimeError('Invalid new_format value.') f.seek(0) img = Image.open(f) if ((new_format == 'jpeg' and img.mode != 'RGB') or (new_format is None and img.format == 'JPEG' and img.mode != 'RGB')): do_convert = True if dju_settings.DJU_IMG_CONVERT_JPEG_TO_RGB: img = get_image_as_rgb(f) if img is not None: do_convert = False if do_convert: current_format = img.format img = img.convert('RGB') img.format = current_format max_width, max_height = max_size img_width, img_height = img.size img_format = img.format.lower() ch_size = ch_format = False if max_width is None: max_width = int(((img_width / float(img_height)) * max_height)) elif max_height is None: max_height = int(((img_height / float(img_width)) * max_width)) if (img_width, img_height) != (max_width, max_height): tasks = [] if fill: if (img_width < max_width or img_height < max_height) and not stretch: k = max(max_width / float(img_width), max_height / float(img_height)) w, h = max_width / k, max_height / k left, top = int((img_width - w) / 2.), int((img_height - h) / 2.) tasks.append(('crop', ((left, top, int(left + w), int(top + h)),), {})) else: k = min(img_width / float(max_width), img_height / float(max_height)) w, h = img_width / k, img_height / k tasks.append(('resize', ((int(w), int(h)), Image.LANCZOS), {})) left, top = int((w - max_width) / 2.), int((h - max_height) / 2.) tasks.append(('crop', ((left, top, left + max_width, top + max_height),), {})) elif ((img_width > max_width or img_height > max_height) or (img_width < max_width and img_height < max_height and stretch)): k = max(img_width / float(max_width), img_height / float(max_height)) w, h = int(img_width / k), int(img_height / k) tasks.append(('resize', ((w, h), Image.LANCZOS), {})) for img_method, method_args, method_kwargs in tasks: if ((img_method == 'resize' and method_args[0] == (img_width, img_height)) or (img_method == 'crop' and method_args[0] == (0, 0, img.size[0], img.size[1]))): continue img = getattr(img, img_method)(*method_args, **method_kwargs) ch_size = True if new_format and new_format != img_format: img_format = new_format ch_format = True if not ch_format and img_format == 'jpeg' and force_jpeg_save: ch_format = True if return_new_image: t = StringIO() _save_img(img, t, img_format=img_format, quality=jpeg_quality, progressive=True, optimize=True) return t if ch_size or ch_format: img.load() truncate_file(f) _save_img(img, f, img_format=img_format, quality=jpeg_quality, progressive=True, optimize=True) if isinstance(f, UploadedFile): f.seek(0, 2) f.size = f.tell() set_uploaded_file_content_type_and_file_ext(f, img_format) return ch_size or ch_format
liminspace/dju-image
dju_image/image.py
is_image
python
def is_image(f, types=('png', 'jpeg', 'gif'), set_content_type=True): assert isinstance(types, (list, tuple)) t = image_get_format(f) if t not in [t.lower() for t in types]: return False if set_content_type: set_uploaded_file_content_type_and_file_ext(f, t) return True
Return True if file f is image (types type) and set its correct content_type and filename extension. Example: if is_image(request.FILES['file']): print 'File is image' if is_image(open('/tmp/image.jpeg', 'rb')): print 'File is image'
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/image.py#L42-L58
[ "def image_get_format(f):\n \"\"\"\n Return image format for file-object f. (jpeg, png, gif etc.)\n All formats: http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html\n Example:\n if image_get_format(request.FILES['image']) == 'jpeg':\n print 'Image is JPEG'\n\n ...
# coding=utf-8 import os import subprocess from cStringIO import StringIO from PIL import Image, ImageFile from contextlib import contextmanager from django.core.files.uploadedfile import UploadedFile from dju_common.file import truncate_file from . import settings as dju_settings def image_get_format(f): """ Return image format for file-object f. (jpeg, png, gif etc.) All formats: http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html Example: if image_get_format(request.FILES['image']) == 'jpeg': print 'Image is JPEG' if image_get_format(open('/tmp/image.png', 'rb')) == 'png': print 'File is PNG' """ f.seek(0) try: img = Image.open(f) t = img.format.lower() except IOError: t = None return t def set_uploaded_file_content_type_and_file_ext(f, img_format): assert isinstance(img_format, basestring) img_format = img_format.lower() if img_format not in dju_settings.DJU_IMG_UPLOAD_IMG_EXTS: raise RuntimeError if isinstance(f, UploadedFile): f.content_type = 'image/{}'.format(img_format) f.name = os.path.splitext(f.name)[0] + '.' + img_format @contextmanager def image_save_buffer_fix(maxblock=1048576): """ Contextmanager that change MAXBLOCK in ImageFile. """ before = ImageFile.MAXBLOCK ImageFile.MAXBLOCK = maxblock try: yield finally: ImageFile.MAXBLOCK = before def _save_img(img, f, img_format, **kwargs): if isinstance(f, UploadedFile): f = f.file modes = ({}, {'mb_x': 5}, {'mb_x': 10}, {'mb_x': 10, 'disable_optimize': True}, {'mb_x': 10, 'disable_optimize': True, 'disable_progressive': True}) maxblock = max(ImageFile.MAXBLOCK, img.size[0] * img.size[1]) last_error = None if img_format.upper() == 'JPEG' and img.mode != 'RGB': current_format = img.format img = img.convert('RGB') img.format = current_format for mode in modes: try: kw = kwargs.copy() if mode.get('disable_optimize'): kw.pop('optimize') if mode.get('disable_progressive'): kw.pop('progressive') with image_save_buffer_fix(maxblock * mode.get('mb_x', 1)): img.save(f, format=img_format, **kw) last_error = None break except IOError, e: last_error = e if last_error: raise last_error if image_get_format(f) == 'jpeg' and dju_settings.DJU_IMG_USE_JPEGTRAN: f.seek(0) try: p = subprocess.Popen(['jpegtran', '-copy', 'none', '-optimize', '-progressive'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) r = p.communicate(f.read())[0] except IOError: r = None if r: truncate_file(f) f.write(r) def get_image_as_rgb(f): f.seek(0) try: p = subprocess.Popen(['convert', '-colorspace', 'rgb', '-', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) r = p.communicate(f.read())[0] except IOError: r = None if r: return Image.open(StringIO(r)) def optimize_png_file(f, o=None): """ Use pngquant for optimize PNG-image. f - path to input image file or file-object. o - path to output image file or file-object for save result. NOTICE: f and o can not be of different type """ if isinstance(f, basestring): if o is None: o = f else: assert isinstance(o, basestring) try: subprocess.check_call(['pngquant', '--force', '--output', o, f]) except subprocess.CalledProcessError: return False return True if not hasattr(f, 'read'): raise RuntimeError if o is None: o = f else: if not hasattr(f, 'write'): raise RuntimeError f.seek(0) try: p = subprocess.Popen(['pngquant', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) r = p.communicate(f.read())[0] except IOError: r = None if r: truncate_file(o) o.write(r) return True return False def adjust_image(f, max_size=(800, 800), new_format=None, jpeg_quality=90, fill=False, stretch=False, return_new_image=False, force_jpeg_save=True): """ Підганяє зображення під параметри. max_size - максимальний розмір картинки. один з розмірів може бути None (авто) new_format - формат файлу (jpeg, png, gif). якщо None, тоді буде використаний формат оригіналу jpeg_quality - якість JPEG fill - чи зображення має бути заповненим при обрізці (інакше буде вписане) stretch - чи розтягувати, якщо картинка замаленька return_new_image - якщо True, тоді буде повертатись новий об'єкт StringIO картинки. Інакше bool, чи файл змінювався. force_jpeg_save - якщо True, тоді якщо файл JPEG, то він буде перезбережений в будь-якому випадку """ assert isinstance(max_size, (list, tuple)) and len(max_size) == 2 assert 0 < jpeg_quality <= 100 if new_format: new_format = new_format.lower() if new_format not in ('jpeg', 'png', 'gif'): raise RuntimeError('Invalid new_format value.') f.seek(0) img = Image.open(f) if ((new_format == 'jpeg' and img.mode != 'RGB') or (new_format is None and img.format == 'JPEG' and img.mode != 'RGB')): do_convert = True if dju_settings.DJU_IMG_CONVERT_JPEG_TO_RGB: img = get_image_as_rgb(f) if img is not None: do_convert = False if do_convert: current_format = img.format img = img.convert('RGB') img.format = current_format max_width, max_height = max_size img_width, img_height = img.size img_format = img.format.lower() ch_size = ch_format = False if max_width is None: max_width = int(((img_width / float(img_height)) * max_height)) elif max_height is None: max_height = int(((img_height / float(img_width)) * max_width)) if (img_width, img_height) != (max_width, max_height): tasks = [] if fill: if (img_width < max_width or img_height < max_height) and not stretch: k = max(max_width / float(img_width), max_height / float(img_height)) w, h = max_width / k, max_height / k left, top = int((img_width - w) / 2.), int((img_height - h) / 2.) tasks.append(('crop', ((left, top, int(left + w), int(top + h)),), {})) else: k = min(img_width / float(max_width), img_height / float(max_height)) w, h = img_width / k, img_height / k tasks.append(('resize', ((int(w), int(h)), Image.LANCZOS), {})) left, top = int((w - max_width) / 2.), int((h - max_height) / 2.) tasks.append(('crop', ((left, top, left + max_width, top + max_height),), {})) elif ((img_width > max_width or img_height > max_height) or (img_width < max_width and img_height < max_height and stretch)): k = max(img_width / float(max_width), img_height / float(max_height)) w, h = int(img_width / k), int(img_height / k) tasks.append(('resize', ((w, h), Image.LANCZOS), {})) for img_method, method_args, method_kwargs in tasks: if ((img_method == 'resize' and method_args[0] == (img_width, img_height)) or (img_method == 'crop' and method_args[0] == (0, 0, img.size[0], img.size[1]))): continue img = getattr(img, img_method)(*method_args, **method_kwargs) ch_size = True if new_format and new_format != img_format: img_format = new_format ch_format = True if not ch_format and img_format == 'jpeg' and force_jpeg_save: ch_format = True if return_new_image: t = StringIO() _save_img(img, t, img_format=img_format, quality=jpeg_quality, progressive=True, optimize=True) return t if ch_size or ch_format: img.load() truncate_file(f) _save_img(img, f, img_format=img_format, quality=jpeg_quality, progressive=True, optimize=True) if isinstance(f, UploadedFile): f.seek(0, 2) f.size = f.tell() set_uploaded_file_content_type_and_file_ext(f, img_format) return ch_size or ch_format
liminspace/dju-image
dju_image/image.py
image_save_buffer_fix
python
def image_save_buffer_fix(maxblock=1048576): before = ImageFile.MAXBLOCK ImageFile.MAXBLOCK = maxblock try: yield finally: ImageFile.MAXBLOCK = before
Contextmanager that change MAXBLOCK in ImageFile.
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/image.py#L62-L71
null
# coding=utf-8 import os import subprocess from cStringIO import StringIO from PIL import Image, ImageFile from contextlib import contextmanager from django.core.files.uploadedfile import UploadedFile from dju_common.file import truncate_file from . import settings as dju_settings def image_get_format(f): """ Return image format for file-object f. (jpeg, png, gif etc.) All formats: http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html Example: if image_get_format(request.FILES['image']) == 'jpeg': print 'Image is JPEG' if image_get_format(open('/tmp/image.png', 'rb')) == 'png': print 'File is PNG' """ f.seek(0) try: img = Image.open(f) t = img.format.lower() except IOError: t = None return t def set_uploaded_file_content_type_and_file_ext(f, img_format): assert isinstance(img_format, basestring) img_format = img_format.lower() if img_format not in dju_settings.DJU_IMG_UPLOAD_IMG_EXTS: raise RuntimeError if isinstance(f, UploadedFile): f.content_type = 'image/{}'.format(img_format) f.name = os.path.splitext(f.name)[0] + '.' + img_format def is_image(f, types=('png', 'jpeg', 'gif'), set_content_type=True): """ Return True if file f is image (types type) and set its correct content_type and filename extension. Example: if is_image(request.FILES['file']): print 'File is image' if is_image(open('/tmp/image.jpeg', 'rb')): print 'File is image' """ assert isinstance(types, (list, tuple)) t = image_get_format(f) if t not in [t.lower() for t in types]: return False if set_content_type: set_uploaded_file_content_type_and_file_ext(f, t) return True @contextmanager def _save_img(img, f, img_format, **kwargs): if isinstance(f, UploadedFile): f = f.file modes = ({}, {'mb_x': 5}, {'mb_x': 10}, {'mb_x': 10, 'disable_optimize': True}, {'mb_x': 10, 'disable_optimize': True, 'disable_progressive': True}) maxblock = max(ImageFile.MAXBLOCK, img.size[0] * img.size[1]) last_error = None if img_format.upper() == 'JPEG' and img.mode != 'RGB': current_format = img.format img = img.convert('RGB') img.format = current_format for mode in modes: try: kw = kwargs.copy() if mode.get('disable_optimize'): kw.pop('optimize') if mode.get('disable_progressive'): kw.pop('progressive') with image_save_buffer_fix(maxblock * mode.get('mb_x', 1)): img.save(f, format=img_format, **kw) last_error = None break except IOError, e: last_error = e if last_error: raise last_error if image_get_format(f) == 'jpeg' and dju_settings.DJU_IMG_USE_JPEGTRAN: f.seek(0) try: p = subprocess.Popen(['jpegtran', '-copy', 'none', '-optimize', '-progressive'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) r = p.communicate(f.read())[0] except IOError: r = None if r: truncate_file(f) f.write(r) def get_image_as_rgb(f): f.seek(0) try: p = subprocess.Popen(['convert', '-colorspace', 'rgb', '-', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) r = p.communicate(f.read())[0] except IOError: r = None if r: return Image.open(StringIO(r)) def optimize_png_file(f, o=None): """ Use pngquant for optimize PNG-image. f - path to input image file or file-object. o - path to output image file or file-object for save result. NOTICE: f and o can not be of different type """ if isinstance(f, basestring): if o is None: o = f else: assert isinstance(o, basestring) try: subprocess.check_call(['pngquant', '--force', '--output', o, f]) except subprocess.CalledProcessError: return False return True if not hasattr(f, 'read'): raise RuntimeError if o is None: o = f else: if not hasattr(f, 'write'): raise RuntimeError f.seek(0) try: p = subprocess.Popen(['pngquant', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) r = p.communicate(f.read())[0] except IOError: r = None if r: truncate_file(o) o.write(r) return True return False def adjust_image(f, max_size=(800, 800), new_format=None, jpeg_quality=90, fill=False, stretch=False, return_new_image=False, force_jpeg_save=True): """ Підганяє зображення під параметри. max_size - максимальний розмір картинки. один з розмірів може бути None (авто) new_format - формат файлу (jpeg, png, gif). якщо None, тоді буде використаний формат оригіналу jpeg_quality - якість JPEG fill - чи зображення має бути заповненим при обрізці (інакше буде вписане) stretch - чи розтягувати, якщо картинка замаленька return_new_image - якщо True, тоді буде повертатись новий об'єкт StringIO картинки. Інакше bool, чи файл змінювався. force_jpeg_save - якщо True, тоді якщо файл JPEG, то він буде перезбережений в будь-якому випадку """ assert isinstance(max_size, (list, tuple)) and len(max_size) == 2 assert 0 < jpeg_quality <= 100 if new_format: new_format = new_format.lower() if new_format not in ('jpeg', 'png', 'gif'): raise RuntimeError('Invalid new_format value.') f.seek(0) img = Image.open(f) if ((new_format == 'jpeg' and img.mode != 'RGB') or (new_format is None and img.format == 'JPEG' and img.mode != 'RGB')): do_convert = True if dju_settings.DJU_IMG_CONVERT_JPEG_TO_RGB: img = get_image_as_rgb(f) if img is not None: do_convert = False if do_convert: current_format = img.format img = img.convert('RGB') img.format = current_format max_width, max_height = max_size img_width, img_height = img.size img_format = img.format.lower() ch_size = ch_format = False if max_width is None: max_width = int(((img_width / float(img_height)) * max_height)) elif max_height is None: max_height = int(((img_height / float(img_width)) * max_width)) if (img_width, img_height) != (max_width, max_height): tasks = [] if fill: if (img_width < max_width or img_height < max_height) and not stretch: k = max(max_width / float(img_width), max_height / float(img_height)) w, h = max_width / k, max_height / k left, top = int((img_width - w) / 2.), int((img_height - h) / 2.) tasks.append(('crop', ((left, top, int(left + w), int(top + h)),), {})) else: k = min(img_width / float(max_width), img_height / float(max_height)) w, h = img_width / k, img_height / k tasks.append(('resize', ((int(w), int(h)), Image.LANCZOS), {})) left, top = int((w - max_width) / 2.), int((h - max_height) / 2.) tasks.append(('crop', ((left, top, left + max_width, top + max_height),), {})) elif ((img_width > max_width or img_height > max_height) or (img_width < max_width and img_height < max_height and stretch)): k = max(img_width / float(max_width), img_height / float(max_height)) w, h = int(img_width / k), int(img_height / k) tasks.append(('resize', ((w, h), Image.LANCZOS), {})) for img_method, method_args, method_kwargs in tasks: if ((img_method == 'resize' and method_args[0] == (img_width, img_height)) or (img_method == 'crop' and method_args[0] == (0, 0, img.size[0], img.size[1]))): continue img = getattr(img, img_method)(*method_args, **method_kwargs) ch_size = True if new_format and new_format != img_format: img_format = new_format ch_format = True if not ch_format and img_format == 'jpeg' and force_jpeg_save: ch_format = True if return_new_image: t = StringIO() _save_img(img, t, img_format=img_format, quality=jpeg_quality, progressive=True, optimize=True) return t if ch_size or ch_format: img.load() truncate_file(f) _save_img(img, f, img_format=img_format, quality=jpeg_quality, progressive=True, optimize=True) if isinstance(f, UploadedFile): f.seek(0, 2) f.size = f.tell() set_uploaded_file_content_type_and_file_ext(f, img_format) return ch_size or ch_format
liminspace/dju-image
dju_image/image.py
optimize_png_file
python
def optimize_png_file(f, o=None): if isinstance(f, basestring): if o is None: o = f else: assert isinstance(o, basestring) try: subprocess.check_call(['pngquant', '--force', '--output', o, f]) except subprocess.CalledProcessError: return False return True if not hasattr(f, 'read'): raise RuntimeError if o is None: o = f else: if not hasattr(f, 'write'): raise RuntimeError f.seek(0) try: p = subprocess.Popen(['pngquant', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) r = p.communicate(f.read())[0] except IOError: r = None if r: truncate_file(o) o.write(r) return True return False
Use pngquant for optimize PNG-image. f - path to input image file or file-object. o - path to output image file or file-object for save result. NOTICE: f and o can not be of different type
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/image.py#L128-L162
null
# coding=utf-8 import os import subprocess from cStringIO import StringIO from PIL import Image, ImageFile from contextlib import contextmanager from django.core.files.uploadedfile import UploadedFile from dju_common.file import truncate_file from . import settings as dju_settings def image_get_format(f): """ Return image format for file-object f. (jpeg, png, gif etc.) All formats: http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html Example: if image_get_format(request.FILES['image']) == 'jpeg': print 'Image is JPEG' if image_get_format(open('/tmp/image.png', 'rb')) == 'png': print 'File is PNG' """ f.seek(0) try: img = Image.open(f) t = img.format.lower() except IOError: t = None return t def set_uploaded_file_content_type_and_file_ext(f, img_format): assert isinstance(img_format, basestring) img_format = img_format.lower() if img_format not in dju_settings.DJU_IMG_UPLOAD_IMG_EXTS: raise RuntimeError if isinstance(f, UploadedFile): f.content_type = 'image/{}'.format(img_format) f.name = os.path.splitext(f.name)[0] + '.' + img_format def is_image(f, types=('png', 'jpeg', 'gif'), set_content_type=True): """ Return True if file f is image (types type) and set its correct content_type and filename extension. Example: if is_image(request.FILES['file']): print 'File is image' if is_image(open('/tmp/image.jpeg', 'rb')): print 'File is image' """ assert isinstance(types, (list, tuple)) t = image_get_format(f) if t not in [t.lower() for t in types]: return False if set_content_type: set_uploaded_file_content_type_and_file_ext(f, t) return True @contextmanager def image_save_buffer_fix(maxblock=1048576): """ Contextmanager that change MAXBLOCK in ImageFile. """ before = ImageFile.MAXBLOCK ImageFile.MAXBLOCK = maxblock try: yield finally: ImageFile.MAXBLOCK = before def _save_img(img, f, img_format, **kwargs): if isinstance(f, UploadedFile): f = f.file modes = ({}, {'mb_x': 5}, {'mb_x': 10}, {'mb_x': 10, 'disable_optimize': True}, {'mb_x': 10, 'disable_optimize': True, 'disable_progressive': True}) maxblock = max(ImageFile.MAXBLOCK, img.size[0] * img.size[1]) last_error = None if img_format.upper() == 'JPEG' and img.mode != 'RGB': current_format = img.format img = img.convert('RGB') img.format = current_format for mode in modes: try: kw = kwargs.copy() if mode.get('disable_optimize'): kw.pop('optimize') if mode.get('disable_progressive'): kw.pop('progressive') with image_save_buffer_fix(maxblock * mode.get('mb_x', 1)): img.save(f, format=img_format, **kw) last_error = None break except IOError, e: last_error = e if last_error: raise last_error if image_get_format(f) == 'jpeg' and dju_settings.DJU_IMG_USE_JPEGTRAN: f.seek(0) try: p = subprocess.Popen(['jpegtran', '-copy', 'none', '-optimize', '-progressive'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) r = p.communicate(f.read())[0] except IOError: r = None if r: truncate_file(f) f.write(r) def get_image_as_rgb(f): f.seek(0) try: p = subprocess.Popen(['convert', '-colorspace', 'rgb', '-', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) r = p.communicate(f.read())[0] except IOError: r = None if r: return Image.open(StringIO(r)) def adjust_image(f, max_size=(800, 800), new_format=None, jpeg_quality=90, fill=False, stretch=False, return_new_image=False, force_jpeg_save=True): """ Підганяє зображення під параметри. max_size - максимальний розмір картинки. один з розмірів може бути None (авто) new_format - формат файлу (jpeg, png, gif). якщо None, тоді буде використаний формат оригіналу jpeg_quality - якість JPEG fill - чи зображення має бути заповненим при обрізці (інакше буде вписане) stretch - чи розтягувати, якщо картинка замаленька return_new_image - якщо True, тоді буде повертатись новий об'єкт StringIO картинки. Інакше bool, чи файл змінювався. force_jpeg_save - якщо True, тоді якщо файл JPEG, то він буде перезбережений в будь-якому випадку """ assert isinstance(max_size, (list, tuple)) and len(max_size) == 2 assert 0 < jpeg_quality <= 100 if new_format: new_format = new_format.lower() if new_format not in ('jpeg', 'png', 'gif'): raise RuntimeError('Invalid new_format value.') f.seek(0) img = Image.open(f) if ((new_format == 'jpeg' and img.mode != 'RGB') or (new_format is None and img.format == 'JPEG' and img.mode != 'RGB')): do_convert = True if dju_settings.DJU_IMG_CONVERT_JPEG_TO_RGB: img = get_image_as_rgb(f) if img is not None: do_convert = False if do_convert: current_format = img.format img = img.convert('RGB') img.format = current_format max_width, max_height = max_size img_width, img_height = img.size img_format = img.format.lower() ch_size = ch_format = False if max_width is None: max_width = int(((img_width / float(img_height)) * max_height)) elif max_height is None: max_height = int(((img_height / float(img_width)) * max_width)) if (img_width, img_height) != (max_width, max_height): tasks = [] if fill: if (img_width < max_width or img_height < max_height) and not stretch: k = max(max_width / float(img_width), max_height / float(img_height)) w, h = max_width / k, max_height / k left, top = int((img_width - w) / 2.), int((img_height - h) / 2.) tasks.append(('crop', ((left, top, int(left + w), int(top + h)),), {})) else: k = min(img_width / float(max_width), img_height / float(max_height)) w, h = img_width / k, img_height / k tasks.append(('resize', ((int(w), int(h)), Image.LANCZOS), {})) left, top = int((w - max_width) / 2.), int((h - max_height) / 2.) tasks.append(('crop', ((left, top, left + max_width, top + max_height),), {})) elif ((img_width > max_width or img_height > max_height) or (img_width < max_width and img_height < max_height and stretch)): k = max(img_width / float(max_width), img_height / float(max_height)) w, h = int(img_width / k), int(img_height / k) tasks.append(('resize', ((w, h), Image.LANCZOS), {})) for img_method, method_args, method_kwargs in tasks: if ((img_method == 'resize' and method_args[0] == (img_width, img_height)) or (img_method == 'crop' and method_args[0] == (0, 0, img.size[0], img.size[1]))): continue img = getattr(img, img_method)(*method_args, **method_kwargs) ch_size = True if new_format and new_format != img_format: img_format = new_format ch_format = True if not ch_format and img_format == 'jpeg' and force_jpeg_save: ch_format = True if return_new_image: t = StringIO() _save_img(img, t, img_format=img_format, quality=jpeg_quality, progressive=True, optimize=True) return t if ch_size or ch_format: img.load() truncate_file(f) _save_img(img, f, img_format=img_format, quality=jpeg_quality, progressive=True, optimize=True) if isinstance(f, UploadedFile): f.seek(0, 2) f.size = f.tell() set_uploaded_file_content_type_and_file_ext(f, img_format) return ch_size or ch_format
liminspace/dju-image
dju_image/image.py
adjust_image
python
def adjust_image(f, max_size=(800, 800), new_format=None, jpeg_quality=90, fill=False, stretch=False, return_new_image=False, force_jpeg_save=True): assert isinstance(max_size, (list, tuple)) and len(max_size) == 2 assert 0 < jpeg_quality <= 100 if new_format: new_format = new_format.lower() if new_format not in ('jpeg', 'png', 'gif'): raise RuntimeError('Invalid new_format value.') f.seek(0) img = Image.open(f) if ((new_format == 'jpeg' and img.mode != 'RGB') or (new_format is None and img.format == 'JPEG' and img.mode != 'RGB')): do_convert = True if dju_settings.DJU_IMG_CONVERT_JPEG_TO_RGB: img = get_image_as_rgb(f) if img is not None: do_convert = False if do_convert: current_format = img.format img = img.convert('RGB') img.format = current_format max_width, max_height = max_size img_width, img_height = img.size img_format = img.format.lower() ch_size = ch_format = False if max_width is None: max_width = int(((img_width / float(img_height)) * max_height)) elif max_height is None: max_height = int(((img_height / float(img_width)) * max_width)) if (img_width, img_height) != (max_width, max_height): tasks = [] if fill: if (img_width < max_width or img_height < max_height) and not stretch: k = max(max_width / float(img_width), max_height / float(img_height)) w, h = max_width / k, max_height / k left, top = int((img_width - w) / 2.), int((img_height - h) / 2.) tasks.append(('crop', ((left, top, int(left + w), int(top + h)),), {})) else: k = min(img_width / float(max_width), img_height / float(max_height)) w, h = img_width / k, img_height / k tasks.append(('resize', ((int(w), int(h)), Image.LANCZOS), {})) left, top = int((w - max_width) / 2.), int((h - max_height) / 2.) tasks.append(('crop', ((left, top, left + max_width, top + max_height),), {})) elif ((img_width > max_width or img_height > max_height) or (img_width < max_width and img_height < max_height and stretch)): k = max(img_width / float(max_width), img_height / float(max_height)) w, h = int(img_width / k), int(img_height / k) tasks.append(('resize', ((w, h), Image.LANCZOS), {})) for img_method, method_args, method_kwargs in tasks: if ((img_method == 'resize' and method_args[0] == (img_width, img_height)) or (img_method == 'crop' and method_args[0] == (0, 0, img.size[0], img.size[1]))): continue img = getattr(img, img_method)(*method_args, **method_kwargs) ch_size = True if new_format and new_format != img_format: img_format = new_format ch_format = True if not ch_format and img_format == 'jpeg' and force_jpeg_save: ch_format = True if return_new_image: t = StringIO() _save_img(img, t, img_format=img_format, quality=jpeg_quality, progressive=True, optimize=True) return t if ch_size or ch_format: img.load() truncate_file(f) _save_img(img, f, img_format=img_format, quality=jpeg_quality, progressive=True, optimize=True) if isinstance(f, UploadedFile): f.seek(0, 2) f.size = f.tell() set_uploaded_file_content_type_and_file_ext(f, img_format) return ch_size or ch_format
Підганяє зображення під параметри. max_size - максимальний розмір картинки. один з розмірів може бути None (авто) new_format - формат файлу (jpeg, png, gif). якщо None, тоді буде використаний формат оригіналу jpeg_quality - якість JPEG fill - чи зображення має бути заповненим при обрізці (інакше буде вписане) stretch - чи розтягувати, якщо картинка замаленька return_new_image - якщо True, тоді буде повертатись новий об'єкт StringIO картинки. Інакше bool, чи файл змінювався. force_jpeg_save - якщо True, тоді якщо файл JPEG, то він буде перезбережений в будь-якому випадку
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/image.py#L165-L246
[ "def set_uploaded_file_content_type_and_file_ext(f, img_format):\n assert isinstance(img_format, basestring)\n img_format = img_format.lower()\n if img_format not in dju_settings.DJU_IMG_UPLOAD_IMG_EXTS:\n raise RuntimeError\n if isinstance(f, UploadedFile):\n f.content_type = 'image/{}'.f...
# coding=utf-8 import os import subprocess from cStringIO import StringIO from PIL import Image, ImageFile from contextlib import contextmanager from django.core.files.uploadedfile import UploadedFile from dju_common.file import truncate_file from . import settings as dju_settings def image_get_format(f): """ Return image format for file-object f. (jpeg, png, gif etc.) All formats: http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html Example: if image_get_format(request.FILES['image']) == 'jpeg': print 'Image is JPEG' if image_get_format(open('/tmp/image.png', 'rb')) == 'png': print 'File is PNG' """ f.seek(0) try: img = Image.open(f) t = img.format.lower() except IOError: t = None return t def set_uploaded_file_content_type_and_file_ext(f, img_format): assert isinstance(img_format, basestring) img_format = img_format.lower() if img_format not in dju_settings.DJU_IMG_UPLOAD_IMG_EXTS: raise RuntimeError if isinstance(f, UploadedFile): f.content_type = 'image/{}'.format(img_format) f.name = os.path.splitext(f.name)[0] + '.' + img_format def is_image(f, types=('png', 'jpeg', 'gif'), set_content_type=True): """ Return True if file f is image (types type) and set its correct content_type and filename extension. Example: if is_image(request.FILES['file']): print 'File is image' if is_image(open('/tmp/image.jpeg', 'rb')): print 'File is image' """ assert isinstance(types, (list, tuple)) t = image_get_format(f) if t not in [t.lower() for t in types]: return False if set_content_type: set_uploaded_file_content_type_and_file_ext(f, t) return True @contextmanager def image_save_buffer_fix(maxblock=1048576): """ Contextmanager that change MAXBLOCK in ImageFile. """ before = ImageFile.MAXBLOCK ImageFile.MAXBLOCK = maxblock try: yield finally: ImageFile.MAXBLOCK = before def _save_img(img, f, img_format, **kwargs): if isinstance(f, UploadedFile): f = f.file modes = ({}, {'mb_x': 5}, {'mb_x': 10}, {'mb_x': 10, 'disable_optimize': True}, {'mb_x': 10, 'disable_optimize': True, 'disable_progressive': True}) maxblock = max(ImageFile.MAXBLOCK, img.size[0] * img.size[1]) last_error = None if img_format.upper() == 'JPEG' and img.mode != 'RGB': current_format = img.format img = img.convert('RGB') img.format = current_format for mode in modes: try: kw = kwargs.copy() if mode.get('disable_optimize'): kw.pop('optimize') if mode.get('disable_progressive'): kw.pop('progressive') with image_save_buffer_fix(maxblock * mode.get('mb_x', 1)): img.save(f, format=img_format, **kw) last_error = None break except IOError, e: last_error = e if last_error: raise last_error if image_get_format(f) == 'jpeg' and dju_settings.DJU_IMG_USE_JPEGTRAN: f.seek(0) try: p = subprocess.Popen(['jpegtran', '-copy', 'none', '-optimize', '-progressive'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) r = p.communicate(f.read())[0] except IOError: r = None if r: truncate_file(f) f.write(r) def get_image_as_rgb(f): f.seek(0) try: p = subprocess.Popen(['convert', '-colorspace', 'rgb', '-', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) r = p.communicate(f.read())[0] except IOError: r = None if r: return Image.open(StringIO(r)) def optimize_png_file(f, o=None): """ Use pngquant for optimize PNG-image. f - path to input image file or file-object. o - path to output image file or file-object for save result. NOTICE: f and o can not be of different type """ if isinstance(f, basestring): if o is None: o = f else: assert isinstance(o, basestring) try: subprocess.check_call(['pngquant', '--force', '--output', o, f]) except subprocess.CalledProcessError: return False return True if not hasattr(f, 'read'): raise RuntimeError if o is None: o = f else: if not hasattr(f, 'write'): raise RuntimeError f.seek(0) try: p = subprocess.Popen(['pngquant', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) r = p.communicate(f.read())[0] except IOError: r = None if r: truncate_file(o) o.write(r) return True return False
liminspace/dju-image
dju_image/views.py
upload_image
python
def upload_image(request): if request.method != 'POST': return HttpResponseNotAllowed(('POST',)) result = {'uploaded': [], 'errors': []} files = request.FILES.getlist('images[]') if not files: result['errors'].append(unicode(ERROR_MESSAGES['no_uploaded_files'])) return send_json(result) try: profile = request.POST.get('profile', 'default') conf = get_profile_configs(profile) except ValueError, e: result['errors'].append(unicode(e)) return send_json(result) for i in xrange(min(len(files), dju_settings.DJU_IMG_UPLOAD_MAX_FILES)): f = files[i] if not is_image(f, types=conf['TYPES']): result['errors'].append( unicode(ERROR_MESSAGES['wrong_file_format']) % {'name': f.name, 'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))} ) continue adjust_image(f, max_size=conf['MAX_SIZE'], new_format=conf['FORMAT'], jpeg_quality=conf['JPEG_QUALITY'], fill=conf['FILL'], stretch=conf['STRETCH']) img_id = generate_img_id(profile, ext=image_get_format(f), label=request.POST.get('label'), tmp=True) relative_path = get_relative_path_from_img_id(img_id) full_path = media_path(relative_path) save_file(f, full_path) data = { 'url': settings.MEDIA_URL + relative_path, 'rel_url': relative_path, 'img_id': img_id, 'variants': {}, } for v_conf in conf['VARIANTS']: label = v_conf['LABEL'] if not label: label = get_variant_label(v_conf) v_f = adjust_image(f, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=label, ext=image_get_format(v_f)) v_full_path = media_path(v_relative_path) save_file(v_f, v_full_path) data['variants'][label] = { 'url': settings.MEDIA_URL + v_relative_path, 'rel_url': v_relative_path, } result['uploaded'].append(data) return send_json(result)
Вюха, яка зберігає завантажений файл. Структура запиту: FILES images[]: файли зображеннь POST DATA profile: назва профілю (для визначення налаштувань збреження) (опціонально) label: додаток до назви файлу при збереженні (опціонально) Структура відповіді: Тип відповіді: JSON { 'uploaded': [ { 'url': 'повний url до головного файла', 'rel_url': 'відносний від MEDIA url головного файла', 'img_id': 'ідентифікатор для збереження в БД', // 'profilename:abcdef_abcd_label.png', 'variants': { 'variant label': { 'url': 'повний url до варіанта', 'rel_url': 'відносний від MEDIA url головного файла' }, ... } }, ... ], 'errors': ['error message', ...] }
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/views.py#L20-L100
[ "def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False):\n \"\"\"\n Returns path to file relative MEDIA_URL.\n \"\"\"\n profile, base_name = img_id.split(':', 1)\n conf = get_profile_configs(profile)\n if not variant_label:\n status_suffix = dju_settings....
# coding=utf-8 from django.conf import settings from django.http import HttpResponseNotAllowed from django.utils.translation import ugettext_lazy from dju_common.http import send_json from dju_image.image import image_get_format, adjust_image, is_image from dju_image.tools import (get_profile_configs, save_file, generate_img_id, get_relative_path_from_img_id, get_variant_label, media_path) from dju_image import settings as dju_settings ERROR_MESSAGES = { 'no_uploaded_files': ugettext_lazy('Uploaded files not found.'), 'wrong_file_format': ugettext_lazy('Format of uploaded file "%(name)s" is not allowed. ' 'Allowed formats is: %(formats)s.'), 'wrong_profile': ugettext_lazy('') }
liminspace/dju-image
dju_image/maintenance.py
remove_old_tmp_files
python
def remove_old_tmp_files(profiles=None, max_lifetime=(7 * 24)): assert isinstance(profiles, (list, tuple)) or profiles is None if profiles is None: profiles = dju_settings.DJU_IMG_UPLOAD_PROFILES.keys() profiles = set(('default',) + tuple(profiles)) total = removed = 0 old_dt = datetime.datetime.utcnow() - datetime.timedelta(hours=max_lifetime) for profile in profiles: conf = get_profile_configs(profile=profile) root_path = os.path.join(settings.MEDIA_ROOT, dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH']) for file_path in get_files_recursive(root_path): m = re_tmp.match(os.path.basename(file_path)) if m is None: continue total += 1 fdt = dtstr_to_datetime(m.group('dtstr')) if fdt and old_dt > fdt: os.remove(file_path) removed += 1 return removed, total
Removes old temp files that is older than expiration_hours. If profiles is None then will be use all profiles.
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/maintenance.py#L23-L46
[ "def get_profile_configs(profile=None, use_cache=True):\n \"\"\"\n Returns upload configs for profile.\n \"\"\"\n if use_cache and profile in _profile_configs_cache:\n return _profile_configs_cache[profile]\n profile_conf = None\n if profile is not None:\n try:\n profile_c...
# coding=utf-8 import os import re import datetime from django.conf import settings from dju_common.tools import dtstr_to_datetime from .image import adjust_image, image_get_format from .tools import get_profile_configs, get_variant_label, get_relative_path_from_img_id, media_path, save_file from . import settings as dju_settings re_tmp = re.compile(r'^{pref}(?P<dtstr>[a-z0-9]{7,9})_[a-z0-9]{4}.*$'.replace( '{pref}', dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX )) def get_files_recursive(path): for root, dirs, files in os.walk(path): for fn in files: yield os.path.join(root, fn).replace('\\', '/') def remake_images_variants(profiles, clear=True): """ Перестворює варіанти для картинок згідно налаштувань. profiles - список профілів, для картинок яких треба перестворити варіанти. clear - якщо True, тоді перед створенням варіантів будуть видалені ВСІ попередні варіанти. """ assert isinstance(profiles, (list, tuple)) or profiles is None if profiles is None: profiles = dju_settings.DJU_IMG_UPLOAD_PROFILES.keys() profiles = set(('default',) + tuple(profiles)) removed = remade = 0 for profile in profiles: conf = get_profile_configs(profile=profile) root_path = os.path.join(settings.MEDIA_ROOT, dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH']) if clear: for fn in get_files_recursive(root_path): if dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX in os.path.basename(fn): os.remove(fn) removed += 1 for fn in get_files_recursive(root_path): filename = os.path.basename(fn) if dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX in filename: continue if dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX not in filename: continue img_id = '{profile}:{name}'.format( profile=profile, name=filename[:filename.find(dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX)] ) with open(fn, 'rb') as f: for v_conf in conf['VARIANTS']: label = v_conf['LABEL'] if not label: label = get_variant_label(v_conf) v_f = adjust_image(f, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=label, ext=image_get_format(v_f)) v_full_path = media_path(v_relative_path) save_file(v_f, v_full_path) remade += 1 return removed, remade def update_wrong_hashes(): """ Оновлює хеші в назвах файлів. Запускати після зміни ключа DJU_IMG_UPLOAD_KEY. """ pass # todo do it def clean(): """ Видаляє файли, в яких невірний хеш та зайві варіанти. """ pass # todo do it
liminspace/dju-image
dju_image/maintenance.py
remake_images_variants
python
def remake_images_variants(profiles, clear=True): assert isinstance(profiles, (list, tuple)) or profiles is None if profiles is None: profiles = dju_settings.DJU_IMG_UPLOAD_PROFILES.keys() profiles = set(('default',) + tuple(profiles)) removed = remade = 0 for profile in profiles: conf = get_profile_configs(profile=profile) root_path = os.path.join(settings.MEDIA_ROOT, dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH']) if clear: for fn in get_files_recursive(root_path): if dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX in os.path.basename(fn): os.remove(fn) removed += 1 for fn in get_files_recursive(root_path): filename = os.path.basename(fn) if dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX in filename: continue if dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX not in filename: continue img_id = '{profile}:{name}'.format( profile=profile, name=filename[:filename.find(dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX)] ) with open(fn, 'rb') as f: for v_conf in conf['VARIANTS']: label = v_conf['LABEL'] if not label: label = get_variant_label(v_conf) v_f = adjust_image(f, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=label, ext=image_get_format(v_f)) v_full_path = media_path(v_relative_path) save_file(v_f, v_full_path) remade += 1 return removed, remade
Перестворює варіанти для картинок згідно налаштувань. profiles - список профілів, для картинок яких треба перестворити варіанти. clear - якщо True, тоді перед створенням варіантів будуть видалені ВСІ попередні варіанти.
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/maintenance.py#L49-L91
[ "def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False):\n \"\"\"\n Returns path to file relative MEDIA_URL.\n \"\"\"\n profile, base_name = img_id.split(':', 1)\n conf = get_profile_configs(profile)\n if not variant_label:\n status_suffix = dju_settings....
# coding=utf-8 import os import re import datetime from django.conf import settings from dju_common.tools import dtstr_to_datetime from .image import adjust_image, image_get_format from .tools import get_profile_configs, get_variant_label, get_relative_path_from_img_id, media_path, save_file from . import settings as dju_settings re_tmp = re.compile(r'^{pref}(?P<dtstr>[a-z0-9]{7,9})_[a-z0-9]{4}.*$'.replace( '{pref}', dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX )) def get_files_recursive(path): for root, dirs, files in os.walk(path): for fn in files: yield os.path.join(root, fn).replace('\\', '/') def remove_old_tmp_files(profiles=None, max_lifetime=(7 * 24)): """ Removes old temp files that is older than expiration_hours. If profiles is None then will be use all profiles. """ assert isinstance(profiles, (list, tuple)) or profiles is None if profiles is None: profiles = dju_settings.DJU_IMG_UPLOAD_PROFILES.keys() profiles = set(('default',) + tuple(profiles)) total = removed = 0 old_dt = datetime.datetime.utcnow() - datetime.timedelta(hours=max_lifetime) for profile in profiles: conf = get_profile_configs(profile=profile) root_path = os.path.join(settings.MEDIA_ROOT, dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH']) for file_path in get_files_recursive(root_path): m = re_tmp.match(os.path.basename(file_path)) if m is None: continue total += 1 fdt = dtstr_to_datetime(m.group('dtstr')) if fdt and old_dt > fdt: os.remove(file_path) removed += 1 return removed, total def update_wrong_hashes(): """ Оновлює хеші в назвах файлів. Запускати після зміни ключа DJU_IMG_UPLOAD_KEY. """ pass # todo do it def clean(): """ Видаляє файли, в яких невірний хеш та зайві варіанти. """ pass # todo do it
liminspace/dju-image
dju_image/tools.py
save_file
python
def save_file(f, full_path): make_dirs_for_file_path(full_path, mode=dju_settings.DJU_IMG_CHMOD_DIR) with open(full_path, 'wb') as t: f.seek(0) while True: buf = f.read(dju_settings.DJU_IMG_RW_FILE_BUFFER_SIZE) if not buf: break t.write(buf) os.chmod(full_path, dju_settings.DJU_IMG_CHMOD_FILE)
Saves file f to full_path and set rules.
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/tools.py#L35-L47
null
# coding=utf-8 import glob import os import copy import re import hashlib from django.utils.crypto import get_random_string from django.utils.translation import ugettext_lazy from django.conf import settings from dju_common.file import make_dirs_for_file_path from dju_common.tools import datetime_to_dtstr from dju_image.image import is_image, adjust_image, image_get_format from . import settings as dju_settings ERROR_MESSAGES = { 'unknown_profile': ugettext_lazy('Unknown profile "%(profile)s".'), 'filename_hasnt_tmp_prefix': ugettext_lazy('Filename "%(filename)s" has not temporary prefix.'), } HASH_SIZE = 10 _profile_configs_cache = {} def clear_profile_configs_cache(): _profile_configs_cache.clear() def media_path(path): return os.path.join(settings.MEDIA_ROOT, path).replace('\\', '/') def get_profile_configs(profile=None, use_cache=True): """ Returns upload configs for profile. """ if use_cache and profile in _profile_configs_cache: return _profile_configs_cache[profile] profile_conf = None if profile is not None: try: profile_conf = dju_settings.DJU_IMG_UPLOAD_PROFILES[profile] except KeyError: if profile != 'default': raise ValueError(unicode(ERROR_MESSAGES['unknown_profile']) % {'profile': profile}) conf = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_DEFAULT) if profile_conf: conf.update(copy.deepcopy(profile_conf)) for v_i in xrange(len(conf['VARIANTS'])): v = conf['VARIANTS'][v_i] conf['VARIANTS'][v_i] = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_VARIANT_DEFAULT) conf['VARIANTS'][v_i].update(v) if use_cache: _profile_configs_cache[profile] = conf return conf def generate_img_id(profile, ext=None, label=None, tmp=False): """ Generates img_id. """ if ext and not ext.startswith('.'): ext = '.' + ext if label: label = re.sub(r'[^a-z0-9_\-]', '', label, flags=re.I) label = re.sub(r'_+', '_', label) label = label[:60] return '{profile}:{tmp}{dtstr}_{rand}{label}{ext}'.format( profile=profile, tmp=(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX if tmp else ''), dtstr=datetime_to_dtstr(), rand=get_random_string(4, 'abcdefghijklmnopqrstuvwxyz0123456789'), label=(('_' + label) if label else ''), ext=(ext or ''), ) def get_hash(name, variant_label=None): # name must be without label, for example 'uniqname_rand' h = hashlib.sha1(name + (variant_label or '') + dju_settings.DJU_IMG_UPLOAD_KEY).hexdigest() return h[:HASH_SIZE] def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False): """ Returns path to file relative MEDIA_URL. """ profile, base_name = img_id.split(':', 1) conf = get_profile_configs(profile) if not variant_label: status_suffix = dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX else: status_suffix = dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX name, file_ext = os.path.splitext(base_name) prefix = '' if name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): name = name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] prefix = dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX name_parts = name.split('_', 2) name = '{name}{status_suffix}{hash}'.format( name=name, status_suffix=status_suffix, hash=get_hash('_'.join(name_parts[:2]), variant_label=variant_label) ) if variant_label: name += '_' + variant_label if ext: file_ext = ext elif variant_label: for var_conf in conf['VARIANTS']: var_conf_label = var_conf['LABEL'] or get_variant_label(var_conf) if var_conf_label == variant_label: if var_conf['FORMAT']: file_ext = var_conf['FORMAT'].lower() break if file_ext and not file_ext.startswith('.'): file_ext = '.' + file_ext relative_path = os.path.join( dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH'], name_parts[0][-2:], (prefix + name + file_ext) ).replace('\\', '/') if create_dirs: path = media_path(relative_path) make_dirs_for_file_path(path, mode=dju_settings.DJU_IMG_CHMOD_DIR) return relative_path def is_img_id_exists(img_id): """ Checks if img_id has real file on filesystem. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) return os.path.isfile(main_path) def is_img_id_valid(img_id): """ Checks if img_id is valid. """ t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE) t = re.sub(r'\.+', '.', t) if img_id != t or img_id.count(':') != 1: return False profile, base_name = img_id.split(':', 1) if not profile or not base_name: return False try: get_profile_configs(profile) except ValueError: return False return True def get_variant_label(v_conf): """ Generates name for variant images based settings (by variants sizes). """ if v_conf['MAX_SIZE'][0] is None: return 'h{}'.format(v_conf['MAX_SIZE'][1]) if v_conf['MAX_SIZE'][1] is None: return 'w{}'.format(v_conf['MAX_SIZE'][0]) return '{}x{}'.format(*v_conf['MAX_SIZE']) variant_hash_label_re = re.compile(r'^.+?{suf}([a-z0-9]{{hs}})_(.+?)(?:|\.[A-Za-z]{3,4})$'.replace( '{suf}', dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX ).replace( '{hs}', str(HASH_SIZE) )) def get_files_by_img_id(img_id, check_hash=True): """ Шукає файли для img_id. Повертає: { 'main': 'relative path to main image', 'variants': { 'label': 'relative path to variant image by label', ... } } Якщо check_hash=True, тоді файли з невірним хешем будуть ігноруватись. Якщо файл не існує, тоді поверає None. Пошук варіантів відбуваться в файловій системі не залежно від налаштувань. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) if not os.path.isfile(main_path): return None filename = os.path.basename(main_rel_path) name_left_part = filename.split(dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX, 1)[0] img_name = name_left_part if img_name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): img_name = img_name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] img_name_parts = img_name.split('_', 2) img_name = '_'.join(img_name_parts[:2]) search_pattern = name_left_part + dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX + '*' search_dir = os.path.dirname(main_path) variants = {} for var_path in glob.iglob(os.path.join(search_dir, search_pattern.replace('\\', '/'))): var_filename = os.path.basename(var_path) m = variant_hash_label_re.match(var_filename) if not m: continue var_hash, var_label = m.groups() if check_hash and var_hash != get_hash(img_name, var_label): continue variants[var_label] = os.path.relpath(var_path, settings.MEDIA_ROOT) return { 'main': main_rel_path, 'variants': variants, } def remove_all_files_of_img_id(img_id): """ Removes all img_id's files. """ files = get_files_by_img_id(img_id, check_hash=False) if files: os.remove(media_path(files['main'])) for fn in files['variants'].values(): os.remove(media_path(fn)) def img_id_has_tmp_prefix(img_id): return (':' + dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX) in img_id def remove_tmp_prefix_from_filename(filename): """ Remove tmp prefix from filename. """ if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename}) return filename[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] def remove_tmp_prefix_from_file_path(file_path): """ Remove tmp prefix from file path or url. """ path, filename = os.path.split(file_path) return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\', '/') def make_permalink(img_id): """ Removes tmp prefix from filename and rename main and variant files. Returns img_id without tmp prefix. """ profile, filename = img_id.split(':', 1) new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename) urls = get_files_by_img_id(img_id) if urls is None: return urls move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))} for var_label, var_file_path in urls['variants'].iteritems(): move_list.add((var_file_path, remove_tmp_prefix_from_file_path(var_file_path))) for file_path_from, file_path_to in move_list: os.rename(media_path(file_path_from), media_path(file_path_to)) return new_img_id def _custom_upload(f, profile, label, conf): t = adjust_image(f, max_size=conf['MAX_SIZE'], new_format=conf['FORMAT'], jpeg_quality=conf['JPEG_QUALITY'], fill=conf['FILL'], stretch=conf['STRETCH'], return_new_image=True) img_id = generate_img_id(profile, ext=image_get_format(f), label=label, tmp=True) relative_path = get_relative_path_from_img_id(img_id) full_path = media_path(relative_path) save_file(t, full_path) for v_conf in conf['VARIANTS']: v_label = v_conf['LABEL'] if not v_label: v_label = get_variant_label(v_conf) v_t = adjust_image(t, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=v_label, ext=image_get_format(v_t)) v_full_path = media_path(v_relative_path) save_file(v_t, v_full_path) return img_id def upload_from_fs(fn, profile=None, label=None): """ Saves image from fn with TMP prefix and returns img_id. """ if not os.path.isfile(fn): raise ValueError('File is not exists: {}'.format(fn)) if profile is None: profile = 'default' conf = get_profile_configs(profile) with open(fn, 'rb') as f: if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file "%(name)s" is not allowed. ' 'Allowed formats is: %(formats)s.') % {'name': fn, 'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf) def upload_from_fileobject(f, profile=None, label=None): """ Saves image from f with TMP prefix and returns img_id. """ if profile is None: profile = 'default' conf = get_profile_configs(profile) f.seek(0) if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file is not allowed. ' 'Allowed formats is: %(formats)s.') % {'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf)
liminspace/dju-image
dju_image/tools.py
get_profile_configs
python
def get_profile_configs(profile=None, use_cache=True): if use_cache and profile in _profile_configs_cache: return _profile_configs_cache[profile] profile_conf = None if profile is not None: try: profile_conf = dju_settings.DJU_IMG_UPLOAD_PROFILES[profile] except KeyError: if profile != 'default': raise ValueError(unicode(ERROR_MESSAGES['unknown_profile']) % {'profile': profile}) conf = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_DEFAULT) if profile_conf: conf.update(copy.deepcopy(profile_conf)) for v_i in xrange(len(conf['VARIANTS'])): v = conf['VARIANTS'][v_i] conf['VARIANTS'][v_i] = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_VARIANT_DEFAULT) conf['VARIANTS'][v_i].update(v) if use_cache: _profile_configs_cache[profile] = conf return conf
Returns upload configs for profile.
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/tools.py#L50-L72
null
# coding=utf-8 import glob import os import copy import re import hashlib from django.utils.crypto import get_random_string from django.utils.translation import ugettext_lazy from django.conf import settings from dju_common.file import make_dirs_for_file_path from dju_common.tools import datetime_to_dtstr from dju_image.image import is_image, adjust_image, image_get_format from . import settings as dju_settings ERROR_MESSAGES = { 'unknown_profile': ugettext_lazy('Unknown profile "%(profile)s".'), 'filename_hasnt_tmp_prefix': ugettext_lazy('Filename "%(filename)s" has not temporary prefix.'), } HASH_SIZE = 10 _profile_configs_cache = {} def clear_profile_configs_cache(): _profile_configs_cache.clear() def media_path(path): return os.path.join(settings.MEDIA_ROOT, path).replace('\\', '/') def save_file(f, full_path): """ Saves file f to full_path and set rules. """ make_dirs_for_file_path(full_path, mode=dju_settings.DJU_IMG_CHMOD_DIR) with open(full_path, 'wb') as t: f.seek(0) while True: buf = f.read(dju_settings.DJU_IMG_RW_FILE_BUFFER_SIZE) if not buf: break t.write(buf) os.chmod(full_path, dju_settings.DJU_IMG_CHMOD_FILE) def generate_img_id(profile, ext=None, label=None, tmp=False): """ Generates img_id. """ if ext and not ext.startswith('.'): ext = '.' + ext if label: label = re.sub(r'[^a-z0-9_\-]', '', label, flags=re.I) label = re.sub(r'_+', '_', label) label = label[:60] return '{profile}:{tmp}{dtstr}_{rand}{label}{ext}'.format( profile=profile, tmp=(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX if tmp else ''), dtstr=datetime_to_dtstr(), rand=get_random_string(4, 'abcdefghijklmnopqrstuvwxyz0123456789'), label=(('_' + label) if label else ''), ext=(ext or ''), ) def get_hash(name, variant_label=None): # name must be without label, for example 'uniqname_rand' h = hashlib.sha1(name + (variant_label or '') + dju_settings.DJU_IMG_UPLOAD_KEY).hexdigest() return h[:HASH_SIZE] def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False): """ Returns path to file relative MEDIA_URL. """ profile, base_name = img_id.split(':', 1) conf = get_profile_configs(profile) if not variant_label: status_suffix = dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX else: status_suffix = dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX name, file_ext = os.path.splitext(base_name) prefix = '' if name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): name = name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] prefix = dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX name_parts = name.split('_', 2) name = '{name}{status_suffix}{hash}'.format( name=name, status_suffix=status_suffix, hash=get_hash('_'.join(name_parts[:2]), variant_label=variant_label) ) if variant_label: name += '_' + variant_label if ext: file_ext = ext elif variant_label: for var_conf in conf['VARIANTS']: var_conf_label = var_conf['LABEL'] or get_variant_label(var_conf) if var_conf_label == variant_label: if var_conf['FORMAT']: file_ext = var_conf['FORMAT'].lower() break if file_ext and not file_ext.startswith('.'): file_ext = '.' + file_ext relative_path = os.path.join( dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH'], name_parts[0][-2:], (prefix + name + file_ext) ).replace('\\', '/') if create_dirs: path = media_path(relative_path) make_dirs_for_file_path(path, mode=dju_settings.DJU_IMG_CHMOD_DIR) return relative_path def is_img_id_exists(img_id): """ Checks if img_id has real file on filesystem. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) return os.path.isfile(main_path) def is_img_id_valid(img_id): """ Checks if img_id is valid. """ t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE) t = re.sub(r'\.+', '.', t) if img_id != t or img_id.count(':') != 1: return False profile, base_name = img_id.split(':', 1) if not profile or not base_name: return False try: get_profile_configs(profile) except ValueError: return False return True def get_variant_label(v_conf): """ Generates name for variant images based settings (by variants sizes). """ if v_conf['MAX_SIZE'][0] is None: return 'h{}'.format(v_conf['MAX_SIZE'][1]) if v_conf['MAX_SIZE'][1] is None: return 'w{}'.format(v_conf['MAX_SIZE'][0]) return '{}x{}'.format(*v_conf['MAX_SIZE']) variant_hash_label_re = re.compile(r'^.+?{suf}([a-z0-9]{{hs}})_(.+?)(?:|\.[A-Za-z]{3,4})$'.replace( '{suf}', dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX ).replace( '{hs}', str(HASH_SIZE) )) def get_files_by_img_id(img_id, check_hash=True): """ Шукає файли для img_id. Повертає: { 'main': 'relative path to main image', 'variants': { 'label': 'relative path to variant image by label', ... } } Якщо check_hash=True, тоді файли з невірним хешем будуть ігноруватись. Якщо файл не існує, тоді поверає None. Пошук варіантів відбуваться в файловій системі не залежно від налаштувань. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) if not os.path.isfile(main_path): return None filename = os.path.basename(main_rel_path) name_left_part = filename.split(dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX, 1)[0] img_name = name_left_part if img_name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): img_name = img_name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] img_name_parts = img_name.split('_', 2) img_name = '_'.join(img_name_parts[:2]) search_pattern = name_left_part + dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX + '*' search_dir = os.path.dirname(main_path) variants = {} for var_path in glob.iglob(os.path.join(search_dir, search_pattern.replace('\\', '/'))): var_filename = os.path.basename(var_path) m = variant_hash_label_re.match(var_filename) if not m: continue var_hash, var_label = m.groups() if check_hash and var_hash != get_hash(img_name, var_label): continue variants[var_label] = os.path.relpath(var_path, settings.MEDIA_ROOT) return { 'main': main_rel_path, 'variants': variants, } def remove_all_files_of_img_id(img_id): """ Removes all img_id's files. """ files = get_files_by_img_id(img_id, check_hash=False) if files: os.remove(media_path(files['main'])) for fn in files['variants'].values(): os.remove(media_path(fn)) def img_id_has_tmp_prefix(img_id): return (':' + dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX) in img_id def remove_tmp_prefix_from_filename(filename): """ Remove tmp prefix from filename. """ if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename}) return filename[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] def remove_tmp_prefix_from_file_path(file_path): """ Remove tmp prefix from file path or url. """ path, filename = os.path.split(file_path) return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\', '/') def make_permalink(img_id): """ Removes tmp prefix from filename and rename main and variant files. Returns img_id without tmp prefix. """ profile, filename = img_id.split(':', 1) new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename) urls = get_files_by_img_id(img_id) if urls is None: return urls move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))} for var_label, var_file_path in urls['variants'].iteritems(): move_list.add((var_file_path, remove_tmp_prefix_from_file_path(var_file_path))) for file_path_from, file_path_to in move_list: os.rename(media_path(file_path_from), media_path(file_path_to)) return new_img_id def _custom_upload(f, profile, label, conf): t = adjust_image(f, max_size=conf['MAX_SIZE'], new_format=conf['FORMAT'], jpeg_quality=conf['JPEG_QUALITY'], fill=conf['FILL'], stretch=conf['STRETCH'], return_new_image=True) img_id = generate_img_id(profile, ext=image_get_format(f), label=label, tmp=True) relative_path = get_relative_path_from_img_id(img_id) full_path = media_path(relative_path) save_file(t, full_path) for v_conf in conf['VARIANTS']: v_label = v_conf['LABEL'] if not v_label: v_label = get_variant_label(v_conf) v_t = adjust_image(t, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=v_label, ext=image_get_format(v_t)) v_full_path = media_path(v_relative_path) save_file(v_t, v_full_path) return img_id def upload_from_fs(fn, profile=None, label=None): """ Saves image from fn with TMP prefix and returns img_id. """ if not os.path.isfile(fn): raise ValueError('File is not exists: {}'.format(fn)) if profile is None: profile = 'default' conf = get_profile_configs(profile) with open(fn, 'rb') as f: if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file "%(name)s" is not allowed. ' 'Allowed formats is: %(formats)s.') % {'name': fn, 'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf) def upload_from_fileobject(f, profile=None, label=None): """ Saves image from f with TMP prefix and returns img_id. """ if profile is None: profile = 'default' conf = get_profile_configs(profile) f.seek(0) if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file is not allowed. ' 'Allowed formats is: %(formats)s.') % {'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf)
liminspace/dju-image
dju_image/tools.py
generate_img_id
python
def generate_img_id(profile, ext=None, label=None, tmp=False): if ext and not ext.startswith('.'): ext = '.' + ext if label: label = re.sub(r'[^a-z0-9_\-]', '', label, flags=re.I) label = re.sub(r'_+', '_', label) label = label[:60] return '{profile}:{tmp}{dtstr}_{rand}{label}{ext}'.format( profile=profile, tmp=(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX if tmp else ''), dtstr=datetime_to_dtstr(), rand=get_random_string(4, 'abcdefghijklmnopqrstuvwxyz0123456789'), label=(('_' + label) if label else ''), ext=(ext or ''), )
Generates img_id.
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/tools.py#L75-L92
null
# coding=utf-8 import glob import os import copy import re import hashlib from django.utils.crypto import get_random_string from django.utils.translation import ugettext_lazy from django.conf import settings from dju_common.file import make_dirs_for_file_path from dju_common.tools import datetime_to_dtstr from dju_image.image import is_image, adjust_image, image_get_format from . import settings as dju_settings ERROR_MESSAGES = { 'unknown_profile': ugettext_lazy('Unknown profile "%(profile)s".'), 'filename_hasnt_tmp_prefix': ugettext_lazy('Filename "%(filename)s" has not temporary prefix.'), } HASH_SIZE = 10 _profile_configs_cache = {} def clear_profile_configs_cache(): _profile_configs_cache.clear() def media_path(path): return os.path.join(settings.MEDIA_ROOT, path).replace('\\', '/') def save_file(f, full_path): """ Saves file f to full_path and set rules. """ make_dirs_for_file_path(full_path, mode=dju_settings.DJU_IMG_CHMOD_DIR) with open(full_path, 'wb') as t: f.seek(0) while True: buf = f.read(dju_settings.DJU_IMG_RW_FILE_BUFFER_SIZE) if not buf: break t.write(buf) os.chmod(full_path, dju_settings.DJU_IMG_CHMOD_FILE) def get_profile_configs(profile=None, use_cache=True): """ Returns upload configs for profile. """ if use_cache and profile in _profile_configs_cache: return _profile_configs_cache[profile] profile_conf = None if profile is not None: try: profile_conf = dju_settings.DJU_IMG_UPLOAD_PROFILES[profile] except KeyError: if profile != 'default': raise ValueError(unicode(ERROR_MESSAGES['unknown_profile']) % {'profile': profile}) conf = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_DEFAULT) if profile_conf: conf.update(copy.deepcopy(profile_conf)) for v_i in xrange(len(conf['VARIANTS'])): v = conf['VARIANTS'][v_i] conf['VARIANTS'][v_i] = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_VARIANT_DEFAULT) conf['VARIANTS'][v_i].update(v) if use_cache: _profile_configs_cache[profile] = conf return conf def get_hash(name, variant_label=None): # name must be without label, for example 'uniqname_rand' h = hashlib.sha1(name + (variant_label or '') + dju_settings.DJU_IMG_UPLOAD_KEY).hexdigest() return h[:HASH_SIZE] def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False): """ Returns path to file relative MEDIA_URL. """ profile, base_name = img_id.split(':', 1) conf = get_profile_configs(profile) if not variant_label: status_suffix = dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX else: status_suffix = dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX name, file_ext = os.path.splitext(base_name) prefix = '' if name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): name = name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] prefix = dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX name_parts = name.split('_', 2) name = '{name}{status_suffix}{hash}'.format( name=name, status_suffix=status_suffix, hash=get_hash('_'.join(name_parts[:2]), variant_label=variant_label) ) if variant_label: name += '_' + variant_label if ext: file_ext = ext elif variant_label: for var_conf in conf['VARIANTS']: var_conf_label = var_conf['LABEL'] or get_variant_label(var_conf) if var_conf_label == variant_label: if var_conf['FORMAT']: file_ext = var_conf['FORMAT'].lower() break if file_ext and not file_ext.startswith('.'): file_ext = '.' + file_ext relative_path = os.path.join( dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH'], name_parts[0][-2:], (prefix + name + file_ext) ).replace('\\', '/') if create_dirs: path = media_path(relative_path) make_dirs_for_file_path(path, mode=dju_settings.DJU_IMG_CHMOD_DIR) return relative_path def is_img_id_exists(img_id): """ Checks if img_id has real file on filesystem. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) return os.path.isfile(main_path) def is_img_id_valid(img_id): """ Checks if img_id is valid. """ t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE) t = re.sub(r'\.+', '.', t) if img_id != t or img_id.count(':') != 1: return False profile, base_name = img_id.split(':', 1) if not profile or not base_name: return False try: get_profile_configs(profile) except ValueError: return False return True def get_variant_label(v_conf): """ Generates name for variant images based settings (by variants sizes). """ if v_conf['MAX_SIZE'][0] is None: return 'h{}'.format(v_conf['MAX_SIZE'][1]) if v_conf['MAX_SIZE'][1] is None: return 'w{}'.format(v_conf['MAX_SIZE'][0]) return '{}x{}'.format(*v_conf['MAX_SIZE']) variant_hash_label_re = re.compile(r'^.+?{suf}([a-z0-9]{{hs}})_(.+?)(?:|\.[A-Za-z]{3,4})$'.replace( '{suf}', dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX ).replace( '{hs}', str(HASH_SIZE) )) def get_files_by_img_id(img_id, check_hash=True): """ Шукає файли для img_id. Повертає: { 'main': 'relative path to main image', 'variants': { 'label': 'relative path to variant image by label', ... } } Якщо check_hash=True, тоді файли з невірним хешем будуть ігноруватись. Якщо файл не існує, тоді поверає None. Пошук варіантів відбуваться в файловій системі не залежно від налаштувань. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) if not os.path.isfile(main_path): return None filename = os.path.basename(main_rel_path) name_left_part = filename.split(dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX, 1)[0] img_name = name_left_part if img_name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): img_name = img_name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] img_name_parts = img_name.split('_', 2) img_name = '_'.join(img_name_parts[:2]) search_pattern = name_left_part + dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX + '*' search_dir = os.path.dirname(main_path) variants = {} for var_path in glob.iglob(os.path.join(search_dir, search_pattern.replace('\\', '/'))): var_filename = os.path.basename(var_path) m = variant_hash_label_re.match(var_filename) if not m: continue var_hash, var_label = m.groups() if check_hash and var_hash != get_hash(img_name, var_label): continue variants[var_label] = os.path.relpath(var_path, settings.MEDIA_ROOT) return { 'main': main_rel_path, 'variants': variants, } def remove_all_files_of_img_id(img_id): """ Removes all img_id's files. """ files = get_files_by_img_id(img_id, check_hash=False) if files: os.remove(media_path(files['main'])) for fn in files['variants'].values(): os.remove(media_path(fn)) def img_id_has_tmp_prefix(img_id): return (':' + dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX) in img_id def remove_tmp_prefix_from_filename(filename): """ Remove tmp prefix from filename. """ if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename}) return filename[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] def remove_tmp_prefix_from_file_path(file_path): """ Remove tmp prefix from file path or url. """ path, filename = os.path.split(file_path) return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\', '/') def make_permalink(img_id): """ Removes tmp prefix from filename and rename main and variant files. Returns img_id without tmp prefix. """ profile, filename = img_id.split(':', 1) new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename) urls = get_files_by_img_id(img_id) if urls is None: return urls move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))} for var_label, var_file_path in urls['variants'].iteritems(): move_list.add((var_file_path, remove_tmp_prefix_from_file_path(var_file_path))) for file_path_from, file_path_to in move_list: os.rename(media_path(file_path_from), media_path(file_path_to)) return new_img_id def _custom_upload(f, profile, label, conf): t = adjust_image(f, max_size=conf['MAX_SIZE'], new_format=conf['FORMAT'], jpeg_quality=conf['JPEG_QUALITY'], fill=conf['FILL'], stretch=conf['STRETCH'], return_new_image=True) img_id = generate_img_id(profile, ext=image_get_format(f), label=label, tmp=True) relative_path = get_relative_path_from_img_id(img_id) full_path = media_path(relative_path) save_file(t, full_path) for v_conf in conf['VARIANTS']: v_label = v_conf['LABEL'] if not v_label: v_label = get_variant_label(v_conf) v_t = adjust_image(t, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=v_label, ext=image_get_format(v_t)) v_full_path = media_path(v_relative_path) save_file(v_t, v_full_path) return img_id def upload_from_fs(fn, profile=None, label=None): """ Saves image from fn with TMP prefix and returns img_id. """ if not os.path.isfile(fn): raise ValueError('File is not exists: {}'.format(fn)) if profile is None: profile = 'default' conf = get_profile_configs(profile) with open(fn, 'rb') as f: if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file "%(name)s" is not allowed. ' 'Allowed formats is: %(formats)s.') % {'name': fn, 'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf) def upload_from_fileobject(f, profile=None, label=None): """ Saves image from f with TMP prefix and returns img_id. """ if profile is None: profile = 'default' conf = get_profile_configs(profile) f.seek(0) if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file is not allowed. ' 'Allowed formats is: %(formats)s.') % {'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf)
liminspace/dju-image
dju_image/tools.py
get_relative_path_from_img_id
python
def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False): profile, base_name = img_id.split(':', 1) conf = get_profile_configs(profile) if not variant_label: status_suffix = dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX else: status_suffix = dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX name, file_ext = os.path.splitext(base_name) prefix = '' if name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): name = name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] prefix = dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX name_parts = name.split('_', 2) name = '{name}{status_suffix}{hash}'.format( name=name, status_suffix=status_suffix, hash=get_hash('_'.join(name_parts[:2]), variant_label=variant_label) ) if variant_label: name += '_' + variant_label if ext: file_ext = ext elif variant_label: for var_conf in conf['VARIANTS']: var_conf_label = var_conf['LABEL'] or get_variant_label(var_conf) if var_conf_label == variant_label: if var_conf['FORMAT']: file_ext = var_conf['FORMAT'].lower() break if file_ext and not file_ext.startswith('.'): file_ext = '.' + file_ext relative_path = os.path.join( dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH'], name_parts[0][-2:], (prefix + name + file_ext) ).replace('\\', '/') if create_dirs: path = media_path(relative_path) make_dirs_for_file_path(path, mode=dju_settings.DJU_IMG_CHMOD_DIR) return relative_path
Returns path to file relative MEDIA_URL.
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/tools.py#L101-L144
[ "def get_profile_configs(profile=None, use_cache=True):\n \"\"\"\n Returns upload configs for profile.\n \"\"\"\n if use_cache and profile in _profile_configs_cache:\n return _profile_configs_cache[profile]\n profile_conf = None\n if profile is not None:\n try:\n profile_c...
# coding=utf-8 import glob import os import copy import re import hashlib from django.utils.crypto import get_random_string from django.utils.translation import ugettext_lazy from django.conf import settings from dju_common.file import make_dirs_for_file_path from dju_common.tools import datetime_to_dtstr from dju_image.image import is_image, adjust_image, image_get_format from . import settings as dju_settings ERROR_MESSAGES = { 'unknown_profile': ugettext_lazy('Unknown profile "%(profile)s".'), 'filename_hasnt_tmp_prefix': ugettext_lazy('Filename "%(filename)s" has not temporary prefix.'), } HASH_SIZE = 10 _profile_configs_cache = {} def clear_profile_configs_cache(): _profile_configs_cache.clear() def media_path(path): return os.path.join(settings.MEDIA_ROOT, path).replace('\\', '/') def save_file(f, full_path): """ Saves file f to full_path and set rules. """ make_dirs_for_file_path(full_path, mode=dju_settings.DJU_IMG_CHMOD_DIR) with open(full_path, 'wb') as t: f.seek(0) while True: buf = f.read(dju_settings.DJU_IMG_RW_FILE_BUFFER_SIZE) if not buf: break t.write(buf) os.chmod(full_path, dju_settings.DJU_IMG_CHMOD_FILE) def get_profile_configs(profile=None, use_cache=True): """ Returns upload configs for profile. """ if use_cache and profile in _profile_configs_cache: return _profile_configs_cache[profile] profile_conf = None if profile is not None: try: profile_conf = dju_settings.DJU_IMG_UPLOAD_PROFILES[profile] except KeyError: if profile != 'default': raise ValueError(unicode(ERROR_MESSAGES['unknown_profile']) % {'profile': profile}) conf = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_DEFAULT) if profile_conf: conf.update(copy.deepcopy(profile_conf)) for v_i in xrange(len(conf['VARIANTS'])): v = conf['VARIANTS'][v_i] conf['VARIANTS'][v_i] = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_VARIANT_DEFAULT) conf['VARIANTS'][v_i].update(v) if use_cache: _profile_configs_cache[profile] = conf return conf def generate_img_id(profile, ext=None, label=None, tmp=False): """ Generates img_id. """ if ext and not ext.startswith('.'): ext = '.' + ext if label: label = re.sub(r'[^a-z0-9_\-]', '', label, flags=re.I) label = re.sub(r'_+', '_', label) label = label[:60] return '{profile}:{tmp}{dtstr}_{rand}{label}{ext}'.format( profile=profile, tmp=(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX if tmp else ''), dtstr=datetime_to_dtstr(), rand=get_random_string(4, 'abcdefghijklmnopqrstuvwxyz0123456789'), label=(('_' + label) if label else ''), ext=(ext or ''), ) def get_hash(name, variant_label=None): # name must be without label, for example 'uniqname_rand' h = hashlib.sha1(name + (variant_label or '') + dju_settings.DJU_IMG_UPLOAD_KEY).hexdigest() return h[:HASH_SIZE] def is_img_id_exists(img_id): """ Checks if img_id has real file on filesystem. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) return os.path.isfile(main_path) def is_img_id_valid(img_id): """ Checks if img_id is valid. """ t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE) t = re.sub(r'\.+', '.', t) if img_id != t or img_id.count(':') != 1: return False profile, base_name = img_id.split(':', 1) if not profile or not base_name: return False try: get_profile_configs(profile) except ValueError: return False return True def get_variant_label(v_conf): """ Generates name for variant images based settings (by variants sizes). """ if v_conf['MAX_SIZE'][0] is None: return 'h{}'.format(v_conf['MAX_SIZE'][1]) if v_conf['MAX_SIZE'][1] is None: return 'w{}'.format(v_conf['MAX_SIZE'][0]) return '{}x{}'.format(*v_conf['MAX_SIZE']) variant_hash_label_re = re.compile(r'^.+?{suf}([a-z0-9]{{hs}})_(.+?)(?:|\.[A-Za-z]{3,4})$'.replace( '{suf}', dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX ).replace( '{hs}', str(HASH_SIZE) )) def get_files_by_img_id(img_id, check_hash=True): """ Шукає файли для img_id. Повертає: { 'main': 'relative path to main image', 'variants': { 'label': 'relative path to variant image by label', ... } } Якщо check_hash=True, тоді файли з невірним хешем будуть ігноруватись. Якщо файл не існує, тоді поверає None. Пошук варіантів відбуваться в файловій системі не залежно від налаштувань. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) if not os.path.isfile(main_path): return None filename = os.path.basename(main_rel_path) name_left_part = filename.split(dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX, 1)[0] img_name = name_left_part if img_name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): img_name = img_name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] img_name_parts = img_name.split('_', 2) img_name = '_'.join(img_name_parts[:2]) search_pattern = name_left_part + dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX + '*' search_dir = os.path.dirname(main_path) variants = {} for var_path in glob.iglob(os.path.join(search_dir, search_pattern.replace('\\', '/'))): var_filename = os.path.basename(var_path) m = variant_hash_label_re.match(var_filename) if not m: continue var_hash, var_label = m.groups() if check_hash and var_hash != get_hash(img_name, var_label): continue variants[var_label] = os.path.relpath(var_path, settings.MEDIA_ROOT) return { 'main': main_rel_path, 'variants': variants, } def remove_all_files_of_img_id(img_id): """ Removes all img_id's files. """ files = get_files_by_img_id(img_id, check_hash=False) if files: os.remove(media_path(files['main'])) for fn in files['variants'].values(): os.remove(media_path(fn)) def img_id_has_tmp_prefix(img_id): return (':' + dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX) in img_id def remove_tmp_prefix_from_filename(filename): """ Remove tmp prefix from filename. """ if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename}) return filename[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] def remove_tmp_prefix_from_file_path(file_path): """ Remove tmp prefix from file path or url. """ path, filename = os.path.split(file_path) return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\', '/') def make_permalink(img_id): """ Removes tmp prefix from filename and rename main and variant files. Returns img_id without tmp prefix. """ profile, filename = img_id.split(':', 1) new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename) urls = get_files_by_img_id(img_id) if urls is None: return urls move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))} for var_label, var_file_path in urls['variants'].iteritems(): move_list.add((var_file_path, remove_tmp_prefix_from_file_path(var_file_path))) for file_path_from, file_path_to in move_list: os.rename(media_path(file_path_from), media_path(file_path_to)) return new_img_id def _custom_upload(f, profile, label, conf): t = adjust_image(f, max_size=conf['MAX_SIZE'], new_format=conf['FORMAT'], jpeg_quality=conf['JPEG_QUALITY'], fill=conf['FILL'], stretch=conf['STRETCH'], return_new_image=True) img_id = generate_img_id(profile, ext=image_get_format(f), label=label, tmp=True) relative_path = get_relative_path_from_img_id(img_id) full_path = media_path(relative_path) save_file(t, full_path) for v_conf in conf['VARIANTS']: v_label = v_conf['LABEL'] if not v_label: v_label = get_variant_label(v_conf) v_t = adjust_image(t, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=v_label, ext=image_get_format(v_t)) v_full_path = media_path(v_relative_path) save_file(v_t, v_full_path) return img_id def upload_from_fs(fn, profile=None, label=None): """ Saves image from fn with TMP prefix and returns img_id. """ if not os.path.isfile(fn): raise ValueError('File is not exists: {}'.format(fn)) if profile is None: profile = 'default' conf = get_profile_configs(profile) with open(fn, 'rb') as f: if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file "%(name)s" is not allowed. ' 'Allowed formats is: %(formats)s.') % {'name': fn, 'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf) def upload_from_fileobject(f, profile=None, label=None): """ Saves image from f with TMP prefix and returns img_id. """ if profile is None: profile = 'default' conf = get_profile_configs(profile) f.seek(0) if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file is not allowed. ' 'Allowed formats is: %(formats)s.') % {'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf)
liminspace/dju-image
dju_image/tools.py
is_img_id_exists
python
def is_img_id_exists(img_id): main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) return os.path.isfile(main_path)
Checks if img_id has real file on filesystem.
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/tools.py#L147-L153
[ "def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False):\n \"\"\"\n Returns path to file relative MEDIA_URL.\n \"\"\"\n profile, base_name = img_id.split(':', 1)\n conf = get_profile_configs(profile)\n if not variant_label:\n status_suffix = dju_settings....
# coding=utf-8 import glob import os import copy import re import hashlib from django.utils.crypto import get_random_string from django.utils.translation import ugettext_lazy from django.conf import settings from dju_common.file import make_dirs_for_file_path from dju_common.tools import datetime_to_dtstr from dju_image.image import is_image, adjust_image, image_get_format from . import settings as dju_settings ERROR_MESSAGES = { 'unknown_profile': ugettext_lazy('Unknown profile "%(profile)s".'), 'filename_hasnt_tmp_prefix': ugettext_lazy('Filename "%(filename)s" has not temporary prefix.'), } HASH_SIZE = 10 _profile_configs_cache = {} def clear_profile_configs_cache(): _profile_configs_cache.clear() def media_path(path): return os.path.join(settings.MEDIA_ROOT, path).replace('\\', '/') def save_file(f, full_path): """ Saves file f to full_path and set rules. """ make_dirs_for_file_path(full_path, mode=dju_settings.DJU_IMG_CHMOD_DIR) with open(full_path, 'wb') as t: f.seek(0) while True: buf = f.read(dju_settings.DJU_IMG_RW_FILE_BUFFER_SIZE) if not buf: break t.write(buf) os.chmod(full_path, dju_settings.DJU_IMG_CHMOD_FILE) def get_profile_configs(profile=None, use_cache=True): """ Returns upload configs for profile. """ if use_cache and profile in _profile_configs_cache: return _profile_configs_cache[profile] profile_conf = None if profile is not None: try: profile_conf = dju_settings.DJU_IMG_UPLOAD_PROFILES[profile] except KeyError: if profile != 'default': raise ValueError(unicode(ERROR_MESSAGES['unknown_profile']) % {'profile': profile}) conf = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_DEFAULT) if profile_conf: conf.update(copy.deepcopy(profile_conf)) for v_i in xrange(len(conf['VARIANTS'])): v = conf['VARIANTS'][v_i] conf['VARIANTS'][v_i] = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_VARIANT_DEFAULT) conf['VARIANTS'][v_i].update(v) if use_cache: _profile_configs_cache[profile] = conf return conf def generate_img_id(profile, ext=None, label=None, tmp=False): """ Generates img_id. """ if ext and not ext.startswith('.'): ext = '.' + ext if label: label = re.sub(r'[^a-z0-9_\-]', '', label, flags=re.I) label = re.sub(r'_+', '_', label) label = label[:60] return '{profile}:{tmp}{dtstr}_{rand}{label}{ext}'.format( profile=profile, tmp=(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX if tmp else ''), dtstr=datetime_to_dtstr(), rand=get_random_string(4, 'abcdefghijklmnopqrstuvwxyz0123456789'), label=(('_' + label) if label else ''), ext=(ext or ''), ) def get_hash(name, variant_label=None): # name must be without label, for example 'uniqname_rand' h = hashlib.sha1(name + (variant_label or '') + dju_settings.DJU_IMG_UPLOAD_KEY).hexdigest() return h[:HASH_SIZE] def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False): """ Returns path to file relative MEDIA_URL. """ profile, base_name = img_id.split(':', 1) conf = get_profile_configs(profile) if not variant_label: status_suffix = dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX else: status_suffix = dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX name, file_ext = os.path.splitext(base_name) prefix = '' if name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): name = name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] prefix = dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX name_parts = name.split('_', 2) name = '{name}{status_suffix}{hash}'.format( name=name, status_suffix=status_suffix, hash=get_hash('_'.join(name_parts[:2]), variant_label=variant_label) ) if variant_label: name += '_' + variant_label if ext: file_ext = ext elif variant_label: for var_conf in conf['VARIANTS']: var_conf_label = var_conf['LABEL'] or get_variant_label(var_conf) if var_conf_label == variant_label: if var_conf['FORMAT']: file_ext = var_conf['FORMAT'].lower() break if file_ext and not file_ext.startswith('.'): file_ext = '.' + file_ext relative_path = os.path.join( dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH'], name_parts[0][-2:], (prefix + name + file_ext) ).replace('\\', '/') if create_dirs: path = media_path(relative_path) make_dirs_for_file_path(path, mode=dju_settings.DJU_IMG_CHMOD_DIR) return relative_path def is_img_id_valid(img_id): """ Checks if img_id is valid. """ t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE) t = re.sub(r'\.+', '.', t) if img_id != t or img_id.count(':') != 1: return False profile, base_name = img_id.split(':', 1) if not profile or not base_name: return False try: get_profile_configs(profile) except ValueError: return False return True def get_variant_label(v_conf): """ Generates name for variant images based settings (by variants sizes). """ if v_conf['MAX_SIZE'][0] is None: return 'h{}'.format(v_conf['MAX_SIZE'][1]) if v_conf['MAX_SIZE'][1] is None: return 'w{}'.format(v_conf['MAX_SIZE'][0]) return '{}x{}'.format(*v_conf['MAX_SIZE']) variant_hash_label_re = re.compile(r'^.+?{suf}([a-z0-9]{{hs}})_(.+?)(?:|\.[A-Za-z]{3,4})$'.replace( '{suf}', dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX ).replace( '{hs}', str(HASH_SIZE) )) def get_files_by_img_id(img_id, check_hash=True): """ Шукає файли для img_id. Повертає: { 'main': 'relative path to main image', 'variants': { 'label': 'relative path to variant image by label', ... } } Якщо check_hash=True, тоді файли з невірним хешем будуть ігноруватись. Якщо файл не існує, тоді поверає None. Пошук варіантів відбуваться в файловій системі не залежно від налаштувань. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) if not os.path.isfile(main_path): return None filename = os.path.basename(main_rel_path) name_left_part = filename.split(dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX, 1)[0] img_name = name_left_part if img_name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): img_name = img_name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] img_name_parts = img_name.split('_', 2) img_name = '_'.join(img_name_parts[:2]) search_pattern = name_left_part + dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX + '*' search_dir = os.path.dirname(main_path) variants = {} for var_path in glob.iglob(os.path.join(search_dir, search_pattern.replace('\\', '/'))): var_filename = os.path.basename(var_path) m = variant_hash_label_re.match(var_filename) if not m: continue var_hash, var_label = m.groups() if check_hash and var_hash != get_hash(img_name, var_label): continue variants[var_label] = os.path.relpath(var_path, settings.MEDIA_ROOT) return { 'main': main_rel_path, 'variants': variants, } def remove_all_files_of_img_id(img_id): """ Removes all img_id's files. """ files = get_files_by_img_id(img_id, check_hash=False) if files: os.remove(media_path(files['main'])) for fn in files['variants'].values(): os.remove(media_path(fn)) def img_id_has_tmp_prefix(img_id): return (':' + dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX) in img_id def remove_tmp_prefix_from_filename(filename): """ Remove tmp prefix from filename. """ if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename}) return filename[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] def remove_tmp_prefix_from_file_path(file_path): """ Remove tmp prefix from file path or url. """ path, filename = os.path.split(file_path) return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\', '/') def make_permalink(img_id): """ Removes tmp prefix from filename and rename main and variant files. Returns img_id without tmp prefix. """ profile, filename = img_id.split(':', 1) new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename) urls = get_files_by_img_id(img_id) if urls is None: return urls move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))} for var_label, var_file_path in urls['variants'].iteritems(): move_list.add((var_file_path, remove_tmp_prefix_from_file_path(var_file_path))) for file_path_from, file_path_to in move_list: os.rename(media_path(file_path_from), media_path(file_path_to)) return new_img_id def _custom_upload(f, profile, label, conf): t = adjust_image(f, max_size=conf['MAX_SIZE'], new_format=conf['FORMAT'], jpeg_quality=conf['JPEG_QUALITY'], fill=conf['FILL'], stretch=conf['STRETCH'], return_new_image=True) img_id = generate_img_id(profile, ext=image_get_format(f), label=label, tmp=True) relative_path = get_relative_path_from_img_id(img_id) full_path = media_path(relative_path) save_file(t, full_path) for v_conf in conf['VARIANTS']: v_label = v_conf['LABEL'] if not v_label: v_label = get_variant_label(v_conf) v_t = adjust_image(t, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=v_label, ext=image_get_format(v_t)) v_full_path = media_path(v_relative_path) save_file(v_t, v_full_path) return img_id def upload_from_fs(fn, profile=None, label=None): """ Saves image from fn with TMP prefix and returns img_id. """ if not os.path.isfile(fn): raise ValueError('File is not exists: {}'.format(fn)) if profile is None: profile = 'default' conf = get_profile_configs(profile) with open(fn, 'rb') as f: if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file "%(name)s" is not allowed. ' 'Allowed formats is: %(formats)s.') % {'name': fn, 'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf) def upload_from_fileobject(f, profile=None, label=None): """ Saves image from f with TMP prefix and returns img_id. """ if profile is None: profile = 'default' conf = get_profile_configs(profile) f.seek(0) if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file is not allowed. ' 'Allowed formats is: %(formats)s.') % {'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf)
liminspace/dju-image
dju_image/tools.py
is_img_id_valid
python
def is_img_id_valid(img_id): t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE) t = re.sub(r'\.+', '.', t) if img_id != t or img_id.count(':') != 1: return False profile, base_name = img_id.split(':', 1) if not profile or not base_name: return False try: get_profile_configs(profile) except ValueError: return False return True
Checks if img_id is valid.
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/tools.py#L156-L171
null
# coding=utf-8 import glob import os import copy import re import hashlib from django.utils.crypto import get_random_string from django.utils.translation import ugettext_lazy from django.conf import settings from dju_common.file import make_dirs_for_file_path from dju_common.tools import datetime_to_dtstr from dju_image.image import is_image, adjust_image, image_get_format from . import settings as dju_settings ERROR_MESSAGES = { 'unknown_profile': ugettext_lazy('Unknown profile "%(profile)s".'), 'filename_hasnt_tmp_prefix': ugettext_lazy('Filename "%(filename)s" has not temporary prefix.'), } HASH_SIZE = 10 _profile_configs_cache = {} def clear_profile_configs_cache(): _profile_configs_cache.clear() def media_path(path): return os.path.join(settings.MEDIA_ROOT, path).replace('\\', '/') def save_file(f, full_path): """ Saves file f to full_path and set rules. """ make_dirs_for_file_path(full_path, mode=dju_settings.DJU_IMG_CHMOD_DIR) with open(full_path, 'wb') as t: f.seek(0) while True: buf = f.read(dju_settings.DJU_IMG_RW_FILE_BUFFER_SIZE) if not buf: break t.write(buf) os.chmod(full_path, dju_settings.DJU_IMG_CHMOD_FILE) def get_profile_configs(profile=None, use_cache=True): """ Returns upload configs for profile. """ if use_cache and profile in _profile_configs_cache: return _profile_configs_cache[profile] profile_conf = None if profile is not None: try: profile_conf = dju_settings.DJU_IMG_UPLOAD_PROFILES[profile] except KeyError: if profile != 'default': raise ValueError(unicode(ERROR_MESSAGES['unknown_profile']) % {'profile': profile}) conf = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_DEFAULT) if profile_conf: conf.update(copy.deepcopy(profile_conf)) for v_i in xrange(len(conf['VARIANTS'])): v = conf['VARIANTS'][v_i] conf['VARIANTS'][v_i] = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_VARIANT_DEFAULT) conf['VARIANTS'][v_i].update(v) if use_cache: _profile_configs_cache[profile] = conf return conf def generate_img_id(profile, ext=None, label=None, tmp=False): """ Generates img_id. """ if ext and not ext.startswith('.'): ext = '.' + ext if label: label = re.sub(r'[^a-z0-9_\-]', '', label, flags=re.I) label = re.sub(r'_+', '_', label) label = label[:60] return '{profile}:{tmp}{dtstr}_{rand}{label}{ext}'.format( profile=profile, tmp=(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX if tmp else ''), dtstr=datetime_to_dtstr(), rand=get_random_string(4, 'abcdefghijklmnopqrstuvwxyz0123456789'), label=(('_' + label) if label else ''), ext=(ext or ''), ) def get_hash(name, variant_label=None): # name must be without label, for example 'uniqname_rand' h = hashlib.sha1(name + (variant_label or '') + dju_settings.DJU_IMG_UPLOAD_KEY).hexdigest() return h[:HASH_SIZE] def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False): """ Returns path to file relative MEDIA_URL. """ profile, base_name = img_id.split(':', 1) conf = get_profile_configs(profile) if not variant_label: status_suffix = dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX else: status_suffix = dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX name, file_ext = os.path.splitext(base_name) prefix = '' if name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): name = name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] prefix = dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX name_parts = name.split('_', 2) name = '{name}{status_suffix}{hash}'.format( name=name, status_suffix=status_suffix, hash=get_hash('_'.join(name_parts[:2]), variant_label=variant_label) ) if variant_label: name += '_' + variant_label if ext: file_ext = ext elif variant_label: for var_conf in conf['VARIANTS']: var_conf_label = var_conf['LABEL'] or get_variant_label(var_conf) if var_conf_label == variant_label: if var_conf['FORMAT']: file_ext = var_conf['FORMAT'].lower() break if file_ext and not file_ext.startswith('.'): file_ext = '.' + file_ext relative_path = os.path.join( dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH'], name_parts[0][-2:], (prefix + name + file_ext) ).replace('\\', '/') if create_dirs: path = media_path(relative_path) make_dirs_for_file_path(path, mode=dju_settings.DJU_IMG_CHMOD_DIR) return relative_path def is_img_id_exists(img_id): """ Checks if img_id has real file on filesystem. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) return os.path.isfile(main_path) def get_variant_label(v_conf): """ Generates name for variant images based settings (by variants sizes). """ if v_conf['MAX_SIZE'][0] is None: return 'h{}'.format(v_conf['MAX_SIZE'][1]) if v_conf['MAX_SIZE'][1] is None: return 'w{}'.format(v_conf['MAX_SIZE'][0]) return '{}x{}'.format(*v_conf['MAX_SIZE']) variant_hash_label_re = re.compile(r'^.+?{suf}([a-z0-9]{{hs}})_(.+?)(?:|\.[A-Za-z]{3,4})$'.replace( '{suf}', dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX ).replace( '{hs}', str(HASH_SIZE) )) def get_files_by_img_id(img_id, check_hash=True): """ Шукає файли для img_id. Повертає: { 'main': 'relative path to main image', 'variants': { 'label': 'relative path to variant image by label', ... } } Якщо check_hash=True, тоді файли з невірним хешем будуть ігноруватись. Якщо файл не існує, тоді поверає None. Пошук варіантів відбуваться в файловій системі не залежно від налаштувань. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) if not os.path.isfile(main_path): return None filename = os.path.basename(main_rel_path) name_left_part = filename.split(dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX, 1)[0] img_name = name_left_part if img_name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): img_name = img_name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] img_name_parts = img_name.split('_', 2) img_name = '_'.join(img_name_parts[:2]) search_pattern = name_left_part + dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX + '*' search_dir = os.path.dirname(main_path) variants = {} for var_path in glob.iglob(os.path.join(search_dir, search_pattern.replace('\\', '/'))): var_filename = os.path.basename(var_path) m = variant_hash_label_re.match(var_filename) if not m: continue var_hash, var_label = m.groups() if check_hash and var_hash != get_hash(img_name, var_label): continue variants[var_label] = os.path.relpath(var_path, settings.MEDIA_ROOT) return { 'main': main_rel_path, 'variants': variants, } def remove_all_files_of_img_id(img_id): """ Removes all img_id's files. """ files = get_files_by_img_id(img_id, check_hash=False) if files: os.remove(media_path(files['main'])) for fn in files['variants'].values(): os.remove(media_path(fn)) def img_id_has_tmp_prefix(img_id): return (':' + dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX) in img_id def remove_tmp_prefix_from_filename(filename): """ Remove tmp prefix from filename. """ if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename}) return filename[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] def remove_tmp_prefix_from_file_path(file_path): """ Remove tmp prefix from file path or url. """ path, filename = os.path.split(file_path) return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\', '/') def make_permalink(img_id): """ Removes tmp prefix from filename and rename main and variant files. Returns img_id without tmp prefix. """ profile, filename = img_id.split(':', 1) new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename) urls = get_files_by_img_id(img_id) if urls is None: return urls move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))} for var_label, var_file_path in urls['variants'].iteritems(): move_list.add((var_file_path, remove_tmp_prefix_from_file_path(var_file_path))) for file_path_from, file_path_to in move_list: os.rename(media_path(file_path_from), media_path(file_path_to)) return new_img_id def _custom_upload(f, profile, label, conf): t = adjust_image(f, max_size=conf['MAX_SIZE'], new_format=conf['FORMAT'], jpeg_quality=conf['JPEG_QUALITY'], fill=conf['FILL'], stretch=conf['STRETCH'], return_new_image=True) img_id = generate_img_id(profile, ext=image_get_format(f), label=label, tmp=True) relative_path = get_relative_path_from_img_id(img_id) full_path = media_path(relative_path) save_file(t, full_path) for v_conf in conf['VARIANTS']: v_label = v_conf['LABEL'] if not v_label: v_label = get_variant_label(v_conf) v_t = adjust_image(t, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=v_label, ext=image_get_format(v_t)) v_full_path = media_path(v_relative_path) save_file(v_t, v_full_path) return img_id def upload_from_fs(fn, profile=None, label=None): """ Saves image from fn with TMP prefix and returns img_id. """ if not os.path.isfile(fn): raise ValueError('File is not exists: {}'.format(fn)) if profile is None: profile = 'default' conf = get_profile_configs(profile) with open(fn, 'rb') as f: if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file "%(name)s" is not allowed. ' 'Allowed formats is: %(formats)s.') % {'name': fn, 'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf) def upload_from_fileobject(f, profile=None, label=None): """ Saves image from f with TMP prefix and returns img_id. """ if profile is None: profile = 'default' conf = get_profile_configs(profile) f.seek(0) if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file is not allowed. ' 'Allowed formats is: %(formats)s.') % {'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf)
liminspace/dju-image
dju_image/tools.py
get_variant_label
python
def get_variant_label(v_conf): if v_conf['MAX_SIZE'][0] is None: return 'h{}'.format(v_conf['MAX_SIZE'][1]) if v_conf['MAX_SIZE'][1] is None: return 'w{}'.format(v_conf['MAX_SIZE'][0]) return '{}x{}'.format(*v_conf['MAX_SIZE'])
Generates name for variant images based settings (by variants sizes).
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/tools.py#L174-L182
null
# coding=utf-8 import glob import os import copy import re import hashlib from django.utils.crypto import get_random_string from django.utils.translation import ugettext_lazy from django.conf import settings from dju_common.file import make_dirs_for_file_path from dju_common.tools import datetime_to_dtstr from dju_image.image import is_image, adjust_image, image_get_format from . import settings as dju_settings ERROR_MESSAGES = { 'unknown_profile': ugettext_lazy('Unknown profile "%(profile)s".'), 'filename_hasnt_tmp_prefix': ugettext_lazy('Filename "%(filename)s" has not temporary prefix.'), } HASH_SIZE = 10 _profile_configs_cache = {} def clear_profile_configs_cache(): _profile_configs_cache.clear() def media_path(path): return os.path.join(settings.MEDIA_ROOT, path).replace('\\', '/') def save_file(f, full_path): """ Saves file f to full_path and set rules. """ make_dirs_for_file_path(full_path, mode=dju_settings.DJU_IMG_CHMOD_DIR) with open(full_path, 'wb') as t: f.seek(0) while True: buf = f.read(dju_settings.DJU_IMG_RW_FILE_BUFFER_SIZE) if not buf: break t.write(buf) os.chmod(full_path, dju_settings.DJU_IMG_CHMOD_FILE) def get_profile_configs(profile=None, use_cache=True): """ Returns upload configs for profile. """ if use_cache and profile in _profile_configs_cache: return _profile_configs_cache[profile] profile_conf = None if profile is not None: try: profile_conf = dju_settings.DJU_IMG_UPLOAD_PROFILES[profile] except KeyError: if profile != 'default': raise ValueError(unicode(ERROR_MESSAGES['unknown_profile']) % {'profile': profile}) conf = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_DEFAULT) if profile_conf: conf.update(copy.deepcopy(profile_conf)) for v_i in xrange(len(conf['VARIANTS'])): v = conf['VARIANTS'][v_i] conf['VARIANTS'][v_i] = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_VARIANT_DEFAULT) conf['VARIANTS'][v_i].update(v) if use_cache: _profile_configs_cache[profile] = conf return conf def generate_img_id(profile, ext=None, label=None, tmp=False): """ Generates img_id. """ if ext and not ext.startswith('.'): ext = '.' + ext if label: label = re.sub(r'[^a-z0-9_\-]', '', label, flags=re.I) label = re.sub(r'_+', '_', label) label = label[:60] return '{profile}:{tmp}{dtstr}_{rand}{label}{ext}'.format( profile=profile, tmp=(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX if tmp else ''), dtstr=datetime_to_dtstr(), rand=get_random_string(4, 'abcdefghijklmnopqrstuvwxyz0123456789'), label=(('_' + label) if label else ''), ext=(ext or ''), ) def get_hash(name, variant_label=None): # name must be without label, for example 'uniqname_rand' h = hashlib.sha1(name + (variant_label or '') + dju_settings.DJU_IMG_UPLOAD_KEY).hexdigest() return h[:HASH_SIZE] def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False): """ Returns path to file relative MEDIA_URL. """ profile, base_name = img_id.split(':', 1) conf = get_profile_configs(profile) if not variant_label: status_suffix = dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX else: status_suffix = dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX name, file_ext = os.path.splitext(base_name) prefix = '' if name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): name = name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] prefix = dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX name_parts = name.split('_', 2) name = '{name}{status_suffix}{hash}'.format( name=name, status_suffix=status_suffix, hash=get_hash('_'.join(name_parts[:2]), variant_label=variant_label) ) if variant_label: name += '_' + variant_label if ext: file_ext = ext elif variant_label: for var_conf in conf['VARIANTS']: var_conf_label = var_conf['LABEL'] or get_variant_label(var_conf) if var_conf_label == variant_label: if var_conf['FORMAT']: file_ext = var_conf['FORMAT'].lower() break if file_ext and not file_ext.startswith('.'): file_ext = '.' + file_ext relative_path = os.path.join( dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH'], name_parts[0][-2:], (prefix + name + file_ext) ).replace('\\', '/') if create_dirs: path = media_path(relative_path) make_dirs_for_file_path(path, mode=dju_settings.DJU_IMG_CHMOD_DIR) return relative_path def is_img_id_exists(img_id): """ Checks if img_id has real file on filesystem. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) return os.path.isfile(main_path) def is_img_id_valid(img_id): """ Checks if img_id is valid. """ t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE) t = re.sub(r'\.+', '.', t) if img_id != t or img_id.count(':') != 1: return False profile, base_name = img_id.split(':', 1) if not profile or not base_name: return False try: get_profile_configs(profile) except ValueError: return False return True variant_hash_label_re = re.compile(r'^.+?{suf}([a-z0-9]{{hs}})_(.+?)(?:|\.[A-Za-z]{3,4})$'.replace( '{suf}', dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX ).replace( '{hs}', str(HASH_SIZE) )) def get_files_by_img_id(img_id, check_hash=True): """ Шукає файли для img_id. Повертає: { 'main': 'relative path to main image', 'variants': { 'label': 'relative path to variant image by label', ... } } Якщо check_hash=True, тоді файли з невірним хешем будуть ігноруватись. Якщо файл не існує, тоді поверає None. Пошук варіантів відбуваться в файловій системі не залежно від налаштувань. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) if not os.path.isfile(main_path): return None filename = os.path.basename(main_rel_path) name_left_part = filename.split(dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX, 1)[0] img_name = name_left_part if img_name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): img_name = img_name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] img_name_parts = img_name.split('_', 2) img_name = '_'.join(img_name_parts[:2]) search_pattern = name_left_part + dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX + '*' search_dir = os.path.dirname(main_path) variants = {} for var_path in glob.iglob(os.path.join(search_dir, search_pattern.replace('\\', '/'))): var_filename = os.path.basename(var_path) m = variant_hash_label_re.match(var_filename) if not m: continue var_hash, var_label = m.groups() if check_hash and var_hash != get_hash(img_name, var_label): continue variants[var_label] = os.path.relpath(var_path, settings.MEDIA_ROOT) return { 'main': main_rel_path, 'variants': variants, } def remove_all_files_of_img_id(img_id): """ Removes all img_id's files. """ files = get_files_by_img_id(img_id, check_hash=False) if files: os.remove(media_path(files['main'])) for fn in files['variants'].values(): os.remove(media_path(fn)) def img_id_has_tmp_prefix(img_id): return (':' + dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX) in img_id def remove_tmp_prefix_from_filename(filename): """ Remove tmp prefix from filename. """ if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename}) return filename[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] def remove_tmp_prefix_from_file_path(file_path): """ Remove tmp prefix from file path or url. """ path, filename = os.path.split(file_path) return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\', '/') def make_permalink(img_id): """ Removes tmp prefix from filename and rename main and variant files. Returns img_id without tmp prefix. """ profile, filename = img_id.split(':', 1) new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename) urls = get_files_by_img_id(img_id) if urls is None: return urls move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))} for var_label, var_file_path in urls['variants'].iteritems(): move_list.add((var_file_path, remove_tmp_prefix_from_file_path(var_file_path))) for file_path_from, file_path_to in move_list: os.rename(media_path(file_path_from), media_path(file_path_to)) return new_img_id def _custom_upload(f, profile, label, conf): t = adjust_image(f, max_size=conf['MAX_SIZE'], new_format=conf['FORMAT'], jpeg_quality=conf['JPEG_QUALITY'], fill=conf['FILL'], stretch=conf['STRETCH'], return_new_image=True) img_id = generate_img_id(profile, ext=image_get_format(f), label=label, tmp=True) relative_path = get_relative_path_from_img_id(img_id) full_path = media_path(relative_path) save_file(t, full_path) for v_conf in conf['VARIANTS']: v_label = v_conf['LABEL'] if not v_label: v_label = get_variant_label(v_conf) v_t = adjust_image(t, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=v_label, ext=image_get_format(v_t)) v_full_path = media_path(v_relative_path) save_file(v_t, v_full_path) return img_id def upload_from_fs(fn, profile=None, label=None): """ Saves image from fn with TMP prefix and returns img_id. """ if not os.path.isfile(fn): raise ValueError('File is not exists: {}'.format(fn)) if profile is None: profile = 'default' conf = get_profile_configs(profile) with open(fn, 'rb') as f: if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file "%(name)s" is not allowed. ' 'Allowed formats is: %(formats)s.') % {'name': fn, 'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf) def upload_from_fileobject(f, profile=None, label=None): """ Saves image from f with TMP prefix and returns img_id. """ if profile is None: profile = 'default' conf = get_profile_configs(profile) f.seek(0) if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file is not allowed. ' 'Allowed formats is: %(formats)s.') % {'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf)
liminspace/dju-image
dju_image/tools.py
get_files_by_img_id
python
def get_files_by_img_id(img_id, check_hash=True): main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) if not os.path.isfile(main_path): return None filename = os.path.basename(main_rel_path) name_left_part = filename.split(dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX, 1)[0] img_name = name_left_part if img_name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): img_name = img_name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] img_name_parts = img_name.split('_', 2) img_name = '_'.join(img_name_parts[:2]) search_pattern = name_left_part + dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX + '*' search_dir = os.path.dirname(main_path) variants = {} for var_path in glob.iglob(os.path.join(search_dir, search_pattern.replace('\\', '/'))): var_filename = os.path.basename(var_path) m = variant_hash_label_re.match(var_filename) if not m: continue var_hash, var_label = m.groups() if check_hash and var_hash != get_hash(img_name, var_label): continue variants[var_label] = os.path.relpath(var_path, settings.MEDIA_ROOT) return { 'main': main_rel_path, 'variants': variants, }
Шукає файли для img_id. Повертає: { 'main': 'relative path to main image', 'variants': { 'label': 'relative path to variant image by label', ... } } Якщо check_hash=True, тоді файли з невірним хешем будуть ігноруватись. Якщо файл не існує, тоді поверає None. Пошук варіантів відбуваться в файловій системі не залежно від налаштувань.
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/tools.py#L192-L233
[ "def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False):\n \"\"\"\n Returns path to file relative MEDIA_URL.\n \"\"\"\n profile, base_name = img_id.split(':', 1)\n conf = get_profile_configs(profile)\n if not variant_label:\n status_suffix = dju_settings....
# coding=utf-8 import glob import os import copy import re import hashlib from django.utils.crypto import get_random_string from django.utils.translation import ugettext_lazy from django.conf import settings from dju_common.file import make_dirs_for_file_path from dju_common.tools import datetime_to_dtstr from dju_image.image import is_image, adjust_image, image_get_format from . import settings as dju_settings ERROR_MESSAGES = { 'unknown_profile': ugettext_lazy('Unknown profile "%(profile)s".'), 'filename_hasnt_tmp_prefix': ugettext_lazy('Filename "%(filename)s" has not temporary prefix.'), } HASH_SIZE = 10 _profile_configs_cache = {} def clear_profile_configs_cache(): _profile_configs_cache.clear() def media_path(path): return os.path.join(settings.MEDIA_ROOT, path).replace('\\', '/') def save_file(f, full_path): """ Saves file f to full_path and set rules. """ make_dirs_for_file_path(full_path, mode=dju_settings.DJU_IMG_CHMOD_DIR) with open(full_path, 'wb') as t: f.seek(0) while True: buf = f.read(dju_settings.DJU_IMG_RW_FILE_BUFFER_SIZE) if not buf: break t.write(buf) os.chmod(full_path, dju_settings.DJU_IMG_CHMOD_FILE) def get_profile_configs(profile=None, use_cache=True): """ Returns upload configs for profile. """ if use_cache and profile in _profile_configs_cache: return _profile_configs_cache[profile] profile_conf = None if profile is not None: try: profile_conf = dju_settings.DJU_IMG_UPLOAD_PROFILES[profile] except KeyError: if profile != 'default': raise ValueError(unicode(ERROR_MESSAGES['unknown_profile']) % {'profile': profile}) conf = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_DEFAULT) if profile_conf: conf.update(copy.deepcopy(profile_conf)) for v_i in xrange(len(conf['VARIANTS'])): v = conf['VARIANTS'][v_i] conf['VARIANTS'][v_i] = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_VARIANT_DEFAULT) conf['VARIANTS'][v_i].update(v) if use_cache: _profile_configs_cache[profile] = conf return conf def generate_img_id(profile, ext=None, label=None, tmp=False): """ Generates img_id. """ if ext and not ext.startswith('.'): ext = '.' + ext if label: label = re.sub(r'[^a-z0-9_\-]', '', label, flags=re.I) label = re.sub(r'_+', '_', label) label = label[:60] return '{profile}:{tmp}{dtstr}_{rand}{label}{ext}'.format( profile=profile, tmp=(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX if tmp else ''), dtstr=datetime_to_dtstr(), rand=get_random_string(4, 'abcdefghijklmnopqrstuvwxyz0123456789'), label=(('_' + label) if label else ''), ext=(ext or ''), ) def get_hash(name, variant_label=None): # name must be without label, for example 'uniqname_rand' h = hashlib.sha1(name + (variant_label or '') + dju_settings.DJU_IMG_UPLOAD_KEY).hexdigest() return h[:HASH_SIZE] def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False): """ Returns path to file relative MEDIA_URL. """ profile, base_name = img_id.split(':', 1) conf = get_profile_configs(profile) if not variant_label: status_suffix = dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX else: status_suffix = dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX name, file_ext = os.path.splitext(base_name) prefix = '' if name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): name = name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] prefix = dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX name_parts = name.split('_', 2) name = '{name}{status_suffix}{hash}'.format( name=name, status_suffix=status_suffix, hash=get_hash('_'.join(name_parts[:2]), variant_label=variant_label) ) if variant_label: name += '_' + variant_label if ext: file_ext = ext elif variant_label: for var_conf in conf['VARIANTS']: var_conf_label = var_conf['LABEL'] or get_variant_label(var_conf) if var_conf_label == variant_label: if var_conf['FORMAT']: file_ext = var_conf['FORMAT'].lower() break if file_ext and not file_ext.startswith('.'): file_ext = '.' + file_ext relative_path = os.path.join( dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH'], name_parts[0][-2:], (prefix + name + file_ext) ).replace('\\', '/') if create_dirs: path = media_path(relative_path) make_dirs_for_file_path(path, mode=dju_settings.DJU_IMG_CHMOD_DIR) return relative_path def is_img_id_exists(img_id): """ Checks if img_id has real file on filesystem. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) return os.path.isfile(main_path) def is_img_id_valid(img_id): """ Checks if img_id is valid. """ t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE) t = re.sub(r'\.+', '.', t) if img_id != t or img_id.count(':') != 1: return False profile, base_name = img_id.split(':', 1) if not profile or not base_name: return False try: get_profile_configs(profile) except ValueError: return False return True def get_variant_label(v_conf): """ Generates name for variant images based settings (by variants sizes). """ if v_conf['MAX_SIZE'][0] is None: return 'h{}'.format(v_conf['MAX_SIZE'][1]) if v_conf['MAX_SIZE'][1] is None: return 'w{}'.format(v_conf['MAX_SIZE'][0]) return '{}x{}'.format(*v_conf['MAX_SIZE']) variant_hash_label_re = re.compile(r'^.+?{suf}([a-z0-9]{{hs}})_(.+?)(?:|\.[A-Za-z]{3,4})$'.replace( '{suf}', dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX ).replace( '{hs}', str(HASH_SIZE) )) def remove_all_files_of_img_id(img_id): """ Removes all img_id's files. """ files = get_files_by_img_id(img_id, check_hash=False) if files: os.remove(media_path(files['main'])) for fn in files['variants'].values(): os.remove(media_path(fn)) def img_id_has_tmp_prefix(img_id): return (':' + dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX) in img_id def remove_tmp_prefix_from_filename(filename): """ Remove tmp prefix from filename. """ if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename}) return filename[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] def remove_tmp_prefix_from_file_path(file_path): """ Remove tmp prefix from file path or url. """ path, filename = os.path.split(file_path) return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\', '/') def make_permalink(img_id): """ Removes tmp prefix from filename and rename main and variant files. Returns img_id without tmp prefix. """ profile, filename = img_id.split(':', 1) new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename) urls = get_files_by_img_id(img_id) if urls is None: return urls move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))} for var_label, var_file_path in urls['variants'].iteritems(): move_list.add((var_file_path, remove_tmp_prefix_from_file_path(var_file_path))) for file_path_from, file_path_to in move_list: os.rename(media_path(file_path_from), media_path(file_path_to)) return new_img_id def _custom_upload(f, profile, label, conf): t = adjust_image(f, max_size=conf['MAX_SIZE'], new_format=conf['FORMAT'], jpeg_quality=conf['JPEG_QUALITY'], fill=conf['FILL'], stretch=conf['STRETCH'], return_new_image=True) img_id = generate_img_id(profile, ext=image_get_format(f), label=label, tmp=True) relative_path = get_relative_path_from_img_id(img_id) full_path = media_path(relative_path) save_file(t, full_path) for v_conf in conf['VARIANTS']: v_label = v_conf['LABEL'] if not v_label: v_label = get_variant_label(v_conf) v_t = adjust_image(t, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=v_label, ext=image_get_format(v_t)) v_full_path = media_path(v_relative_path) save_file(v_t, v_full_path) return img_id def upload_from_fs(fn, profile=None, label=None): """ Saves image from fn with TMP prefix and returns img_id. """ if not os.path.isfile(fn): raise ValueError('File is not exists: {}'.format(fn)) if profile is None: profile = 'default' conf = get_profile_configs(profile) with open(fn, 'rb') as f: if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file "%(name)s" is not allowed. ' 'Allowed formats is: %(formats)s.') % {'name': fn, 'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf) def upload_from_fileobject(f, profile=None, label=None): """ Saves image from f with TMP prefix and returns img_id. """ if profile is None: profile = 'default' conf = get_profile_configs(profile) f.seek(0) if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file is not allowed. ' 'Allowed formats is: %(formats)s.') % {'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf)
liminspace/dju-image
dju_image/tools.py
remove_all_files_of_img_id
python
def remove_all_files_of_img_id(img_id): files = get_files_by_img_id(img_id, check_hash=False) if files: os.remove(media_path(files['main'])) for fn in files['variants'].values(): os.remove(media_path(fn))
Removes all img_id's files.
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/tools.py#L236-L244
[ "def media_path(path):\n return os.path.join(settings.MEDIA_ROOT, path).replace('\\\\', '/')\n", "def get_files_by_img_id(img_id, check_hash=True):\n \"\"\"\n Шукає файли для img_id.\n Повертає:\n {\n 'main': 'relative path to main image',\n 'variants': {\n 'label': 'relati...
# coding=utf-8 import glob import os import copy import re import hashlib from django.utils.crypto import get_random_string from django.utils.translation import ugettext_lazy from django.conf import settings from dju_common.file import make_dirs_for_file_path from dju_common.tools import datetime_to_dtstr from dju_image.image import is_image, adjust_image, image_get_format from . import settings as dju_settings ERROR_MESSAGES = { 'unknown_profile': ugettext_lazy('Unknown profile "%(profile)s".'), 'filename_hasnt_tmp_prefix': ugettext_lazy('Filename "%(filename)s" has not temporary prefix.'), } HASH_SIZE = 10 _profile_configs_cache = {} def clear_profile_configs_cache(): _profile_configs_cache.clear() def media_path(path): return os.path.join(settings.MEDIA_ROOT, path).replace('\\', '/') def save_file(f, full_path): """ Saves file f to full_path and set rules. """ make_dirs_for_file_path(full_path, mode=dju_settings.DJU_IMG_CHMOD_DIR) with open(full_path, 'wb') as t: f.seek(0) while True: buf = f.read(dju_settings.DJU_IMG_RW_FILE_BUFFER_SIZE) if not buf: break t.write(buf) os.chmod(full_path, dju_settings.DJU_IMG_CHMOD_FILE) def get_profile_configs(profile=None, use_cache=True): """ Returns upload configs for profile. """ if use_cache and profile in _profile_configs_cache: return _profile_configs_cache[profile] profile_conf = None if profile is not None: try: profile_conf = dju_settings.DJU_IMG_UPLOAD_PROFILES[profile] except KeyError: if profile != 'default': raise ValueError(unicode(ERROR_MESSAGES['unknown_profile']) % {'profile': profile}) conf = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_DEFAULT) if profile_conf: conf.update(copy.deepcopy(profile_conf)) for v_i in xrange(len(conf['VARIANTS'])): v = conf['VARIANTS'][v_i] conf['VARIANTS'][v_i] = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_VARIANT_DEFAULT) conf['VARIANTS'][v_i].update(v) if use_cache: _profile_configs_cache[profile] = conf return conf def generate_img_id(profile, ext=None, label=None, tmp=False): """ Generates img_id. """ if ext and not ext.startswith('.'): ext = '.' + ext if label: label = re.sub(r'[^a-z0-9_\-]', '', label, flags=re.I) label = re.sub(r'_+', '_', label) label = label[:60] return '{profile}:{tmp}{dtstr}_{rand}{label}{ext}'.format( profile=profile, tmp=(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX if tmp else ''), dtstr=datetime_to_dtstr(), rand=get_random_string(4, 'abcdefghijklmnopqrstuvwxyz0123456789'), label=(('_' + label) if label else ''), ext=(ext or ''), ) def get_hash(name, variant_label=None): # name must be without label, for example 'uniqname_rand' h = hashlib.sha1(name + (variant_label or '') + dju_settings.DJU_IMG_UPLOAD_KEY).hexdigest() return h[:HASH_SIZE] def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False): """ Returns path to file relative MEDIA_URL. """ profile, base_name = img_id.split(':', 1) conf = get_profile_configs(profile) if not variant_label: status_suffix = dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX else: status_suffix = dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX name, file_ext = os.path.splitext(base_name) prefix = '' if name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): name = name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] prefix = dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX name_parts = name.split('_', 2) name = '{name}{status_suffix}{hash}'.format( name=name, status_suffix=status_suffix, hash=get_hash('_'.join(name_parts[:2]), variant_label=variant_label) ) if variant_label: name += '_' + variant_label if ext: file_ext = ext elif variant_label: for var_conf in conf['VARIANTS']: var_conf_label = var_conf['LABEL'] or get_variant_label(var_conf) if var_conf_label == variant_label: if var_conf['FORMAT']: file_ext = var_conf['FORMAT'].lower() break if file_ext and not file_ext.startswith('.'): file_ext = '.' + file_ext relative_path = os.path.join( dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH'], name_parts[0][-2:], (prefix + name + file_ext) ).replace('\\', '/') if create_dirs: path = media_path(relative_path) make_dirs_for_file_path(path, mode=dju_settings.DJU_IMG_CHMOD_DIR) return relative_path def is_img_id_exists(img_id): """ Checks if img_id has real file on filesystem. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) return os.path.isfile(main_path) def is_img_id_valid(img_id): """ Checks if img_id is valid. """ t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE) t = re.sub(r'\.+', '.', t) if img_id != t or img_id.count(':') != 1: return False profile, base_name = img_id.split(':', 1) if not profile or not base_name: return False try: get_profile_configs(profile) except ValueError: return False return True def get_variant_label(v_conf): """ Generates name for variant images based settings (by variants sizes). """ if v_conf['MAX_SIZE'][0] is None: return 'h{}'.format(v_conf['MAX_SIZE'][1]) if v_conf['MAX_SIZE'][1] is None: return 'w{}'.format(v_conf['MAX_SIZE'][0]) return '{}x{}'.format(*v_conf['MAX_SIZE']) variant_hash_label_re = re.compile(r'^.+?{suf}([a-z0-9]{{hs}})_(.+?)(?:|\.[A-Za-z]{3,4})$'.replace( '{suf}', dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX ).replace( '{hs}', str(HASH_SIZE) )) def get_files_by_img_id(img_id, check_hash=True): """ Шукає файли для img_id. Повертає: { 'main': 'relative path to main image', 'variants': { 'label': 'relative path to variant image by label', ... } } Якщо check_hash=True, тоді файли з невірним хешем будуть ігноруватись. Якщо файл не існує, тоді поверає None. Пошук варіантів відбуваться в файловій системі не залежно від налаштувань. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) if not os.path.isfile(main_path): return None filename = os.path.basename(main_rel_path) name_left_part = filename.split(dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX, 1)[0] img_name = name_left_part if img_name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): img_name = img_name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] img_name_parts = img_name.split('_', 2) img_name = '_'.join(img_name_parts[:2]) search_pattern = name_left_part + dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX + '*' search_dir = os.path.dirname(main_path) variants = {} for var_path in glob.iglob(os.path.join(search_dir, search_pattern.replace('\\', '/'))): var_filename = os.path.basename(var_path) m = variant_hash_label_re.match(var_filename) if not m: continue var_hash, var_label = m.groups() if check_hash and var_hash != get_hash(img_name, var_label): continue variants[var_label] = os.path.relpath(var_path, settings.MEDIA_ROOT) return { 'main': main_rel_path, 'variants': variants, } def img_id_has_tmp_prefix(img_id): return (':' + dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX) in img_id def remove_tmp_prefix_from_filename(filename): """ Remove tmp prefix from filename. """ if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename}) return filename[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] def remove_tmp_prefix_from_file_path(file_path): """ Remove tmp prefix from file path or url. """ path, filename = os.path.split(file_path) return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\', '/') def make_permalink(img_id): """ Removes tmp prefix from filename and rename main and variant files. Returns img_id without tmp prefix. """ profile, filename = img_id.split(':', 1) new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename) urls = get_files_by_img_id(img_id) if urls is None: return urls move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))} for var_label, var_file_path in urls['variants'].iteritems(): move_list.add((var_file_path, remove_tmp_prefix_from_file_path(var_file_path))) for file_path_from, file_path_to in move_list: os.rename(media_path(file_path_from), media_path(file_path_to)) return new_img_id def _custom_upload(f, profile, label, conf): t = adjust_image(f, max_size=conf['MAX_SIZE'], new_format=conf['FORMAT'], jpeg_quality=conf['JPEG_QUALITY'], fill=conf['FILL'], stretch=conf['STRETCH'], return_new_image=True) img_id = generate_img_id(profile, ext=image_get_format(f), label=label, tmp=True) relative_path = get_relative_path_from_img_id(img_id) full_path = media_path(relative_path) save_file(t, full_path) for v_conf in conf['VARIANTS']: v_label = v_conf['LABEL'] if not v_label: v_label = get_variant_label(v_conf) v_t = adjust_image(t, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=v_label, ext=image_get_format(v_t)) v_full_path = media_path(v_relative_path) save_file(v_t, v_full_path) return img_id def upload_from_fs(fn, profile=None, label=None): """ Saves image from fn with TMP prefix and returns img_id. """ if not os.path.isfile(fn): raise ValueError('File is not exists: {}'.format(fn)) if profile is None: profile = 'default' conf = get_profile_configs(profile) with open(fn, 'rb') as f: if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file "%(name)s" is not allowed. ' 'Allowed formats is: %(formats)s.') % {'name': fn, 'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf) def upload_from_fileobject(f, profile=None, label=None): """ Saves image from f with TMP prefix and returns img_id. """ if profile is None: profile = 'default' conf = get_profile_configs(profile) f.seek(0) if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file is not allowed. ' 'Allowed formats is: %(formats)s.') % {'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf)
liminspace/dju-image
dju_image/tools.py
remove_tmp_prefix_from_filename
python
def remove_tmp_prefix_from_filename(filename): if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename}) return filename[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):]
Remove tmp prefix from filename.
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/tools.py#L251-L257
null
# coding=utf-8 import glob import os import copy import re import hashlib from django.utils.crypto import get_random_string from django.utils.translation import ugettext_lazy from django.conf import settings from dju_common.file import make_dirs_for_file_path from dju_common.tools import datetime_to_dtstr from dju_image.image import is_image, adjust_image, image_get_format from . import settings as dju_settings ERROR_MESSAGES = { 'unknown_profile': ugettext_lazy('Unknown profile "%(profile)s".'), 'filename_hasnt_tmp_prefix': ugettext_lazy('Filename "%(filename)s" has not temporary prefix.'), } HASH_SIZE = 10 _profile_configs_cache = {} def clear_profile_configs_cache(): _profile_configs_cache.clear() def media_path(path): return os.path.join(settings.MEDIA_ROOT, path).replace('\\', '/') def save_file(f, full_path): """ Saves file f to full_path and set rules. """ make_dirs_for_file_path(full_path, mode=dju_settings.DJU_IMG_CHMOD_DIR) with open(full_path, 'wb') as t: f.seek(0) while True: buf = f.read(dju_settings.DJU_IMG_RW_FILE_BUFFER_SIZE) if not buf: break t.write(buf) os.chmod(full_path, dju_settings.DJU_IMG_CHMOD_FILE) def get_profile_configs(profile=None, use_cache=True): """ Returns upload configs for profile. """ if use_cache and profile in _profile_configs_cache: return _profile_configs_cache[profile] profile_conf = None if profile is not None: try: profile_conf = dju_settings.DJU_IMG_UPLOAD_PROFILES[profile] except KeyError: if profile != 'default': raise ValueError(unicode(ERROR_MESSAGES['unknown_profile']) % {'profile': profile}) conf = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_DEFAULT) if profile_conf: conf.update(copy.deepcopy(profile_conf)) for v_i in xrange(len(conf['VARIANTS'])): v = conf['VARIANTS'][v_i] conf['VARIANTS'][v_i] = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_VARIANT_DEFAULT) conf['VARIANTS'][v_i].update(v) if use_cache: _profile_configs_cache[profile] = conf return conf def generate_img_id(profile, ext=None, label=None, tmp=False): """ Generates img_id. """ if ext and not ext.startswith('.'): ext = '.' + ext if label: label = re.sub(r'[^a-z0-9_\-]', '', label, flags=re.I) label = re.sub(r'_+', '_', label) label = label[:60] return '{profile}:{tmp}{dtstr}_{rand}{label}{ext}'.format( profile=profile, tmp=(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX if tmp else ''), dtstr=datetime_to_dtstr(), rand=get_random_string(4, 'abcdefghijklmnopqrstuvwxyz0123456789'), label=(('_' + label) if label else ''), ext=(ext or ''), ) def get_hash(name, variant_label=None): # name must be without label, for example 'uniqname_rand' h = hashlib.sha1(name + (variant_label or '') + dju_settings.DJU_IMG_UPLOAD_KEY).hexdigest() return h[:HASH_SIZE] def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False): """ Returns path to file relative MEDIA_URL. """ profile, base_name = img_id.split(':', 1) conf = get_profile_configs(profile) if not variant_label: status_suffix = dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX else: status_suffix = dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX name, file_ext = os.path.splitext(base_name) prefix = '' if name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): name = name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] prefix = dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX name_parts = name.split('_', 2) name = '{name}{status_suffix}{hash}'.format( name=name, status_suffix=status_suffix, hash=get_hash('_'.join(name_parts[:2]), variant_label=variant_label) ) if variant_label: name += '_' + variant_label if ext: file_ext = ext elif variant_label: for var_conf in conf['VARIANTS']: var_conf_label = var_conf['LABEL'] or get_variant_label(var_conf) if var_conf_label == variant_label: if var_conf['FORMAT']: file_ext = var_conf['FORMAT'].lower() break if file_ext and not file_ext.startswith('.'): file_ext = '.' + file_ext relative_path = os.path.join( dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH'], name_parts[0][-2:], (prefix + name + file_ext) ).replace('\\', '/') if create_dirs: path = media_path(relative_path) make_dirs_for_file_path(path, mode=dju_settings.DJU_IMG_CHMOD_DIR) return relative_path def is_img_id_exists(img_id): """ Checks if img_id has real file on filesystem. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) return os.path.isfile(main_path) def is_img_id_valid(img_id): """ Checks if img_id is valid. """ t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE) t = re.sub(r'\.+', '.', t) if img_id != t or img_id.count(':') != 1: return False profile, base_name = img_id.split(':', 1) if not profile or not base_name: return False try: get_profile_configs(profile) except ValueError: return False return True def get_variant_label(v_conf): """ Generates name for variant images based settings (by variants sizes). """ if v_conf['MAX_SIZE'][0] is None: return 'h{}'.format(v_conf['MAX_SIZE'][1]) if v_conf['MAX_SIZE'][1] is None: return 'w{}'.format(v_conf['MAX_SIZE'][0]) return '{}x{}'.format(*v_conf['MAX_SIZE']) variant_hash_label_re = re.compile(r'^.+?{suf}([a-z0-9]{{hs}})_(.+?)(?:|\.[A-Za-z]{3,4})$'.replace( '{suf}', dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX ).replace( '{hs}', str(HASH_SIZE) )) def get_files_by_img_id(img_id, check_hash=True): """ Шукає файли для img_id. Повертає: { 'main': 'relative path to main image', 'variants': { 'label': 'relative path to variant image by label', ... } } Якщо check_hash=True, тоді файли з невірним хешем будуть ігноруватись. Якщо файл не існує, тоді поверає None. Пошук варіантів відбуваться в файловій системі не залежно від налаштувань. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) if not os.path.isfile(main_path): return None filename = os.path.basename(main_rel_path) name_left_part = filename.split(dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX, 1)[0] img_name = name_left_part if img_name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): img_name = img_name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] img_name_parts = img_name.split('_', 2) img_name = '_'.join(img_name_parts[:2]) search_pattern = name_left_part + dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX + '*' search_dir = os.path.dirname(main_path) variants = {} for var_path in glob.iglob(os.path.join(search_dir, search_pattern.replace('\\', '/'))): var_filename = os.path.basename(var_path) m = variant_hash_label_re.match(var_filename) if not m: continue var_hash, var_label = m.groups() if check_hash and var_hash != get_hash(img_name, var_label): continue variants[var_label] = os.path.relpath(var_path, settings.MEDIA_ROOT) return { 'main': main_rel_path, 'variants': variants, } def remove_all_files_of_img_id(img_id): """ Removes all img_id's files. """ files = get_files_by_img_id(img_id, check_hash=False) if files: os.remove(media_path(files['main'])) for fn in files['variants'].values(): os.remove(media_path(fn)) def img_id_has_tmp_prefix(img_id): return (':' + dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX) in img_id def remove_tmp_prefix_from_file_path(file_path): """ Remove tmp prefix from file path or url. """ path, filename = os.path.split(file_path) return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\', '/') def make_permalink(img_id): """ Removes tmp prefix from filename and rename main and variant files. Returns img_id without tmp prefix. """ profile, filename = img_id.split(':', 1) new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename) urls = get_files_by_img_id(img_id) if urls is None: return urls move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))} for var_label, var_file_path in urls['variants'].iteritems(): move_list.add((var_file_path, remove_tmp_prefix_from_file_path(var_file_path))) for file_path_from, file_path_to in move_list: os.rename(media_path(file_path_from), media_path(file_path_to)) return new_img_id def _custom_upload(f, profile, label, conf): t = adjust_image(f, max_size=conf['MAX_SIZE'], new_format=conf['FORMAT'], jpeg_quality=conf['JPEG_QUALITY'], fill=conf['FILL'], stretch=conf['STRETCH'], return_new_image=True) img_id = generate_img_id(profile, ext=image_get_format(f), label=label, tmp=True) relative_path = get_relative_path_from_img_id(img_id) full_path = media_path(relative_path) save_file(t, full_path) for v_conf in conf['VARIANTS']: v_label = v_conf['LABEL'] if not v_label: v_label = get_variant_label(v_conf) v_t = adjust_image(t, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=v_label, ext=image_get_format(v_t)) v_full_path = media_path(v_relative_path) save_file(v_t, v_full_path) return img_id def upload_from_fs(fn, profile=None, label=None): """ Saves image from fn with TMP prefix and returns img_id. """ if not os.path.isfile(fn): raise ValueError('File is not exists: {}'.format(fn)) if profile is None: profile = 'default' conf = get_profile_configs(profile) with open(fn, 'rb') as f: if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file "%(name)s" is not allowed. ' 'Allowed formats is: %(formats)s.') % {'name': fn, 'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf) def upload_from_fileobject(f, profile=None, label=None): """ Saves image from f with TMP prefix and returns img_id. """ if profile is None: profile = 'default' conf = get_profile_configs(profile) f.seek(0) if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file is not allowed. ' 'Allowed formats is: %(formats)s.') % {'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf)
liminspace/dju-image
dju_image/tools.py
remove_tmp_prefix_from_file_path
python
def remove_tmp_prefix_from_file_path(file_path): path, filename = os.path.split(file_path) return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\', '/')
Remove tmp prefix from file path or url.
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/tools.py#L260-L265
[ "def remove_tmp_prefix_from_filename(filename):\n \"\"\"\n Remove tmp prefix from filename.\n \"\"\"\n if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):\n raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename})\n return filename[len(dju_settin...
# coding=utf-8 import glob import os import copy import re import hashlib from django.utils.crypto import get_random_string from django.utils.translation import ugettext_lazy from django.conf import settings from dju_common.file import make_dirs_for_file_path from dju_common.tools import datetime_to_dtstr from dju_image.image import is_image, adjust_image, image_get_format from . import settings as dju_settings ERROR_MESSAGES = { 'unknown_profile': ugettext_lazy('Unknown profile "%(profile)s".'), 'filename_hasnt_tmp_prefix': ugettext_lazy('Filename "%(filename)s" has not temporary prefix.'), } HASH_SIZE = 10 _profile_configs_cache = {} def clear_profile_configs_cache(): _profile_configs_cache.clear() def media_path(path): return os.path.join(settings.MEDIA_ROOT, path).replace('\\', '/') def save_file(f, full_path): """ Saves file f to full_path and set rules. """ make_dirs_for_file_path(full_path, mode=dju_settings.DJU_IMG_CHMOD_DIR) with open(full_path, 'wb') as t: f.seek(0) while True: buf = f.read(dju_settings.DJU_IMG_RW_FILE_BUFFER_SIZE) if not buf: break t.write(buf) os.chmod(full_path, dju_settings.DJU_IMG_CHMOD_FILE) def get_profile_configs(profile=None, use_cache=True): """ Returns upload configs for profile. """ if use_cache and profile in _profile_configs_cache: return _profile_configs_cache[profile] profile_conf = None if profile is not None: try: profile_conf = dju_settings.DJU_IMG_UPLOAD_PROFILES[profile] except KeyError: if profile != 'default': raise ValueError(unicode(ERROR_MESSAGES['unknown_profile']) % {'profile': profile}) conf = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_DEFAULT) if profile_conf: conf.update(copy.deepcopy(profile_conf)) for v_i in xrange(len(conf['VARIANTS'])): v = conf['VARIANTS'][v_i] conf['VARIANTS'][v_i] = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_VARIANT_DEFAULT) conf['VARIANTS'][v_i].update(v) if use_cache: _profile_configs_cache[profile] = conf return conf def generate_img_id(profile, ext=None, label=None, tmp=False): """ Generates img_id. """ if ext and not ext.startswith('.'): ext = '.' + ext if label: label = re.sub(r'[^a-z0-9_\-]', '', label, flags=re.I) label = re.sub(r'_+', '_', label) label = label[:60] return '{profile}:{tmp}{dtstr}_{rand}{label}{ext}'.format( profile=profile, tmp=(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX if tmp else ''), dtstr=datetime_to_dtstr(), rand=get_random_string(4, 'abcdefghijklmnopqrstuvwxyz0123456789'), label=(('_' + label) if label else ''), ext=(ext or ''), ) def get_hash(name, variant_label=None): # name must be without label, for example 'uniqname_rand' h = hashlib.sha1(name + (variant_label or '') + dju_settings.DJU_IMG_UPLOAD_KEY).hexdigest() return h[:HASH_SIZE] def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False): """ Returns path to file relative MEDIA_URL. """ profile, base_name = img_id.split(':', 1) conf = get_profile_configs(profile) if not variant_label: status_suffix = dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX else: status_suffix = dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX name, file_ext = os.path.splitext(base_name) prefix = '' if name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): name = name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] prefix = dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX name_parts = name.split('_', 2) name = '{name}{status_suffix}{hash}'.format( name=name, status_suffix=status_suffix, hash=get_hash('_'.join(name_parts[:2]), variant_label=variant_label) ) if variant_label: name += '_' + variant_label if ext: file_ext = ext elif variant_label: for var_conf in conf['VARIANTS']: var_conf_label = var_conf['LABEL'] or get_variant_label(var_conf) if var_conf_label == variant_label: if var_conf['FORMAT']: file_ext = var_conf['FORMAT'].lower() break if file_ext and not file_ext.startswith('.'): file_ext = '.' + file_ext relative_path = os.path.join( dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH'], name_parts[0][-2:], (prefix + name + file_ext) ).replace('\\', '/') if create_dirs: path = media_path(relative_path) make_dirs_for_file_path(path, mode=dju_settings.DJU_IMG_CHMOD_DIR) return relative_path def is_img_id_exists(img_id): """ Checks if img_id has real file on filesystem. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) return os.path.isfile(main_path) def is_img_id_valid(img_id): """ Checks if img_id is valid. """ t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE) t = re.sub(r'\.+', '.', t) if img_id != t or img_id.count(':') != 1: return False profile, base_name = img_id.split(':', 1) if not profile or not base_name: return False try: get_profile_configs(profile) except ValueError: return False return True def get_variant_label(v_conf): """ Generates name for variant images based settings (by variants sizes). """ if v_conf['MAX_SIZE'][0] is None: return 'h{}'.format(v_conf['MAX_SIZE'][1]) if v_conf['MAX_SIZE'][1] is None: return 'w{}'.format(v_conf['MAX_SIZE'][0]) return '{}x{}'.format(*v_conf['MAX_SIZE']) variant_hash_label_re = re.compile(r'^.+?{suf}([a-z0-9]{{hs}})_(.+?)(?:|\.[A-Za-z]{3,4})$'.replace( '{suf}', dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX ).replace( '{hs}', str(HASH_SIZE) )) def get_files_by_img_id(img_id, check_hash=True): """ Шукає файли для img_id. Повертає: { 'main': 'relative path to main image', 'variants': { 'label': 'relative path to variant image by label', ... } } Якщо check_hash=True, тоді файли з невірним хешем будуть ігноруватись. Якщо файл не існує, тоді поверає None. Пошук варіантів відбуваться в файловій системі не залежно від налаштувань. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) if not os.path.isfile(main_path): return None filename = os.path.basename(main_rel_path) name_left_part = filename.split(dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX, 1)[0] img_name = name_left_part if img_name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): img_name = img_name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] img_name_parts = img_name.split('_', 2) img_name = '_'.join(img_name_parts[:2]) search_pattern = name_left_part + dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX + '*' search_dir = os.path.dirname(main_path) variants = {} for var_path in glob.iglob(os.path.join(search_dir, search_pattern.replace('\\', '/'))): var_filename = os.path.basename(var_path) m = variant_hash_label_re.match(var_filename) if not m: continue var_hash, var_label = m.groups() if check_hash and var_hash != get_hash(img_name, var_label): continue variants[var_label] = os.path.relpath(var_path, settings.MEDIA_ROOT) return { 'main': main_rel_path, 'variants': variants, } def remove_all_files_of_img_id(img_id): """ Removes all img_id's files. """ files = get_files_by_img_id(img_id, check_hash=False) if files: os.remove(media_path(files['main'])) for fn in files['variants'].values(): os.remove(media_path(fn)) def img_id_has_tmp_prefix(img_id): return (':' + dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX) in img_id def remove_tmp_prefix_from_filename(filename): """ Remove tmp prefix from filename. """ if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename}) return filename[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] def make_permalink(img_id): """ Removes tmp prefix from filename and rename main and variant files. Returns img_id without tmp prefix. """ profile, filename = img_id.split(':', 1) new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename) urls = get_files_by_img_id(img_id) if urls is None: return urls move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))} for var_label, var_file_path in urls['variants'].iteritems(): move_list.add((var_file_path, remove_tmp_prefix_from_file_path(var_file_path))) for file_path_from, file_path_to in move_list: os.rename(media_path(file_path_from), media_path(file_path_to)) return new_img_id def _custom_upload(f, profile, label, conf): t = adjust_image(f, max_size=conf['MAX_SIZE'], new_format=conf['FORMAT'], jpeg_quality=conf['JPEG_QUALITY'], fill=conf['FILL'], stretch=conf['STRETCH'], return_new_image=True) img_id = generate_img_id(profile, ext=image_get_format(f), label=label, tmp=True) relative_path = get_relative_path_from_img_id(img_id) full_path = media_path(relative_path) save_file(t, full_path) for v_conf in conf['VARIANTS']: v_label = v_conf['LABEL'] if not v_label: v_label = get_variant_label(v_conf) v_t = adjust_image(t, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=v_label, ext=image_get_format(v_t)) v_full_path = media_path(v_relative_path) save_file(v_t, v_full_path) return img_id def upload_from_fs(fn, profile=None, label=None): """ Saves image from fn with TMP prefix and returns img_id. """ if not os.path.isfile(fn): raise ValueError('File is not exists: {}'.format(fn)) if profile is None: profile = 'default' conf = get_profile_configs(profile) with open(fn, 'rb') as f: if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file "%(name)s" is not allowed. ' 'Allowed formats is: %(formats)s.') % {'name': fn, 'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf) def upload_from_fileobject(f, profile=None, label=None): """ Saves image from f with TMP prefix and returns img_id. """ if profile is None: profile = 'default' conf = get_profile_configs(profile) f.seek(0) if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file is not allowed. ' 'Allowed formats is: %(formats)s.') % {'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf)
liminspace/dju-image
dju_image/tools.py
make_permalink
python
def make_permalink(img_id): profile, filename = img_id.split(':', 1) new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename) urls = get_files_by_img_id(img_id) if urls is None: return urls move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))} for var_label, var_file_path in urls['variants'].iteritems(): move_list.add((var_file_path, remove_tmp_prefix_from_file_path(var_file_path))) for file_path_from, file_path_to in move_list: os.rename(media_path(file_path_from), media_path(file_path_to)) return new_img_id
Removes tmp prefix from filename and rename main and variant files. Returns img_id without tmp prefix.
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/tools.py#L268-L283
[ "def media_path(path):\n return os.path.join(settings.MEDIA_ROOT, path).replace('\\\\', '/')\n", "def get_files_by_img_id(img_id, check_hash=True):\n \"\"\"\n Шукає файли для img_id.\n Повертає:\n {\n 'main': 'relative path to main image',\n 'variants': {\n 'label': 'relati...
# coding=utf-8 import glob import os import copy import re import hashlib from django.utils.crypto import get_random_string from django.utils.translation import ugettext_lazy from django.conf import settings from dju_common.file import make_dirs_for_file_path from dju_common.tools import datetime_to_dtstr from dju_image.image import is_image, adjust_image, image_get_format from . import settings as dju_settings ERROR_MESSAGES = { 'unknown_profile': ugettext_lazy('Unknown profile "%(profile)s".'), 'filename_hasnt_tmp_prefix': ugettext_lazy('Filename "%(filename)s" has not temporary prefix.'), } HASH_SIZE = 10 _profile_configs_cache = {} def clear_profile_configs_cache(): _profile_configs_cache.clear() def media_path(path): return os.path.join(settings.MEDIA_ROOT, path).replace('\\', '/') def save_file(f, full_path): """ Saves file f to full_path and set rules. """ make_dirs_for_file_path(full_path, mode=dju_settings.DJU_IMG_CHMOD_DIR) with open(full_path, 'wb') as t: f.seek(0) while True: buf = f.read(dju_settings.DJU_IMG_RW_FILE_BUFFER_SIZE) if not buf: break t.write(buf) os.chmod(full_path, dju_settings.DJU_IMG_CHMOD_FILE) def get_profile_configs(profile=None, use_cache=True): """ Returns upload configs for profile. """ if use_cache and profile in _profile_configs_cache: return _profile_configs_cache[profile] profile_conf = None if profile is not None: try: profile_conf = dju_settings.DJU_IMG_UPLOAD_PROFILES[profile] except KeyError: if profile != 'default': raise ValueError(unicode(ERROR_MESSAGES['unknown_profile']) % {'profile': profile}) conf = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_DEFAULT) if profile_conf: conf.update(copy.deepcopy(profile_conf)) for v_i in xrange(len(conf['VARIANTS'])): v = conf['VARIANTS'][v_i] conf['VARIANTS'][v_i] = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_VARIANT_DEFAULT) conf['VARIANTS'][v_i].update(v) if use_cache: _profile_configs_cache[profile] = conf return conf def generate_img_id(profile, ext=None, label=None, tmp=False): """ Generates img_id. """ if ext and not ext.startswith('.'): ext = '.' + ext if label: label = re.sub(r'[^a-z0-9_\-]', '', label, flags=re.I) label = re.sub(r'_+', '_', label) label = label[:60] return '{profile}:{tmp}{dtstr}_{rand}{label}{ext}'.format( profile=profile, tmp=(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX if tmp else ''), dtstr=datetime_to_dtstr(), rand=get_random_string(4, 'abcdefghijklmnopqrstuvwxyz0123456789'), label=(('_' + label) if label else ''), ext=(ext or ''), ) def get_hash(name, variant_label=None): # name must be without label, for example 'uniqname_rand' h = hashlib.sha1(name + (variant_label or '') + dju_settings.DJU_IMG_UPLOAD_KEY).hexdigest() return h[:HASH_SIZE] def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False): """ Returns path to file relative MEDIA_URL. """ profile, base_name = img_id.split(':', 1) conf = get_profile_configs(profile) if not variant_label: status_suffix = dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX else: status_suffix = dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX name, file_ext = os.path.splitext(base_name) prefix = '' if name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): name = name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] prefix = dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX name_parts = name.split('_', 2) name = '{name}{status_suffix}{hash}'.format( name=name, status_suffix=status_suffix, hash=get_hash('_'.join(name_parts[:2]), variant_label=variant_label) ) if variant_label: name += '_' + variant_label if ext: file_ext = ext elif variant_label: for var_conf in conf['VARIANTS']: var_conf_label = var_conf['LABEL'] or get_variant_label(var_conf) if var_conf_label == variant_label: if var_conf['FORMAT']: file_ext = var_conf['FORMAT'].lower() break if file_ext and not file_ext.startswith('.'): file_ext = '.' + file_ext relative_path = os.path.join( dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH'], name_parts[0][-2:], (prefix + name + file_ext) ).replace('\\', '/') if create_dirs: path = media_path(relative_path) make_dirs_for_file_path(path, mode=dju_settings.DJU_IMG_CHMOD_DIR) return relative_path def is_img_id_exists(img_id): """ Checks if img_id has real file on filesystem. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) return os.path.isfile(main_path) def is_img_id_valid(img_id): """ Checks if img_id is valid. """ t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE) t = re.sub(r'\.+', '.', t) if img_id != t or img_id.count(':') != 1: return False profile, base_name = img_id.split(':', 1) if not profile or not base_name: return False try: get_profile_configs(profile) except ValueError: return False return True def get_variant_label(v_conf): """ Generates name for variant images based settings (by variants sizes). """ if v_conf['MAX_SIZE'][0] is None: return 'h{}'.format(v_conf['MAX_SIZE'][1]) if v_conf['MAX_SIZE'][1] is None: return 'w{}'.format(v_conf['MAX_SIZE'][0]) return '{}x{}'.format(*v_conf['MAX_SIZE']) variant_hash_label_re = re.compile(r'^.+?{suf}([a-z0-9]{{hs}})_(.+?)(?:|\.[A-Za-z]{3,4})$'.replace( '{suf}', dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX ).replace( '{hs}', str(HASH_SIZE) )) def get_files_by_img_id(img_id, check_hash=True): """ Шукає файли для img_id. Повертає: { 'main': 'relative path to main image', 'variants': { 'label': 'relative path to variant image by label', ... } } Якщо check_hash=True, тоді файли з невірним хешем будуть ігноруватись. Якщо файл не існує, тоді поверає None. Пошук варіантів відбуваться в файловій системі не залежно від налаштувань. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) if not os.path.isfile(main_path): return None filename = os.path.basename(main_rel_path) name_left_part = filename.split(dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX, 1)[0] img_name = name_left_part if img_name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): img_name = img_name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] img_name_parts = img_name.split('_', 2) img_name = '_'.join(img_name_parts[:2]) search_pattern = name_left_part + dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX + '*' search_dir = os.path.dirname(main_path) variants = {} for var_path in glob.iglob(os.path.join(search_dir, search_pattern.replace('\\', '/'))): var_filename = os.path.basename(var_path) m = variant_hash_label_re.match(var_filename) if not m: continue var_hash, var_label = m.groups() if check_hash and var_hash != get_hash(img_name, var_label): continue variants[var_label] = os.path.relpath(var_path, settings.MEDIA_ROOT) return { 'main': main_rel_path, 'variants': variants, } def remove_all_files_of_img_id(img_id): """ Removes all img_id's files. """ files = get_files_by_img_id(img_id, check_hash=False) if files: os.remove(media_path(files['main'])) for fn in files['variants'].values(): os.remove(media_path(fn)) def img_id_has_tmp_prefix(img_id): return (':' + dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX) in img_id def remove_tmp_prefix_from_filename(filename): """ Remove tmp prefix from filename. """ if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename}) return filename[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] def remove_tmp_prefix_from_file_path(file_path): """ Remove tmp prefix from file path or url. """ path, filename = os.path.split(file_path) return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\', '/') def _custom_upload(f, profile, label, conf): t = adjust_image(f, max_size=conf['MAX_SIZE'], new_format=conf['FORMAT'], jpeg_quality=conf['JPEG_QUALITY'], fill=conf['FILL'], stretch=conf['STRETCH'], return_new_image=True) img_id = generate_img_id(profile, ext=image_get_format(f), label=label, tmp=True) relative_path = get_relative_path_from_img_id(img_id) full_path = media_path(relative_path) save_file(t, full_path) for v_conf in conf['VARIANTS']: v_label = v_conf['LABEL'] if not v_label: v_label = get_variant_label(v_conf) v_t = adjust_image(t, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=v_label, ext=image_get_format(v_t)) v_full_path = media_path(v_relative_path) save_file(v_t, v_full_path) return img_id def upload_from_fs(fn, profile=None, label=None): """ Saves image from fn with TMP prefix and returns img_id. """ if not os.path.isfile(fn): raise ValueError('File is not exists: {}'.format(fn)) if profile is None: profile = 'default' conf = get_profile_configs(profile) with open(fn, 'rb') as f: if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file "%(name)s" is not allowed. ' 'Allowed formats is: %(formats)s.') % {'name': fn, 'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf) def upload_from_fileobject(f, profile=None, label=None): """ Saves image from f with TMP prefix and returns img_id. """ if profile is None: profile = 'default' conf = get_profile_configs(profile) f.seek(0) if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file is not allowed. ' 'Allowed formats is: %(formats)s.') % {'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf)
liminspace/dju-image
dju_image/tools.py
upload_from_fs
python
def upload_from_fs(fn, profile=None, label=None): if not os.path.isfile(fn): raise ValueError('File is not exists: {}'.format(fn)) if profile is None: profile = 'default' conf = get_profile_configs(profile) with open(fn, 'rb') as f: if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file "%(name)s" is not allowed. ' 'Allowed formats is: %(formats)s.') % {'name': fn, 'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf)
Saves image from fn with TMP prefix and returns img_id.
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/tools.py#L308-L323
[ "def is_image(f, types=('png', 'jpeg', 'gif'), set_content_type=True):\n \"\"\"\n Return True if file f is image (types type) and set its correct content_type and filename extension.\n Example:\n if is_image(request.FILES['file']):\n print 'File is image'\n\n if is_image(open('/tmp...
# coding=utf-8 import glob import os import copy import re import hashlib from django.utils.crypto import get_random_string from django.utils.translation import ugettext_lazy from django.conf import settings from dju_common.file import make_dirs_for_file_path from dju_common.tools import datetime_to_dtstr from dju_image.image import is_image, adjust_image, image_get_format from . import settings as dju_settings ERROR_MESSAGES = { 'unknown_profile': ugettext_lazy('Unknown profile "%(profile)s".'), 'filename_hasnt_tmp_prefix': ugettext_lazy('Filename "%(filename)s" has not temporary prefix.'), } HASH_SIZE = 10 _profile_configs_cache = {} def clear_profile_configs_cache(): _profile_configs_cache.clear() def media_path(path): return os.path.join(settings.MEDIA_ROOT, path).replace('\\', '/') def save_file(f, full_path): """ Saves file f to full_path and set rules. """ make_dirs_for_file_path(full_path, mode=dju_settings.DJU_IMG_CHMOD_DIR) with open(full_path, 'wb') as t: f.seek(0) while True: buf = f.read(dju_settings.DJU_IMG_RW_FILE_BUFFER_SIZE) if not buf: break t.write(buf) os.chmod(full_path, dju_settings.DJU_IMG_CHMOD_FILE) def get_profile_configs(profile=None, use_cache=True): """ Returns upload configs for profile. """ if use_cache and profile in _profile_configs_cache: return _profile_configs_cache[profile] profile_conf = None if profile is not None: try: profile_conf = dju_settings.DJU_IMG_UPLOAD_PROFILES[profile] except KeyError: if profile != 'default': raise ValueError(unicode(ERROR_MESSAGES['unknown_profile']) % {'profile': profile}) conf = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_DEFAULT) if profile_conf: conf.update(copy.deepcopy(profile_conf)) for v_i in xrange(len(conf['VARIANTS'])): v = conf['VARIANTS'][v_i] conf['VARIANTS'][v_i] = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_VARIANT_DEFAULT) conf['VARIANTS'][v_i].update(v) if use_cache: _profile_configs_cache[profile] = conf return conf def generate_img_id(profile, ext=None, label=None, tmp=False): """ Generates img_id. """ if ext and not ext.startswith('.'): ext = '.' + ext if label: label = re.sub(r'[^a-z0-9_\-]', '', label, flags=re.I) label = re.sub(r'_+', '_', label) label = label[:60] return '{profile}:{tmp}{dtstr}_{rand}{label}{ext}'.format( profile=profile, tmp=(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX if tmp else ''), dtstr=datetime_to_dtstr(), rand=get_random_string(4, 'abcdefghijklmnopqrstuvwxyz0123456789'), label=(('_' + label) if label else ''), ext=(ext or ''), ) def get_hash(name, variant_label=None): # name must be without label, for example 'uniqname_rand' h = hashlib.sha1(name + (variant_label or '') + dju_settings.DJU_IMG_UPLOAD_KEY).hexdigest() return h[:HASH_SIZE] def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False): """ Returns path to file relative MEDIA_URL. """ profile, base_name = img_id.split(':', 1) conf = get_profile_configs(profile) if not variant_label: status_suffix = dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX else: status_suffix = dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX name, file_ext = os.path.splitext(base_name) prefix = '' if name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): name = name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] prefix = dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX name_parts = name.split('_', 2) name = '{name}{status_suffix}{hash}'.format( name=name, status_suffix=status_suffix, hash=get_hash('_'.join(name_parts[:2]), variant_label=variant_label) ) if variant_label: name += '_' + variant_label if ext: file_ext = ext elif variant_label: for var_conf in conf['VARIANTS']: var_conf_label = var_conf['LABEL'] or get_variant_label(var_conf) if var_conf_label == variant_label: if var_conf['FORMAT']: file_ext = var_conf['FORMAT'].lower() break if file_ext and not file_ext.startswith('.'): file_ext = '.' + file_ext relative_path = os.path.join( dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH'], name_parts[0][-2:], (prefix + name + file_ext) ).replace('\\', '/') if create_dirs: path = media_path(relative_path) make_dirs_for_file_path(path, mode=dju_settings.DJU_IMG_CHMOD_DIR) return relative_path def is_img_id_exists(img_id): """ Checks if img_id has real file on filesystem. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) return os.path.isfile(main_path) def is_img_id_valid(img_id): """ Checks if img_id is valid. """ t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE) t = re.sub(r'\.+', '.', t) if img_id != t or img_id.count(':') != 1: return False profile, base_name = img_id.split(':', 1) if not profile or not base_name: return False try: get_profile_configs(profile) except ValueError: return False return True def get_variant_label(v_conf): """ Generates name for variant images based settings (by variants sizes). """ if v_conf['MAX_SIZE'][0] is None: return 'h{}'.format(v_conf['MAX_SIZE'][1]) if v_conf['MAX_SIZE'][1] is None: return 'w{}'.format(v_conf['MAX_SIZE'][0]) return '{}x{}'.format(*v_conf['MAX_SIZE']) variant_hash_label_re = re.compile(r'^.+?{suf}([a-z0-9]{{hs}})_(.+?)(?:|\.[A-Za-z]{3,4})$'.replace( '{suf}', dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX ).replace( '{hs}', str(HASH_SIZE) )) def get_files_by_img_id(img_id, check_hash=True): """ Шукає файли для img_id. Повертає: { 'main': 'relative path to main image', 'variants': { 'label': 'relative path to variant image by label', ... } } Якщо check_hash=True, тоді файли з невірним хешем будуть ігноруватись. Якщо файл не існує, тоді поверає None. Пошук варіантів відбуваться в файловій системі не залежно від налаштувань. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) if not os.path.isfile(main_path): return None filename = os.path.basename(main_rel_path) name_left_part = filename.split(dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX, 1)[0] img_name = name_left_part if img_name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): img_name = img_name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] img_name_parts = img_name.split('_', 2) img_name = '_'.join(img_name_parts[:2]) search_pattern = name_left_part + dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX + '*' search_dir = os.path.dirname(main_path) variants = {} for var_path in glob.iglob(os.path.join(search_dir, search_pattern.replace('\\', '/'))): var_filename = os.path.basename(var_path) m = variant_hash_label_re.match(var_filename) if not m: continue var_hash, var_label = m.groups() if check_hash and var_hash != get_hash(img_name, var_label): continue variants[var_label] = os.path.relpath(var_path, settings.MEDIA_ROOT) return { 'main': main_rel_path, 'variants': variants, } def remove_all_files_of_img_id(img_id): """ Removes all img_id's files. """ files = get_files_by_img_id(img_id, check_hash=False) if files: os.remove(media_path(files['main'])) for fn in files['variants'].values(): os.remove(media_path(fn)) def img_id_has_tmp_prefix(img_id): return (':' + dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX) in img_id def remove_tmp_prefix_from_filename(filename): """ Remove tmp prefix from filename. """ if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename}) return filename[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] def remove_tmp_prefix_from_file_path(file_path): """ Remove tmp prefix from file path or url. """ path, filename = os.path.split(file_path) return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\', '/') def make_permalink(img_id): """ Removes tmp prefix from filename and rename main and variant files. Returns img_id without tmp prefix. """ profile, filename = img_id.split(':', 1) new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename) urls = get_files_by_img_id(img_id) if urls is None: return urls move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))} for var_label, var_file_path in urls['variants'].iteritems(): move_list.add((var_file_path, remove_tmp_prefix_from_file_path(var_file_path))) for file_path_from, file_path_to in move_list: os.rename(media_path(file_path_from), media_path(file_path_to)) return new_img_id def _custom_upload(f, profile, label, conf): t = adjust_image(f, max_size=conf['MAX_SIZE'], new_format=conf['FORMAT'], jpeg_quality=conf['JPEG_QUALITY'], fill=conf['FILL'], stretch=conf['STRETCH'], return_new_image=True) img_id = generate_img_id(profile, ext=image_get_format(f), label=label, tmp=True) relative_path = get_relative_path_from_img_id(img_id) full_path = media_path(relative_path) save_file(t, full_path) for v_conf in conf['VARIANTS']: v_label = v_conf['LABEL'] if not v_label: v_label = get_variant_label(v_conf) v_t = adjust_image(t, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=v_label, ext=image_get_format(v_t)) v_full_path = media_path(v_relative_path) save_file(v_t, v_full_path) return img_id def upload_from_fileobject(f, profile=None, label=None): """ Saves image from f with TMP prefix and returns img_id. """ if profile is None: profile = 'default' conf = get_profile_configs(profile) f.seek(0) if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file is not allowed. ' 'Allowed formats is: %(formats)s.') % {'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf)
liminspace/dju-image
dju_image/tools.py
upload_from_fileobject
python
def upload_from_fileobject(f, profile=None, label=None): if profile is None: profile = 'default' conf = get_profile_configs(profile) f.seek(0) if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file is not allowed. ' 'Allowed formats is: %(formats)s.') % {'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf)
Saves image from f with TMP prefix and returns img_id.
train
https://github.com/liminspace/dju-image/blob/b06eb3be2069cd6cb52cf1e26c2c761883142d4e/dju_image/tools.py#L326-L339
[ "def is_image(f, types=('png', 'jpeg', 'gif'), set_content_type=True):\n \"\"\"\n Return True if file f is image (types type) and set its correct content_type and filename extension.\n Example:\n if is_image(request.FILES['file']):\n print 'File is image'\n\n if is_image(open('/tmp...
# coding=utf-8 import glob import os import copy import re import hashlib from django.utils.crypto import get_random_string from django.utils.translation import ugettext_lazy from django.conf import settings from dju_common.file import make_dirs_for_file_path from dju_common.tools import datetime_to_dtstr from dju_image.image import is_image, adjust_image, image_get_format from . import settings as dju_settings ERROR_MESSAGES = { 'unknown_profile': ugettext_lazy('Unknown profile "%(profile)s".'), 'filename_hasnt_tmp_prefix': ugettext_lazy('Filename "%(filename)s" has not temporary prefix.'), } HASH_SIZE = 10 _profile_configs_cache = {} def clear_profile_configs_cache(): _profile_configs_cache.clear() def media_path(path): return os.path.join(settings.MEDIA_ROOT, path).replace('\\', '/') def save_file(f, full_path): """ Saves file f to full_path and set rules. """ make_dirs_for_file_path(full_path, mode=dju_settings.DJU_IMG_CHMOD_DIR) with open(full_path, 'wb') as t: f.seek(0) while True: buf = f.read(dju_settings.DJU_IMG_RW_FILE_BUFFER_SIZE) if not buf: break t.write(buf) os.chmod(full_path, dju_settings.DJU_IMG_CHMOD_FILE) def get_profile_configs(profile=None, use_cache=True): """ Returns upload configs for profile. """ if use_cache and profile in _profile_configs_cache: return _profile_configs_cache[profile] profile_conf = None if profile is not None: try: profile_conf = dju_settings.DJU_IMG_UPLOAD_PROFILES[profile] except KeyError: if profile != 'default': raise ValueError(unicode(ERROR_MESSAGES['unknown_profile']) % {'profile': profile}) conf = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_DEFAULT) if profile_conf: conf.update(copy.deepcopy(profile_conf)) for v_i in xrange(len(conf['VARIANTS'])): v = conf['VARIANTS'][v_i] conf['VARIANTS'][v_i] = copy.deepcopy(dju_settings.DJU_IMG_UPLOAD_PROFILE_VARIANT_DEFAULT) conf['VARIANTS'][v_i].update(v) if use_cache: _profile_configs_cache[profile] = conf return conf def generate_img_id(profile, ext=None, label=None, tmp=False): """ Generates img_id. """ if ext and not ext.startswith('.'): ext = '.' + ext if label: label = re.sub(r'[^a-z0-9_\-]', '', label, flags=re.I) label = re.sub(r'_+', '_', label) label = label[:60] return '{profile}:{tmp}{dtstr}_{rand}{label}{ext}'.format( profile=profile, tmp=(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX if tmp else ''), dtstr=datetime_to_dtstr(), rand=get_random_string(4, 'abcdefghijklmnopqrstuvwxyz0123456789'), label=(('_' + label) if label else ''), ext=(ext or ''), ) def get_hash(name, variant_label=None): # name must be without label, for example 'uniqname_rand' h = hashlib.sha1(name + (variant_label or '') + dju_settings.DJU_IMG_UPLOAD_KEY).hexdigest() return h[:HASH_SIZE] def get_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False): """ Returns path to file relative MEDIA_URL. """ profile, base_name = img_id.split(':', 1) conf = get_profile_configs(profile) if not variant_label: status_suffix = dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX else: status_suffix = dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX name, file_ext = os.path.splitext(base_name) prefix = '' if name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): name = name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] prefix = dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX name_parts = name.split('_', 2) name = '{name}{status_suffix}{hash}'.format( name=name, status_suffix=status_suffix, hash=get_hash('_'.join(name_parts[:2]), variant_label=variant_label) ) if variant_label: name += '_' + variant_label if ext: file_ext = ext elif variant_label: for var_conf in conf['VARIANTS']: var_conf_label = var_conf['LABEL'] or get_variant_label(var_conf) if var_conf_label == variant_label: if var_conf['FORMAT']: file_ext = var_conf['FORMAT'].lower() break if file_ext and not file_ext.startswith('.'): file_ext = '.' + file_ext relative_path = os.path.join( dju_settings.DJU_IMG_UPLOAD_SUBDIR, conf['PATH'], name_parts[0][-2:], (prefix + name + file_ext) ).replace('\\', '/') if create_dirs: path = media_path(relative_path) make_dirs_for_file_path(path, mode=dju_settings.DJU_IMG_CHMOD_DIR) return relative_path def is_img_id_exists(img_id): """ Checks if img_id has real file on filesystem. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) return os.path.isfile(main_path) def is_img_id_valid(img_id): """ Checks if img_id is valid. """ t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE) t = re.sub(r'\.+', '.', t) if img_id != t or img_id.count(':') != 1: return False profile, base_name = img_id.split(':', 1) if not profile or not base_name: return False try: get_profile_configs(profile) except ValueError: return False return True def get_variant_label(v_conf): """ Generates name for variant images based settings (by variants sizes). """ if v_conf['MAX_SIZE'][0] is None: return 'h{}'.format(v_conf['MAX_SIZE'][1]) if v_conf['MAX_SIZE'][1] is None: return 'w{}'.format(v_conf['MAX_SIZE'][0]) return '{}x{}'.format(*v_conf['MAX_SIZE']) variant_hash_label_re = re.compile(r'^.+?{suf}([a-z0-9]{{hs}})_(.+?)(?:|\.[A-Za-z]{3,4})$'.replace( '{suf}', dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX ).replace( '{hs}', str(HASH_SIZE) )) def get_files_by_img_id(img_id, check_hash=True): """ Шукає файли для img_id. Повертає: { 'main': 'relative path to main image', 'variants': { 'label': 'relative path to variant image by label', ... } } Якщо check_hash=True, тоді файли з невірним хешем будуть ігноруватись. Якщо файл не існує, тоді поверає None. Пошук варіантів відбуваться в файловій системі не залежно від налаштувань. """ main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) if not os.path.isfile(main_path): return None filename = os.path.basename(main_rel_path) name_left_part = filename.split(dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX, 1)[0] img_name = name_left_part if img_name.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): img_name = img_name[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] img_name_parts = img_name.split('_', 2) img_name = '_'.join(img_name_parts[:2]) search_pattern = name_left_part + dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX + '*' search_dir = os.path.dirname(main_path) variants = {} for var_path in glob.iglob(os.path.join(search_dir, search_pattern.replace('\\', '/'))): var_filename = os.path.basename(var_path) m = variant_hash_label_re.match(var_filename) if not m: continue var_hash, var_label = m.groups() if check_hash and var_hash != get_hash(img_name, var_label): continue variants[var_label] = os.path.relpath(var_path, settings.MEDIA_ROOT) return { 'main': main_rel_path, 'variants': variants, } def remove_all_files_of_img_id(img_id): """ Removes all img_id's files. """ files = get_files_by_img_id(img_id, check_hash=False) if files: os.remove(media_path(files['main'])) for fn in files['variants'].values(): os.remove(media_path(fn)) def img_id_has_tmp_prefix(img_id): return (':' + dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX) in img_id def remove_tmp_prefix_from_filename(filename): """ Remove tmp prefix from filename. """ if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename}) return filename[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):] def remove_tmp_prefix_from_file_path(file_path): """ Remove tmp prefix from file path or url. """ path, filename = os.path.split(file_path) return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\', '/') def make_permalink(img_id): """ Removes tmp prefix from filename and rename main and variant files. Returns img_id without tmp prefix. """ profile, filename = img_id.split(':', 1) new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename) urls = get_files_by_img_id(img_id) if urls is None: return urls move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))} for var_label, var_file_path in urls['variants'].iteritems(): move_list.add((var_file_path, remove_tmp_prefix_from_file_path(var_file_path))) for file_path_from, file_path_to in move_list: os.rename(media_path(file_path_from), media_path(file_path_to)) return new_img_id def _custom_upload(f, profile, label, conf): t = adjust_image(f, max_size=conf['MAX_SIZE'], new_format=conf['FORMAT'], jpeg_quality=conf['JPEG_QUALITY'], fill=conf['FILL'], stretch=conf['STRETCH'], return_new_image=True) img_id = generate_img_id(profile, ext=image_get_format(f), label=label, tmp=True) relative_path = get_relative_path_from_img_id(img_id) full_path = media_path(relative_path) save_file(t, full_path) for v_conf in conf['VARIANTS']: v_label = v_conf['LABEL'] if not v_label: v_label = get_variant_label(v_conf) v_t = adjust_image(t, max_size=v_conf['MAX_SIZE'], new_format=v_conf['FORMAT'], jpeg_quality=v_conf['JPEG_QUALITY'], fill=v_conf['FILL'], stretch=v_conf['STRETCH'], return_new_image=True) v_relative_path = get_relative_path_from_img_id(img_id, variant_label=v_label, ext=image_get_format(v_t)) v_full_path = media_path(v_relative_path) save_file(v_t, v_full_path) return img_id def upload_from_fs(fn, profile=None, label=None): """ Saves image from fn with TMP prefix and returns img_id. """ if not os.path.isfile(fn): raise ValueError('File is not exists: {}'.format(fn)) if profile is None: profile = 'default' conf = get_profile_configs(profile) with open(fn, 'rb') as f: if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file "%(name)s" is not allowed. ' 'Allowed formats is: %(formats)s.') % {'name': fn, 'formats': ', '.join(map(lambda t: t.upper(), conf['TYPES']))}) raise RuntimeError(msg) return _custom_upload(f, profile, label, conf)
andy29485/embypy
embypy/objects/folders.py
Playlist.songs
python
async def songs(self): '''list of songs in the playlist |force| |coro| Returns ------- list of type :class:`embypy.objects.Audio` ''' items = [] for i in await self.items: if i.type == 'Audio': items.append(i) elif hasattr(i, 'songs'): items.extend(await i.songs) return items
list of songs in the playlist |force| |coro| Returns ------- list of type :class:`embypy.objects.Audio`
train
https://github.com/andy29485/embypy/blob/cde658d380965caaf4789d4d182d045b0346797b/embypy/objects/folders.py#L82-L100
null
class Playlist(Folder): '''Class representing emby playlist objects Parameters ---------- object_dict : dict same as for `EmbyObject` connector : embypy.utils.connector.Connector same as for `EmbyObject` ''' def __init__(self, object_dict, connector): super().__init__(object_dict, connector) @property def songs_sync(self): return self.connector.sync_run(self.songs) @property @property def songs_force_sync(self): return self.connector.sync_run(self.songs_force) @property async def songs_force(self): items = [] for i in await self.items_force: if i.type == 'Audio': items.append(i) elif hasattr(i, 'songs'): items.extend(await i.songs) return items @property async def items_force(self): items = await self.connector.getJson( 'Playlists/{Id}/Items'.format(Id=self.id), remote=False, SortOrder='Ascending', SortBy='SortName', ) items = await self.process(items) self.extras['items'] = items return items def add_items_sync(self, *items): return self.connector.sync_run(self.add_items_sync(*items)) async def add_items(self, *items): '''append items to the playlist |coro| Parameters ---------- items : array_like list of items to add(or their ids) See Also -------- remove_items : ''' items = [item.id for item in await self.process(items)] if not items: return await self.connector.post('Playlists/{Id}/Items'.format(Id=self.id), data={'Ids': ','.join(items)}, remote=False ) def remove_items_sync(self, *items): return self.connector.sync_run(self.remove_items_sync(*items)) async def remove_items(self, *items): '''remove items from the playlist |coro| Parameters ---------- items : array_like list of items to remove(or their ids) See Also -------- add_items : ''' items = [i.id for i in (await self.process(items)) if i in self.items] if not items: return await self.connector.delete( 'Playlists/{Id}/Items'.format(Id=self.id), EntryIds=','.join(items), remote=False )
andy29485/embypy
embypy/objects/folders.py
Playlist.add_items
python
async def add_items(self, *items): '''append items to the playlist |coro| Parameters ---------- items : array_like list of items to add(or their ids) See Also -------- remove_items : ''' items = [item.id for item in await self.process(items)] if not items: return await self.connector.post('Playlists/{Id}/Items'.format(Id=self.id), data={'Ids': ','.join(items)}, remote=False )
append items to the playlist |coro| Parameters ---------- items : array_like list of items to add(or their ids) See Also -------- remove_items :
train
https://github.com/andy29485/embypy/blob/cde658d380965caaf4789d4d182d045b0346797b/embypy/objects/folders.py#L129-L149
[ "async def process(self, object_dict):\n '''[for internal use] convert json/dict into python object\n\n |coro|\n\n Parameters\n ----------\n object_dict : dict\n json representation of object from emby\n\n Notes\n -----\n if a string is given, it is assumed to be an id, obj is returned.\n if a list is g...
class Playlist(Folder): '''Class representing emby playlist objects Parameters ---------- object_dict : dict same as for `EmbyObject` connector : embypy.utils.connector.Connector same as for `EmbyObject` ''' def __init__(self, object_dict, connector): super().__init__(object_dict, connector) @property def songs_sync(self): return self.connector.sync_run(self.songs) @property async def songs(self): '''list of songs in the playlist |force| |coro| Returns ------- list of type :class:`embypy.objects.Audio` ''' items = [] for i in await self.items: if i.type == 'Audio': items.append(i) elif hasattr(i, 'songs'): items.extend(await i.songs) return items @property def songs_force_sync(self): return self.connector.sync_run(self.songs_force) @property async def songs_force(self): items = [] for i in await self.items_force: if i.type == 'Audio': items.append(i) elif hasattr(i, 'songs'): items.extend(await i.songs) return items @property async def items_force(self): items = await self.connector.getJson( 'Playlists/{Id}/Items'.format(Id=self.id), remote=False, SortOrder='Ascending', SortBy='SortName', ) items = await self.process(items) self.extras['items'] = items return items def add_items_sync(self, *items): return self.connector.sync_run(self.add_items_sync(*items)) def remove_items_sync(self, *items): return self.connector.sync_run(self.remove_items_sync(*items)) async def remove_items(self, *items): '''remove items from the playlist |coro| Parameters ---------- items : array_like list of items to remove(or their ids) See Also -------- add_items : ''' items = [i.id for i in (await self.process(items)) if i in self.items] if not items: return await self.connector.delete( 'Playlists/{Id}/Items'.format(Id=self.id), EntryIds=','.join(items), remote=False )
andy29485/embypy
embypy/objects/folders.py
Playlist.remove_items
python
async def remove_items(self, *items): '''remove items from the playlist |coro| Parameters ---------- items : array_like list of items to remove(or their ids) See Also -------- add_items : ''' items = [i.id for i in (await self.process(items)) if i in self.items] if not items: return await self.connector.delete( 'Playlists/{Id}/Items'.format(Id=self.id), EntryIds=','.join(items), remote=False )
remove items from the playlist |coro| Parameters ---------- items : array_like list of items to remove(or their ids) See Also -------- add_items :
train
https://github.com/andy29485/embypy/blob/cde658d380965caaf4789d4d182d045b0346797b/embypy/objects/folders.py#L154-L176
[ "async def process(self, object_dict):\n '''[for internal use] convert json/dict into python object\n\n |coro|\n\n Parameters\n ----------\n object_dict : dict\n json representation of object from emby\n\n Notes\n -----\n if a string is given, it is assumed to be an id, obj is returned.\n if a list is g...
class Playlist(Folder): '''Class representing emby playlist objects Parameters ---------- object_dict : dict same as for `EmbyObject` connector : embypy.utils.connector.Connector same as for `EmbyObject` ''' def __init__(self, object_dict, connector): super().__init__(object_dict, connector) @property def songs_sync(self): return self.connector.sync_run(self.songs) @property async def songs(self): '''list of songs in the playlist |force| |coro| Returns ------- list of type :class:`embypy.objects.Audio` ''' items = [] for i in await self.items: if i.type == 'Audio': items.append(i) elif hasattr(i, 'songs'): items.extend(await i.songs) return items @property def songs_force_sync(self): return self.connector.sync_run(self.songs_force) @property async def songs_force(self): items = [] for i in await self.items_force: if i.type == 'Audio': items.append(i) elif hasattr(i, 'songs'): items.extend(await i.songs) return items @property async def items_force(self): items = await self.connector.getJson( 'Playlists/{Id}/Items'.format(Id=self.id), remote=False, SortOrder='Ascending', SortBy='SortName', ) items = await self.process(items) self.extras['items'] = items return items def add_items_sync(self, *items): return self.connector.sync_run(self.add_items_sync(*items)) async def add_items(self, *items): '''append items to the playlist |coro| Parameters ---------- items : array_like list of items to add(or their ids) See Also -------- remove_items : ''' items = [item.id for item in await self.process(items)] if not items: return await self.connector.post('Playlists/{Id}/Items'.format(Id=self.id), data={'Ids': ','.join(items)}, remote=False ) def remove_items_sync(self, *items): return self.connector.sync_run(self.remove_items_sync(*items))
andy29485/embypy
embypy/objects/folders.py
BoxSet.movies
python
async def movies(self): '''list of movies in the collection |force| |coro| Returns ------- list of type :class:`embypy.objects.Movie` ''' items = [] for i in await self.items: if i.type == 'Movie': items.append(i) elif hasattr(i, 'movies'): items.extend(await i.movies) return items
list of movies in the collection |force| |coro| Returns ------- list of type :class:`embypy.objects.Movie`
train
https://github.com/andy29485/embypy/blob/cde658d380965caaf4789d4d182d045b0346797b/embypy/objects/folders.py#L196-L214
null
class BoxSet(Folder): '''Class representing emby boxsets/collection objects Parameters ---------- object_dict : dict same as for `EmbyObject` connector : embypy.utils.connector.Connector same as for `EmbyObject` ''' def __init__(self, object_dict, connector): super().__init__(object_dict, connector) @property def movies_sync(self): return self.connector.sync_run(self.movies) @property @property def movies_force_sync(self): return self.connector.sync_run(self.movies_force) @property async def movies_force(self): items = [] for i in await self.items_force: if i.type == 'Movie': items.append(i) elif hasattr(i, 'movies'): items.extend(await i.movies) return items @property def shows_sync(self): return self.series_sync @property def series_sync(self): return self.connector.sync_run(self.series) @property async def shows(self): return await self.series @property async def series(self): '''list of series in the collection |force| |coro| Returns ------- list of type :class:`embypy.objects.Series` ''' items = [] for i in await self.items: if i.type == 'Series': items.append(i) elif hasattr(i, 'series'): items.extend(await i.series) return items @property def shows_force_sync(self): return self.series_force_sync @property def series_force_sync(self): return self.connector.sync_run(self.series_force) @property async def shows(self): return await self.series_force @property async def series_force(self): items = [] for i in await self.items_force: if i.type == 'Series': items.append(i) elif hasattr(i, 'series'): items.extend(await i.series) return items
andy29485/embypy
embypy/objects/folders.py
BoxSet.series
python
async def series(self): '''list of series in the collection |force| |coro| Returns ------- list of type :class:`embypy.objects.Series` ''' items = [] for i in await self.items: if i.type == 'Series': items.append(i) elif hasattr(i, 'series'): items.extend(await i.series) return items
list of series in the collection |force| |coro| Returns ------- list of type :class:`embypy.objects.Series`
train
https://github.com/andy29485/embypy/blob/cde658d380965caaf4789d4d182d045b0346797b/embypy/objects/folders.py#L243-L261
null
class BoxSet(Folder): '''Class representing emby boxsets/collection objects Parameters ---------- object_dict : dict same as for `EmbyObject` connector : embypy.utils.connector.Connector same as for `EmbyObject` ''' def __init__(self, object_dict, connector): super().__init__(object_dict, connector) @property def movies_sync(self): return self.connector.sync_run(self.movies) @property async def movies(self): '''list of movies in the collection |force| |coro| Returns ------- list of type :class:`embypy.objects.Movie` ''' items = [] for i in await self.items: if i.type == 'Movie': items.append(i) elif hasattr(i, 'movies'): items.extend(await i.movies) return items @property def movies_force_sync(self): return self.connector.sync_run(self.movies_force) @property async def movies_force(self): items = [] for i in await self.items_force: if i.type == 'Movie': items.append(i) elif hasattr(i, 'movies'): items.extend(await i.movies) return items @property def shows_sync(self): return self.series_sync @property def series_sync(self): return self.connector.sync_run(self.series) @property async def shows(self): return await self.series @property @property def shows_force_sync(self): return self.series_force_sync @property def series_force_sync(self): return self.connector.sync_run(self.series_force) @property async def shows(self): return await self.series_force @property async def series_force(self): items = [] for i in await self.items_force: if i.type == 'Series': items.append(i) elif hasattr(i, 'series'): items.extend(await i.series) return items
andy29485/embypy
embypy/objects/misc.py
Audio.album_primary_image_url
python
def album_primary_image_url(self): '''The image of the album''' path = '/Items/{}/Images/Primary'.format(self.album_id) return self.connector.get_url(path, attach_api_key=False)
The image of the album
train
https://github.com/andy29485/embypy/blob/cde658d380965caaf4789d4d182d045b0346797b/embypy/objects/misc.py#L118-L121
null
class Audio(EmbyObject): '''Class representing generic emby Audio objects Parameters ---------- object_dict : dict same as for `EmbyObject` connector : embypy.utils.connector.Connector same as for `EmbyObject` ''' def __init__(self, object_dict, connector): super().__init__(object_dict, connector) @property def album_id(self): '''the id of the album this song is in''' return self.object_dict.get('AlbumId') @property def album_sync(self): return self.connector.sync_run(self.album) @property async def album(self): '''The album that the song belongs to |coro| Returns ------- :class:`embypy.objects.MusicAlbum` ''' return await self.process(self.album_id) @property def index_number(self): '''track number on disc''' return self.object_dict.get('IndexNumber', 1) @index_number.setter def index_number(self, value): self.object_dict['IndexNumber'] = value @property def track_number(self): '''track number on disc''' return self.index_number @track_number.setter def track_number(self, value): self.index_number = value @property def album_artist_ids(self): '''list of album artist ids''' return [a['Id'] for a in self.object_dict.get('AlbumArtists', [])] @property def album_artist_names(self): '''names of album artists''' return self.object_dict.get('AlbumArtist', '').split(';') @property def album_artists_sync(self): return self.connector.sync_run(self.album_artists) @property async def album_artists(self): ''' |coro| Returns ------- list of type :class:`embypy.objects.MusicArtist` ''' return await self.process(self.album_artist_ids) @property def artist_ids(self): return [a['Id'] for a in self.object_dict.get('ArtistItems', [])] @property def artist_names(self): '''names of song artists''' return self.object_dict.get('Artists', []) @property def artists_sync(self): return self.connector.sync_run(self.artists) @property async def artists(self): ''' |coro| Returns ------- list of type :class:`embypy.objects.MusicArtist` ''' return await self.process(self.artist_ids) @property def album_primary_image_tag(self): '''The image tag of the album''' return self.object_dict.get('AlbumPrimaryImageTag') @property @property def media_type(self): return self.object_dict.get('MediaType', 'Audio') @property def type(self): return self.object_dict.get('Type', 'Audio') @property def stream_url(self): '''stream for this song - not re-encoded''' path = '/Audio/{}/universal'.format(self.id) return self.connector.get_url(path, userId=self.connector.userid, MaxStreamingBitrate=140000000, Container='opus', TranscodingContainer='opus', AudioCodec='opus', MaxSampleRate=48000, PlaySessionId=1496213367201 #TODO no hard code )
andy29485/embypy
embypy/objects/misc.py
Audio.stream_url
python
def stream_url(self): '''stream for this song - not re-encoded''' path = '/Audio/{}/universal'.format(self.id) return self.connector.get_url(path, userId=self.connector.userid, MaxStreamingBitrate=140000000, Container='opus', TranscodingContainer='opus', AudioCodec='opus', MaxSampleRate=48000, PlaySessionId=1496213367201 #TODO no hard code )
stream for this song - not re-encoded
train
https://github.com/andy29485/embypy/blob/cde658d380965caaf4789d4d182d045b0346797b/embypy/objects/misc.py#L132-L143
null
class Audio(EmbyObject): '''Class representing generic emby Audio objects Parameters ---------- object_dict : dict same as for `EmbyObject` connector : embypy.utils.connector.Connector same as for `EmbyObject` ''' def __init__(self, object_dict, connector): super().__init__(object_dict, connector) @property def album_id(self): '''the id of the album this song is in''' return self.object_dict.get('AlbumId') @property def album_sync(self): return self.connector.sync_run(self.album) @property async def album(self): '''The album that the song belongs to |coro| Returns ------- :class:`embypy.objects.MusicAlbum` ''' return await self.process(self.album_id) @property def index_number(self): '''track number on disc''' return self.object_dict.get('IndexNumber', 1) @index_number.setter def index_number(self, value): self.object_dict['IndexNumber'] = value @property def track_number(self): '''track number on disc''' return self.index_number @track_number.setter def track_number(self, value): self.index_number = value @property def album_artist_ids(self): '''list of album artist ids''' return [a['Id'] for a in self.object_dict.get('AlbumArtists', [])] @property def album_artist_names(self): '''names of album artists''' return self.object_dict.get('AlbumArtist', '').split(';') @property def album_artists_sync(self): return self.connector.sync_run(self.album_artists) @property async def album_artists(self): ''' |coro| Returns ------- list of type :class:`embypy.objects.MusicArtist` ''' return await self.process(self.album_artist_ids) @property def artist_ids(self): return [a['Id'] for a in self.object_dict.get('ArtistItems', [])] @property def artist_names(self): '''names of song artists''' return self.object_dict.get('Artists', []) @property def artists_sync(self): return self.connector.sync_run(self.artists) @property async def artists(self): ''' |coro| Returns ------- list of type :class:`embypy.objects.MusicArtist` ''' return await self.process(self.artist_ids) @property def album_primary_image_tag(self): '''The image tag of the album''' return self.object_dict.get('AlbumPrimaryImageTag') @property def album_primary_image_url(self): '''The image of the album''' path = '/Items/{}/Images/Primary'.format(self.album_id) return self.connector.get_url(path, attach_api_key=False) @property def media_type(self): return self.object_dict.get('MediaType', 'Audio') @property def type(self): return self.object_dict.get('Type', 'Audio') @property
andy29485/embypy
embypy/utils/connector.py
WebSocket.handler
python
async def handler(self): '''Handle loop, get and process messages''' self.ws = await websockets.connect(self.url, ssl=self.ssl) while self.ws: message = await self.ws.recv() for handle in self.on_message: if asyncio.iscoroutinefunction(handle): await handle(self, message) else: handle(self, message)
Handle loop, get and process messages
train
https://github.com/andy29485/embypy/blob/cde658d380965caaf4789d4d182d045b0346797b/embypy/utils/connector.py#L39-L48
null
class WebSocket: '''Basic websocet that runs function when messages are recived Parameters ---------- conn : embypy.utils.Connector connector object url : str uri of websocet server ssl_str : str path to the ssl certificate for confirmation ''' def __init__(self, conn, url, ssl_str=None): self.on_message = [] self.url = url self.conn = conn if type(ssl_str) == str: self.ssl = ssl.SSLContext(ssl.PROTOCOL_SSLv23) self.ssl.load_verify_locations(cafile=ssl_str) else: self.ssl = ssl_str def connect(self): '''Establish a connection''' #TODO - authenticate to emby self.loop.create_task(self.handler()) async def send(message): if not self.ws: return False return await self.ws.send(message) def send_sync(message): return self.loop.run_until_complete(self.send(message)) def close(self): '''close connection to socket''' self.ws.close() self.ws = None
andy29485/embypy
embypy/utils/connector.py
Connector.get_url
python
def get_url(self, path='/', websocket=False, remote=True, attach_api_key=True, userId=None, pass_uid=False, **query): '''construct a url for an emby request Parameters ---------- path : str uri path(excluding domain and port) of get request for emby websocket : bool, optional if true, then `ws(s)` are used instead of `http(s)` remote : bool, optional if true, remote-address is used (default True) attach_api_key : bool, optional if true, apikey is added to the query (default True) userId : str, optional uid to use, if none, default is used pass_uid : bool, optional if true, uid is added to the query (default False) query : karg dict additional parameters to set (part of url after the `?`) Also See -------- get : getJson : post : delete : Returns ------- full url ''' userId = userId or self.userid if attach_api_key and self.api_key: query.update({'api_key':self.api_key, 'deviceId': self.device_id}) if pass_uid: query['userId'] = userId if remote: url = self.urlremote or self.url else: url = self.url if websocket: scheme = {'http':'ws', 'https':'wss'}[url.scheme] else: scheme = url.scheme netloc = url.netloc + '/emby' url = urlunparse((scheme, netloc, path, '', '{params}', '')).format( UserId = userId, ApiKey = self.api_key, DeviceId = self.device_id, params = urlencode(query) ) return url[:-1] if url[-1] == '?' else url
construct a url for an emby request Parameters ---------- path : str uri path(excluding domain and port) of get request for emby websocket : bool, optional if true, then `ws(s)` are used instead of `http(s)` remote : bool, optional if true, remote-address is used (default True) attach_api_key : bool, optional if true, apikey is added to the query (default True) userId : str, optional uid to use, if none, default is used pass_uid : bool, optional if true, uid is added to the query (default False) query : karg dict additional parameters to set (part of url after the `?`) Also See -------- get : getJson : post : delete : Returns ------- full url
train
https://github.com/andy29485/embypy/blob/cde658d380965caaf4789d4d182d045b0346797b/embypy/utils/connector.py#L201-L257
null
class Connector: '''Class responsible for comunication with emby Parameters ---------- url : str url to connect to api-key : str api key generated by emby, used for authentication token : str similar to api key, but is meant for user logins address-remote : str, optional alt url to connect to, pulic facing (see notes) ssl : str, optional path to ssl certificate - for self signed certs userid : str, optional emby id of the user you wish to connect as username : str, optional username for login (see notes) password : str, optional password for login (see notes) device_id : str device id as registered in emby timeout : int number of seconds to wait before timeout for a request tries : int number of times to try a request before throwing an error loop : asyncio.AbstractEventLoop if given all calls should be awaitable Notes ----- This class/object should NOT be used (except internally). Tf a address-remote url is given, then that will be used for output, such as the `embypy.objects.EmbyObject.url` atribute. `url` will always be used when making requests - thus I recomend using the local address for `url` and the remote address for `address-remote` username/password authentication is not supported as of yet ''' def __init__(self, url, **kargs): if ('api_key' not in kargs or 'device_id' not in kargs) and \ ('username' not in kargs or 'password' not in kargs): raise ValueError('provide api key and device id or username/password') urlremote = kargs.get('address-remote') self.ssl = kargs.get('ssl', True) self.userid = kargs.get('userid') self.token = kargs.get('token') self.api_key = kargs.get('api_key', self.token) self.username = kargs.get('username') self.password = kargs.get('password') self.device_id = kargs.get('device_id', 'EmbyPy') self.timeout = kargs.get('timeout', 30) self.tries = kargs.get('tries', 3) self.loop = kargs.get('loop', asyncio.get_event_loop()) self.url = urlparse(url) self.urlremote = urlparse(urlremote) if urlremote else urlremote if self.ssl and type(self.ssl) == str: self.ssl = ssl.SSLContext(ssl.PROTOCOL_SSLv23) self.ssl.load_verify_locations(cafile=self.ssl) conn = aiohttp.TCPConnector(ssl_context=self.ssl) self.session = aiohttp.ClientSession( headers={ 'Authorization': 'MediaBrowser Client="{0}",Device="{0}",DeviceId="{1}",Version="{2}"' .format('EmbyPy', self.device_id, __version__) }, connector=conn ) #connect to websocket is user wants to if 'ws' in kargs: self.ws = WebSocket(self, self.get_url(websocket=True), self.ssl) else: self.ws = None # authenticate to emby if password was given if self.password and self.username and not self.token: self.login_sync() def __del__(self): try: Connector.sync_run(self.session.close()) except: self.loop.run_until_complete(self.session.close()) @staticmethod def sync_run(f): if asyncio.iscoroutinefunction(f): f = f() if asyncio.iscoroutine(f): return asyncio.get_event_loop().run_until_complete(f) elif callable(f): return f() else: return f def get_sync(self, *args, **kargs): return self.sync_run(self.get(*args, **kargs)) def delete_sync(self, *args, **kargs): return self.sync_run(self.delete(*args, **kargs)) def post_sync(self, *args, **kargs): return self.sync_run(self.post(*args, **kargs)) def getJson_sync(self, *args, **kargs): return self.sync_run(self.getJson(*args, **kargs)) def login_sync(self): return self.sync_run(self.login()) async def login(self): data = await self.post('/Users/AuthenticateByName', data={ 'username':self.username, 'pw':self.password, }, send_raw=True, format='json', ) data = await data.json() self.token = data.get('AccessToken', '') self.userid = data.get('User', {}).get('Id') self.api_key = self.token self.session._default_headers.update( {'X-MediaBrowser-Token': self.token} ) async def _process_resp(self, resp): if (not resp or resp.status == 401) and self.username: await self.login() await resp.close() return False return True def add_on_message(self, func): '''add function that handles websocket messages''' return self.ws.on_message.append(func) async def get(self, path, **query): '''return a get request Parameters ---------- path : str same as get_url query : kargs dict additional info to pass to get_url See Also -------- get_url : getJson : Returns ------- requests.models.Response the response that was given ''' url = self.get_url(path, **query) for i in range(self.tries+1): try: resp = await self.session.get(url, timeout=self.timeout) if await self._process_resp(resp): return resp else: continue except aiohttp.ClientConnectionError: if i >= self.tries: raise aiohttp.ClientConnectionError( 'Emby server is probably down' ) async def delete(self, path, **query): '''send a delete request Parameters ---------- path : str same as get_url query : kargs dict additional info to pass to get_url See Also -------- get_url : Returns ------- requests.models.Response the response that was given ''' url = self.get_url(path, **query) for i in range(self.tries+1): try: resp = await self.session.delete(url, timeout=self.timeout) if await self._process_resp(resp): return resp else: continue except aiohttp.ClientConnectionError: if i >= self.tries: raise aiohttp.ClientConnectionError( 'Emby server is probably down' ) async def post(self, path, data={}, send_raw=False, **params): '''sends post request Parameters ---------- path : str same as get_url query : kargs dict additional info to pass to get_url See Also -------- get_url : Returns ------- requests.models.Response the response that was given ''' url = self.get_url(path, **params) jstr = json.dumps(data) for i in range(self.tries+1): try: if send_raw: resp = await self.session.post(url, data=data, timeout=self.timeout) else: resp = await self.session.post(url, data=jstr, timeout=self.timeout) if await self._process_resp(resp): return resp else: continue except aiohttp.ClientConnectionError: if i >= self.tries: raise aiohttp.ClientConnectionError( 'Emby server is probably down' ) async def getJson(self, path, **query): '''wrapper for get, parses response as json Parameters ---------- path : str same as get_url query : kargs dict additional info to pass to get_url See Also -------- get_url : get : Returns ------- dict the response content as a dict ''' for i in range(self.tries+1): try: return await (await self.get(path, **query)).json() except: if i >= self.tries: raise
andy29485/embypy
embypy/utils/connector.py
Connector.get
python
async def get(self, path, **query): '''return a get request Parameters ---------- path : str same as get_url query : kargs dict additional info to pass to get_url See Also -------- get_url : getJson : Returns ------- requests.models.Response the response that was given ''' url = self.get_url(path, **query) for i in range(self.tries+1): try: resp = await self.session.get(url, timeout=self.timeout) if await self._process_resp(resp): return resp else: continue except aiohttp.ClientConnectionError: if i >= self.tries: raise aiohttp.ClientConnectionError( 'Emby server is probably down' )
return a get request Parameters ---------- path : str same as get_url query : kargs dict additional info to pass to get_url See Also -------- get_url : getJson : Returns ------- requests.models.Response the response that was given
train
https://github.com/andy29485/embypy/blob/cde658d380965caaf4789d4d182d045b0346797b/embypy/utils/connector.py#L270-L303
[ "def get_url(self, path='/', websocket=False, remote=True,\n attach_api_key=True, userId=None, pass_uid=False, **query):\n '''construct a url for an emby request\n\n Parameters\n ----------\n path : str\n uri path(excluding domain and port) of get request for emby\n websocket : bool, optional\n ...
class Connector: '''Class responsible for comunication with emby Parameters ---------- url : str url to connect to api-key : str api key generated by emby, used for authentication token : str similar to api key, but is meant for user logins address-remote : str, optional alt url to connect to, pulic facing (see notes) ssl : str, optional path to ssl certificate - for self signed certs userid : str, optional emby id of the user you wish to connect as username : str, optional username for login (see notes) password : str, optional password for login (see notes) device_id : str device id as registered in emby timeout : int number of seconds to wait before timeout for a request tries : int number of times to try a request before throwing an error loop : asyncio.AbstractEventLoop if given all calls should be awaitable Notes ----- This class/object should NOT be used (except internally). Tf a address-remote url is given, then that will be used for output, such as the `embypy.objects.EmbyObject.url` atribute. `url` will always be used when making requests - thus I recomend using the local address for `url` and the remote address for `address-remote` username/password authentication is not supported as of yet ''' def __init__(self, url, **kargs): if ('api_key' not in kargs or 'device_id' not in kargs) and \ ('username' not in kargs or 'password' not in kargs): raise ValueError('provide api key and device id or username/password') urlremote = kargs.get('address-remote') self.ssl = kargs.get('ssl', True) self.userid = kargs.get('userid') self.token = kargs.get('token') self.api_key = kargs.get('api_key', self.token) self.username = kargs.get('username') self.password = kargs.get('password') self.device_id = kargs.get('device_id', 'EmbyPy') self.timeout = kargs.get('timeout', 30) self.tries = kargs.get('tries', 3) self.loop = kargs.get('loop', asyncio.get_event_loop()) self.url = urlparse(url) self.urlremote = urlparse(urlremote) if urlremote else urlremote if self.ssl and type(self.ssl) == str: self.ssl = ssl.SSLContext(ssl.PROTOCOL_SSLv23) self.ssl.load_verify_locations(cafile=self.ssl) conn = aiohttp.TCPConnector(ssl_context=self.ssl) self.session = aiohttp.ClientSession( headers={ 'Authorization': 'MediaBrowser Client="{0}",Device="{0}",DeviceId="{1}",Version="{2}"' .format('EmbyPy', self.device_id, __version__) }, connector=conn ) #connect to websocket is user wants to if 'ws' in kargs: self.ws = WebSocket(self, self.get_url(websocket=True), self.ssl) else: self.ws = None # authenticate to emby if password was given if self.password and self.username and not self.token: self.login_sync() def __del__(self): try: Connector.sync_run(self.session.close()) except: self.loop.run_until_complete(self.session.close()) @staticmethod def sync_run(f): if asyncio.iscoroutinefunction(f): f = f() if asyncio.iscoroutine(f): return asyncio.get_event_loop().run_until_complete(f) elif callable(f): return f() else: return f def get_sync(self, *args, **kargs): return self.sync_run(self.get(*args, **kargs)) def delete_sync(self, *args, **kargs): return self.sync_run(self.delete(*args, **kargs)) def post_sync(self, *args, **kargs): return self.sync_run(self.post(*args, **kargs)) def getJson_sync(self, *args, **kargs): return self.sync_run(self.getJson(*args, **kargs)) def login_sync(self): return self.sync_run(self.login()) async def login(self): data = await self.post('/Users/AuthenticateByName', data={ 'username':self.username, 'pw':self.password, }, send_raw=True, format='json', ) data = await data.json() self.token = data.get('AccessToken', '') self.userid = data.get('User', {}).get('Id') self.api_key = self.token self.session._default_headers.update( {'X-MediaBrowser-Token': self.token} ) def get_url(self, path='/', websocket=False, remote=True, attach_api_key=True, userId=None, pass_uid=False, **query): '''construct a url for an emby request Parameters ---------- path : str uri path(excluding domain and port) of get request for emby websocket : bool, optional if true, then `ws(s)` are used instead of `http(s)` remote : bool, optional if true, remote-address is used (default True) attach_api_key : bool, optional if true, apikey is added to the query (default True) userId : str, optional uid to use, if none, default is used pass_uid : bool, optional if true, uid is added to the query (default False) query : karg dict additional parameters to set (part of url after the `?`) Also See -------- get : getJson : post : delete : Returns ------- full url ''' userId = userId or self.userid if attach_api_key and self.api_key: query.update({'api_key':self.api_key, 'deviceId': self.device_id}) if pass_uid: query['userId'] = userId if remote: url = self.urlremote or self.url else: url = self.url if websocket: scheme = {'http':'ws', 'https':'wss'}[url.scheme] else: scheme = url.scheme netloc = url.netloc + '/emby' url = urlunparse((scheme, netloc, path, '', '{params}', '')).format( UserId = userId, ApiKey = self.api_key, DeviceId = self.device_id, params = urlencode(query) ) return url[:-1] if url[-1] == '?' else url async def _process_resp(self, resp): if (not resp or resp.status == 401) and self.username: await self.login() await resp.close() return False return True def add_on_message(self, func): '''add function that handles websocket messages''' return self.ws.on_message.append(func) async def delete(self, path, **query): '''send a delete request Parameters ---------- path : str same as get_url query : kargs dict additional info to pass to get_url See Also -------- get_url : Returns ------- requests.models.Response the response that was given ''' url = self.get_url(path, **query) for i in range(self.tries+1): try: resp = await self.session.delete(url, timeout=self.timeout) if await self._process_resp(resp): return resp else: continue except aiohttp.ClientConnectionError: if i >= self.tries: raise aiohttp.ClientConnectionError( 'Emby server is probably down' ) async def post(self, path, data={}, send_raw=False, **params): '''sends post request Parameters ---------- path : str same as get_url query : kargs dict additional info to pass to get_url See Also -------- get_url : Returns ------- requests.models.Response the response that was given ''' url = self.get_url(path, **params) jstr = json.dumps(data) for i in range(self.tries+1): try: if send_raw: resp = await self.session.post(url, data=data, timeout=self.timeout) else: resp = await self.session.post(url, data=jstr, timeout=self.timeout) if await self._process_resp(resp): return resp else: continue except aiohttp.ClientConnectionError: if i >= self.tries: raise aiohttp.ClientConnectionError( 'Emby server is probably down' ) async def getJson(self, path, **query): '''wrapper for get, parses response as json Parameters ---------- path : str same as get_url query : kargs dict additional info to pass to get_url See Also -------- get_url : get : Returns ------- dict the response content as a dict ''' for i in range(self.tries+1): try: return await (await self.get(path, **query)).json() except: if i >= self.tries: raise