comment_sentiment.go 12 KB

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