comment_sentiment.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. // +build tensorflow
  2. package leaves
  3. import (
  4. "fmt"
  5. "io"
  6. "os"
  7. "regexp"
  8. "sort"
  9. "strings"
  10. "github.com/gogo/protobuf/proto"
  11. "gopkg.in/bblfsh/sdk.v2/uast"
  12. "gopkg.in/bblfsh/sdk.v2/uast/nodes"
  13. progress "gopkg.in/cheggaaa/pb.v1"
  14. "gopkg.in/src-d/go-git.v4"
  15. "gopkg.in/src-d/go-git.v4/plumbing"
  16. "gopkg.in/src-d/hercules.v10/internal/core"
  17. "gopkg.in/src-d/hercules.v10/internal/pb"
  18. items "gopkg.in/src-d/hercules.v10/internal/plumbing"
  19. uast_items "gopkg.in/src-d/hercules.v10/internal/plumbing/uast"
  20. sentiment "gopkg.in/vmarkovtsev/BiDiSentiment.v1"
  21. )
  22. // CommentSentimentAnalysis measures comment sentiment through time.
  23. type CommentSentimentAnalysis struct {
  24. core.NoopMerger
  25. core.OneShotMergeProcessor
  26. MinCommentLength int
  27. Gap float32
  28. commentsByTick map[int][]string
  29. commitsByTick map[int][]plumbing.Hash
  30. xpather *uast_items.ChangesXPather
  31. l core.Logger
  32. }
  33. // CommentSentimentResult contains the sentiment values per tick, where 1 means very negative
  34. // and 0 means very positive.
  35. type CommentSentimentResult struct {
  36. EmotionsByTick map[int]float32
  37. CommentsByTick map[int][]string
  38. commitsByTick map[int][]plumbing.Hash
  39. }
  40. const (
  41. ConfigCommentSentimentMinLength = "CommentSentiment.MinLength"
  42. ConfigCommentSentimentGap = "CommentSentiment.Gap"
  43. DefaultCommentSentimentCommentMinLength = 20
  44. DefaultCommentSentimentGap = float32(0.5)
  45. // CommentLettersRatio is the threshold to filter impure comments which contain code.
  46. CommentLettersRatio = 0.6
  47. )
  48. var (
  49. filteredFirstCharRE = regexp.MustCompile("[^a-zA-Z0-9]")
  50. filteredCharsRE = regexp.MustCompile("[^-a-zA-Z0-9_:;,./?!#&%+*=\\n \\t()]+")
  51. charsRE = regexp.MustCompile("[a-zA-Z]+")
  52. functionNameRE = regexp.MustCompile("\\s*[a-zA-Z_][a-zA-Z_0-9]*\\(\\)")
  53. whitespaceRE = regexp.MustCompile("\\s+")
  54. licenseRE = regexp.MustCompile("(?i)[li[cs]en[cs][ei]|copyright|©")
  55. )
  56. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  57. func (sent *CommentSentimentAnalysis) Name() string {
  58. return "Sentiment"
  59. }
  60. // Provides returns the list of names of entities which are produced by this PipelineItem.
  61. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  62. // to this list. Also used by core.Registry to build the global map of providers.
  63. func (sent *CommentSentimentAnalysis) Provides() []string {
  64. return []string{}
  65. }
  66. // Requires returns the list of names of entities which are needed by this PipelineItem.
  67. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  68. // entities are Provides() upstream.
  69. func (sent *CommentSentimentAnalysis) Requires() []string {
  70. arr := [...]string{uast_items.DependencyUastChanges, items.DependencyTick}
  71. return arr[:]
  72. }
  73. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  74. func (sent *CommentSentimentAnalysis) ListConfigurationOptions() []core.ConfigurationOption {
  75. options := [...]core.ConfigurationOption{{
  76. Name: ConfigCommentSentimentMinLength,
  77. Description: "Minimum length of the comment to be analyzed.",
  78. Flag: "min-comment-len",
  79. Type: core.IntConfigurationOption,
  80. Default: DefaultCommentSentimentCommentMinLength}, {
  81. Name: ConfigCommentSentimentGap,
  82. Description: "Sentiment value threshold, values between 0.5 - X/2 and 0.5 + x/2 will not be " +
  83. "considered. Must be >= 0 and < 1. The purpose is to exclude neutral comments.",
  84. Flag: "sentiment-gap",
  85. Type: core.FloatConfigurationOption,
  86. Default: DefaultCommentSentimentGap},
  87. }
  88. return options[:]
  89. }
  90. // Flag returns the command line switch which activates the analysis.
  91. func (sent *CommentSentimentAnalysis) Flag() string {
  92. return "sentiment"
  93. }
  94. // Description returns the text which explains what the analysis is doing.
  95. func (sent *CommentSentimentAnalysis) Description() string {
  96. return "Classifies each new or changed comment per commit as containing positive or " +
  97. "negative emotions. The classifier outputs a real number between 0 and 1," +
  98. "1 is the most positive and 0 is the most negative."
  99. }
  100. // Configure sets the properties previously published by ListConfigurationOptions().
  101. func (sent *CommentSentimentAnalysis) Configure(facts map[string]interface{}) error {
  102. if l, exists := facts[core.ConfigLogger].(core.Logger); exists {
  103. sent.l = l
  104. }
  105. if val, exists := facts[ConfigCommentSentimentGap]; exists {
  106. sent.Gap = val.(float32)
  107. }
  108. if val, exists := facts[ConfigCommentSentimentMinLength]; exists {
  109. sent.MinCommentLength = val.(int)
  110. }
  111. sent.validate()
  112. sent.commitsByTick = facts[items.FactCommitsByTick].(map[int][]plumbing.Hash)
  113. return nil
  114. }
  115. func (sent *CommentSentimentAnalysis) validate() {
  116. if sent.Gap < 0 || sent.Gap >= 1 {
  117. sent.l.Warnf("Sentiment gap is too big: %f => reset to the default %f",
  118. sent.Gap, DefaultCommentSentimentGap)
  119. sent.Gap = DefaultCommentSentimentGap
  120. }
  121. if sent.MinCommentLength < 10 {
  122. sent.l.Warnf("Comment minimum length is too small: %d => reset to the default %d",
  123. sent.MinCommentLength, DefaultCommentSentimentCommentMinLength)
  124. sent.MinCommentLength = DefaultCommentSentimentCommentMinLength
  125. }
  126. }
  127. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  128. // calls. The repository which is going to be analysed is supplied as an argument.
  129. func (sent *CommentSentimentAnalysis) Initialize(repository *git.Repository) error {
  130. sent.l = core.NewLogger()
  131. sent.commentsByTick = map[int][]string{}
  132. sent.xpather = &uast_items.ChangesXPather{XPath: "//uast:Comment"}
  133. sent.validate()
  134. sent.OneShotMergeProcessor.Initialize()
  135. return nil
  136. }
  137. // Consume runs this PipelineItem on the next commit data.
  138. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  139. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  140. // This function returns the mapping with analysis results. The keys must be the same as
  141. // in Provides(). If there was an error, nil is returned.
  142. func (sent *CommentSentimentAnalysis) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  143. if !sent.ShouldConsumeCommit(deps) {
  144. return nil, nil
  145. }
  146. changes := deps[uast_items.DependencyUastChanges].([]uast_items.Change)
  147. tick := deps[items.DependencyTick].(int)
  148. commentNodes, _ := sent.xpather.Extract(changes)
  149. comments := sent.mergeComments(commentNodes)
  150. tickComments := sent.commentsByTick[tick]
  151. if tickComments == nil {
  152. tickComments = []string{}
  153. }
  154. tickComments = append(tickComments, comments...)
  155. sent.commentsByTick[tick] = tickComments
  156. return nil, nil
  157. }
  158. // Finalize returns the result of the analysis. Further Consume() calls are not expected.
  159. func (sent *CommentSentimentAnalysis) Finalize() interface{} {
  160. result := CommentSentimentResult{
  161. EmotionsByTick: map[int]float32{},
  162. CommentsByTick: map[int][]string{},
  163. commitsByTick: sent.commitsByTick,
  164. }
  165. ticks := make([]int, 0, len(sent.commentsByTick))
  166. for tick := range sent.commentsByTick {
  167. ticks = append(ticks, tick)
  168. }
  169. sort.Ints(ticks)
  170. var texts []string
  171. for _, key := range ticks {
  172. texts = append(texts, sent.commentsByTick[key]...)
  173. }
  174. session, err := sentiment.OpenSession()
  175. if err != nil {
  176. panic(err)
  177. }
  178. defer session.Close()
  179. var bar *progress.ProgressBar
  180. callback := func(pos int, total int) {
  181. if bar == nil {
  182. bar = progress.New(total)
  183. bar.Callback = func(msg string) {
  184. os.Stderr.WriteString("\r" + msg)
  185. }
  186. bar.NotPrint = true
  187. bar.ShowPercent = false
  188. bar.ShowSpeed = false
  189. bar.SetMaxWidth(80)
  190. bar.Start()
  191. }
  192. bar.Set(pos)
  193. }
  194. // we run the bulk evaluation in the end for efficiency
  195. weights, err := sentiment.EvaluateWithProgress(texts, session, callback)
  196. if bar != nil {
  197. bar.Finish()
  198. }
  199. if err != nil {
  200. panic(err)
  201. }
  202. pos := 0
  203. for _, key := range ticks {
  204. sum := float32(0)
  205. comments := make([]string, 0, len(sent.commentsByTick[key]))
  206. for _, comment := range sent.commentsByTick[key] {
  207. if weights[pos] < 0.5*(1-sent.Gap) || weights[pos] > 0.5*(1+sent.Gap) {
  208. sum += weights[pos]
  209. comments = append(comments, comment)
  210. }
  211. pos++
  212. }
  213. if len(comments) > 0 {
  214. result.EmotionsByTick[key] = sum / float32(len(comments))
  215. result.CommentsByTick[key] = comments
  216. }
  217. }
  218. return result
  219. }
  220. // Fork clones this PipelineItem.
  221. func (sent *CommentSentimentAnalysis) Fork(n int) []core.PipelineItem {
  222. return core.ForkSamePipelineItem(sent, n)
  223. }
  224. // Serialize converts the analysis result as returned by Finalize() to text or bytes.
  225. // The text format is YAML and the bytes format is Protocol Buffers.
  226. func (sent *CommentSentimentAnalysis) Serialize(result interface{}, binary bool, writer io.Writer) error {
  227. sentimentResult := result.(CommentSentimentResult)
  228. if binary {
  229. return sent.serializeBinary(&sentimentResult, writer)
  230. }
  231. sent.serializeText(&sentimentResult, writer)
  232. return nil
  233. }
  234. func (sent *CommentSentimentAnalysis) serializeText(result *CommentSentimentResult, writer io.Writer) {
  235. ticks := make([]int, 0, len(result.EmotionsByTick))
  236. for tick := range result.EmotionsByTick {
  237. ticks = append(ticks, tick)
  238. }
  239. sort.Ints(ticks)
  240. for _, tick := range ticks {
  241. commits := result.commitsByTick[tick]
  242. hashes := make([]string, len(commits))
  243. for i, hash := range commits {
  244. hashes[i] = hash.String()
  245. }
  246. fmt.Fprintf(writer, " %d: [%.4f, [%s], \"%s\"]\n",
  247. tick, result.EmotionsByTick[tick], strings.Join(hashes, ","),
  248. strings.Join(result.CommentsByTick[tick], "|"))
  249. }
  250. }
  251. func (sent *CommentSentimentAnalysis) serializeBinary(
  252. result *CommentSentimentResult, writer io.Writer) error {
  253. message := pb.CommentSentimentResults{
  254. SentimentByTick: map[int32]*pb.Sentiment{},
  255. }
  256. for key, val := range result.EmotionsByTick {
  257. commits := make([]string, len(result.commitsByTick[key]))
  258. for i, commit := range result.commitsByTick[key] {
  259. commits[i] = commit.String()
  260. }
  261. message.SentimentByTick[int32(key)] = &pb.Sentiment{
  262. Value: val,
  263. Comments: result.CommentsByTick[key],
  264. Commits: commits,
  265. }
  266. }
  267. serialized, err := proto.Marshal(&message)
  268. if err != nil {
  269. return err
  270. }
  271. writer.Write(serialized)
  272. return nil
  273. }
  274. func (sent *CommentSentimentAnalysis) mergeComments(extracted []nodes.Node) []string {
  275. var mergedComments []string
  276. lines := map[int][]nodes.Node{}
  277. for _, node := range extracted {
  278. pos := uast.PositionsOf(node.(nodes.Object))
  279. if pos.Start() == nil {
  280. continue
  281. }
  282. lineno := int(pos.Start().Line)
  283. lines[lineno] = append(lines[lineno], node)
  284. }
  285. lineNums := make([]int, 0, len(lines))
  286. for line := range lines {
  287. lineNums = append(lineNums, line)
  288. }
  289. sort.Ints(lineNums)
  290. var buffer []string
  291. for i, line := range lineNums {
  292. lineNodes := lines[line]
  293. maxEnd := line
  294. for _, node := range lineNodes {
  295. pos := uast.PositionsOf(node.(nodes.Object))
  296. if pos.End() != nil && maxEnd < int(pos.End().Line) {
  297. maxEnd = int(pos.End().Line)
  298. }
  299. token := strings.TrimSpace(string(node.(nodes.Object)["Text"].(nodes.String)))
  300. if token != "" {
  301. buffer = append(buffer, token)
  302. }
  303. }
  304. if i < len(lineNums)-1 && lineNums[i+1] <= maxEnd+1 {
  305. continue
  306. }
  307. mergedComments = append(mergedComments, strings.Join(buffer, "\n"))
  308. buffer = make([]string, 0, len(buffer))
  309. }
  310. // We remove unneeded chars and filter too short comments
  311. filteredComments := make([]string, 0, len(mergedComments))
  312. for _, comment := range mergedComments {
  313. comment = strings.TrimSpace(comment)
  314. if comment == "" || filteredFirstCharRE.MatchString(comment[:1]) {
  315. // heuristic - we discard docstrings
  316. continue
  317. }
  318. // heuristic - remove function names
  319. comment = functionNameRE.ReplaceAllString(comment, "")
  320. comment = filteredCharsRE.ReplaceAllString(comment, "")
  321. if len(comment) < sent.MinCommentLength {
  322. continue
  323. }
  324. // collapse whitespace
  325. comment = whitespaceRE.ReplaceAllString(comment, " ")
  326. // heuristic - number of letters must be at least 60%
  327. charsCount := 0
  328. for _, match := range charsRE.FindAllStringIndex(comment, -1) {
  329. charsCount += match[1] - match[0]
  330. }
  331. if charsCount < int(float32(len(comment))*CommentLettersRatio) {
  332. continue
  333. }
  334. // heuristic - license
  335. if licenseRE.MatchString(comment) {
  336. continue
  337. }
  338. filteredComments = append(filteredComments, comment)
  339. }
  340. return filteredComments
  341. }
  342. func init() {
  343. core.Registry.Register(&CommentSentimentAnalysis{})
  344. }