comment_sentiment.go 12 KB

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