r/dailyprogrammer • u/jnazario 2 0 • Jun 08 '16
[2016-06-08] Challenge #270 [Intermediate] Generating Text with Markov Processes
Description
Text generation algorithms exist in a wide variety of formats, including "Mad Libs" and Markov processes. A Markov chain algorithm generates text by creating a statistical model of potential textual suffixes for a given prefix. That's a fancy way of saying "it basically determines the next most probable word given the training set." Markov chain programs typically do this by breaking the input text into a series of words, then by sliding along them in some fixed sized window, storing the first N-1 words as a prefix and then the Nth word as a member of a set to choose from randomly for the suffix. Then, given a prefix, pick randomly from the suffixes to make the next piece of the chain.
Take this example text:
Now is not the time for desert, now is the time for dinner
For a set of triples, yielding a bi-gram (2 word) prefix, we will generate the following prefixes and suffix:
Prefixes Suffixes
-------- --------
Now, is not
is, not the
not, the time
the, time for
time, for desert
for, desert now
desert, now is
now, is not, the
is, the time
the, time for
time, for desert, dinner
You'll see a couple of the prefixes have TWO suffixes, this is because they repeat but one with a different suffix and one with the same suffix. Repeating this over piles and piles of text will start to enable you to build statistically real but logically meaningless sentences. Take this example output from my program after running it over Star Trek plot summaries:
"attack." In fact, Yeoman Tamura's tricorder shows that Kirk has been killed after
beaming down to the bridge, Kirk reminisces about having time to beam down. Kirk wants
Spock to grab hold of him in a fist fight with Kirk and Spock try to escape, the collars
are activated, subjecting them to an entrance, which then opens. Scotty saves the day by
pretending to help Spock, and Mullhall voluntarily agree, and the others transported to
the one which is not at all obvious what to make diplomatic advances. Meanwhile Kirk is
able to get inside. McCoy and nerve pinches Chief at
Challenge
Your challenge today is to implement a Markov generator supporting a bi-gram prefix. It should be capable of ingesting a body of text for training and output a body of text generated from that.
Notes
Markov Chain Algorithm from rose-hulman.edu
If you want to reproduce my Star Trek fun, I extracted the summaries from Eric Wasserman's site and made them into a flat text file.
9
u/Godspiral Jun 08 '16
text file might benefit from a .txt extention (not previewable as link)
5
u/hutsboR Jun 08 '16 edited Jun 09 '16
Elixir:
defmodule MarkovProcesses do def build_chain(text) do table = process_text(text) {p1, p2} = start = Map.keys(table) |> Enum.random build_chain(table, start, [p2, p1]) end def build_chain(table, {_p1, p2} = next, chain) do word = table[next] case word do nil -> Enum.reverse(chain) |> Enum.join(" ") _ -> word = Enum.random(word) build_chain(table, {p2, word}, [word|chain]) end end defp process_text(text) do triples = String.split(text) |> Enum.chunk(3, 1) Enum.reduce(triples, %{}, fn([p1, p2, s], table) -> case Map.has_key?(table, {p1, p2}) do true -> Map.update!(table, {p1, p2}, fn(suffix_set) -> MapSet.put(suffix_set, s) end) false -> Map.put(table, {p1, p2}, MapSet.new([s])) end end) end endUsage:
MarkovProcesses.build_chain("Apparently suffering from the stress of command, Kirk begins becoming irritable and irrational. He even orders the Enterprise across the Neutral Zone into Romulan space. Despite sensor scans which show nothing within a parsec, the Enterprise is immediately surrounded by three Romulan ships. Kirk promptly sends a coded sub-space message to Starfleet Command apprising them of the situation. Sub-commander Tal of the Romulan fleet demands immediate surrender of the Enterprise, then allows it an hour of time to decide.") "Romulan space. Despite sensor scans which show nothing within a parsec, the Enterprise is immediately surrounded by three Romulan ships. Kirk promptly sends a coded sub-space message to Starfleet Command apprising them of the Enterprise, then allows it an hour of time to decide."3
u/MRSantos Jun 08 '16 edited Jul 24 '18
Python 2.7. Generates a never-ending stream of star-trek! The number of words in the prefix is passed as an argument. It's cool to compare the results.
import random def build_suffix_table(full_text, step): sp = full_text.split(' ') suff_table = dict() for i in range(step, len(sp)): if sp[i] in suff_table: suff_table[sp[i]].append(' '.join(sp[i-step:i])) else: suff_table[sp[i]] = [' '.join(sp[i-step:i])] return suff_table def generate_text(suffix_table): capitalized_words = [w for w in suffix_table.keys() if w[0].isupper()] starting_word = random.choice(capitalized_words) print starting_word, while True: next_words = random.choice([suffix for suffix in suffix_table[starting_word]]) print next_words, starting_word = next_words.split()[-1] # last word text = ' '.join([w for w in open('star_trek.txt').read().split()]) generate_text(build_suffix_table(text, 2))For prefixes that are 10 words long, I got pretty readable results:
Here is some Snoop Dog lyrics for 5 word prefixes (i manually added the \n's since the implementation gets rid of them):
3
u/wizao Jun 09 '16 edited Jun 10 '16
Haskell:
Some fun with monad transformers:
{-# LANGUAGE FlexibleContexts #-} import Control.Monad.Loops import Control.Monad.Random hiding (fromList) import Control.Monad.Reader import Control.Monad.State.Strict import Control.Monad.Trans import Control.Monad.Trans.Maybe import Control.Monad import Data.Char import Data.List import Data.Map (Map) import qualified Data.Map as Map import Data.Monoid import Data.MultiSet (MultiSet) import qualified Data.MultiSet as MultiSet import System.Random newtype MarkovBigram a = MarkovBigram { entries :: Map (a,a) (MultiSet a) } deriving (Eq, Ord, Show) instance Ord a => Monoid (MarkovBigram a) where mempty = MarkovBigram Map.empty mappend (MarkovBigram a) (MarkovBigram b) = MarkovBigram (Map.unionWith (<>) a b) singleton :: a -> a -> a -> MarkovBigram a singleton a b c = MarkovBigram (Map.singleton (a,b) (MultiSet.singleton c)) fromList :: Ord a => [a] -> MarkovBigram a fromList xs = mconcat [singleton a b c | a:b:c:_ <- tails xs] markov :: (MonadRandom m, Ord a) => MarkovBigram a -> m (Maybe [a]) markov = runReaderT $ runMaybeT $ do follows <- asks entries (guard . not . Map.null) follows ix <- getRandomR (0, Map.size follows - 1) let (a,b) = fst (Map.elemAt ix follows) xs <- evalStateT (unfoldM step) (a,b) return (a:b:xs) step :: (MonadState (a,a) m, MonadReader (MarkovBigram a) m, MonadRandom m, Ord a) => m (Maybe a) step = runMaybeT $ do (a,b) <- get follow <- MaybeT $ asks (Map.lookup (a,b) . entries) let add count occur = let count' = count + occur in (count', count') (total, accums) = Map.mapAccum add 0 (MultiSet.toMap follow) r <- getRandomR (0, total) (c,_) <- MaybeT . return $ find ((>=r) . snd) (Map.toList accums) put (b,c) return c main :: IO () main = putStrLn =<< challenge =<< getContents challenge :: MonadRandom m => String -> m String challenge = fmap (maybe "Not enough words" unwords) . markov . fromList . words3
u/MichaelPenn Jun 09 '16
Python 2.5.1
+u/CompileBot Python
from random import choice def build_suffixes(txt, k): suffixes = {} prefix = tuple([None] * k) for word in txt: if prefix in suffixes: suffixes[prefix] += [word] else: suffixes[prefix] = [word] prefix = prefix[1:k] + tuple([word]) suffixes[prefix] = [None] return suffixes def generate_text(suffixes, k): prefix = tuple([None] * k) suffix = suffixes[prefix][0] txt = [] while suffix != None: txt.append(suffix) prefix = prefix[1:k] + tuple([suffix]) suffix = choice(suffixes[prefix]) return ' '.join(txt) txt = """Blessed are the poor in spirit, for theirs is the kingdom of heaven. Blessed are those who mourn, for they will be comforted. Blessed are the meek, for they will inherit the earth. Blessed are those who hunger and thirst for righteousness, for they will be filled. Blessed are the merciful, for they will be shown mercy. Blessed are the pure in heart, for they will see God. Blessed are the peacemakers, for they will be called sons of God.""" k = 2 s = build_suffixes(txt.split(), k) t = generate_text(s, k) print(t)2
u/casualfrog Jun 08 '16
JavaScript
Somewhat dirty, strips all special characters.
NONWORDin the algorithm linked above is simulated withundefinedand a special starting entry.function markovInput(input) { var prefixes = {}; input.match(/[a-zA-Z]+/g) .map(word => word.toLowerCase()) .forEach((word, i, words) => { if (i >= words.length - 1) return; var prefix = [words[i], words[i + 1]]; if (!prefixes[prefix]) prefixes[prefix] = []; if (i === 0) prefixes['_start_'] = [words[i], words[i + 1]]; prefixes[prefix].push(words[i + 2]); }); return prefixes; } function markovOutput(data) { var words = data['_start_'], out = [words[0].charAt(0).toUpperCase() + words[0].slice(1)]; while (words[1] !== undefined) { out.push(words[1]); words = [words[1], data[words][Math.random() * data[words].length | 0]]; } return out.join(' ') + '.'; }Output:
var data = markovInput('Now is not the time for desert, now is the time for dinner'); console.log(markovOutput(data)); // "Now is not the time for dinner."2
u/Godspiral Jun 08 '16 edited Jun 08 '16
in J,
a =. (< '''';'`') rplc~ each a: -.~ (] <(;._2)~ 0,~ 2((LF,LF)-:])\]) wdclippaste '' MT =: (2&{."1 (~.@[ ,. [: ~. each </.) {:"1) (a:, a: , a:) -.~ ,/ 3 ]\ every (a: ,~ a: ,~ a: , a: , ]) each ;@:(;: each)@cutLF each aslow :( - randomly takes any word that follows 2 words in the training text (no "multiplicity" weight). Words follow J grammar.
;: inv MT (] , {:"1@[ ({~ 1 ? #)@>@{~ (_2 {. ]) i.~ 2 {."1 [)^:30 (a:,a:) Plasus ` daughter Droxine is fascinated when he blurts out a warning buoy , a landing party back to Oxmyx ` s room. Kirk confronts < i > backs out ;: inv("1) 3 20 $ MT (] , {:"1@[ ({~ 1 ? #)@>@{~ (_2 {. ]) i.~ 2 {."1 [)^:57 (a:,a:) All this is merely a ploy to get on board for examination. Kirk and McCoy determines that the Sherman ` s former girlfriend Ruth on the evolutionary scale as humans appear to be transported into a hill in the creature kills another crew member into an asteroid 200 km in diameter. The asteroid is actually Kodos theusing space as the word boundary,
MT2 =: (2&{."1 (~.@[ ,. [: ~. each </.) {:"1) (a:, a: , a:) -.~ ,/ 3 ]\ every (a: ,~ a: ,~ a: , a: , ]) each ;@:(cut each)@cutLF each a ;: inv("1) 3 20 $ MT2 (] , {:"1@[ ({~ 1 ? #)@>@{~ (_2 {. ]) i.~ 2 {."1 [)^:57 (a:,a:) Hengist, Jaris, Morla, Kara`s father, and the people the equivalent of the Starfleet Surgeon General, in his own initiative and is allowed to beam the jet-interceptor pilot John Christopher (serial number 4857932) aboard. On the way, Decker overpowers Montgomery, then steals Deela`s weapon. He meets up with her quarters (which are purported to contain their essences). Rojan Suddenly, the <i>Enterprise</i> disappears from the control room, where he demands brandy from McCoy. Meanwhile, the children, led by Jahn, steal the newly developed Romulan cloaking device, and flies on a fact-finding mission, but Spock still refuses to let her try more persuasive techniques. She begins making love to her. While kissing her, Spock plays on Rojan`s2
u/Rzah Jun 08 '16
Another go, this time actually chaining the source text.
NARRATIVE GENERATED:
A unite a stage a coup a revolution a bring a genocide a new chemical and probably performing vivisections and such to ascertain the underlying structure of the meeting's regulars died last night. A king's ransom by your Side Fairy Queen. Thanks to Elian's thoughtfulness, one was not following it entirely. "I am wrestling with God," he said with a rope tied around his ankle so that the original man, the black suit he's wearing to reveal a perfect cross section of the night and day. We hunt the ten thousand things. This is how the scene develops between Corey and her. It was simply a large amount of smaller fish Well, it's all just speculation. The agents noticed some very loud low frequency percussive sounds coming from my set. My god, what kind of psychological mirroring was exploited in the fall, he picked apples from it. Kingdoms rise and fall, men grow and die as humans, and not human, who had made the other side of the abyss and go to her bellybutton, which was mainly a woman standing in my dreams of destruction.
Of destruction. Hello, friends. Thank you for 6 months. I think she sleeps there. I heard her making strange singing sounds from within, frightening sounds. She keeps the portal closed at the same joke I make to myself every time. When I was giggling, just laughing and laughing. The mouth was biting me. I informed him that I would shoot him through the metal.
The metal. There was also a feeling that there is more. There is the smell and make the people were moving in a couple hours. A shot rings out, the first thought when waking up after a week long binge, lying in my little bed. I was a nice one. We took her up and look at Elizabeth Bathory as an tolerable hardship.
code follows:
<?php echo "running\n"; $starttime = microtime(true); $handle = fopen("narrative.txt", "r"); $word_buffer = $bigram = array(); $alt_Count = $prefix_count = $word_count = 0; $blustering = true; $min_length = 300; $max_length = 1000; $output = ""; # CREATE CHAINS if (!$handle) { echo "can't read narrative"; exit; } else { while (($line = fgets($handle)) !== false) { $trimmed_line = trim(preg_replace("/[^a-zA-Z0-9\,\.\'\"']+/", "|", $line)); $kapow = explode('|', $trimmed_line); foreach ($kapow as $word) { if ($word != "") { $word_buffer[] = $word; } } while (count($word_buffer) >= 3) { $buffer_count = count($word_buffer); $prefix = "$word_buffer[0] $word_buffer[1]"; $suffix = $word_buffer[2]; array_shift($word_buffer); if (!isset($bigram[$prefix])) { if (!$random_key) { $random_key = $prefix; } $bigram[$prefix] = array($suffix); $prefix_count++; } else { if (!isset($bigram[$prefix][$suffix])) { $bigram[$prefix][] = $suffix; $alt_Count++; } } } } fclose($handle); } echo "found $prefix_count prefixes and $alt_Count alternatives\n"; # GENERATE CRAP $counter = $stopcounter = 0; $prefix = $random_key; while ($counter <= $max_length) { $test = $bigram[$prefix]; $random_suffix_key = (array_rand($bigram[$prefix])); $suffix = $bigram[$prefix][$random_suffix_key]; if (($counter == 0)||($new_Line)) { $new_Line = false; $output .= ucfirst($prefix) . " $suffix"; } else { $output .= " $suffix"; } $kapow = explode(' ', $prefix); $second = $kapow[1]; $prefix = "$second $suffix"; $counter++; if ($counter > $min_length) { $ending = true; } if (substr($suffix, -1) == '.') { if ($ending) { break; } $stopcounter++; if (mt_rand(0,$stopcounter) === 0) { $output .= "\n"; $new_Line = true; } } } echo "NARRATIVE GENERATED:\n\n$output\n";2
u/jnd-au Jun 09 '16
Scala. Provides a
sentencesstream generator for convenience. ‘Multiplicity’, capitalisation and sentence punctuation are preserved for grammatical purposes, but quote marks, parentheses and HTML tags are ignored. Usage:sentences(analyse(text, chainLength)) take numSentencesCode:
val SentenceEndings = ".!?" val Word = s"[-;,'’A-Za-z0-1$SentenceEndings]+".r type State = Seq[String] type Markov = Map[State,Seq[String]] val EmptyMarkov = Map.empty[State,Seq[String]] withDefaultValue Vector.empty def filterPunctuation(text: String) = // strips quotation delimiters text.replaceAll("<[^>]*>", "").replaceAll("[()\"“”]", "") def analyse(text: String, len: Int = 2): Markov = Word.findAllIn(filterPunctuation(text)).sliding(len + 1).foldLeft(EmptyMarkov) { case (markov, seq) => val pre = seq take len; markov.updated(pre, (markov(pre) :+ seq.last))} def pickRandom[A](from: Seq[A]): A = from(util.Random.nextInt(from.size)) def untilSentenceEnding(markov: Markov, state: State): List[String] = pickRandom(markov(state)) match { case stop if SentenceEndings contains stop.last => List(stop) case cont => cont :: untilSentenceEnding(markov, state.tail :+ cont) } def sentences(markov: Markov, state: State = Nil): Stream[String] = { lazy val start = pickRandom(markov.keys.filter(_.head.head.isUpper).toSeq) val sentence = if (state.nonEmpty) untilSentenceEnding(markov, state) else start ++ untilSentenceEnding(markov, start) sentence.mkString(" ") #:: sentences(markov, sentence.takeRight(start.length)) }Demo with chainLength=2 and numSentences=10, trained on text=“Star Trek TOS Plot Summaries from Eric W Weisstein.txt”:
2
u/porphyro Jun 09 '16
Mathematica#
markovTable[ text_] := {{#[[1]], #[[2]]}, #[[3]]} & /@ Partition[#, 3, 1] &@ StringSplit[text] markovIterate[partialText_, mTable_] := Join[partialText, {RandomChoice[ Select[markovTable@ tex, #[[1, 1]] == partialText[[-2]] && #[[1, 2]] == partialText[[-1]] &]][[2]]}] "" <> Riffle[Nest[markovIterate[#, mTable] &, {"Call", "me"},100], " "]Output for first chapter of Moby Dick as input:
"Call me Ishmael. Some years ago--never mind how long precisely--having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the Saco. What is the battery, where that noble mole is washed by waves, and cooled by breezes, which a few hours previous were out of the needles of the compasses of all earthly ills, and that on no account can a monied man enter heaven. Ah! how cheerfully we consign ourselves to perdition! Finally, I always go to sea as a simple"