Class: Ebooks::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/twitter_ebooks/model.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#hashObject

Returns the value of attribute hash.



10
11
12
# File 'lib/twitter_ebooks/model.rb', line 10

def hash
  @hash
end

#keywordsObject

Returns the value of attribute keywords.



10
11
12
# File 'lib/twitter_ebooks/model.rb', line 10

def keywords
  @keywords
end

#mentionsObject

Returns the value of attribute mentions.



10
11
12
# File 'lib/twitter_ebooks/model.rb', line 10

def mentions
  @mentions
end

#sentencesObject

Returns the value of attribute sentences.



10
11
12
# File 'lib/twitter_ebooks/model.rb', line 10

def sentences
  @sentences
end

Class Method Details

.consume(txtpath) ⇒ Object



12
13
14
# File 'lib/twitter_ebooks/model.rb', line 12

def self.consume(txtpath)
  Model.new.consume(txtpath)
end

.load(path) ⇒ Object



16
17
18
# File 'lib/twitter_ebooks/model.rb', line 16

def self.load(path)
  Marshal.load(File.read(path))
end

Instance Method Details

#consume(path) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/twitter_ebooks/model.rb', line 20

def consume(path)
  content = File.read(path)
  @hash = Digest::MD5.hexdigest(content)

  if path.split('.')[-1] == "json"
    log "Reading json corpus from #{path}"
    lines = JSON.parse(content, symbolize_names: true).map do |tweet|
      tweet[:text]
    end
  else
    log "Reading plaintext corpus from #{path}"
    lines = content.split("\n")
  end

  log "Removing commented lines and sorting mentions"

  keeping = []
  mentions = []
  lines.each do |l|
    next if l.start_with?('#') # Remove commented lines
    next if l.include?('RT') || l.include?('MT') # Remove soft retweets
    
    if l.include?('@')
      mentions << l
    else
      keeping << l
    end
  end
  text = NLP.normalize(keeping.join("\n")) # Normalize weird characters
  mention_text = NLP.normalize(mentions.join("\n"))

  log "Segmenting text into sentences"

  statements = NLP.sentences(text)
  mentions = NLP.sentences(mention_text)

  log "Tokenizing #{statements.length} statements and #{mentions.length} mentions"
  @sentences = []
  @mentions = []

  statements.each do |s|
    @sentences << NLP.tokenize(s).reject do |t|
      t.start_with?('@') || t.start_with?('http')
    end
  end

  mentions.each do |s|
    @mentions << NLP.tokenize(s).reject do |t|
      t.start_with?('@') || t.start_with?('http')
    end
  end

  log "Ranking keywords"
  @keywords = NLP.keywords(@sentences)

  self
end

#find_relevant(sentences, input) ⇒ Object

Finds all relevant tokenized sentences to given input by comparing non-stopword token overlaps



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/twitter_ebooks/model.rb', line 144

def find_relevant(sentences, input)
  relevant = []
  slightly_relevant = []

  tokenized = NLP.tokenize(input).map(&:downcase)

  sentences.each do |sent|
    tokenized.each do |token|
      if sent.map(&:downcase).include?(token)
        relevant << sent unless NLP.stopword?(token)
        slightly_relevant << sent
      end
    end
  end

  [relevant, slightly_relevant]
end

#fix(tweet) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/twitter_ebooks/model.rb', line 85

def fix(tweet)
  # This seems to require an external api call
  #begin
  #  fixer = NLP.gingerice.parse(tweet)
  #  log fixer if fixer['corrections']
  #  tweet = fixer['result']
  #rescue Exception => e
  #  log e.message
  #  log e.backtrace
  #end

  NLP.htmlentities.decode tweet
end

#make_response(input, limit = 140, sentences = @mentions) ⇒ Object

Generates a response by looking for related sentences in the corpus and building a smaller generator from these



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/twitter_ebooks/model.rb', line 164

def make_response(input, limit=140, sentences=@mentions)
  # Prefer mentions
  relevant, slightly_relevant = find_relevant(sentences, input)

  if relevant.length >= 3
    generator = SuffixGenerator.build(relevant)
    make_statement(limit, generator)
  elsif slightly_relevant.length >= 5
    generator = SuffixGenerator.build(slightly_relevant)
    make_statement(limit, generator)
  elsif sentences.equal?(@mentions)
    make_response(input, limit, @sentences)
  else
    make_statement(limit)
  end
end

#make_statement(limit = 140, generator = nil, retry_limit = 10) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/twitter_ebooks/model.rb', line 104

def make_statement(limit=140, generator=nil, retry_limit=10)
  responding = !generator.nil?
  generator ||= SuffixGenerator.build(@sentences)

  retries = 0
  tweet = ""

  while (tokens = generator.generate(3, :bigrams)) do
    next if tokens.length <= 3 && !responding
    break if valid_tweet?(tokens, limit)

    retries += 1
    break if retries >= retry_limit
  end

  if verbatim?(tokens) && tokens.length > 3 # We made a verbatim tweet by accident
    while (tokens = generator.generate(3, :unigrams)) do
      break if valid_tweet?(tokens, limit) && !verbatim?(tokens)

      retries += 1
      break if retries >= retry_limit
    end
  end

  tweet = NLP.reconstruct(tokens)

  if retries >= retry_limit
    log "Unable to produce valid non-verbatim tweet; using \"#{tweet}\""
  end

  fix tweet
end

#save(path) ⇒ Object



78
79
80
81
82
83
# File 'lib/twitter_ebooks/model.rb', line 78

def save(path)
  File.open(path, 'w') do |f|
    f.write(Marshal.dump(self))
  end
  self
end

#valid_tweet?(tokens, limit) ⇒ Boolean

Returns:

  • (Boolean)


99
100
101
102
# File 'lib/twitter_ebooks/model.rb', line 99

def valid_tweet?(tokens, limit)
  tweet = NLP.reconstruct(tokens)
  tweet.length <= limit && !NLP.unmatched_enclosers?(tweet)
end

#verbatim?(tokens) ⇒ Boolean

Test if a sentence has been copied verbatim from original

Returns:

  • (Boolean)


138
139
140
# File 'lib/twitter_ebooks/model.rb', line 138

def verbatim?(tokens)
  @sentences.include?(tokens) || @mentions.include?(tokens)
end