From 863a5d838205c52c9a0134897b5ee28164f87295 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Sun, 8 Nov 2026 07:40:54 +0300 Subject: publish --- part2/app/Main.hs | 50 +++++++++++++++++++ part2/res/text0.txt | 1 + part2/src/Lib.hs | 136 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 187 insertions(+) create mode 100644 part2/app/Main.hs create mode 100644 part2/res/text0.txt create mode 100644 part2/src/Lib.hs (limited to 'part2') diff --git a/part2/app/Main.hs b/part2/app/Main.hs new file mode 100644 index 0000000..73a7e55 --- /dev/null +++ b/part2/app/Main.hs @@ -0,0 +1,50 @@ +module Main + ( main + ) where + +import Control.Monad.Trans.State +import Data.Map (Map) +import qualified Data.Map as Map +import Lib +import System.Environment (getArgs, getProgName) +import System.Exit (die) +import System.IO +import System.Random (getStdGen) +import UnescapingPrint (ushow) + +saveDictionary :: FilePath -> Map String [String] -> IO () +saveDictionary filePath dict = + withFile filePath WriteMode $ \h -> + mapM_ + (\(k, v) -> hPutStrLn h $ ushow k ++ ": " ++ ushow v) + (Map.toList dict) + +main :: IO () +main = + getArgs >>= \args -> + getStdGen >>= \gen -> + case args of + (dict1Path:initial:dict2Path:nstr:[]) -> + readFile dict1Path >>= \text1 -> + readFile dict2Path >>= \text2 -> + let dict1 = buildDictionary (processText text1) + dict2 = buildDictionary (processText text2) + n = read nstr :: Int + in saveDictionary "./tmp/dict1.txt" dict1 >> + saveDictionary "./tmp/dict2.txt" dict2 >> + mapM_ + putStrLn + (execLogStdGen gen $ twoModelDialog dict1 dict2 initial n) + (dictPath:initial:[]) -> + readFile dictPath >>= \text -> + let dict = buildDictionary (processText text) + in saveDictionary "./tmp/dict.txt" dict >> + case evalState (processInput dict initial) gen of + Just s -> putStrLn s + Nothing -> + die $ + "There is no \"" ++ + initial ++ "\" in the constructed dictionary!" + _ -> + getProgName >>= \arg0 -> + die $ "Usage: " ++ arg0 ++ " DICT1 INITIAL [DICT2 N]" diff --git a/part2/res/text0.txt b/part2/res/text0.txt new file mode 100644 index 0000000..1700adc --- /dev/null +++ b/part2/res/text0.txt @@ -0,0 +1 @@ +a b, c d e! b c d? e b c# a ^d. a f; f. diff --git a/part2/src/Lib.hs b/part2/src/Lib.hs new file mode 100644 index 0000000..22b54e9 --- /dev/null +++ b/part2/src/Lib.hs @@ -0,0 +1,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) -- cgit v1.3.1