comment_sentiment.go 11 KB

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