comment_sentiment.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. // +build tensorflow
  2. package leaves
  3. import (
  4. "fmt"
  5. "io"
  6. "log"
  7. "os"
  8. "regexp"
  9. "sort"
  10. "strings"
  11. "github.com/gogo/protobuf/proto"
  12. "gopkg.in/bblfsh/sdk.v2/uast"
  13. "gopkg.in/bblfsh/sdk.v2/uast/nodes"
  14. progress "gopkg.in/cheggaaa/pb.v1"
  15. "gopkg.in/src-d/go-git.v4"
  16. "gopkg.in/src-d/go-git.v4/plumbing"
  17. "gopkg.in/src-d/hercules.v10/internal/core"
  18. "gopkg.in/src-d/hercules.v10/internal/pb"
  19. items "gopkg.in/src-d/hercules.v10/internal/plumbing"
  20. uast_items "gopkg.in/src-d/hercules.v10/internal/plumbing/uast"
  21. "gopkg.in/vmarkovtsev/BiDiSentiment.v1"
  22. )
  23. // CommentSentimentAnalysis measures comment sentiment through time.
  24. type CommentSentimentAnalysis struct {
  25. core.NoopMerger
  26. core.OneShotMergeProcessor
  27. MinCommentLength int
  28. Gap float32
  29. commentsByTick map[int][]string
  30. commitsByTick map[int][]plumbing.Hash
  31. xpather *uast_items.ChangesXPather
  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 val, exists := facts[ConfigCommentSentimentGap]; exists {
  103. sent.Gap = val.(float32)
  104. }
  105. if val, exists := facts[ConfigCommentSentimentMinLength]; exists {
  106. sent.MinCommentLength = val.(int)
  107. }
  108. sent.validate()
  109. sent.commitsByTick = facts[items.FactCommitsByTick].(map[int][]plumbing.Hash)
  110. return nil
  111. }
  112. func (sent *CommentSentimentAnalysis) validate() {
  113. if sent.Gap < 0 || sent.Gap >= 1 {
  114. log.Printf("Sentiment gap is too big: %f => reset to the default %f",
  115. sent.Gap, DefaultCommentSentimentGap)
  116. sent.Gap = DefaultCommentSentimentGap
  117. }
  118. if sent.MinCommentLength < 10 {
  119. log.Printf("Comment minimum length is too small: %d => reset to the default %d",
  120. sent.MinCommentLength, DefaultCommentSentimentCommentMinLength)
  121. sent.MinCommentLength = DefaultCommentSentimentCommentMinLength
  122. }
  123. }
  124. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  125. // calls. The repository which is going to be analysed is supplied as an argument.
  126. func (sent *CommentSentimentAnalysis) Initialize(repository *git.Repository) error {
  127. sent.commentsByTick = map[int][]string{}
  128. sent.xpather = &uast_items.ChangesXPather{XPath: "//uast:Comment"}
  129. sent.validate()
  130. sent.OneShotMergeProcessor.Initialize()
  131. return nil
  132. }
  133. // Consume runs this PipelineItem on the next commit data.
  134. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  135. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  136. // This function returns the mapping with analysis results. The keys must be the same as
  137. // in Provides(). If there was an error, nil is returned.
  138. func (sent *CommentSentimentAnalysis) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  139. if !sent.ShouldConsumeCommit(deps) {
  140. return nil, nil
  141. }
  142. changes := deps[uast_items.DependencyUastChanges].([]uast_items.Change)
  143. tick := deps[items.DependencyTick].(int)
  144. commentNodes, _ := sent.xpather.Extract(changes)
  145. comments := sent.mergeComments(commentNodes)
  146. tickComments := sent.commentsByTick[tick]
  147. if tickComments == nil {
  148. tickComments = []string{}
  149. }
  150. tickComments = append(tickComments, comments...)
  151. sent.commentsByTick[tick] = tickComments
  152. return nil, nil
  153. }
  154. // Finalize returns the result of the analysis. Further Consume() calls are not expected.
  155. func (sent *CommentSentimentAnalysis) Finalize() interface{} {
  156. result := CommentSentimentResult{
  157. EmotionsByTick: map[int]float32{},
  158. CommentsByTick: map[int][]string{},
  159. commitsByTick: sent.commitsByTick,
  160. }
  161. ticks := make([]int, 0, len(sent.commentsByTick))
  162. for tick := range sent.commentsByTick {
  163. ticks = append(ticks, tick)
  164. }
  165. sort.Ints(ticks)
  166. var texts []string
  167. for _, key := range ticks {
  168. texts = append(texts, sent.commentsByTick[key]...)
  169. }
  170. session, err := sentiment.OpenSession()
  171. if err != nil {
  172. panic(err)
  173. }
  174. defer session.Close()
  175. var bar *progress.ProgressBar
  176. callback := func(pos int, total int) {
  177. if bar == nil {
  178. bar = progress.New(total)
  179. bar.Callback = func(msg string) {
  180. os.Stderr.WriteString("\r" + msg)
  181. }
  182. bar.NotPrint = true
  183. bar.ShowPercent = false
  184. bar.ShowSpeed = false
  185. bar.SetMaxWidth(80)
  186. bar.Start()
  187. }
  188. bar.Set(pos)
  189. }
  190. // we run the bulk evaluation in the end for efficiency
  191. weights, err := sentiment.EvaluateWithProgress(texts, session, callback)
  192. if bar != nil {
  193. bar.Finish()
  194. }
  195. if err != nil {
  196. panic(err)
  197. }
  198. pos := 0
  199. for _, key := range ticks {
  200. sum := float32(0)
  201. comments := make([]string, 0, len(sent.commentsByTick[key]))
  202. for _, comment := range sent.commentsByTick[key] {
  203. if weights[pos] < 0.5*(1-sent.Gap) || weights[pos] > 0.5*(1+sent.Gap) {
  204. sum += weights[pos]
  205. comments = append(comments, comment)
  206. }
  207. pos++
  208. }
  209. if len(comments) > 0 {
  210. result.EmotionsByTick[key] = sum / float32(len(comments))
  211. result.CommentsByTick[key] = comments
  212. }
  213. }
  214. return result
  215. }
  216. // Fork clones this PipelineItem.
  217. func (sent *CommentSentimentAnalysis) Fork(n int) []core.PipelineItem {
  218. return core.ForkSamePipelineItem(sent, n)
  219. }
  220. // Serialize converts the analysis result as returned by Finalize() to text or bytes.
  221. // The text format is YAML and the bytes format is Protocol Buffers.
  222. func (sent *CommentSentimentAnalysis) Serialize(result interface{}, binary bool, writer io.Writer) error {
  223. sentimentResult := result.(CommentSentimentResult)
  224. if binary {
  225. return sent.serializeBinary(&sentimentResult, writer)
  226. }
  227. sent.serializeText(&sentimentResult, writer)
  228. return nil
  229. }
  230. func (sent *CommentSentimentAnalysis) serializeText(result *CommentSentimentResult, writer io.Writer) {
  231. ticks := make([]int, 0, len(result.EmotionsByTick))
  232. for tick := range result.EmotionsByTick {
  233. ticks = append(ticks, tick)
  234. }
  235. sort.Ints(ticks)
  236. for _, tick := range ticks {
  237. commits := result.commitsByTick[tick]
  238. hashes := make([]string, len(commits))
  239. for i, hash := range commits {
  240. hashes[i] = hash.String()
  241. }
  242. fmt.Fprintf(writer, " %d: [%.4f, [%s], \"%s\"]\n",
  243. tick, result.EmotionsByTick[tick], strings.Join(hashes, ","),
  244. strings.Join(result.CommentsByTick[tick], "|"))
  245. }
  246. }
  247. func (sent *CommentSentimentAnalysis) serializeBinary(
  248. result *CommentSentimentResult, writer io.Writer) error {
  249. message := pb.CommentSentimentResults{
  250. SentimentByTick: map[int32]*pb.Sentiment{},
  251. }
  252. for key, val := range result.EmotionsByTick {
  253. commits := make([]string, len(result.commitsByTick[key]))
  254. for i, commit := range result.commitsByTick[key] {
  255. commits[i] = commit.String()
  256. }
  257. message.SentimentByTick[int32(key)] = &pb.Sentiment{
  258. Value: val,
  259. Comments: result.CommentsByTick[key],
  260. Commits: commits,
  261. }
  262. }
  263. serialized, err := proto.Marshal(&message)
  264. if err != nil {
  265. return err
  266. }
  267. writer.Write(serialized)
  268. return nil
  269. }
  270. func (sent *CommentSentimentAnalysis) mergeComments(extracted []nodes.Node) []string {
  271. var mergedComments []string
  272. lines := map[int][]nodes.Node{}
  273. for _, node := range extracted {
  274. pos := uast.PositionsOf(node.(nodes.Object))
  275. if pos.Start() == nil {
  276. continue
  277. }
  278. lineno := int(pos.Start().Line)
  279. lines[lineno] = append(lines[lineno], node)
  280. }
  281. lineNums := make([]int, 0, len(lines))
  282. for line := range lines {
  283. lineNums = append(lineNums, line)
  284. }
  285. sort.Ints(lineNums)
  286. var buffer []string
  287. for i, line := range lineNums {
  288. lineNodes := lines[line]
  289. maxEnd := line
  290. for _, node := range lineNodes {
  291. pos := uast.PositionsOf(node.(nodes.Object))
  292. if pos.End() != nil && maxEnd < int(pos.End().Line) {
  293. maxEnd = int(pos.End().Line)
  294. }
  295. token := strings.TrimSpace(string(node.(nodes.Object)["Text"].(nodes.String)))
  296. if token != "" {
  297. buffer = append(buffer, token)
  298. }
  299. }
  300. if i < len(lineNums)-1 && lineNums[i+1] <= maxEnd+1 {
  301. continue
  302. }
  303. mergedComments = append(mergedComments, strings.Join(buffer, "\n"))
  304. buffer = make([]string, 0, len(buffer))
  305. }
  306. // We remove unneeded chars and filter too short comments
  307. filteredComments := make([]string, 0, len(mergedComments))
  308. for _, comment := range mergedComments {
  309. comment = strings.TrimSpace(comment)
  310. if comment == "" || filteredFirstCharRE.MatchString(comment[:1]) {
  311. // heuristic - we discard docstrings
  312. continue
  313. }
  314. // heuristic - remove function names
  315. comment = functionNameRE.ReplaceAllString(comment, "")
  316. comment = filteredCharsRE.ReplaceAllString(comment, "")
  317. if len(comment) < sent.MinCommentLength {
  318. continue
  319. }
  320. // collapse whitespace
  321. comment = whitespaceRE.ReplaceAllString(comment, " ")
  322. // heuristic - number of letters must be at least 60%
  323. charsCount := 0
  324. for _, match := range charsRE.FindAllStringIndex(comment, -1) {
  325. charsCount += match[1] - match[0]
  326. }
  327. if charsCount < int(float32(len(comment))*CommentLettersRatio) {
  328. continue
  329. }
  330. // heuristic - license
  331. if licenseRE.MatchString(comment) {
  332. continue
  333. }
  334. filteredComments = append(filteredComments, comment)
  335. }
  336. return filteredComments
  337. }
  338. func init() {
  339. core.Registry.Register(&CommentSentimentAnalysis{})
  340. }