plottool.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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, edgecolor='grey', facecolor='yellow', text=col_headers[i], loc='center')
  70. table[t_offset, i].set_fontsize(12)
  71. for i in range(nrows):
  72. for j in range(ncols):
  73. table.add_cell(i + offset, j, width=widths[j], height=height*row_heights_mul[i], edgecolor='grey', text=table_data[i][j], loc='center')
  74. table[i + offset, j].set_fontsize(14)
  75. if not table_data[i][5].startswith('-'):
  76. table[i + offset, j].get_text().set_color('red')
  77. ax.add_table(table)
  78. if localfile:
  79. plt.savefig(localfile, format='png')
  80. return localfile
  81. else:
  82. buf = StringIO.StringIO()
  83. plt.savefig(buf, format='png')
  84. return buf.getvalue()
  85. def plot_records(data, col_headers, title, prefix):
  86. nrows = len(data)
  87. if nrows == 0:
  88. return
  89. ncols = len(col_headers) if col_headers else len(data[0])
  90. ret = []
  91. files = []
  92. start = 0
  93. step = 120
  94. i = 1
  95. while True:
  96. if start==0 and ('百万组' in title or '十万组' in title or '菜鸟组' in title ):
  97. step = 10
  98. else:
  99. step = 120
  100. part = data[start: start + step]
  101. part_nrows = len(part)
  102. filename = u'/tmp/{}{}.png'.format(title.split('-')[1][:3], i)
  103. if start == 0:
  104. png_bytes = plot_records_as_table_and_convert_to_png(
  105. (part_nrows, ncols),
  106. part,
  107. col_headers,
  108. title,filename)
  109. else:
  110. png_bytes = plot_records_as_table_and_convert_to_png(
  111. (part_nrows, ncols),
  112. part,None,None,filename)
  113. logging.error(filename)
  114. files.append(filename)
  115. #image_url = hnoss.upload_from_str(
  116. # png_bytes,
  117. # '{}_{}.png'.format(prefix, uuid.uuid4().hex),
  118. # False)
  119. #ret.append({'filename': filename, 'image_url': image_url})
  120. start += step
  121. i = i+1
  122. if start >= nrows:
  123. break
  124. zpfile = get_zipfile(files)
  125. return zpfile