comment_sentiment.go 11 KB

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