res.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. # -*- coding: UTF-8 -*-
  2. import glob
  3. import os
  4. import re
  5. from PIL import Image
  6. import io
  7. import base64
  8. import logging
  9. logger = logging.getLogger(__name__)
  10. import imghdr
  11. from multiprocessing import Pool
  12. import atexit
  13. import pickle
  14. import requests
  15. from .avatar import AvatarReader
  16. from common.textutil import md5, get_file_b64
  17. from common.timer import timing
  18. from .msg import TYPE_SPEAK
  19. from .audio import parse_wechat_audio_file
  20. LIB_PATH = os.path.dirname(os.path.abspath(__file__))
  21. INTERNAL_EMOJI_DIR = os.path.join(LIB_PATH, 'static', 'internal_emoji')
  22. VOICE_DIRNAME = 'voice2'
  23. IMG_DIRNAME = 'image2'
  24. EMOJI_DIRNAME = 'emoji'
  25. JPEG_QUALITY = 50
  26. class EmojiCache(object):
  27. def __init__(self, fname):
  28. self.fname = fname
  29. if os.path.isfile(fname):
  30. with open(fname, 'rb') as f:
  31. self.dic = pickle.load(f)
  32. else:
  33. self.dic = {}
  34. self._curr_size = len(self.dic)
  35. def query(self, md5):
  36. data, format = self.dic.get(md5, (None, None))
  37. if data is not None and not isinstance(data, str):
  38. data = data.decode('ascii')
  39. return data, format
  40. def fetch(self, md5, url):
  41. try:
  42. logger.info("Requesting emoji {} from {} ...".format(md5, url))
  43. r = requests.get(url).content
  44. im = Image.open(io.BytesIO(r))
  45. format = im.format.lower()
  46. ret = (base64.b64encode(r).decode('ascii'), format)
  47. self.dic[md5] = ret
  48. if len(self.dic) >= self._curr_size + 10:
  49. self.flush()
  50. return ret
  51. except Exception as e:
  52. logger.exception("Error processing emoji from {}".format(url))
  53. return None, None
  54. def flush(self):
  55. if len(self.dic) > self._curr_size:
  56. self._curr_size = len(self.dic)
  57. with open(self.fname, 'wb') as f:
  58. pickle.dump(self.dic, f)
  59. class Resource(object):
  60. """ multimedia resources in chat"""
  61. def __init__(self, parser, res_dir, avt_db):
  62. def check(subdir):
  63. assert os.path.isdir(os.path.join(res_dir, subdir)), \
  64. "No such directory: {}".format(subdir)
  65. [check(k) for k in ['', IMG_DIRNAME, EMOJI_DIRNAME, VOICE_DIRNAME]]
  66. self.emoji_cache = EmojiCache(
  67. os.path.join(os.path.dirname(os.path.abspath(__file__)),
  68. '..', 'emoji.cache'))
  69. self.res_dir = res_dir
  70. self.parser = parser
  71. self.voice_cache_idx = {}
  72. self.img_dir = os.path.join(res_dir, IMG_DIRNAME)
  73. self.voice_dir = os.path.join(res_dir, VOICE_DIRNAME)
  74. self.emoji_dir = os.path.join(res_dir, EMOJI_DIRNAME)
  75. self.avt_reader = AvatarReader(res_dir, avt_db)
  76. def get_voice_filename(self, imgpath):
  77. fname = md5(imgpath.encode('ascii'))
  78. dir1, dir2 = fname[:2], fname[2:4]
  79. ret = os.path.join(self.voice_dir, dir1, dir2,
  80. 'msg_{}.amr'.format(imgpath))
  81. if not os.path.isfile(ret):
  82. logger.error("Voice file not found for {}".format(imgpath))
  83. return ""
  84. return ret
  85. def get_voice_mp3(self, imgpath):
  86. """ return mp3 and duration, or empty string and 0 on failure"""
  87. idx = self.voice_cache_idx.get(imgpath)
  88. if idx is None:
  89. return parse_wechat_audio_file(
  90. self.get_voice_filename(imgpath))
  91. return self.voice_cache[idx].get()
  92. def cache_voice_mp3(self, msgs):
  93. """ for speed.
  94. msgs: a collection of WeChatMsg, to cache for later fetch"""
  95. voice_paths = [msg.imgPath for msg in msgs if msg.type == TYPE_SPEAK]
  96. # NOTE: remove all the caching code to debug serial decoding
  97. self.voice_cache_idx = {k: idx for idx, k in enumerate(voice_paths)}
  98. pool = Pool(3)
  99. atexit.register(lambda x: x.terminate(), pool)
  100. self.voice_cache = [pool.apply_async(parse_wechat_audio_file,
  101. (self.get_voice_filename(k),)) for k in voice_paths]
  102. def get_avatar(self, username):
  103. """ return base64 unicode string"""
  104. im = self.avt_reader.get_avatar(username)
  105. if im is None:
  106. return ""
  107. buf = io.BytesIO()
  108. try:
  109. im.save(buf, 'JPEG', quality=JPEG_QUALITY)
  110. except IOError:
  111. try:
  112. # sometimes it works the second time...
  113. im.save(buf, 'JPEG', quality=JPEG_QUALITY)
  114. except IOError:
  115. return ""
  116. jpeg_str = buf.getvalue()
  117. return base64.b64encode(jpeg_str).decode('ascii')
  118. def _get_img_file(self, fnames):
  119. """ fnames: a list of filename to search for
  120. return (filename, filename) of (big, small) image.
  121. could be empty string.
  122. """
  123. cands = []
  124. for fname in fnames:
  125. dir1, dir2 = fname[:2], fname[2:4]
  126. dirname = os.path.join(self.img_dir, dir1, dir2)
  127. if not os.path.isdir(dirname):
  128. logger.warn("Directory not found: {}".format(dirname))
  129. continue
  130. for f in os.listdir(dirname):
  131. if fname in f:
  132. full_name = os.path.join(dirname, f)
  133. size = os.path.getsize(full_name)
  134. if size > 0:
  135. cands.append((full_name, size))
  136. if not cands:
  137. return ("", "")
  138. cands = sorted(cands, key=lambda x: x[1])
  139. def name_is_thumbnail(name):
  140. return os.path.basename(name).startswith('th_') \
  141. and not name.endswith('hd')
  142. if len(cands) == 1:
  143. name = cands[0][0]
  144. if name_is_thumbnail(name):
  145. # thumbnail
  146. return ("", name)
  147. else:
  148. logger.warn("Found big image but not thumbnail: {}".format(fname))
  149. return (name, "")
  150. big = cands[-1]
  151. ths = list(filter(name_is_thumbnail, [k[0] for k in cands]))
  152. if not ths:
  153. return (big[0], "")
  154. return (big[0], ths[0])
  155. def get_img(self, fnames):
  156. """
  157. :params fnames: possible file paths
  158. :returns: two base64 jpg string
  159. """
  160. fnames = [k for k in fnames if k] # filter out empty string
  161. big_file, small_file = self._get_img_file(fnames)
  162. def get_jpg_b64(img_file):
  163. if not img_file:
  164. return None
  165. if not img_file.endswith('jpg') and \
  166. imghdr.what(img_file) != 'jpeg':
  167. im = Image.open(open(img_file, 'rb'))
  168. buf = io.BytesIO()
  169. im.convert('RGB').save(buf, 'JPEG', quality=JPEG_QUALITY)
  170. return base64.b64encode(buf.getvalue()).decode('ascii')
  171. return get_file_b64(img_file)
  172. big_file = get_jpg_b64(big_file)
  173. if big_file:
  174. return big_file
  175. return get_jpg_b64(small_file)
  176. def _get_res_emoji(self, md5, pack_id, allow_cover=False):
  177. """
  178. pack_id: can be None
  179. allow_cover: Cover is non-animated. Can be used as a fallback.
  180. """
  181. path = os.path.join(self.emoji_dir, pack_id or '')
  182. candidates = glob.glob(os.path.join(path, '{}*'.format(md5)))
  183. candidates = [k for k in candidates if not k.endswith('_thumb') \
  184. and not re.match('.*_[0-9]+$', k)]
  185. def try_use(f):
  186. if not f: return None
  187. if not imghdr.what(f[0]): # cannot recognize file type
  188. return None
  189. return f[0]
  190. candidates = [k for k in candidates if (allow_cover or not k.endswith('_cover'))]
  191. for cand in candidates:
  192. if imghdr.what(cand):
  193. return get_file_b64(cand), imghdr.what(cand)
  194. return None, None
  195. def _get_internal_emoji(self, fname):
  196. f = os.path.join(INTERNAL_EMOJI_DIR, fname)
  197. return get_file_b64(f), imghdr.what(f)
  198. def get_emoji_by_md5(self, md5):
  199. """ :returns: (b64 unicode img, format)"""
  200. assert md5, md5
  201. if md5 in self.parser.internal_emojis:
  202. # TODO this seems broken
  203. emoji_img, format = self._get_internal_emoji(self.parser.internal_emojis[md5])
  204. logger.warn("Cannot get emoji {}".format(md5))
  205. return None, None
  206. else:
  207. # check cache
  208. img, format = self.emoji_cache.query(md5)
  209. if format:
  210. return img, format
  211. # check resource/emoji/ dir
  212. group = self.parser.emoji_groups.get(md5, None)
  213. emoji_img, format = self._get_res_emoji(md5, group)
  214. if format:
  215. return emoji_img, format
  216. # check url
  217. url = self.parser.emoji_url.get(md5, None)
  218. if url:
  219. emoji_img, format = self.emoji_cache.fetch(md5, url)
  220. if format:
  221. return emoji_img, format
  222. # check resource/emoji dir again, for cover
  223. emoji_img, format = self._get_res_emoji(md5, group, allow_cover=True)
  224. if format:
  225. return emoji_img, format
  226. # first 1k in emoji is encrypted
  227. logger.warn("Cannot get emoji {} in {}".format(md5, group))
  228. return None, None