aboutsummaryrefslogtreecommitdiff
path: root/part2/src/Lib.hs
blob: 22b54e9629d7dc32d4335c6f396d8048e00e7aea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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
136
module Lib
  ( processText
  , buildDictionary
  , processInput
  , twoModelDialog
  , execLogStdGen
  ) where

import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.State
import Control.Monad.Trans.Writer
import Data.Char (isLetter, isSpace, toLower)
import Data.Function ((&))
import Data.Functor.Identity
import Data.List (nub, tails)
import Data.Map (Map)
import qualified Data.Map as Map
import System.Random (StdGen, randomR)

type Log = [String]
type LogStdGen a = WriterT Log (StateT StdGen Identity) a

split :: (Char -> Bool) -> String -> [String]
split _ [] = []
split predicate s =
  let (prefix, rest) = break predicate s
   in prefix :
      case rest of
        [] -> []
        (_:xs) -> split predicate xs

processText :: String -> [[String]]
processText text = text
  & fmap (toLower)
  & split (`elem` ".!?;:()")
  & fmap (split isSpace)
  & (fmap . fmap) (filter isLetter)
  & fmap (filter (not . null))
  & filter (\s -> length s >= 2)

buildDictionary :: [[String]] -> Map String [String]
buildDictionary sentences =
  let bigrams = [(w1, w2) | s <- sentences, (w1:w2:_) <- tails s]
      trigrams = [(w1, w2, w3) | s <- sentences, (w1:w2:w3:_) <- tails s]
      bigramEntries =
        foldr
          (\(w1, w2) acc -> Map.insertWith (++) w1 [w2] acc)
          Map.empty
          bigrams
      trigramEntries =
        foldr
          (\(w1, w2, w3) acc ->
             Map.insertWith (++) w1 [w2 ++ " " ++ w3] $
             Map.insertWith (++) (w1 ++ " " ++ w2) [w3] acc)
          Map.empty
          trigrams
   in Map.map nub $ Map.unionWith (++) bigramEntries trigramEntries

random :: Int -> Int -> State StdGen Int
random f t =
  get >>= \gen ->
  let (len, gen') = randomR (f, t) gen
  in put gen' >> return len

generatePhrase :: Map String [String] -> String -> State StdGen String
generatePhrase dict start =
  random 2 15 >>= \len ->
  go start [] len
  where
    go :: String -> [String] -> Int -> State StdGen String
    go key acc n
      | n <= 0 = return $ unwords $ reverse acc
      | otherwise =
        case Map.lookup key dict of
          Nothing -> return $ unwords $ reverse acc
          Just conts ->
             random 0 (length conts - 1) >>= \i ->
              let next = conts !! i
               in go next (next : acc) (n - length (words next))

processInput :: Map String [String] -> String -> State StdGen (Maybe String)
processInput dict input =
  if Map.member input dict
    then generatePhrase dict input >>= \p -> return $ Just p
    else return Nothing

interleave :: [a] -> [a] -> [a]
interleave as bs = concat $ zipWith (\a b -> [a] ++ [b]) as bs

findKeyForResponse :: Map String [String] -> [String] -> Maybe String
findKeyForResponse dict ws =
  case dropWhile (\w -> Map.notMember w dict) keys of
    [] -> Nothing
    (x:_) -> Just x
  where
    rws = reverse ws
    keys =
      (interleave (zipWith (\a b -> b ++ " " ++ a) rws (tail $ rws)) rws) ++
      [head ws]

execLogStdGen :: StdGen -> LogStdGen a -> Log
execLogStdGen gen app = runIdentity $ evalStateT (execWriterT app) gen

dialogStep ::
     Map String [String] -> String -> String -> LogStdGen (Maybe String)
dialogStep dict prevPhrase prefix =
  case findKeyForResponse dict (words prevPhrase) of
    Nothing -> tell [prefix ++ ": There is no continuation"] >> return Nothing
    Just key ->
      lift (generatePhrase dict key) >>= \p ->
        tell [prefix ++ ": " ++ key ++ " => " ++ p] >> return (Just p)

twoModelDialog ::
     Map String [String]
  -> Map String [String]
  -> String
  -> Int
  -> LogStdGen ()
twoModelDialog dict1 dict2 start len =
  if Map.member start dict1
  then loop dict1 dict2 start 0 len
  else tell ["No such key in DICT1: " ++ start] >> return ()
  where
    loop ::
         Map String [String]
      -> Map String [String]
      -> String
      -> Int
      -> Int
      -> LogStdGen ()
    loop _ _ _ _ 0 = return ()
    loop d od prev i l =
      dialogStep d prev ("Model " ++ show (i `mod` 2 + 1)) >>= \resp ->
        case resp of
          Nothing -> return ()
          Just r -> loop od d r (i + 1) (l - 1)