plottool.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. # coding: utf-8
  2. import re
  3. import StringIO
  4. import uuid
  5. import logging
  6. import zipfile,os
  7. import tempfile
  8. import matplotlib as mpl
  9. mpl.use('Agg')
  10. mpl.rcParams['font.family'] = ['SimHei', 'sans-serif']
  11. import matplotlib.pyplot as plt
  12. import matplotlib.table as tb
  13. #from utils.upload_to_oss import hnoss
  14. def get_zipfile(files):
  15. """
  16. """
  17. path = os.path.split(files[0])[0]
  18. temp = tempfile.TemporaryFile()
  19. archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
  20. for f in files:
  21. fname = os.path.split(f)[-1]
  22. archive.write(f,fname)
  23. os.remove(f)
  24. archive.close()
  25. temp.seek(0)
  26. return temp
  27. def plot_records_as_table_and_convert_to_png(
  28. (nrows, ncols),
  29. data,
  30. col_headers=None,
  31. title=None,localfile=None):
  32. """
  33. visual records
  34. """
  35. fig_width = ncols
  36. h_offset = t_offset = 0
  37. if col_headers:
  38. h_offset = 1
  39. if title:
  40. t_offset = 1
  41. offset = h_offset + t_offset
  42. fig_height = offset * 2
  43. table_data = []
  44. row_heights_mul = []
  45. for i in data:
  46. t = [j for j in i]
  47. t[-1] = re.sub(',', '\n', t[-1])
  48. t[-2] = re.sub(',', '\n', t[-2])
  49. nlines = max(t[-1].count('\n'), t[-2].count('\n'))
  50. row_heights_mul.append(nlines + 2)
  51. fig_height += (nlines + 2)
  52. table_data.append(t)
  53. fig = plt.figure(figsize=(fig_width, float(fig_height)/5))
  54. ax = fig.add_axes([0, 0, 1, 1])
  55. ax.axis('off')
  56. table = tb.Table(ax, bbox=[0, 0, 1, 1])
  57. table.auto_set_font_size(False)
  58. widths = [0.05, 0.15, 0.1, 0.1, 0.1, 0.1, 0.2, 0.2]
  59. height = table._approx_text_height()
  60. if title:
  61. for i in range(ncols):
  62. table.add_cell(0, i, width=widths[i], height=height * 4, edgecolor='red', facecolor='red', loc='right')
  63. table[0, 6].get_text().set_text(title)
  64. table[0, 6].set_fontsize(25)
  65. table[0, 6].set_text_props(weight='bold')
  66. table[0, 6].get_text().set_color('yellow')
  67. if col_headers:
  68. for i in range(ncols):
  69. table.add_cell(t_offset, i, width=widths[i], height=height * 2, facecolor='yellow', text=col_headers[i], loc='center')
  70. table[t_offset, i].set_fontsize(12)
  71. table[t_offset, i].set_edgecolor('grey')
  72. for i in range(nrows):
  73. for j in range(ncols):
  74. table.add_cell(i + offset, j, width=widths[j], height=height*row_heights_mul[i], text=table_data[i][j], loc='center')
  75. table[i + offset, j].set_fontsize(14)
  76. table[i + offset, j].set_edgecolor('grey')
  77. if not table_data[i][5].startswith('-'):
  78. table[i + offset, j].get_text().set_color('red')
  79. ax.add_table(table)
  80. if localfile:
  81. plt.savefig(localfile, format='png')
  82. return localfile
  83. else:
  84. buf = StringIO.StringIO()
  85. plt.savefig(buf, format='png')
  86. return buf.getvalue()
  87. def plot_records(data, col_headers, title, prefix):
  88. nrows = len(data)
  89. if nrows == 0:
  90. return
  91. ncols = len(col_headers) if col_headers else len(data[0])
  92. ret = []
  93. files = []
  94. start = 0
  95. step = 120
  96. while True:
  97. if start==0 and ('百万组' in title or '十万组' in title or '菜鸟组' in title ):
  98. step = 10
  99. else:
  100. step = 120
  101. part = data[start: start + step]
  102. part_nrows = len(part)
  103. filename = u'/tmp/{}-{}.png'.format(title.split('-')[1], start)
  104. if start == 0:
  105. png_bytes = plot_records_as_table_and_convert_to_png(
  106. (part_nrows, ncols),
  107. part,
  108. col_headers,
  109. title,filename)
  110. else:
  111. png_bytes = plot_records_as_table_and_convert_to_png(
  112. (part_nrows, ncols),
  113. part,None,None,filename)
  114. logging.error(filename)
  115. files.append(filename)
  116. #image_url = hnoss.upload_from_str(
  117. # png_bytes,
  118. # '{}_{}.png'.format(prefix, uuid.uuid4().hex),
  119. # False)
  120. #ret.append({'filename': filename, 'image_url': image_url})
  121. start += step
  122. if start >= nrows:
  123. break
  124. zpfile = get_zipfile(files)
  125. return zpfile