labours.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. import argparse
  2. from datetime import datetime, timedelta
  3. import io
  4. import os
  5. import re
  6. import sys
  7. import tempfile
  8. import threading
  9. import time
  10. import warnings
  11. try:
  12. from clint.textui import progress
  13. except ImportError:
  14. print("Warning: clint is not installed, no fancy progressbars in the terminal for you.")
  15. progress = None
  16. import numpy
  17. import yaml
  18. if sys.version_info[0] < 3:
  19. # OK, ancients, I will support Python 2, but you owe me a beer
  20. input = raw_input
  21. def parse_args():
  22. parser = argparse.ArgumentParser()
  23. parser.add_argument("-o", "--output", default="",
  24. help="Path to the output file/directory (empty for display).")
  25. parser.add_argument("-i", "--input", default="-",
  26. help="Path to the input file (- for stdin).")
  27. parser.add_argument("--text-size", default=12, type=int,
  28. help="Size of the labels and legend.")
  29. parser.add_argument("--backend", help="Matplotlib backend to use.")
  30. parser.add_argument("--style", choices=["black", "white"], default="black",
  31. help="Plot's general color scheme.")
  32. parser.add_argument("--relative", action="store_true",
  33. help="Occupy 100%% height for every measurement.")
  34. parser.add_argument("--couples-tmp-dir", help="Temporary directory to work with couples.")
  35. parser.add_argument("-m", "--mode",
  36. choices=["project", "file", "person", "churn_matrix", "people", "couples",
  37. "all"],
  38. default="project", help="What to plot.")
  39. parser.add_argument(
  40. "--resample", default="year",
  41. help="The way to resample the time series. Possible values are: "
  42. "\"month\", \"year\", \"no\", \"raw\" and pandas offset aliases ("
  43. "http://pandas.pydata.org/pandas-docs/stable/timeseries.html"
  44. "#offset-aliases).")
  45. parser.add_argument("--disable-projector", action="store_true",
  46. help="Do not run Tensorflow Projector on couples.")
  47. parser.add_argument("--max-people", default=20, type=int,
  48. help="Maximum number of developers in churn matrix and people plots.")
  49. args = parser.parse_args()
  50. return args
  51. def read_input(args):
  52. sys.stdout.write("Reading the input... ")
  53. sys.stdout.flush()
  54. yaml.reader.Reader.NON_PRINTABLE = re.compile(r"(?!x)x")
  55. try:
  56. loader = yaml.CLoader
  57. except AttributeError:
  58. print("Warning: failed to import yaml.CLoader, falling back to slow yaml.Loader")
  59. loader = yaml.Loader
  60. try:
  61. if args.input != "-":
  62. with open(args.input) as fin:
  63. data = yaml.load(fin, Loader=loader)
  64. else:
  65. data = yaml.load(sys.stdin, Loader=loader)
  66. except (UnicodeEncodeError, yaml.reader.ReaderError) as e:
  67. print("\nInvalid unicode in the input: %s\nPlease filter it through fix_yaml_unicode.py" %
  68. e)
  69. sys.exit(1)
  70. print("done")
  71. return data["burndown"], data["project"], data.get("files"), data.get("people_sequence"), \
  72. data.get("people"), data.get("people_interaction"), data.get("files_coocc"), \
  73. data.get("people_coocc")
  74. def calculate_average_lifetime(matrix):
  75. lifetimes = numpy.zeros(matrix.shape[1] - 1)
  76. for band in matrix:
  77. start = 0
  78. for i, line in enumerate(band):
  79. if i == 0 or band[i - 1] == 0:
  80. start += 1
  81. continue
  82. lifetimes[i - start] = band[i - 1] - line
  83. lifetimes[i - start] = band[i - 1]
  84. return (lifetimes.dot(numpy.arange(1, matrix.shape[1], 1))
  85. / (lifetimes.sum() * matrix.shape[1]))
  86. def load_main(header, name, matrix, resample):
  87. import pandas
  88. start = header["begin"]
  89. last = header["end"]
  90. granularity = header["granularity"]
  91. sampling = header["sampling"]
  92. start = datetime.fromtimestamp(int(start))
  93. last = datetime.fromtimestamp(int(last))
  94. granularity = int(granularity)
  95. sampling = int(sampling)
  96. matrix = numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  97. for line in matrix.split("\n")]).T
  98. print(name, "lifetime index:", calculate_average_lifetime(matrix))
  99. finish = start + timedelta(days=matrix.shape[1] * sampling)
  100. if resample not in ("no", "raw"):
  101. # Interpolate the day x day matrix.
  102. # Each day brings equal weight in the granularity.
  103. # Sampling's interpolation is linear.
  104. daily_matrix = numpy.zeros(
  105. (matrix.shape[0] * granularity, matrix.shape[1] * sampling),
  106. dtype=numpy.float32)
  107. epsrange = numpy.arange(0, 1, 1.0 / sampling)
  108. for y in range(matrix.shape[0]):
  109. for x in range(matrix.shape[1]):
  110. previous = matrix[y, x - 1] if x > 0 else 0
  111. value = ((previous + (matrix[y, x] - previous) * epsrange)
  112. / granularity)[numpy.newaxis, :]
  113. if (y + 1) * granularity <= x * sampling:
  114. daily_matrix[y * granularity:(y + 1) * granularity,
  115. x * sampling:(x + 1) * sampling] = value
  116. elif y * granularity <= (x + 1) * sampling:
  117. for suby in range(y * granularity, (y + 1) * granularity):
  118. for subx in range(suby, (x + 1) * sampling):
  119. daily_matrix[suby, subx] = matrix[
  120. y, x] / granularity
  121. daily_matrix[(last - start).days:] = 0
  122. # Resample the bands
  123. aliases = {
  124. "year": "A",
  125. "month": "M"
  126. }
  127. resample = aliases.get(resample, resample)
  128. periods = 0
  129. date_granularity_sampling = [start]
  130. while date_granularity_sampling[-1] < finish:
  131. periods += 1
  132. date_granularity_sampling = pandas.date_range(
  133. start, periods=periods, freq=resample)
  134. date_range_sampling = pandas.date_range(
  135. date_granularity_sampling[0],
  136. periods=(finish - date_granularity_sampling[0]).days,
  137. freq="1D")
  138. # Fill the new square matrix
  139. matrix = numpy.zeros(
  140. (len(date_granularity_sampling), len(date_range_sampling)),
  141. dtype=numpy.float32)
  142. for i, gdt in enumerate(date_granularity_sampling):
  143. istart = (date_granularity_sampling[i - 1] - start).days \
  144. if i > 0 else 0
  145. ifinish = (gdt - start).days
  146. for j, sdt in enumerate(date_range_sampling):
  147. if (sdt - start).days >= istart:
  148. break
  149. matrix[i, j:] = \
  150. daily_matrix[istart:ifinish, (sdt - start).days:].sum(axis=0)
  151. # Hardcode some cases to improve labels" readability
  152. if resample in ("year", "A"):
  153. labels = [dt.year for dt in date_granularity_sampling]
  154. elif resample in ("month", "M"):
  155. labels = [dt.strftime("%Y %B") for dt in date_granularity_sampling]
  156. else:
  157. labels = [dt.date() for dt in date_granularity_sampling]
  158. else:
  159. labels = [
  160. "%s - %s" % ((start + timedelta(days=i * granularity)).date(),
  161. (
  162. start + timedelta(days=(i + 1) * granularity)).date())
  163. for i in range(matrix.shape[0])]
  164. if len(labels) > 18:
  165. warnings.warn("Too many labels - consider resampling.")
  166. resample = "M" # fake resampling type is checked while plotting
  167. date_range_sampling = pandas.date_range(
  168. start + timedelta(days=sampling), periods=matrix.shape[1],
  169. freq="%dD" % sampling)
  170. return name, matrix, date_range_sampling, labels, granularity, sampling, resample
  171. def load_churn_matrix(contents):
  172. matrix = numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  173. for line in contents.split("\n")])
  174. return matrix
  175. def load_people(header, sequence, contents):
  176. import pandas
  177. start = header["begin"]
  178. last = header["end"]
  179. sampling = header["sampling"]
  180. start = datetime.fromtimestamp(int(start))
  181. last = datetime.fromtimestamp(int(last))
  182. sampling = int(sampling)
  183. people = []
  184. for name in sequence:
  185. people.append(numpy.array([numpy.fromstring(line, dtype=int, sep=" ")
  186. for line in contents[name].split("\n")]).sum(axis=1))
  187. people = numpy.array(people)
  188. date_range_sampling = pandas.date_range(
  189. start + timedelta(days=sampling), periods=people[0].shape[0],
  190. freq="%dD" % sampling)
  191. return sequence, people, date_range_sampling, last
  192. def apply_plot_style(figure, axes, legend, style, text_size):
  193. figure.set_size_inches(12, 9)
  194. for side in ("bottom", "top", "left", "right"):
  195. axes.spines[side].set_color(style)
  196. for axis in (axes.xaxis, axes.yaxis):
  197. axis.label.update(dict(fontsize=text_size, color=style))
  198. for axis in ("x", "y"):
  199. axes.tick_params(axis=axis, colors=style, labelsize=text_size)
  200. if legend is not None:
  201. frame = legend.get_frame()
  202. for setter in (frame.set_facecolor, frame.set_edgecolor):
  203. setter("black" if style == "white" else "white")
  204. for text in legend.get_texts():
  205. text.set_color(style)
  206. def get_plot_path(base, name):
  207. root, ext = os.path.splitext(base)
  208. if not ext:
  209. ext = ".png"
  210. output = os.path.join(root, name + ext)
  211. os.makedirs(os.path.dirname(output), exist_ok=True)
  212. return output
  213. def deploy_plot(title, output, style):
  214. import matplotlib.pyplot as pyplot
  215. if not output:
  216. pyplot.gcf().canvas.set_window_title(title)
  217. pyplot.show()
  218. else:
  219. if title:
  220. pyplot.title(title, color=style)
  221. try:
  222. pyplot.tight_layout()
  223. except:
  224. print("Warning: failed to set the tight layout")
  225. pyplot.savefig(output, transparent=True)
  226. pyplot.clf()
  227. def plot_burndown(args, target, name, matrix, date_range_sampling, labels, granularity,
  228. sampling, resample):
  229. import matplotlib
  230. if args.backend:
  231. matplotlib.use(args.backend)
  232. import matplotlib.pyplot as pyplot
  233. pyplot.stackplot(date_range_sampling, matrix, labels=labels)
  234. if args.relative:
  235. for i in range(matrix.shape[1]):
  236. matrix[:, i] /= matrix[:, i].sum()
  237. pyplot.ylim(0, 1)
  238. legend_loc = 3
  239. else:
  240. legend_loc = 2
  241. legend = pyplot.legend(loc=legend_loc, fontsize=args.text_size)
  242. pyplot.ylabel("Lines of code")
  243. pyplot.xlabel("Time")
  244. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.style, args.text_size)
  245. pyplot.xlim(date_range_sampling[0], date_range_sampling[-1])
  246. locator = pyplot.gca().xaxis.get_major_locator()
  247. # set the optimal xticks locator
  248. if "M" not in resample:
  249. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  250. locs = pyplot.gca().get_xticks().tolist()
  251. if len(locs) >= 16:
  252. pyplot.gca().xaxis.set_major_locator(matplotlib.dates.YearLocator())
  253. locs = pyplot.gca().get_xticks().tolist()
  254. if len(locs) >= 16:
  255. pyplot.gca().xaxis.set_major_locator(locator)
  256. if locs[0] < pyplot.xlim()[0]:
  257. del locs[0]
  258. endindex = -1
  259. if len(locs) >= 2 and \
  260. pyplot.xlim()[1] - locs[-1] > (locs[-1] - locs[-2]) / 2:
  261. locs.append(pyplot.xlim()[1])
  262. endindex = len(locs) - 1
  263. startindex = -1
  264. if len(locs) >= 2 and \
  265. locs[0] - pyplot.xlim()[0] > (locs[1] - locs[0]) / 2:
  266. locs.append(pyplot.xlim()[0])
  267. startindex = len(locs) - 1
  268. pyplot.gca().set_xticks(locs)
  269. # hacking time!
  270. labels = pyplot.gca().get_xticklabels()
  271. if startindex >= 0:
  272. labels[startindex].set_text(date_range_sampling[0].date())
  273. labels[startindex].set_text = lambda _: None
  274. labels[startindex].set_rotation(30)
  275. labels[startindex].set_ha("right")
  276. if endindex >= 0:
  277. labels[endindex].set_text(date_range_sampling[-1].date())
  278. labels[endindex].set_text = lambda _: None
  279. labels[endindex].set_rotation(30)
  280. labels[endindex].set_ha("right")
  281. title = "%s %d x %d (granularity %d, sampling %d)" % \
  282. ((name,) + matrix.shape + (granularity, sampling))
  283. output = args.output
  284. if output:
  285. if args.mode == "project" and target == "project":
  286. output = args.output
  287. else:
  288. if target == "project":
  289. name = "project"
  290. output = get_plot_path(args.output, name)
  291. deploy_plot(title, output, args.style)
  292. def plot_many(args, target, header, parts):
  293. if not args.output:
  294. print("Warning: output not set, showing %d plots." % len(parts))
  295. itercnt = progress.bar(parts.items(), expected_size=len(parts)) \
  296. if progress is not None else parts.items()
  297. stdout = io.StringIO()
  298. for name, matrix in itercnt:
  299. backup = sys.stdout
  300. sys.stdout = stdout
  301. plot_burndown(args, target, *load_main(header, name, matrix, args.resample))
  302. sys.stdout = backup
  303. sys.stdout.write(stdout.getvalue())
  304. def plot_churn_matrix(args, repo, people, matrix):
  305. matrix = matrix.astype(float)
  306. if matrix.shape[0] > args.max_people:
  307. order = numpy.argsort(-matrix[:, 0])
  308. matrix = matrix[order[:args.max_people]][:, [0, 1] + list(order[:args.max_people])]
  309. people = [people[i] for i in order]
  310. print("Warning: truncated people to most productive %d" % args.max_people)
  311. zeros = matrix[:, 0] == 0
  312. matrix[zeros, :] = 1
  313. matrix /= matrix[:, 0][:, None]
  314. matrix = -matrix[:, 1:]
  315. matrix[zeros, :] = 0
  316. for i, name in enumerate(people):
  317. if len(name) > 40:
  318. people[i] = name[:37] + "..."
  319. import matplotlib
  320. if args.backend:
  321. matplotlib.use(args.backend)
  322. import matplotlib.pyplot as pyplot
  323. s = 4 + matrix.shape[1] * 0.3
  324. fig = pyplot.figure(figsize=(s, s))
  325. ax = fig.add_subplot(111)
  326. ax.xaxis.set_label_position("top")
  327. ax.matshow(matrix, cmap=pyplot.cm.OrRd)
  328. ax.set_xticks(numpy.arange(0, matrix.shape[1]))
  329. ax.set_yticks(numpy.arange(0, matrix.shape[0]))
  330. ax.set_xticklabels(["Unidentified"] + people, rotation=90, ha="center")
  331. ax.set_yticklabels(people, va="center")
  332. ax.set_xticks(numpy.arange(0.5, matrix.shape[1] + 0.5), minor=True)
  333. ax.set_yticks(numpy.arange(0.5, matrix.shape[0] + 0.5), minor=True)
  334. ax.grid(which="minor")
  335. apply_plot_style(fig, ax, None, args.style, args.text_size)
  336. if not args.output:
  337. pos1 = ax.get_position()
  338. pos2 = (pos1.x0 + 0.245, pos1.y0 - 0.1, pos1.width * 0.9, pos1.height * 0.9)
  339. ax.set_position(pos2)
  340. if args.mode == "all":
  341. output = get_plot_path(args.output, "matrix")
  342. else:
  343. output = args.output
  344. title = "%s %d developers overwrite" % (repo, matrix.shape[0])
  345. if args.output:
  346. # FIXME(vmarkovtsev): otherwise the title is screwed in savefig()
  347. title = ""
  348. deploy_plot(title, output, args.style)
  349. def plot_people(args, repo, names, people, date_range, last):
  350. import matplotlib
  351. if args.backend:
  352. matplotlib.use(args.backend)
  353. import matplotlib.pyplot as pyplot
  354. if people.shape[0] > args.max_people:
  355. order = numpy.argsort(-people.sum(axis=1))
  356. people = people[order[:args.max_people]]
  357. names = [names[i] for i in order[:args.max_people]]
  358. print("Warning: truncated people to most owning %d" % args.max_people)
  359. for i, name in enumerate(names):
  360. if len(name) > 40:
  361. names[i] = name[:37] + "..."
  362. pyplot.stackplot(date_range, people, labels=names)
  363. pyplot.xlim(date_range[0], last)
  364. if args.relative:
  365. for i in range(people.shape[1]):
  366. people[:, i] /= people[:, i].sum()
  367. pyplot.ylim(0, 1)
  368. legend_loc = 3
  369. else:
  370. legend_loc = 2
  371. legend = pyplot.legend(loc=legend_loc, fontsize=args.text_size)
  372. apply_plot_style(pyplot.gcf(), pyplot.gca(), legend, args.style, args.text_size)
  373. if args.mode == "all":
  374. output = get_plot_path(args.output, "people")
  375. else:
  376. output = args.output
  377. deploy_plot("%s code ratio through time" % repo, output, args.style)
  378. def train_embeddings(coocc_tree, tmpdir, shard_size=4096):
  379. from scipy.sparse import csr_matrix
  380. import tensorflow as tf
  381. try:
  382. from . import swivel
  383. except SystemError:
  384. import swivel
  385. index = coocc_tree["index"]
  386. nshards = len(index) // shard_size
  387. if nshards * shard_size < len(index):
  388. nshards += 1
  389. shard_size = len(index) // nshards
  390. nshards = len(index) // shard_size
  391. remainder = len(index) - nshards * shard_size
  392. if remainder > 0:
  393. lengths = numpy.array([len(cd) for cd in coocc_tree["matrix"]])
  394. filtered = sorted(numpy.argsort(lengths)[remainder:])
  395. else:
  396. filtered = list(range(len(index)))
  397. print("Reading the sparse matrix...")
  398. data = []
  399. indices = []
  400. indptr = [0]
  401. for row, cd in enumerate(coocc_tree["matrix"]):
  402. for col, val in sorted(cd.items()):
  403. data.append(val)
  404. indices.append(col)
  405. indptr.append(indptr[-1] + len(cd))
  406. matrix = csr_matrix((data, indices, indptr), shape=(len(index), len(index)))
  407. if len(filtered) < len(index):
  408. matrix = matrix[filtered, :][:, filtered]
  409. meta_index = []
  410. for i, j in enumerate(filtered):
  411. meta_index.append((index[j], matrix[i, i]))
  412. index = [mi[0] for mi in meta_index]
  413. with tempfile.TemporaryDirectory(prefix="hercules_labours_", dir=tmpdir or None) as tmproot:
  414. print("Writing Swivel metadata...")
  415. vocabulary = "\n".join(index)
  416. with open(os.path.join(tmproot, "row_vocab.txt"), "w") as out:
  417. out.write(vocabulary)
  418. with open(os.path.join(tmproot, "col_vocab.txt"), "w") as out:
  419. out.write(vocabulary)
  420. del vocabulary
  421. bool_sums = matrix.indptr[1:] - matrix.indptr[:-1]
  422. bool_sums_str = "\n".join(map(str, bool_sums.tolist()))
  423. with open(os.path.join(tmproot, "row_sums.txt"), "w") as out:
  424. out.write(bool_sums_str)
  425. with open(os.path.join(tmproot, "col_sums.txt"), "w") as out:
  426. out.write(bool_sums_str)
  427. del bool_sums_str
  428. reorder = numpy.argsort(-bool_sums)
  429. print("Writing Swivel shards...")
  430. for row in range(nshards):
  431. for col in range(nshards):
  432. def _int64s(xs):
  433. return tf.train.Feature(
  434. int64_list=tf.train.Int64List(value=list(xs)))
  435. def _floats(xs):
  436. return tf.train.Feature(
  437. float_list=tf.train.FloatList(value=list(xs)))
  438. indices_row = reorder[row::nshards]
  439. indices_col = reorder[col::nshards]
  440. shard = matrix[indices_row][:, indices_col].tocoo()
  441. example = tf.train.Example(features=tf.train.Features(feature={
  442. "global_row": _int64s(indices_row),
  443. "global_col": _int64s(indices_col),
  444. "sparse_local_row": _int64s(shard.row),
  445. "sparse_local_col": _int64s(shard.col),
  446. "sparse_value": _floats(shard.data)}))
  447. with open(os.path.join(tmproot, "shard-%03d-%03d.pb" % (row, col)), "wb") as out:
  448. out.write(example.SerializeToString())
  449. print("Training Swivel model...")
  450. swivel.FLAGS.submatrix_rows = shard_size
  451. swivel.FLAGS.submatrix_cols = shard_size
  452. if len(meta_index) < 10000:
  453. embedding_size = 50
  454. num_epochs = 200
  455. elif len(meta_index) < 100000:
  456. embedding_size = 100
  457. num_epochs = 250
  458. elif len(meta_index) < 500000:
  459. embedding_size = 200
  460. num_epochs = 300
  461. else:
  462. embedding_size = 300
  463. num_epochs = 200
  464. swivel.FLAGS.embedding_size = embedding_size
  465. swivel.FLAGS.input_base_path = tmproot
  466. swivel.FLAGS.output_base_path = tmproot
  467. swivel.FLAGS.loss_multiplier = 1.0 / shard_size
  468. swivel.FLAGS.num_epochs = num_epochs
  469. swivel.main(None)
  470. print("Reading Swivel embeddings...")
  471. embeddings = []
  472. with open(os.path.join(tmproot, "row_embedding.tsv")) as frow:
  473. with open(os.path.join(tmproot, "col_embedding.tsv")) as fcol:
  474. for i, (lrow, lcol) in enumerate(zip(frow, fcol)):
  475. prow, pcol = (l.split("\t", 1) for l in (lrow, lcol))
  476. assert prow[0] == pcol[0]
  477. erow, ecol = \
  478. (numpy.fromstring(p[1], dtype=numpy.float32, sep="\t")
  479. for p in (prow, pcol))
  480. embeddings.append((erow + ecol) / 2)
  481. return meta_index, embeddings
  482. class CORSWebServer(object):
  483. def __init__(self):
  484. self.thread = threading.Thread(target=self.serve)
  485. self.server = None
  486. def serve(self):
  487. outer = self
  488. try:
  489. from http.server import HTTPServer, SimpleHTTPRequestHandler, test
  490. except ImportError: # Python 2
  491. from BaseHTTPServer import HTTPServer, test
  492. from SimpleHTTPServer import SimpleHTTPRequestHandler
  493. class ClojureServer(HTTPServer):
  494. def __init__(self, *args, **kwargs):
  495. HTTPServer.__init__(self, *args, **kwargs)
  496. outer.server = self
  497. class CORSRequestHandler(SimpleHTTPRequestHandler):
  498. def end_headers (self):
  499. self.send_header("Access-Control-Allow-Origin", "*")
  500. SimpleHTTPRequestHandler.end_headers(self)
  501. test(CORSRequestHandler, ClojureServer)
  502. def start(self):
  503. self.thread.start()
  504. def stop(self):
  505. if self.running:
  506. self.server.shutdown()
  507. self.thread.join()
  508. @property
  509. def running(self):
  510. return self.server is not None
  511. web_server = CORSWebServer()
  512. def write_embeddings(name, output, run_server, index, embeddings):
  513. print("Writing Tensorflow Projector files...")
  514. if not output:
  515. output = "couples_" + name
  516. metaf = "%s_%s_meta.tsv" % (output, name)
  517. with open(metaf, "w") as fout:
  518. fout.write("name\tcommits\n")
  519. for pair in index:
  520. fout.write("%s\t%s\n" % pair)
  521. print("Wrote", metaf)
  522. dataf = "%s_%s_data.tsv" % (output, name)
  523. with open(dataf, "w") as fout:
  524. for vec in embeddings:
  525. fout.write("\t".join(str(v) for v in vec))
  526. fout.write("\n")
  527. print("Wrote", dataf)
  528. jsonf = "%s_%s.json" % (output, name)
  529. with open(jsonf, "w") as fout:
  530. fout.write("""{
  531. "embeddings": [
  532. {
  533. "tensorName": "%s %s coupling",
  534. "tensorShape": [%s, %s],
  535. "tensorPath": "http://0.0.0.0:8000/%s",
  536. "metadataPath": "http://0.0.0.0:8000/%s"
  537. }
  538. ]
  539. }
  540. """ % (output, name, len(embeddings), len(embeddings[0]), dataf, metaf))
  541. print("Wrote %s", jsonf)
  542. if run_server and not web_server.running:
  543. web_server.start()
  544. url = "http://projector.tensorflow.org/?config=http://0.0.0.0:8000/" + jsonf
  545. print(url)
  546. if run_server:
  547. os.system("xdg-open " + url)
  548. def main():
  549. args = parse_args()
  550. header, main_contents, files_contents, people_sequence, people_contents, people_matrix, \
  551. files_coocc, people_coocc = read_input(args)
  552. name = next(iter(main_contents))
  553. files_warning = "Files stats were not collected. Re-run hercules with -files."
  554. people_warning = "People stats were not collected. Re-run hercules with -people."
  555. if args.mode == "project":
  556. plot_burndown(args, "project",
  557. *load_main(header, name, main_contents[name], args.resample))
  558. elif args.mode == "file":
  559. if not files_contents:
  560. print(files_warning)
  561. return
  562. plot_many(args, "file", header, files_contents)
  563. elif args.mode == "person":
  564. if not people_contents:
  565. print(people_warning)
  566. return
  567. plot_many(args, "person", header, people_contents)
  568. elif args.mode == "churn_matrix":
  569. if not people_contents:
  570. print(people_warning)
  571. return
  572. plot_churn_matrix(args, name, people_sequence, load_churn_matrix(people_matrix))
  573. elif args.mode == "people":
  574. if not people_contents:
  575. print(people_warning)
  576. return
  577. plot_people(args, name, *load_people(header, people_sequence, people_contents))
  578. elif args.mode == "couples":
  579. write_embeddings("files", args.output, not args.disable_projector,
  580. *train_embeddings(files_coocc, args.couples_tmp_dir))
  581. write_embeddings("people", args.output, not args.disable_projector,
  582. *train_embeddings(people_coocc, args.couples_tmp_dir))
  583. elif args.mode == "all":
  584. plot_burndown(args, "project",
  585. *load_main(header, name, main_contents[name], args.resample))
  586. if files_contents:
  587. plot_many(args, "file", header, files_contents)
  588. if people_contents:
  589. plot_many(args, "person", header, people_contents)
  590. plot_churn_matrix(args, name, people_sequence, load_churn_matrix(people_matrix))
  591. plot_people(args, name, *load_people(header, people_sequence, people_contents))
  592. if people_coocc:
  593. assert files_coocc
  594. write_embeddings("files", args.output, not args.disable_projector,
  595. *train_embeddings(files_coocc, args.couples_tmp_dir))
  596. write_embeddings("people", args.output, not args.disable_projector,
  597. *train_embeddings(people_coocc, args.couples_tmp_dir))
  598. if web_server.running:
  599. print("Sleeping for 60 seconds, safe to Ctrl-C")
  600. try:
  601. time.sleep(60)
  602. except KeyboardInterrupt:
  603. pass
  604. web_server.stop()
  605. if __name__ == "__main__":
  606. sys.exit(main())