您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

750 行
20 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. # IMPORTANT: only import safe functions as this module will be included in jinja environment
  5. import frappe
  6. import operator
  7. import re, urllib, datetime, math
  8. import babel.dates
  9. from dateutil import parser
  10. from num2words import num2words
  11. import HTMLParser
  12. from html2text import html2text
  13. DATE_FORMAT = "%Y-%m-%d"
  14. TIME_FORMAT = "%H:%M:%S.%f"
  15. DATETIME_FORMAT = DATE_FORMAT + " " + TIME_FORMAT
  16. # datetime functions
  17. def getdate(string_date=None):
  18. """
  19. Coverts string date (yyyy-mm-dd) to datetime.date object
  20. """
  21. if not string_date:
  22. return get_datetime().date()
  23. if isinstance(string_date, datetime.datetime):
  24. return string_date.date()
  25. elif isinstance(string_date, datetime.date):
  26. return string_date
  27. # dateutil parser does not agree with dates like 0000-00-00
  28. if not string_date or string_date=="0000-00-00":
  29. return None
  30. return parser.parse(string_date).date()
  31. def get_datetime(datetime_str=None):
  32. if not datetime_str:
  33. return now_datetime()
  34. if isinstance(datetime_str, (datetime.datetime, datetime.timedelta)):
  35. return datetime_str
  36. elif isinstance(datetime_str, (list, tuple)):
  37. return datetime.datetime(datetime_str)
  38. elif isinstance(datetime_str, datetime.date):
  39. return datetime.datetime.combine(datetime_str, datetime.time())
  40. # dateutil parser does not agree with dates like 0000-00-00
  41. if not datetime_str or (datetime_str or "").startswith("0000-00-00"):
  42. return None
  43. return parser.parse(datetime_str)
  44. def to_timedelta(time_str):
  45. if isinstance(time_str, basestring):
  46. t = parser.parse(time_str)
  47. return datetime.timedelta(hours=t.hour, minutes=t.minute, seconds=t.second, microseconds=t.microsecond)
  48. else:
  49. return time_str
  50. def add_to_date(date, years=0, months=0, days=0):
  51. """Adds `days` to the given date"""
  52. from dateutil.relativedelta import relativedelta
  53. as_string, as_datetime = False, False
  54. if date==None:
  55. date = now_datetime()
  56. if isinstance(date, basestring):
  57. as_string = True
  58. if " " in date:
  59. as_datetime = True
  60. date = parser.parse(date)
  61. date = date + relativedelta(years=years, months=months, days=days)
  62. if as_string:
  63. if as_datetime:
  64. return date.strftime(DATETIME_FORMAT)
  65. else:
  66. return date.strftime(DATE_FORMAT)
  67. else:
  68. return date
  69. def add_days(date, days):
  70. return add_to_date(date, days=days)
  71. def add_months(date, months):
  72. return add_to_date(date, months=months)
  73. def add_years(date, years):
  74. return add_to_date(date, years=years)
  75. def date_diff(string_ed_date, string_st_date):
  76. return (getdate(string_ed_date) - getdate(string_st_date)).days
  77. def time_diff(string_ed_date, string_st_date):
  78. return get_datetime(string_ed_date) - get_datetime(string_st_date)
  79. def time_diff_in_seconds(string_ed_date, string_st_date):
  80. return time_diff(string_ed_date, string_st_date).total_seconds()
  81. def time_diff_in_hours(string_ed_date, string_st_date):
  82. return round(float(time_diff(string_ed_date, string_st_date).total_seconds()) / 3600, 6)
  83. def now_datetime():
  84. dt = convert_utc_to_user_timezone(datetime.datetime.utcnow())
  85. return dt.replace(tzinfo=None)
  86. def _get_time_zone():
  87. return frappe.db.get_system_setting('time_zone') or 'Asia/Kolkata'
  88. def get_time_zone():
  89. if frappe.local.flags.in_test:
  90. return _get_time_zone()
  91. return frappe.cache().get_value("time_zone", _get_time_zone)
  92. def convert_utc_to_user_timezone(utc_timestamp):
  93. from pytz import timezone, UnknownTimeZoneError
  94. utcnow = timezone('UTC').localize(utc_timestamp)
  95. try:
  96. return utcnow.astimezone(timezone(get_time_zone()))
  97. except UnknownTimeZoneError:
  98. return utcnow
  99. def now():
  100. """return current datetime as yyyy-mm-dd hh:mm:ss"""
  101. if getattr(frappe.local, "current_date", None):
  102. return getdate(frappe.local.current_date).strftime(DATE_FORMAT) + " " + \
  103. now_datetime().strftime(TIME_FORMAT)
  104. else:
  105. return now_datetime().strftime(DATETIME_FORMAT)
  106. def nowdate():
  107. """return current date as yyyy-mm-dd"""
  108. return now_datetime().strftime(DATE_FORMAT)
  109. def today():
  110. return nowdate()
  111. def nowtime():
  112. """return current time in hh:mm"""
  113. return now_datetime().strftime(TIME_FORMAT)
  114. def get_first_day(dt, d_years=0, d_months=0):
  115. """
  116. Returns the first day of the month for the date specified by date object
  117. Also adds `d_years` and `d_months` if specified
  118. """
  119. dt = getdate(dt)
  120. # d_years, d_months are "deltas" to apply to dt
  121. overflow_years, month = divmod(dt.month + d_months - 1, 12)
  122. year = dt.year + d_years + overflow_years
  123. return datetime.date(year, month + 1, 1)
  124. def get_last_day(dt):
  125. """
  126. Returns last day of the month using:
  127. `get_first_day(dt, 0, 1) + datetime.timedelta(-1)`
  128. """
  129. return get_first_day(dt, 0, 1) + datetime.timedelta(-1)
  130. def get_time(time_str):
  131. if isinstance(time_str, datetime.datetime):
  132. return time_str.time()
  133. elif isinstance(time_str, datetime.time):
  134. return time_str
  135. return parser.parse(time_str).time()
  136. def get_datetime_str(datetime_obj):
  137. if isinstance(datetime_obj, basestring):
  138. datetime_obj = get_datetime(datetime_obj)
  139. return datetime_obj.strftime(DATETIME_FORMAT)
  140. def get_user_format():
  141. if getattr(frappe.local, "user_format", None) is None:
  142. frappe.local.user_format = frappe.db.get_default("date_format")
  143. return frappe.local.user_format or "yyyy-mm-dd"
  144. def formatdate(string_date=None, format_string=None):
  145. """
  146. Convers the given string date to :data:`user_format`
  147. User format specified in defaults
  148. Examples:
  149. * dd-mm-yyyy
  150. * mm-dd-yyyy
  151. * dd/mm/yyyy
  152. """
  153. date = getdate(string_date) if string_date else now_datetime().date()
  154. if not format_string:
  155. format_string = get_user_format().replace("mm", "MM")
  156. return babel.dates.format_date(date, format_string, locale=(frappe.local.lang or "").replace("-", "_"))
  157. def format_time(txt):
  158. return babel.dates.format_time(get_time(txt), locale=(frappe.local.lang or "").replace("-", "_"))
  159. def format_datetime(datetime_string, format_string=None):
  160. if not datetime_string:
  161. return
  162. datetime = get_datetime(datetime_string)
  163. if not format_string:
  164. format_string = get_user_format().replace("mm", "MM") + " HH:mm:ss"
  165. return babel.dates.format_datetime(datetime, format_string, locale=(frappe.local.lang or "").replace("-", "_"))
  166. def global_date_format(date):
  167. """returns date as 1 January 2012"""
  168. formatted_date = getdate(date).strftime("%d %B %Y")
  169. return formatted_date.startswith("0") and formatted_date[1:] or formatted_date
  170. def has_common(l1, l2):
  171. """Returns truthy value if there are common elements in lists l1 and l2"""
  172. return set(l1) & set(l2)
  173. def flt(s, precision=None):
  174. """Convert to float (ignore commas)"""
  175. if isinstance(s, basestring):
  176. s = s.replace(',','')
  177. try:
  178. num = float(s)
  179. if precision is not None:
  180. num = rounded(num, precision)
  181. except Exception:
  182. num = 0
  183. return num
  184. def cint(s):
  185. """Convert to integer"""
  186. try: num = int(float(s))
  187. except: num = 0
  188. return num
  189. def cstr(s):
  190. if isinstance(s, unicode):
  191. return s
  192. elif s==None:
  193. return ''
  194. elif isinstance(s, basestring):
  195. return unicode(s, 'utf-8')
  196. else:
  197. return unicode(s)
  198. def rounded(num, precision=0):
  199. """round method for round halfs to nearest even algorithm aka banker's rounding - compatible with python3"""
  200. precision = cint(precision)
  201. multiplier = 10 ** precision
  202. # avoid rounding errors
  203. num = round(num * multiplier if precision else num, 8)
  204. floor = math.floor(num)
  205. decimal_part = num - floor
  206. if not precision and decimal_part == 0.5:
  207. num = floor if (floor % 2 == 0) else floor + 1
  208. else:
  209. num = round(num)
  210. return (num / multiplier) if precision else num
  211. def remainder(numerator, denominator, precision=2):
  212. precision = cint(precision)
  213. multiplier = 10 ** precision
  214. if precision:
  215. _remainder = ((numerator * multiplier) % (denominator * multiplier)) / multiplier
  216. else:
  217. _remainder = numerator % denominator
  218. return flt(_remainder, precision);
  219. def round_based_on_smallest_currency_fraction(value, currency, precision=2):
  220. smallest_currency_fraction_value = flt(frappe.db.get_value("Currency",
  221. currency, "smallest_currency_fraction_value"))
  222. if smallest_currency_fraction_value:
  223. remainder_val = remainder(value, smallest_currency_fraction_value, precision)
  224. if remainder_val > (smallest_currency_fraction_value / 2):
  225. value += smallest_currency_fraction_value - remainder_val
  226. else:
  227. value -= remainder_val
  228. else:
  229. value = rounded(value)
  230. return flt(value, precision)
  231. def encode(obj, encoding="utf-8"):
  232. if isinstance(obj, list):
  233. out = []
  234. for o in obj:
  235. if isinstance(o, unicode):
  236. out.append(o.encode(encoding))
  237. else:
  238. out.append(o)
  239. return out
  240. elif isinstance(obj, unicode):
  241. return obj.encode(encoding)
  242. else:
  243. return obj
  244. def parse_val(v):
  245. """Converts to simple datatypes from SQL query results"""
  246. if isinstance(v, (datetime.date, datetime.datetime)):
  247. v = unicode(v)
  248. elif isinstance(v, datetime.timedelta):
  249. v = ":".join(unicode(v).split(":")[:2])
  250. elif isinstance(v, long):
  251. v = int(v)
  252. return v
  253. def fmt_money(amount, precision=None, currency=None):
  254. """
  255. Convert to string with commas for thousands, millions etc
  256. """
  257. number_format = None
  258. if currency:
  259. number_format = frappe.db.get_value("Currency", currency, "number_format", cache=True)
  260. if not number_format:
  261. number_format = frappe.db.get_default("number_format") or "#,###.##"
  262. decimal_str, comma_str, number_format_precision = get_number_format_info(number_format)
  263. if precision is None:
  264. precision = number_format_precision
  265. amount = '%.*f' % (precision, flt(amount))
  266. if amount.find('.') == -1:
  267. decimals = ''
  268. else:
  269. decimals = amount.split('.')[1]
  270. parts = []
  271. minus = ''
  272. if flt(amount) < 0:
  273. minus = '-'
  274. amount = cstr(abs(flt(amount))).split('.')[0]
  275. if len(amount) > 3:
  276. parts.append(amount[-3:])
  277. amount = amount[:-3]
  278. val = number_format=="#,##,###.##" and 2 or 3
  279. while len(amount) > val:
  280. parts.append(amount[-val:])
  281. amount = amount[:-val]
  282. parts.append(amount)
  283. parts.reverse()
  284. amount = comma_str.join(parts) + ((precision and decimal_str) and (decimal_str + decimals) or "")
  285. amount = minus + amount
  286. if currency and frappe.defaults.get_global_default("hide_currency_symbol") != "Yes":
  287. symbol = frappe.db.get_value("Currency", currency, "symbol") or currency
  288. amount = symbol + " " + amount
  289. return amount
  290. number_format_info = {
  291. "#,###.##": (".", ",", 2),
  292. "#.###,##": (",", ".", 2),
  293. "# ###.##": (".", " ", 2),
  294. "# ###,##": (",", " ", 2),
  295. "#'###.##": (".", "'", 2),
  296. "#, ###.##": (".", ", ", 2),
  297. "#,##,###.##": (".", ",", 2),
  298. "#,###.###": (".", ",", 3),
  299. "#.###": ("", ".", 0),
  300. "#,###": ("", ",", 0)
  301. }
  302. def get_number_format_info(format):
  303. return number_format_info.get(format) or (".", ",", 2)
  304. #
  305. # convet currency to words
  306. #
  307. def money_in_words(number, main_currency = None, fraction_currency=None):
  308. """
  309. Returns string in words with currency and fraction currency.
  310. """
  311. from frappe.utils import get_defaults
  312. _ = frappe._
  313. if not number or flt(number) < 0:
  314. return ""
  315. d = get_defaults()
  316. if not main_currency:
  317. main_currency = d.get('currency', 'INR')
  318. if not fraction_currency:
  319. fraction_currency = frappe.db.get_value("Currency", main_currency, "fraction") or _("Cent")
  320. n = "%.2f" % flt(number)
  321. main, fraction = n.split('.')
  322. if len(fraction)==1: fraction += '0'
  323. number_format = frappe.db.get_value("Currency", main_currency, "number_format", cache=True) or \
  324. frappe.db.get_default("number_format") or "#,###.##"
  325. in_million = True
  326. if number_format == "#,##,###.##": in_million = False
  327. out = main_currency + ' ' + in_words(main, in_million).title()
  328. if cint(fraction):
  329. out = out + ' ' + _('and') + ' ' + in_words(fraction, in_million).title() + ' ' + fraction_currency
  330. return out + ' ' + _('only.')
  331. #
  332. # convert number to words
  333. #
  334. def in_words(integer, in_million=True):
  335. """
  336. Returns string in words for the given integer.
  337. """
  338. locale = 'en_IN' if not in_million else frappe.local.lang
  339. integer = int(integer)
  340. try:
  341. ret = num2words(integer, lang=locale)
  342. except NotImplementedError:
  343. ret = num2words(integer, lang='en')
  344. return ret.replace('-', ' ')
  345. def is_html(text):
  346. out = False
  347. for key in ["<br>", "<p", "<img", "<div"]:
  348. if key in text:
  349. out = True
  350. break
  351. return out
  352. # from Jinja2 code
  353. _striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
  354. def strip_html(text):
  355. """removes anything enclosed in and including <>"""
  356. return _striptags_re.sub("", text)
  357. def escape_html(text):
  358. html_escape_table = {
  359. "&": "&amp;",
  360. '"': "&quot;",
  361. "'": "&apos;",
  362. ">": "&gt;",
  363. "<": "&lt;",
  364. }
  365. return "".join(html_escape_table.get(c,c) for c in text)
  366. def pretty_date(iso_datetime):
  367. """
  368. Takes an ISO time and returns a string representing how
  369. long ago the date represents.
  370. Ported from PrettyDate by John Resig
  371. """
  372. if not iso_datetime: return ''
  373. import math
  374. if isinstance(iso_datetime, basestring):
  375. iso_datetime = datetime.datetime.strptime(iso_datetime, DATETIME_FORMAT)
  376. now_dt = datetime.datetime.strptime(now(), DATETIME_FORMAT)
  377. dt_diff = now_dt - iso_datetime
  378. # available only in python 2.7+
  379. # dt_diff_seconds = dt_diff.total_seconds()
  380. dt_diff_seconds = dt_diff.days * 86400.0 + dt_diff.seconds
  381. dt_diff_days = math.floor(dt_diff_seconds / 86400.0)
  382. # differnt cases
  383. if dt_diff_seconds < 60.0:
  384. return 'just now'
  385. elif dt_diff_seconds < 120.0:
  386. return '1 minute ago'
  387. elif dt_diff_seconds < 3600.0:
  388. return '%s minutes ago' % cint(math.floor(dt_diff_seconds / 60.0))
  389. elif dt_diff_seconds < 7200.0:
  390. return '1 hour ago'
  391. elif dt_diff_seconds < 86400.0:
  392. return '%s hours ago' % cint(math.floor(dt_diff_seconds / 3600.0))
  393. elif dt_diff_days == 1.0:
  394. return 'Yesterday'
  395. elif dt_diff_days < 7.0:
  396. return '%s days ago' % cint(dt_diff_days)
  397. elif dt_diff_days < 31.0:
  398. return '%s week(s) ago' % cint(math.ceil(dt_diff_days / 7.0))
  399. elif dt_diff_days < 365.0:
  400. return '%s months ago' % cint(math.ceil(dt_diff_days / 30.0))
  401. else:
  402. return 'more than %s year(s) ago' % cint(math.floor(dt_diff_days / 365.0))
  403. def comma_or(some_list):
  404. return comma_sep(some_list, frappe._("{0} or {1}"))
  405. def comma_and(some_list):
  406. return comma_sep(some_list, frappe._("{0} and {1}"))
  407. def comma_sep(some_list, pattern):
  408. if isinstance(some_list, (list, tuple)):
  409. # list(some_list) is done to preserve the existing list
  410. some_list = [unicode(s) for s in list(some_list)]
  411. if not some_list:
  412. return ""
  413. elif len(some_list) == 1:
  414. return some_list[0]
  415. else:
  416. some_list = ["'%s'" % s for s in some_list]
  417. return pattern.format(", ".join(frappe._(s) for s in some_list[:-1]), some_list[-1])
  418. else:
  419. return some_list
  420. def new_line_sep(some_list):
  421. if isinstance(some_list, (list, tuple)):
  422. # list(some_list) is done to preserve the existing list
  423. some_list = [unicode(s) for s in list(some_list)]
  424. if not some_list:
  425. return ""
  426. elif len(some_list) == 1:
  427. return some_list[0]
  428. else:
  429. some_list = ["%s" % s for s in some_list]
  430. return format("\n ".join(some_list))
  431. else:
  432. return some_list
  433. def filter_strip_join(some_list, sep):
  434. """given a list, filter None values, strip spaces and join"""
  435. return (cstr(sep)).join((cstr(a).strip() for a in filter(None, some_list)))
  436. def get_url(uri=None, full_address=False):
  437. """get app url from request"""
  438. host_name = frappe.local.conf.host_name or frappe.local.conf.hostname
  439. if uri and (uri.startswith("http://") or uri.startswith("https://")):
  440. return uri
  441. if not host_name:
  442. if hasattr(frappe.local, "request") and frappe.local.request and frappe.local.request.host:
  443. protocol = 'https' == frappe.get_request_header('X-Forwarded-Proto', "") and 'https://' or 'http://'
  444. host_name = protocol + frappe.local.request.host
  445. elif frappe.local.site:
  446. host_name = "http://{}".format(frappe.local.site)
  447. else:
  448. host_name = frappe.db.get_value("Website Settings", "Website Settings",
  449. "subdomain")
  450. if host_name and "http" not in host_name:
  451. host_name = "http://" + host_name
  452. if not host_name:
  453. host_name = "http://localhost"
  454. if not uri and full_address:
  455. uri = frappe.get_request_header("REQUEST_URI", "")
  456. url = urllib.basejoin(host_name, uri) if uri else host_name
  457. return url
  458. def get_host_name():
  459. return get_url().rsplit("//", 1)[-1]
  460. def get_link_to_form(doctype, name, label=None):
  461. if not label: label = name
  462. return """<a href="{0}">{1}</a>""".format(get_url_to_form(doctype, name), label)
  463. def get_url_to_form(doctype, name):
  464. return get_url(uri = "desk#Form/{0}/{1}".format(quoted(doctype), quoted(name)))
  465. def get_url_to_list(doctype):
  466. return get_url(uri = "desk#List/{0}".format(quoted(doctype)))
  467. operator_map = {
  468. # startswith
  469. "^": lambda (a, b): (a or "").startswith(b),
  470. # in or not in a list
  471. "in": lambda (a, b): operator.contains(b, a),
  472. "not in": lambda (a, b): not operator.contains(b, a),
  473. # comparison operators
  474. "=": lambda (a, b): operator.eq(a, b),
  475. "!=": lambda (a, b): operator.ne(a, b),
  476. ">": lambda (a, b): operator.gt(a, b),
  477. "<": lambda (a, b): operator.lt(a, b),
  478. ">=": lambda (a, b): operator.ge(a, b),
  479. "<=": lambda (a, b): operator.le(a, b),
  480. "not None": lambda (a, b): a and True or False,
  481. "None": lambda (a, b): (not a) and True or False
  482. }
  483. def evaluate_filters(doc, filters):
  484. '''Returns true if doc matches filters'''
  485. if isinstance(filters, dict):
  486. for key, value in filters.iteritems():
  487. f = get_filter(None, {key:value})
  488. if not compare(doc.get(f.fieldname), f.operator, f.value):
  489. return False
  490. elif isinstance(filters, (list, tuple)):
  491. for d in filters:
  492. f = get_filter(None, d)
  493. if not compare(doc.get(f.fieldname), f.operator, f.value):
  494. return False
  495. return True
  496. def compare(val1, condition, val2):
  497. ret = False
  498. if condition in operator_map:
  499. ret = operator_map[condition]((val1, val2))
  500. return ret
  501. def get_filter(doctype, f):
  502. """Returns a _dict like
  503. {
  504. "doctype":
  505. "fieldname":
  506. "operator":
  507. "value":
  508. }
  509. """
  510. from frappe.model import default_fields, optional_fields
  511. if isinstance(f, dict):
  512. key, value = f.items()[0]
  513. f = make_filter_tuple(doctype, key, value)
  514. if not isinstance(f, (list, tuple)):
  515. frappe.throw("Filter must be a tuple or list (in a list)")
  516. if len(f) == 3:
  517. f = (doctype, f[0], f[1], f[2])
  518. elif len(f) != 4:
  519. frappe.throw("Filter must have 4 values (doctype, fieldname, operator, value): {0}".format(str(f)))
  520. f = frappe._dict(doctype=f[0], fieldname=f[1], operator=f[2], value=f[3])
  521. if not f.operator:
  522. # if operator is missing
  523. f.operator = "="
  524. valid_operators = ("=", "!=", ">", "<", ">=", "<=", "like", "not like", "in", "not in")
  525. if f.operator not in valid_operators:
  526. frappe.throw("Operator must be one of {0}".format(", ".join(valid_operators)))
  527. if f.doctype and (f.fieldname not in default_fields + optional_fields):
  528. # verify fieldname belongs to the doctype
  529. meta = frappe.get_meta(f.doctype)
  530. if not meta.has_field(f.fieldname):
  531. # try and match the doctype name from child tables
  532. for df in meta.get_table_fields():
  533. if frappe.get_meta(df.options).has_field(f.fieldname):
  534. f.doctype = df.options
  535. break
  536. return f
  537. def make_filter_tuple(doctype, key, value):
  538. '''return a filter tuple like [doctype, key, operator, value]'''
  539. if isinstance(value, (list, tuple)):
  540. return [doctype, key, value[0], value[1]]
  541. else:
  542. return [doctype, key, "=", value]
  543. def scrub_urls(html):
  544. html = expand_relative_urls(html)
  545. # encoding should be responsibility of the composer
  546. # html = quote_urls(html)
  547. return html
  548. def expand_relative_urls(html):
  549. # expand relative urls
  550. url = get_url()
  551. if url.endswith("/"): url = url[:-1]
  552. def _expand_relative_urls(match):
  553. to_expand = list(match.groups())
  554. if not to_expand[2].startswith("/"):
  555. to_expand[2] = "/" + to_expand[2]
  556. to_expand.insert(2, url)
  557. return "".join(to_expand)
  558. return re.sub('(href|src){1}([\s]*=[\s]*[\'"]?)((?!http)[^\'" >]+)([\'"]?)', _expand_relative_urls, html)
  559. def quoted(url):
  560. return cstr(urllib.quote(encode(url), safe=b"~@#$&()*!+=:;,.?/'"))
  561. def quote_urls(html):
  562. def _quote_url(match):
  563. groups = list(match.groups())
  564. groups[2] = quoted(groups[2])
  565. return "".join(groups)
  566. return re.sub('(href|src){1}([\s]*=[\s]*[\'"]?)((?:http)[^\'">]+)([\'"]?)',
  567. _quote_url, html)
  568. def unique(seq):
  569. """use this instead of list(set()) to preserve order of the original list.
  570. Thanks to Stackoverflow: http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order"""
  571. seen = set()
  572. seen_add = seen.add
  573. return [ x for x in seq if not (x in seen or seen_add(x)) ]
  574. def strip(val, chars=None):
  575. # \ufeff is no-width-break, \u200b is no-width-space
  576. return (val or "").replace("\ufeff", "").replace("\u200b", "").strip(chars)
  577. def to_markdown(html):
  578. text = None
  579. try:
  580. text = html2text(html)
  581. except HTMLParser.HTMLParseError:
  582. pass
  583. return text