code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE DeriveGeneric, TypeOperators #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE OverloadedStrings #-} module Hop.Hoplite.Eval where import Hop.Hoplite.Heap import Control.Monad.RWS.Class import Control.Monad.RWS.Strict import Data.Typeable import Data.Data import GHC.Generics import qualified Data.Map.Strict as Map import Numeric.Natural import Data.Text (Text,pack) import Bound import Hop.Hoplite.Types import Control.Lens (view,_1,makeLenses) import Hop.Hoplite.STExcept data Cmd = Cmd { from :: Text , to :: Text , posAmount :: Rational , fakeCryptoSig:: Text } deriving (Eq,Ord,Show,Read,Data,Typeable) data ExpContext ty a = SCEmpty | LetContext (Maybe Text) (Scope (Maybe Text) (Exp ty) a) (ExpContext ty a) | FunAppCtxt [Ref] [Exp ty a] (ExpContext ty a) | PrimAppCtxt PrimOpId [Ref] [Exp ty a] (ExpContext ty a) deriving (Typeable ,Functor ,Foldable ,Traversable ,Generic ,Data ,Eq ,Ord ,Show) data InterpreterError = PrimopTypeMismatch | NonClosureInApplicationPosition | ArityMismatchFailure | HeapLookupFailure | MalformedClosure | MismatchedStackContext | PrimFailure String | UnsupportedTermConstructFailure String deriving (Eq,Ord,Show,Typeable,Data) newtype TransactionId = TransactionId Natural deriving (Eq, Show, Num, Enum, Ord) newtype OpId = OpId Natural deriving (Eq, Show, Num, Enum, Ord) type OrderedOp = (OpId, Cmd) data PersistentState = PersistentState { _persistentNextTxId :: TransactionId , _persistentBalances :: Map.Map Text Rational , _persistentTxes :: [(TransactionId, [OrderedOp])] } deriving (Eq, Show) data InterpreterOverlay = InterpreterOverlay { _overlayNextOpId :: OpId , _overlayBalances :: Map.Map Text Rational } deriving (Eq, Show) newtype BalancesDiff = BalancesDiff { _balancesDiff :: Map.Map Text (Rational, Rational) } -- (before, after) deriving (Eq, Show) data InterpreterDiff = InterpreterDiff { _interpDiffBalances :: BalancesDiff , _interpDiffOps :: [OrderedOp] } deriving (Eq, Show) data InterpreterOutput = InterpreterOutput { _outputDiff :: InterpreterDiff , _outputNextState :: PersistentState } deriving (Eq, Show) $(makeLenses ''PersistentState) $(makeLenses ''InterpreterOverlay) $(makeLenses ''BalancesDiff) $(makeLenses ''InterpreterDiff) $(makeLenses ''InterpreterOutput) initialState :: PersistentState initialState = PersistentState 0 Map.empty [] emptyOverlay :: InterpreterOverlay emptyOverlay = InterpreterOverlay 0 Map.empty -- -- TODO: test mkOutput -- mkOutput :: InterpreterOverlay -> [OrderedOp] -> PersistentState -> InterpreterOutput mkOutput (InterpreterOverlay _ overlayBals) ops (PersistentState txId bals txes) = InterpreterOutput diff nextState where balChanges = Map.intersectionWith (\ a b -> (a, b)) bals overlayBals diff = InterpreterDiff (BalancesDiff balChanges) ops nextState = PersistentState (succ txId) (overlayBals `mappend` bals) ((txId, ops) : txes) runExpr :: Natural -> PersistentState -> (forall v . Exp () v) -- guarantees we have no free variables -> Either (() :+ InterpreterError :+ HeapError) InterpreterOutput runExpr step st expr = fmap projectOutput $ handleSTE id $ runEmptyHeap step $ runRWST (evalExp SCEmpty expr) env emptyOverlay where env = _persistentBalances st projectOutput ((_heapVal, overlay, ops), _heap) = mkOutput overlay ops st type InterpStack s ty b a = RWST (Map.Map Text Rational) [OrderedOp] InterpreterOverlay (HeapStepCounterM (Exp ty) (STE (b :+ InterpreterError :+ HeapError) s)) a evalExp :: (Ord ty,Show ty) => ExpContext ty Ref -> Exp ty Ref -> InterpStack s ty b (HeapVal (Exp ty), Ref) evalExp stk (V rf) = do rp@(_hpval,_ref) <- lift $ heapRefLookupTransitive rf applyStack stk rp evalExp _stk (Force _e)= throwInterpError $ UnsupportedTermConstructFailure "Force" evalExp _stk (Delay _e) = throwInterpError $ UnsupportedTermConstructFailure "Delay" evalExp stk (funE :@ args) = evalClosureApp (FunAppCtxt [] (funE:args) stk ) evalExp stk (ELit l) = do ref <- lift $ heapAllocate (VLitF l) ; applyStack stk (VLitF l, ref) evalExp stk (PrimApp name args) = evalPrimApp (PrimAppCtxt name [] args stk ) evalExp stk (Lam ts bod) = do let val = DirectClosureF (MkClosure (map (ArityBoxed . view _1 )ts ) bod) ref <- lift $ heapAllocate val applyStack stk (val,ref) evalExp stk (Let mv _mty rhsExp scp) = evalExp (LetContext mv scp stk) rhsExp noBlackholeArgs :: (Ord ty,Show ty) => [Ref] -> InterpStack s ty b () noBlackholeArgs rls = lift $ void $ traverse heapRefLookupTransitive rls throwInterpError :: InterpreterError -> InterpStack s ty b a throwInterpError e =lift $ lift $ throwSTE $ (InL . InR) e evalClosureApp :: forall ty s b . (Show ty, Ord ty) => ExpContext ty Ref -> InterpStack s ty b (HeapVal (Exp ty), Ref) evalClosureApp (FunAppCtxt ls [] stk) = do (funRef:argsRef) <- return $ reverse ls (val,_ref) <- lift $ heapRefLookupTransitive funRef noBlackholeArgs argsRef case val of (DirectClosureF (MkClosure wrpNames scp)) | length argsRef == length wrpNames -> let nmMap = Map.fromList $ zip (map _extractArityInfo wrpNames) argsRef substApply :: Var Text (Exp ty2 Ref) -> InterpStack s ty b (Exp ty2 Ref) substApply var = case var of (B nm) -> maybe (throwInterpError MalformedClosure) (\ rf -> lift $ return $ V rf) (Map.lookup nm nmMap) (F term) -> return term in do nextExp <- traverse substApply $ unscope scp evalExp stk $ join nextExp | otherwise -> throwInterpError ArityMismatchFailure _ -> throwInterpError NonClosureInApplicationPosition evalClosureApp (FunAppCtxt ls (h : t) stk) = evalExp (FunAppCtxt ls t stk) h evalClosureApp LetContext {} = throwInterpError MismatchedStackContext evalClosureApp PrimAppCtxt {} = throwInterpError MismatchedStackContext evalClosureApp SCEmpty = throwInterpError MismatchedStackContext evalPrimApp ::(Show ty, Ord ty) => ExpContext ty Ref -> InterpStack s ty b (HeapVal (Exp ty), Ref) evalPrimApp (PrimAppCtxt nm args [] stk) = do noBlackholeArgs args ; applyPrim stk nm $ reverse args evalPrimApp (PrimAppCtxt nm args (h:t) stk) = evalExp (PrimAppCtxt nm args t stk) h evalPrimApp LetContext {} = throwInterpError MismatchedStackContext evalPrimApp FunAppCtxt {} = throwInterpError MismatchedStackContext evalPrimApp SCEmpty = throwInterpError MismatchedStackContext applyStack :: (Ord ty,Show ty) => ExpContext ty Ref -> (HeapVal (Exp ty),Ref) -> InterpStack s ty b (HeapVal (Exp ty), Ref) applyStack SCEmpty p = return p applyStack (LetContext _mv scp stk) (_v,ref) = evalExp stk (instantiate1 (V ref) scp) applyStack (FunAppCtxt ls [] stk) (_,ref) = evalClosureApp (FunAppCtxt (ref : ls) [] stk) applyStack (FunAppCtxt ls (h:t) stk) (_,ref) = evalExp (FunAppCtxt (ref:ls) t stk) h applyStack (PrimAppCtxt nm revArgs [] stk) (_,ref) = evalPrimApp (PrimAppCtxt nm (ref:revArgs) [] stk) applyStack (PrimAppCtxt nm revargs (h:t) stk) (_,ref) = evalExp (PrimAppCtxt nm (ref : revargs) t stk) h lookupPrimAccountBalance :: (Ord ty,Show ty) => Text -> InterpStack s ty b (Maybe Rational) lookupPrimAccountBalance acctNam = do InterpreterOverlay _nextOpId localizedMap <- get case Map.lookup acctNam localizedMap of Just v -> return $ Just v Nothing -> do snapshotMap :: (Map.Map Text Rational ) <- ask case Map.lookup acctNam snapshotMap of Just a -> return $ Just a Nothing -> return Nothing -- this may abort if target account doesn't exist updatePrimAccountBalanceByAdding :: (Ord ty,Show ty) => Text -> Rational -> InterpStack s ty b () updatePrimAccountBalanceByAdding nm amt = do currentBalance <- lookupPrimAccountBalance nm case currentBalance of Nothing -> throwInterpError $ PrimFailure "account doesn't exist " Just current -> do InterpreterOverlay nextOpId localizedMap <- get put $ InterpreterOverlay nextOpId $ (Map.insert nm $! (current + amt)) localizedMap applyPrim :: (Ord ty,Show ty) => ExpContext ty Ref -> PrimOpId -> [Ref] -> InterpStack s ty b (HeapVal (Exp ty), Ref) applyPrim ctxt opid argsRef = do resPair <- applyPrimDemo opid argsRef applyStack ctxt resPair applyRationalArithmetic :: (Ord ty, Show ty) => (Rational -> Rational -> Rational) -> [Ref] -> InterpStack s ty b (HeapVal (Exp ty), Ref) applyRationalArithmetic f [ref1, ref2] = do (ratLit1, _posRatRef) <- lift $ heapRefLookupTransitive ref1 (ratLit2, _posRatRef) <- lift $ heapRefLookupTransitive ref2 case (ratLit1, ratLit2) of (VLitF (LRational rat1), VLitF (LRational rat2)) -> do let val = VLitF $ LRational $ rat1 `f` rat2 ref <- lift $ heapAllocate val return (val,ref) b -> error $ "deep invariant failure: bad args to arithmetic primop, the arguments were" ++ show b applyRationalArithmetic _ refs = error $ "deep invariant failure: wrong number of args to arithmetic primop (2 instead of " ++ show (length refs) ++ ")" applyPrimDemo :: (Ord ty,Show ty) => PrimOpId -> [Ref] -> InterpStack s ty b (HeapVal (Exp ty), Ref) applyPrimDemo (PrimopId "transfer") [fromRef,toRef,posRatRef,fakeCryptoSigRef] = do (fromVal,_reffrom) <- lift $ heapRefLookupTransitive fromRef (toVal,_refto) <- lift $ heapRefLookupTransitive toRef (posRatVal,_posRatRef) <- lift $ heapRefLookupTransitive posRatRef (fakeSigVal,_fakeSigRef) <- lift $ heapRefLookupTransitive fakeCryptoSigRef case (fromVal,toVal,posRatVal,fakeSigVal) of (VLitF (LText fromNm), VLitF (LText toNm), VLitF (LRational amt), VLitF (LText demoSig)) | amt < 0 -> error "transfer command was invoked with a negative amount" | otherwise -> do sourceBalanceM <- lookupPrimAccountBalance fromNm targetBalanceM <- lookupPrimAccountBalance toNm case (sourceBalanceM,targetBalanceM) of (Just _srcB ,Just _targetB) -> do updatePrimAccountBalanceByAdding fromNm (-amt) updatePrimAccountBalanceByAdding toNm amt InterpreterOverlay nextOpId mp <- get tell [(nextOpId, Cmd fromNm toNm amt demoSig)] put $ InterpreterOverlay (succ nextOpId) mp let val = VLitF $ LText $ pack "success" ref <- lift $ heapAllocate val -- this shoudld be unit, but whatever return (val,ref) _bad -> throwInterpError $ PrimFailure $ "invalid account(s)" ++ show (fromNm, toNm) b -> error $ "deep invariant failure : bad args to transfer primop, the arguments were" ++ show b applyPrimDemo (PrimopId "+") refs = applyRationalArithmetic (+) refs applyPrimDemo (PrimopId "-") refs = applyRationalArithmetic (-) refs applyPrimDemo (PrimopId "*") refs = applyRationalArithmetic (*) refs applyPrimDemo (PrimopId "/") refs = applyRationalArithmetic (/) refs applyPrimDemo a b = error $ "called command " ++ show a ++ " with " ++ show (length b) ++ " arguments"
haroldcarr/juno
z-no-longer-used/src/Hop/Hoplite/Eval.hs
bsd-3-clause
12,445
0
22
3,222
3,855
1,973
1,882
246
3
-- | This module provides a simple default configuration which behaves similar -- to a tool such as the Jekyll static site generator (<http://jekyllrb.com/>). -- -- The idea is that you don't have to write your configuration yourself: you -- just follow some conventions, and Hakyll does the rest. -- -- You can generate a site which will serve as a good starting point by running -- the command-line tool: -- -- > hakyll-contrib small-blog -- -- Hakyll will then generate a simple example site for you. The necessary -- configuration is placed in the @small-blog.hs@ file. Compile and run it to create -- the demo site: -- -- > ghc --make small-blog.hs -- > ./small-blog build -- > ./small-blog preview -- -- So, in order to get your site going, you need to follow the conventions for -- the content on your site. -- -- Images should be placed in the @images\/@ or @img\/@ folder. The are copied -- directly. Other static files (but not images) can be placed in @static\/@ or -- @files\/@. The @favicon.ico@ file is an exception, it is just placed in the -- top-level directory. -- -- CSS files should be placed in @css\/@, and JavaScript files in @js\/@. -- -- Then, we arrive at pages. You can create any number of pages on your site: -- just create files in one of the documents pandoc supports (@.html@, -- @.markdown@, @.rst@, @.lhs@...) in the top-level directory. -- -- These pages may use a number of preconfigured @$key$@'s: -- -- * @$recentPosts$@: A list of recent posts, displayed from most recent to -- oldest. By default, 3 posts are shown, altough this can be configured using -- the 'numberOfRecentPosts' field. -- -- * @$allPosts$@: A list of all posts, displayed from most recent to oldest. -- This is very useful for creating an archive page. -- -- * @$chronologicalPosts$@: Similar to @$allPosts$@, but displays the posts in -- chronological order. -- -- For example usage, look at the example site we generated using -- @hakyll-contrib small-blog@. -- -- Now, one can wonder where these posts come from. Simple: all pages in the -- @posts\/@ directory are considered posts. Note that a naming format of -- -- > posts/year-month-date-title.extension -- -- is mandatory. An example: -- -- > posts/2011-06-19-hello-world.markdown -- -- This allows Hakyll to parse the date easily, among other things. Again, look -- at the example site for some example posts. -- -- Additionaly, there is the @templates\/@ folder. This folder holds the -- templates for your site. For a @small-blog@ configuration, your site should -- have /exactly/ three templates: -- -- * @templates\/default.html@: The main template. This should contain your -- HTML doctype, head, etc. -- -- * @templates\/post.html@: A template which is applied to every post before -- it is rendered using the default template. -- -- * @templates\/post-item.html@: A template which is applied to posts in -- listings (e.g. @$chronologicalPosts$@). -- -- Again, the example should clarify things. -- -- This configuration should be enough to create a small personal website. But, -- we have only touched the surface of what is possible with Hakyll. For more -- information, check out the tutorials at: <http://jaspervdj.be/hakyll> -- {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} module Hakyll.Contrib.SmallBlog ( SmallBlogConfiguration (..) , defaultSmallBlogConfiguration , smallBlog , smallBlogWith ) where import Control.Arrow ((>>>)) import Text.Pandoc (ParserState, WriterOptions) import Hakyll -- | Configuration datatype for the 'smallBlog' ruleset -- data SmallBlogConfiguration = SmallBlogConfiguration { -- | Number of recent posts that are available numberOfRecentPosts :: Int , -- | Parser state for pandoc, i.e. read options parserState :: ParserState , -- | Writer options for pandoc writerOptions :: WriterOptions , -- | Atom feed configuration atomFeed :: Maybe FeedConfiguration } deriving (Show) -- | Defaults for 'SmallBlogConfiguration' -- defaultSmallBlogConfiguration :: SmallBlogConfiguration defaultSmallBlogConfiguration = SmallBlogConfiguration { numberOfRecentPosts = 3 , parserState = defaultHakyllParserState , writerOptions = defaultHakyllWriterOptions , atomFeed = Nothing } -- | A default configuration for a small blog -- smallBlog :: Rules smallBlog = smallBlogWith defaultSmallBlogConfiguration -- | Version of 'smallBlog' which allows setting a config -- smallBlogWith :: SmallBlogConfiguration -> Rules smallBlogWith conf = do -- Images and static files ["favicon.ico"] --> copy ["img/**", "images/**"] --> copy ["static/**", "files/**"] --> copy ["js/**", "javascript/**"] --> copy -- CSS files ["css/*.css", "style/*.css", "stylesheets/*.css"] --> css -- All templates ["templates/*"] --> template -- "Dynamic" content ["posts/*"] --> post -- Top-level pages ["*.markdown", "*.md", "*.html", "*.rst", "*.lhs"] --> topLevel -- Rss is optional case atomFeed conf of Nothing -> return () Just f -> do match "atom.xml" $ route idRoute create "atom.xml" $ requireAll_ "posts/*" >>> renderAtom f return () where -- Useful combinator here xs --> f = mapM_ (\p -> match p $ f) xs -- Completely static copy = route idRoute >> compile copyFileCompiler -- CSS directories css = route (setExtension "css") >> compile compressCssCompiler -- Templates template = compile templateCompiler -- Posts post = do route $ setExtension "html" compile $ pageCompilerWith (parserState conf) (writerOptions conf) >>> applyTemplateCompiler "templates/post.html" >>> applyTemplateCompiler "templates/default.html" >>> relativizeUrlsCompiler -- Top-level pages topLevel = do route $ setExtension "html" compile $ pageCompilerWithFields (parserState conf) (writerOptions conf) id topLevelFields >>> applyTemplateCompiler "templates/default.html" >>> relativizeUrlsCompiler -- Add the fields we need to top-level pages topLevelFields = setFieldPostList recentFirst "allPosts" >>> setFieldPostList (take nRecent . recentFirst) "recentPosts" >>> setFieldPostList chronological "chronologicalPosts" -- Create a post list based on ordering/selection setFieldPostList f k = setFieldPageList f "templates/post-item.html" k "posts/*" -- Number of most recent posts to show nRecent = numberOfRecentPosts conf
jaspervdj/hakyll-contrib
src/Hakyll/Contrib/SmallBlog.hs
bsd-3-clause
6,730
0
15
1,430
701
414
287
62
2
{-# LANGUAGE OverloadedStrings #-} module Controllers.TagsTest (tests) where import Data.Text (Text) import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit ((@?=)) import Controllers.Tag import Models.Tag tests :: Test tests = testGroup "Test.Controllers.Tag.saveTags" [ testCase "just empty if input empty" $ (@?=) (filterExistsTags [] []) [] , testCase "just return if no-exists" $ (@?=) (filterExistsTags inputTags []) inputTags , testCase "just empty if input empyt" $ (@?=) (filterExistsTags [] exTags) [] , testCase "got tag1 as only it is new" $ (@?=) (filterExistsTags inputTags exTags) newTag ] -- | All replies which have no children replies -- --testReplyWithoutChildren :: Assertion -------------------------------------------------- -- Exists Tag exTags :: [Tag] exTags = map textToTag inputTagsText textToTag :: Text -> Tag textToTag name = emptyTag { _tagName = name } inputTags :: [Tag] inputTags = newTag ++ exTags newTag :: [Tag] newTag = map textToTag newTagText inputTagsText :: [Text] inputTagsText = ["tag3", "tag2"] newTagText :: [Text] newTagText = ["tag1"]
HaskellCNOrg/snap-web
tests/Controllers/TagsTest.hs
bsd-3-clause
1,284
0
11
304
314
181
133
26
1
-- | Command line parsing flags. module Development.Shake.Args(shakeOptDescrs, shakeArgs, shakeArgsWith) where import Paths_shake import Development.Shake.Types import Development.Shake.Core import Development.Shake.File import Development.Shake.FilePath import Development.Shake.Progress import Development.Shake.Shake import Development.Shake.Timing import Control.Arrow import Control.Concurrent import Control.Exception import Control.Monad import Data.Char import Data.Either import Data.List import Data.Maybe import Data.Time import Data.Version(showVersion) import System.Console.GetOpt import System.Directory import System.Environment import System.Exit -- | Run a build system using command line arguments for configuration. -- The available flags are those from 'shakeOptDescrs', along with a few additional -- @make@ compatible flags that are not represented in 'ShakeOptions', such as @--print-directory@. -- If there are no file arguments then the 'Rules' are used directly, otherwise the file arguments -- are 'want'ed (after calling 'withoutActions'). As an example: -- -- @ -- main = 'shakeArgs' 'shakeOptions'{'shakeFiles' = \"_make/\", 'shakeProgress' = 'progressSimple'} $ do -- 'phony' \"clean\" $ 'Development.Shake.removeFilesAfter' \"_make\" [\"\/\/*\"] -- 'want' [\"_make\/neil.txt\",\"_make\/emily.txt\"] -- \"_make\/*.txt\" '*>' \\out -> -- ... build action here ... -- @ -- -- This build system will default to building @neil.txt@ and @emily.txt@, while showing progress messages, -- and putting the Shake files in locations such as @_make\/.database@. Some example command line flags: -- -- * @main --no-progress@ will turn off progress messages. -- -- * @main -j6@ will build on 6 threads. -- -- * @main --help@ will display a list of supported flags. -- -- * @main clean@ will not build anything, but will remove the @_make@ directory, including the -- any 'shakeFiles'. -- -- * @main _make/henry.txt@ will not build @neil.txt@ or @emily.txt@, but will instead build @henry.txt@. shakeArgs :: ShakeOptions -> Rules () -> IO () shakeArgs opts rules = shakeArgsWith opts [] f where f _ files = return $ Just $ if null files then rules else want (map normalise files) >> withoutActions rules -- | A version of 'shakeArgs' with more flexible handling of command line arguments. -- The caller of 'shakeArgsWith' can add additional flags (the second argument) and chose how to convert -- the flags/arguments into rules (the third argument). Given: -- -- @ -- 'shakeArgsWith' opts flags (\\flagValues argValues -> result) -- @ -- -- * @opts@ is the initial 'ShakeOptions' value, which may have some fields overriden by command line flags. -- This argument is usually 'shakeOptions', perhaps with a few fields overriden. -- -- * @flags@ is a list of flag descriptions, which either produce a 'String' containing an error -- message (typically for flags with invalid arguments, .e.g. @'Left' \"could not parse as int\"@), or a value -- that is passed as @flagValues@. If you have no custom flags, pass @[]@. -- -- * @flagValues@ is a list of custom flags that the user supplied. If @flags == []@ then this list will -- be @[]@. -- -- * @argValues@ is a list of non-flag arguments, which are often treated as files and passed to 'want'. -- -- * @result@ should produce a 'Nothing' to indicate that no building needs to take place, or a 'Just' -- providing the rules that should be used. -- -- As an example of a build system that can use either @gcc@ or @distcc@ for compiling: -- -- @ --import System.Console.GetOpt -- --data Flags = DistCC deriving Eq --flags = [Option \"\" [\"distcc\"] (NoArg $ Right DistCC) \"Run distributed.\"] -- --main = 'shakeArgsWith' 'shakeOptions' flags $ \\flags targets -> return $ Just $ do -- if null targets then 'want' [\"result.exe\"] else 'want' targets -- let compiler = if DistCC \`elem\` flags then \"distcc\" else \"gcc\" -- \"*.o\" '*>' \\out -> do -- 'need' ... -- 'cmd' compiler ... -- ... -- @ -- -- Now you can pass @--distcc@ to use the @distcc@ compiler. shakeArgsWith :: ShakeOptions -> [OptDescr (Either String a)] -> ([a] -> [String] -> IO (Maybe (Rules ()))) -> IO () shakeArgsWith baseOpts userOptions rules = do addTiming "shakeArgsWith" args <- getArgs let (flags,files,errs) = getOpt Permute opts args (flagsError,flag1) = partitionEithers flags (self,user) = partitionEithers flag1 (flagsExtra,flagsShake) = first concat $ unzip self assumeNew = [x | AssumeNew x <- flagsExtra] assumeOld = [x | AssumeOld x <- flagsExtra] changeDirectory = listToMaybe [x | ChangeDirectory x <- flagsExtra] printDirectory = last $ False : [x | PrintDirectory x <- flagsExtra] shakeOpts = foldl (flip ($)) baseOpts flagsShake -- error if you pass some clean and some dirty with specific flags errs <- return $ errs ++ flagsError ++ ["cannot mix " ++ a ++ " and " ++ b | a:b:_ <- [["`--assume-new'" | assumeNew/=[] ] ++ ["`--assume-old'" | assumeOld/=[] ] ++ ["explicit targets" | files/=[]]]] when (errs /= []) $ do putStr $ unlines $ map ("shake: " ++) $ filter (not . null) $ lines $ unlines errs showHelp exitFailure if Help `elem` flagsExtra then do showHelp else if Version `elem` flagsExtra then putStrLn $ "Shake build system, version " ++ showVersion version else do when (Sleep `elem` flagsExtra) $ threadDelay 1000000 start <- getCurrentTime curdir <- getCurrentDirectory let redir = case changeDirectory of Nothing -> id -- get the "html" directory so it caches with the current directory -- required only for debug code Just d -> bracket_ (getDataFileName "html" >> setCurrentDirectory d) (setCurrentDirectory curdir) (ran,res) <- redir $ do when printDirectory $ putStrLn $ "shake: In directory `" ++ curdir ++ "'" rules <- rules user files case rules of Nothing -> return (False,Right ()) Just rules -> do res <- try $ shake shakeOpts rules return (True, res) if not ran || shakeVerbosity shakeOpts < Normal || NoTime `elem` flagsExtra then either throwIO return res else let esc code = if Color `elem` flagsExtra then escape code else id in case res of Left err -> if Exception `elem` flagsExtra then throw err else do putStrLn $ esc "31" $ show (err :: SomeException) exitFailure Right () -> do stop <- getCurrentTime let tot = diffUTCTime stop start (mins,secs) = divMod (ceiling tot) (60 :: Int) time = show mins ++ ":" ++ ['0' | secs < 10] ++ show secs putStrLn $ esc "32" $ "Build completed in " ++ time ++ "m" where opts = map (wrap Left . snd) shakeOptsEx ++ map (wrap Right) userOptions showHelp = putStr $ unlines $ "Usage: shake [options] [target] ..." : "Options:" : showOptDescr opts wrap :: (a -> b) -> OptDescr (Either String a) -> OptDescr (Either String b) wrap f = fmapOptDescr (either Left (Right . f)) showOptDescr :: [OptDescr a] -> [String] showOptDescr xs = concat [ if nargs <= 26 then [" " ++ args ++ replicate (28 - nargs) ' ' ++ desc] else [" " ++ args, replicate 30 ' ' ++ desc] | Option s l arg desc <- xs , let args = intercalate ", " $ map (short arg) s ++ map (long arg) l , let nargs = length args] where short NoArg{} x = "-" ++ [x] short (ReqArg _ b) x = "-" ++ [x] ++ " " ++ b short (OptArg _ b) x = "-" ++ [x] ++ "[=" ++ b ++ "]" long NoArg{} x = "--" ++ x long (ReqArg _ b) x = "--" ++ x ++ "=" ++ b long (OptArg _ b) x = "--" ++ x ++ "[=" ++ b ++ "]" fmapOptDescr :: (a -> b) -> OptDescr a -> OptDescr b fmapOptDescr f (Option a b c d) = Option a b (g c) d where g (NoArg a) = NoArg $ f a g (ReqArg a b) = ReqArg (f . a) b g (OptArg a b) = OptArg (f . a) b -- | A list of command line options that can be used to modify 'ShakeOptions'. Each option returns -- either an error message (invalid argument to the flag) or a function that changes some fields -- in 'ShakeOptions'. The command line flags are @make@ compatible where possbile, but additional -- flags have been added for the extra options Shake supports. shakeOptDescrs :: [OptDescr (Either String (ShakeOptions -> ShakeOptions))] shakeOptDescrs = [fmapOptDescr (either Left (Right . snd)) o | (True, o) <- shakeOptsEx] data Extra = ChangeDirectory FilePath | Version | AssumeNew FilePath | AssumeOld FilePath | PrintDirectory Bool | Color | Help | Sleep | NoTime | Exception deriving Eq unescape :: String -> String unescape ('\ESC':'[':xs) = unescape $ drop 1 $ dropWhile (not . isAlpha) xs unescape (x:xs) = x : unescape xs unescape [] = [] escape :: String -> String -> String escape code x = "\ESC[" ++ code ++ "m" ++ x ++ "\ESC[0m" -- | True if it has a potential effect on ShakeOptions shakeOptsEx :: [(Bool, OptDescr (Either String ([Extra], ShakeOptions -> ShakeOptions)))] shakeOptsEx = [yes $ Option "a" ["abbrev"] (pairArg "abbrev" "FULL=SHORT" $ \a s -> s{shakeAbbreviations=shakeAbbreviations s ++ [a]}) "Use abbreviation in status messages." ,yes $ Option "B" ["always-make"] (noArg $ \s -> s{shakeAssume=Just AssumeDirty}) "Unconditionally make all targets." ,no $ Option "C" ["directory"] (ReqArg (\x -> Right ([ChangeDirectory x],id)) "DIRECTORY") "Change to DIRECTORY before doing anything." ,yes $ Option "" ["color","colour"] (NoArg $ Right ([Color], \s -> s{shakeOutput=outputColor (shakeOutput s)})) "Colorize the output." ,yes $ Option "d" ["debug"] (OptArg (\x -> Right ([], \s -> s{shakeVerbosity=Diagnostic, shakeOutput=outputDebug (shakeOutput s) x})) "FILE") "Print lots of debugging information." ,no $ Option "" ["exception"] (NoArg $ Right ([Exception], id)) "Throw exceptions directly." ,yes $ Option "" ["flush"] (intArg "flush" "N" (\i s -> s{shakeFlush=Just i})) "Flush metadata every N seconds." ,yes $ Option "" ["never-flush"] (noArg $ \s -> s{shakeFlush=Nothing}) "Never explicitly flush metadata." ,no $ Option "h" ["help"] (NoArg $ Right ([Help],id)) "Print this message and exit." ,yes $ Option "j" ["jobs"] (intArg "jobs" "N" $ \i s -> s{shakeThreads=i}) "Allow N jobs/threads at once." ,yes $ Option "k" ["keep-going"] (noArg $ \s -> s{shakeStaunch=True}) "Keep going when some targets can't be made." ,yes $ Option "l" ["lint"] (noArg $ \s -> s{shakeLint=True}) "Perform limited validation after the run." ,yes $ Option "" ["no-lint"] (noArg $ \s -> s{shakeLint=False}) "Turn off --lint." ,yes $ Option "m" ["metadata"] (reqArg "PREFIX" $ \x s -> s{shakeFiles=x}) "Prefix for storing metadata files." ,no $ Option "o" ["old-file","assume-old"] (ReqArg (\x -> Right ([AssumeOld x],id)) "FILE") "Consider FILE to be very old and don't remake it." ,yes $ Option "" ["old-all"] (noArg $ \s -> s{shakeAssume=Just AssumeClean}) "Don't remake any files." ,yes $ Option "" ["assume-skip"] (noArg $ \s -> s{shakeAssume=Just AssumeSkip}) "Don't remake any files this run." ,yes $ Option "r" ["report"] (OptArg (\x -> Right ([], \s -> s{shakeReport=Just $ fromMaybe "report.html" x})) "FILE") "Write out profiling information [to report.html]." ,yes $ Option "" ["no-report"] (noArg $ \s -> s{shakeReport=Nothing}) "Turn off --report." ,yes $ Option "" ["rule-version"] (reqArg "VERSION" $ \x s -> s{shakeVersion=x}) "Version of the build rules." ,yes $ Option "s" ["silent"] (noArg $ \s -> s{shakeVerbosity=Silent}) "Don't print anything." ,no $ Option "" ["sleep"] (NoArg $ Right ([Sleep],id)) "Sleep for a second before building." ,yes $ Option "S" ["no-keep-going","stop"] (noArg $ \s -> s{shakeStaunch=False}) "Turns off -k." ,yes $ Option "" ["storage"] (noArg $ \s -> s{shakeStorageLog=True}) "Write a storage log." ,yes $ Option "p" ["progress"] (optIntArg "progress" "N" (\i s -> s{shakeProgress=progressDisplay (fromMaybe 5 i) progressTitlebar})) "Show progress messages [every N seconds, default 5]." ,yes $ Option " " ["no-progress"] (noArg $ \s -> s{shakeProgress=const $ return ()}) "Don't show progress messages." ,yes $ Option "q" ["quiet"] (noArg $ \s -> s{shakeVerbosity=move (shakeVerbosity s) pred}) "Don't print much." ,no $ Option "" ["no-time"] (NoArg $ Right ([NoTime],id)) "Don't print build time." ,yes $ Option "" ["timings"] (noArg $ \s -> s{shakeTimings=True}) "Print phase timings." ,yes $ Option "t" ["touch"] (noArg $ \s -> s{shakeAssume=Just AssumeClean}) "Assume targets are clean." ,yes $ Option "V" ["verbose","trace"] (noArg $ \s -> s{shakeVerbosity=move (shakeVerbosity s) succ}) "Print tracing information." ,no $ Option "v" ["version"] (NoArg $ Right ([Version],id)) "Print the version number and exit." ,no $ Option "w" ["print-directory"] (NoArg $ Right ([PrintDirectory True],id)) "Print the current directory." ,no $ Option "" ["no-print-directory"] (NoArg $ Right ([PrintDirectory False],id)) "Turn off -w, even if it was turned on implicitly." ,no $ Option "W" ["what-if","new-file","assume-new"] (ReqArg (\x -> Right ([AssumeNew x],id)) "FILE") "Consider FILE to be infinitely new." ] where yes = (,) True no = (,) False move :: Verbosity -> (Int -> Int) -> Verbosity move x by = toEnum $ min (fromEnum mx) $ max (fromEnum mn) $ by $ fromEnum x where (mn,mx) = (asTypeOf minBound x, asTypeOf maxBound x) noArg f = NoArg $ Right ([], f) reqArg a f = ReqArg (\x -> Right ([], f x)) a intArg flag a f = flip ReqArg a $ \x -> case reads x of [(i,"")] | i >= 1 -> Right ([],f i) _ -> Left $ "the `--" ++ flag ++ "' option requires a positive integral argument" optIntArg flag a f = flip OptArg a $ maybe (Right ([], f Nothing)) $ \x -> case reads x of [(i,"")] | i >= 1 -> Right ([],f $ Just i) _ -> Left $ "the `--" ++ flag ++ "' option only allows a positive integral argument" pairArg flag a f = flip ReqArg a $ \x -> case break (== '=') x of (a,'=':b) -> Right ([],f (a,b)) _ -> Left $ "the `--" ++ flag ++ "' option requires an = in the argument" outputDebug output Nothing = output outputDebug output (Just file) = \v msg -> do when (v /= Diagnostic) $ output v msg appendFile file $ unescape msg outputColor output v msg = output v $ escape "34" msg
nh2/shake
Development/Shake/Args.hs
bsd-3-clause
15,139
0
26
3,684
4,319
2,309
2,010
179
9
module Parser.Simulate (doParseSim) where import qualified Data.Text as T import Parser.Utils import Text.Parsec import Text.Parsec.String doParseSim :: T.Text -> Either ParseError [Bool] doParseSim = runParser parseSim () "" . T.unpack . stripLines parseOneSim :: Parser Bool parseOneSim = parseAccept <|> parseReject parseAccept :: Parser Bool parseAccept = string "accept" >> return True parseReject :: Parser Bool parseReject = string "reject" >> return False parseSim :: Parser [Bool] parseSim = parseList parseOneSim (Just $ string "\n")
qfjp/csce_dfa_project_test
src/Parser/Simulate.hs
bsd-3-clause
605
0
8
136
172
92
80
22
1
-- | Media-independent properties of a tracks sound content. module Data.ByteString.IsoBaseFileFormat.Boxes.SoundMediaHeader where import Data.ByteString.IsoBaseFileFormat.Box import Data.ByteString.IsoBaseFileFormat.Boxes.Handler import Data.ByteString.IsoBaseFileFormat.Boxes.SpecificMediaHeader import Data.ByteString.IsoBaseFileFormat.ReExports import Data.ByteString.IsoBaseFileFormat.Util.BoxContent import Data.ByteString.IsoBaseFileFormat.Util.BoxFields import Data.ByteString.IsoBaseFileFormat.Util.FullBox type instance MediaHeaderFor 'AudioTrack = SoundMediaHeader -- | Sound header data box. newtype SoundMediaHeader where SoundMediaHeader :: Template (I16 "balance") 0 :+ Constant (U16 "reserved") 0 -> SoundMediaHeader deriving (Default, IsBoxContent) -- | Create a sound media header data box. soundMediaHeader :: SoundMediaHeader -> Box (FullBox SoundMediaHeader 0) soundMediaHeader = fullBox 0 instance IsBox SoundMediaHeader type instance BoxTypeSymbol SoundMediaHeader = "smhd"
sheyll/isobmff-builder
src/Data/ByteString/IsoBaseFileFormat/Boxes/SoundMediaHeader.hs
bsd-3-clause
1,021
0
10
111
173
106
67
-1
-1
{-# LANGUAGE CPP #-} -- | Provide workarounds for bugs detected in GHC, until they are -- fixed in a later version module Language.Haskell.Refact.Utils.GhcBugWorkArounds ( -- bypassGHCBug7351 getRichTokenStreamWA ) where import qualified Bag as GHC import qualified DynFlags as GHC import qualified ErrUtils as GHC import qualified FastString as GHC import qualified GHC as GHC import qualified HscTypes as GHC import qualified Lexer as GHC import qualified MonadUtils as GHC import qualified Outputable as GHC import qualified SrcLoc as GHC import qualified StringBuffer as GHC import Control.Exception import Data.IORef import System.Directory import System.FilePath import qualified Data.Map as Map import qualified Data.Set as Set import Language.Haskell.GHC.ExactPrint.Types -- import Language.Haskell.Refact.Utils.TypeSyn -- --------------------------------------------------------------------- {- -- http://hackage.haskell.org/trac/ghc/ticket/7351 bypassGHCBug7351 :: [PosToken] -> [PosToken] bypassGHCBug7351 ts = map go ts where go :: (GHC.Located GHC.Token, String) -> (GHC.Located GHC.Token, String) go rt@(GHC.L (GHC.UnhelpfulSpan _) _t,_s) = rt go (GHC.L (GHC.RealSrcSpan l) t,s) = (GHC.L (fixCol l) t,s) fixCol l = GHC.mkSrcSpan (GHC.mkSrcLoc (GHC.srcSpanFile l) (GHC.srcSpanStartLine l) ((GHC.srcSpanStartCol l) - 1)) (GHC.mkSrcLoc (GHC.srcSpanFile l) (GHC.srcSpanEndLine l) ((GHC.srcSpanEndCol l) - 1)) -} -- --------------------------------------------------------------------- -- | Replacement for original 'getRichTokenStream' which will return -- the tokens for a file processed by CPP. -- See bug <http://ghc.haskell.org/trac/ghc/ticket/8265> getRichTokenStreamWA :: GHC.GhcMonad m => GHC.Module -> m [(GHC.Located GHC.Token, String)] getRichTokenStreamWA modu = do (sourceFile, source, flags) <- getModuleSourceAndFlags modu let startLoc = GHC.mkRealSrcLoc (GHC.mkFastString sourceFile) 1 1 case GHC.lexTokenStream source startLoc flags of GHC.POk _ ts -> return $ GHC.addSourceToTokens startLoc source ts GHC.PFailed _span _err -> do strSrcBuf <- getPreprocessedSrc sourceFile case GHC.lexTokenStream strSrcBuf startLoc flags of GHC.POk _ ts -> do directiveToks <- GHC.liftIO $ getPreprocessorAsComments sourceFile nonDirectiveToks <- tokeniseOriginalSrc startLoc flags source let toks = GHC.addSourceToTokens startLoc source ts return $ combineTokens directiveToks nonDirectiveToks toks -- return directiveToks -- return nonDirectiveToks -- return toks GHC.PFailed sspan err -> parseError flags sspan err -- --------------------------------------------------------------------- -- | Combine the three sets of tokens to produce a single set that -- represents the code compiled, and will regenerate the original -- source file. -- [@directiveToks@] are the tokens corresponding to preprocessor -- directives, converted to comments -- [@origSrcToks@] are the tokenised source of the original code, with -- the preprocessor directives stripped out so that -- the lexer does not complain -- [@postCppToks@] are the tokens that the compiler saw originally -- NOTE: this scheme will only work for cpp in -nomacro mode combineTokens :: [(GHC.Located GHC.Token, String)] -> [(GHC.Located GHC.Token, String)] -> [(GHC.Located GHC.Token, String)] -> [(GHC.Located GHC.Token, String)] combineTokens directiveToks origSrcToks postCppToks = toks where locFn (GHC.L l1 _,_) (GHC.L l2 _,_) = compare l1 l2 m1Toks = mergeBy locFn postCppToks directiveToks -- We must now find the set of tokens that are in origSrcToks, but -- not in m1Toks -- GHC.Token does not have Ord, can't use a set directly origSpans = map (\(GHC.L l _,_) -> l) origSrcToks m1Spans = map (\(GHC.L l _,_) -> l) m1Toks missingSpans = (Set.fromList origSpans) Set.\\ (Set.fromList m1Spans) missingToks = filter (\(GHC.L l _,_) -> Set.member l missingSpans) origSrcToks missingAsComments = map mkCommentTok missingToks where mkCommentTok :: (GHC.Located GHC.Token,String) -> (GHC.Located GHC.Token,String) mkCommentTok (GHC.L l _,s) = (GHC.L l (GHC.ITlineComment s),s) toks = mergeBy locFn m1Toks missingAsComments -- --------------------------------------------------------------------- tokeniseOriginalSrc :: GHC.GhcMonad m => GHC.RealSrcLoc -> GHC.DynFlags -> GHC.StringBuffer -> m [(GHC.Located GHC.Token, String)] tokeniseOriginalSrc startLoc flags buf = do let src = stripPreprocessorDirectives buf case GHC.lexTokenStream src startLoc flags of GHC.POk _ ts -> return $ GHC.addSourceToTokens startLoc src ts GHC.PFailed sspan err -> parseError flags sspan err -- --------------------------------------------------------------------- -- | Strip out the CPP directives so that the balance of the source -- can tokenised. stripPreprocessorDirectives :: GHC.StringBuffer -> GHC.StringBuffer stripPreprocessorDirectives buf = buf' where srcByLine = lines $ sbufToString buf noDirectivesLines = map (\line -> if line /= [] && head line == '#' then "" else line) srcByLine buf' = GHC.stringToStringBuffer $ unlines noDirectivesLines -- --------------------------------------------------------------------- sbufToString :: GHC.StringBuffer -> String sbufToString sb@(GHC.StringBuffer _buf len _cur) = GHC.lexemeToString sb len -- --------------------------------------------------------------------- -- | The preprocessed files are placed in a temporary directory, with -- a temporary name, and extension .hscpp. Each of these files has -- three lines at the top identifying the original origin of the -- files, which is ignored by the later stages of compilation except -- to contextualise error messages. getPreprocessedSrc :: GHC.GhcMonad m => FilePath -> m GHC.StringBuffer getPreprocessedSrc srcFile = do df <- GHC.getSessionDynFlags d <- GHC.liftIO $ getTempDir df fileList <- GHC.liftIO $ getDirectoryContents d let suffix = "hscpp" let cppFiles = filter (\f -> getSuffix f == suffix) fileList origNames <- GHC.liftIO $ mapM getOriginalFile $ map (\f -> d </> f) cppFiles let tmpFile = head $ filter (\(o,_) -> o == srcFile) origNames buf <- GHC.liftIO $ GHC.hGetStringBuffer $ snd tmpFile return buf -- --------------------------------------------------------------------- getSuffix :: FilePath -> String getSuffix fname = reverse $ fst $ break (== '.') $ reverse fname -- | A GHC preprocessed file has the following comments at the top -- @ -- # 1 "./test/testdata/BCpp.hs" -- # 1 "<command-line>" -- # 1 "./test/testdata/BCpp.hs" -- @ -- This function reads the first line of the file and returns the -- string in it. -- NOTE: no error checking, will blow up if it fails getOriginalFile :: FilePath -> IO (FilePath,FilePath) getOriginalFile fname = do fcontents <- readFile fname let firstLine = head $ lines fcontents let (_,originalFname) = break (== '"') firstLine return $ (tail $ init $ originalFname,fname) -- --------------------------------------------------------------------- -- | Get the preprocessor directives as comment tokens from the -- source. getPreprocessorAsComments :: FilePath -> IO [(GHC.Located GHC.Token, String)] getPreprocessorAsComments srcFile = do fcontents <- readFile srcFile let directives = filter (\(_lineNum,line) -> line /= [] && head line == '#') $ zip [1..] $ lines fcontents let mkTok (lineNum,line) = (GHC.L l (GHC.ITlineComment line),line) where start = GHC.mkSrcLoc (GHC.mkFastString srcFile) lineNum 1 end = GHC.mkSrcLoc (GHC.mkFastString srcFile) lineNum (length line) l = GHC.mkSrcSpan start end let toks = map mkTok directives return toks -- --------------------------------------------------------------------- #if __GLASGOW_HASKELL__ > 704 parseError :: GHC.DynFlags -> GHC.SrcSpan -> GHC.MsgDoc -> m b parseError dflags sspan err = do throw $ GHC.mkSrcErr (GHC.unitBag $ GHC.mkPlainErrMsg dflags sspan err) #else parseError :: GHC.GhcMonad m => GHC.DynFlags -> GHC.SrcSpan -> GHC.Message -> m b parseError _dflags sspan err = do throw $ GHC.mkSrcErr (GHC.unitBag $ GHC.mkPlainErrMsg sspan err) #endif -- --------------------------------------------------------------------- -- Copied from the GHC source, since not exported getModuleSourceAndFlags :: GHC.GhcMonad m => GHC.Module -> m (String, GHC.StringBuffer, GHC.DynFlags) getModuleSourceAndFlags modu = do m <- GHC.getModSummary (GHC.moduleName modu) case GHC.ml_hs_file $ GHC.ms_location m of Nothing -> #if __GLASGOW_HASKELL__ > 704 do dflags <- GHC.getDynFlags GHC.liftIO $ throwIO $ GHC.mkApiErr dflags (GHC.text "No source available for module " GHC.<+> GHC.ppr modu) #else GHC.liftIO $ throwIO $ GHC.mkApiErr (GHC.text "No source available for module " GHC.<+> GHC.ppr modu) #endif -- error $ ("No source available for module " ++ showGhc mod) Just sourceFile -> do source <- GHC.liftIO $ GHC.hGetStringBuffer sourceFile return (sourceFile, source, GHC.ms_hspp_opts m) -- return our temporary directory within tmp_dir, creating one if we -- don't have one yet getTempDir :: GHC.DynFlags -> IO FilePath getTempDir dflags = do let ref = GHC.dirsToClean dflags tmp_dir = GHC.tmpDir dflags mapping <- readIORef ref case Map.lookup tmp_dir mapping of Nothing -> error "should already be a tmpDir" Just d -> return d -- --------------------------------------------------------------------- -- Copied over from MissingH, the dependency cause travis to fail {- | Merge two sorted lists using into a single, sorted whole, allowing the programmer to specify the comparison function. QuickCheck test property: prop_mergeBy xs ys = mergeBy cmp (sortBy cmp xs) (sortBy cmp ys) == sortBy cmp (xs ++ ys) where types = xs :: [ (Int, Int) ] cmp (x1,_) (x2,_) = compare x1 x2 -} mergeBy :: (a -> a -> Ordering) -> [a] -> [a] -> [a] mergeBy _cmp [] ys = ys mergeBy _cmp xs [] = xs mergeBy cmp (allx@(x:xs)) (ally@(y:ys)) -- Ordering derives Eq, Ord, so the comparison below is valid. -- Explanation left as an exercise for the reader. -- Someone please put this code out of its misery. | (x `cmp` y) <= EQ = x : mergeBy cmp xs ally | otherwise = y : mergeBy cmp allx ys
mpickering/HaRe
src/Language/Haskell/Refact/Utils/GhcBugWorkArounds.hs
bsd-3-clause
10,861
0
21
2,281
2,180
1,147
1,033
126
3
module Main where -- import Data.Functor.Identity (Indentity) import Jetpack import HLS import Types import Lucid -- sk = ansi_setSGR [ansi_mk'Vivid ansi_mk'Blue] main :: IO () main = do putStrLn "starting webserver" let ctx = Ctx {streams = [d2']} spock_runSpock 3000 $ spock_spockT (runM ctx) $ do spock_get "ok" $ do (Ctx{..}) <- lift (M trans_get) spock_json $js_object ["ok" .= (33::Int)] spock_get ("test" <//> spock_var) $ \v -> do liftIO (startVlc demoHLSParams) spock_text v return () newtype M a = M { unM :: TransStateT Ctx IO a } deriving (Functor, Applicative, Monad, MonadIO) data Ctx = Ctx { streams :: [TwitchStream] } doStuffWithVLCOutput :: EnvHandle -> IO () doStuffWithVLCOutput h = -- do forever $ do l <- env_hGetLine h env_hPutStrLn env_stderr l startVlc :: HLSParams -> IO () startVlc hlsParams = do (mb_stdin_hdl, mb_stdout_hdl, mb_stderr_hdl, ph) <- env_createProcess (vlcCmd hlsParams) case mb_stdout_hdl of Nothing -> print "err" Just stdout_hdl -> do forkIO $ doStuffWithVLCOutput stdout_hdl print "Listening" return () vlcCmd :: HLSParams -> EnvCreateProcess vlcCmd hlsParam = env_proc "yes" [vlcCmdParam hlsParam] & set_env_std_in env_mk'CreatePipe & set_env_std_out env_mk'CreatePipe & set_env_std_err env_mk'Inherit a = env_createProcess runM :: Ctx -> M a -> IO a runM ctx = (\x -> trans_evalStateT x ctx) . unM showStream :: Html () showStream = do h1_ [] "Twitch-Streams" table_ $ do (tr_ (td_ (p_ "Hello, World!"))) (tr_ (td_ (p_ "Hello, World!"))) (tr_ (td_ (p_ "Hello, World!")))
rvion/ride
twitch-cast/src/Main.hs
bsd-3-clause
1,644
0
16
356
582
286
296
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Webcrank.Internal.Types where import Control.Applicative import Control.Lens import Control.Monad.Catch import Control.Monad.RWS import Control.Monad.Trans.Either import Control.Monad.Trans.Maybe import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString.UTF8 as B import Data.CaseInsensitive (CI) import Data.HashMap.Strict (HashMap) import Data.List.NonEmpty (NonEmpty) import Data.Text (Text) import Network.HTTP.Date import Network.HTTP.Media import Network.HTTP.Types import Prelude import Webcrank.Internal.Headers -- | A dictionary of functions that Webcrank needs in order to make decisions. data ServerAPI m = ServerAPI { srvGetRequestMethod :: m Method -- ^ Get the request method of the current request. , srvGetRequestURI :: m ByteString -- ^ The full URI of the request. , srvGetRequestHeader :: HeaderName -> m (Maybe ByteString) -- ^ Get the request header of the current request. , srvGetRequestTime :: m HTTPDate -- ^ Get the time the request was received. } type HeadersMap = HashMap HeaderName [ByteString] -- | Content coding type, e.g. gzip, decompress. See @'encodingsProvided'@. type Encoding = CI ByteString -- | Character set type, e.g. utf-8. See @'charsetsProvided'@. type Charset = CI ByteString -- | Response body type. type Body = LB.ByteString -- | Indicates whether client is authorized to perform the requested -- operation on the resource. See @'isAuthorized'@. data Authorized = Authorized -- ^ Tells Webcrank that the client is authorized to perform the -- requested operation on the resource. | Unauthorized ByteString -- ^ Tells Webcrank that the client is not authorized to perform -- the operation on the resource. The value is sent in the -- @WWW-Authenticate@ header of the response, -- e.g. @Basic realm="Webcrank"@. -- | Indicates whether the resource supports multiple character sets -- or not. See @'charsetsProvided'@ data CharsetsProvided = NoCharset -- ^ Indicates that the resource doesn't support any additional -- character sets, all responses from the resource will have the -- same character set, regardless of what the client requests. | CharsetsProvided (NonEmpty (Charset, Body -> Body)) -- ^ The character sets the resource supports along with functions -- for converting the response body. -- | Weak or strong entity tags as used in HTTP ETag and @If-*-Match@ headers. data ETag = StrongETag ByteString | WeakETag ByteString deriving Eq instance Show ETag where show e = B.toString $ case e of StrongETag v -> "\"" <> v <> "\"" WeakETag v -> "W/\"" <> v <> "\"" instance RenderHeader ETag where renderHeader = \case StrongETag v -> quotedString v WeakETag v -> "W/" <> quotedString v data Halt = Halt Status | Error Status LB.ByteString deriving (Eq, Show) -- | Monad transformer for @'Resource'@ functions which can halt the request -- processing early with an error or some other response. Values are created with -- the smart constructors @'werror'@ and @'halt'@. newtype HaltT m a = HaltT { unHaltT :: EitherT Halt m a } deriving ( Functor , Applicative , Monad , MonadIO , MonadTrans , MonadReader r , MonadState s , MonadWriter w , MonadThrow , MonadCatch ) -- | How @POST@ requests should be treated. See @'postAction'@. data PostAction m = PostCreate [Text] -- ^ Treat @POST@s as creating new resources and respond -- with @201 Created@, with the given path in the Location header. | PostCreateRedir [Text] -- ^ Treat @POST@s as creating new resources and respond with -- @301 See Other@, redirecting the client to the new resource. | PostProcess (HaltT m ()) -- ^ Treat @POST@s as a process which is executed without redirect. | PostProcessRedir (HaltT m ByteString) -- ^ Treat @POST@s as a process and redirect the client to a -- different (possibly new) resource. data LogData = LogData instance Monoid LogData where mempty = LogData mappend _ _ = LogData -- | A @Resource@ is a dictionary of functions which are used in the Webcrank -- decision process to determine how requests should be handled. -- -- Each function has a type of either @m a@ or @'HaltT' m a@. -- A resource function which yields a @HaltT m a@ value allows the function -- to terminate the request processing early using @'halt'@ or -- @'werror'@. -- -- The defaults documented are used by the @'resource'@ smart constructor. -- A resource that responds to @GET@ requests with an HTML response would be -- written as -- -- @ -- myResource = resource { contentTypesProvided = return $ [("text/html", return "Hello world!")] } -- @ -- -- @'responseWithBody'@ and @'responseWithHtml'@ are additional -- smart constructors useful creating resources. data Resource m = Resource { serviceAvailable :: HaltT m Bool -- ^ @False@ will result in @503 Service Unavailable@. Defaults to @True@. , uriTooLong :: HaltT m Bool -- ^ @True@ will result in @414 Request Too Long@. Defaults to @False@. , allowedMethods :: m [Method] -- ^ If a @Method@ not in this list is requested, then a @405 Method Not -- Allowed@ will be sent. Defaults to @["GET", "HEAD"]@. , malformedRequest :: HaltT m Bool -- ^ @True@ will result in @400 Bad Request@. Defaults to @False@. , isAuthorized :: HaltT m Authorized -- ^ If @Authorized@, the response will be @401 Unauthorized@. -- @Unauthorized@ will be used as the challenge in the @WWW-Authenticate@ -- header, e.g. @Basic realm="Webcrank"@. -- Defaults to @Authorized@. , forbidden :: HaltT m Bool -- ^ @True@ will result in @403 Forbidden@. Defaults to @False@. , validContentHeaders :: HaltT m Bool -- ^ @False@ will result in @501 Not Implemented@. Defaults to @True@. , knownContentType :: HaltT m Bool -- ^ @False@ will result in @415 Unsupported Media Type@. Defaults to -- @True@. , validEntityLength :: HaltT m Bool -- ^ @False@ will result in @413 Request Entity Too Large@. Defaults to -- @True@. , options :: m ResponseHeaders -- ^ If the OPTIONS method is supported and is used, the headers that -- should appear in the response. Defaults to @[]@. , contentTypesProvided :: m [(MediaType, HaltT m Body)] -- ^ Content negotiation is driven by this function. For example, if a -- client request includes an @Accept@ header with a value that does not -- appear as a @MediaType@ in any of the tuples, then a @406 Not -- Acceptable@ will be sent. If there is a matching @MediaType@, that -- function is used to create the entity when a response should include one. -- Defaults to @[]@. , charsetsProvided :: m CharsetsProvided -- ^ Used on GET requests to ensure that the entity is in @Charset@. -- Defaults to @NoCharset@. , encodingsProvided :: m [(Encoding, Body -> Body)] -- ^ Used on GET requests to ensure that the body is encoded. -- One useful setting is to have the function check on method, and on GET -- requests return @[("identity", id), ("gzip", compress)]@ as this is all -- that is needed to support gzip content encoding. Defaults to -- @[]@. , resourceExists :: HaltT m Bool -- ^ @False@ will result in @404 Not Found@. Defaults to @True@. , generateETag :: MaybeT m ETag -- ^ If this returns an @ETag@, it will be used for the ETag header and for -- comparison in conditional requests. Defaults to @mzero@. , lastModified :: MaybeT m HTTPDate -- ^ If this returns a @HTTPDate@, it will be used for the Last-Modified header -- and for comparison in conditional requests. Defaults to @mzero@. , expires :: MaybeT m HTTPDate -- ^ If this returns a @HTTPDate@, it will be used for the Expires header. -- Defaults to @mzero@. , movedPermanently :: MaybeT (HaltT m) ByteString -- ^ If this returns a URI, the client will receive a 301 Moved Permanently -- with the URI in the Location header. Defaults to @mzero@. , movedTemporarily :: MaybeT (HaltT m) ByteString -- ^ If this returns a URI, the client will receive a 307 Temporary Redirect -- with URI in the Location header. Defaults to @mzero@. , previouslyExisted :: HaltT m Bool -- ^ If this returns @True@, the @movedPermanently@ and @movedTemporarily@ -- callbacks will be invoked to determine whether the response should be -- 301 Moved Permanently, 307 Temporary Redirect, or 410 Gone. Defaults -- to @False@. , allowMissingPost :: HaltT m Bool -- ^ If the resource accepts POST requests to nonexistent resources, then -- this should return @True@. Defaults to @False@. , deleteResource :: HaltT m Bool -- ^ This is called when a DELETE request should be enacted, and should return -- @True@ if the deletion succeeded or has been accepted. Defaults to -- @True@. , deleteCompleted :: HaltT m Bool -- ^ This is only called after a successful @deleteResource@ call, and should -- return @False@ if the deletion was accepted but cannot yet be guaranteed to -- have finished. Defaults to @True@. , postAction :: m (PostAction m) -- ^ If POST requests should be treated as a request to put content into a -- (potentially new) resource as opposed to being a generic submission for -- processing, then this function should return @PostCreate path@. If it -- does return @PostCreate path@, then the rest of the request will be -- treated much like a PUT to the path entry. Otherwise, if it returns -- @PostProcess a@, then the action @a@ will be run. Defaults to -- @PostProcess $ return ()@. , contentTypesAccepted :: m [(MediaType, HaltT m ())] -- ^ This is used similarly to @contentTypesProvided@, except that it is -- for incoming resource representations -- for example, @PUT@ requests. -- Handler functions usually want to use server specific functions to -- access the incoming request body. Defaults to @[]@. , variances :: m [HeaderName] -- ^ This function should return a list of strings with header names that -- should be included in a given response's Vary header. The standard -- conneg headers (Accept, Accept-Encoding, Accept-Charset, -- Accept-Language) do not need to be specified here as Webcrank will add -- the correct elements of those automatically depending on resource -- behavior. Defaults to @[]@. , multipleChoices :: HaltT m Bool -- ^ If this returns @True@, then it is assumed that multiple -- representations of the response are possible and a single one cannot -- be automatically chosen, so a @300 Multiple Choices@ will be sent -- instead of a @200 OK@. Defaults to @False@. , isConflict :: m Bool -- ^ If this returns @True@, the client will receive a 409 Conflict. -- Defaults to @False@. , finishRequest :: m () -- ^ Called just before the final response is constructed and sent. } -- | A wrapper for the @'ServerAPI'@ and @'Resource'@ that should be used -- to process requests to a path. data ResourceData m = ResourceData { _resourceDataServerAPI :: ServerAPI m , _resourceDataResource :: Resource m } makeClassy ''ResourceData -- | Container used to keep track of the decision state and what is known -- about response while processing a request. data ReqData = ReqData { _reqDataRespMediaType :: MediaType , _reqDataRespCharset :: Maybe Charset , _reqDataRespEncoding :: Maybe Encoding , _reqDataDispPath :: [Text] , _reqDataRespHeaders :: HeadersMap , _reqDataRespBody :: Maybe Body } makeClassy ''ReqData
webcrank/webcrank.hs
src/Webcrank/Internal/Types.hs
bsd-3-clause
11,928
0
13
2,477
1,195
734
461
115
0
module CalculatorKata.Day5Spec (spec) where import Test.Hspec import CalculatorKata.Day5 (calculate) spec :: Spec spec = do it "calculates one digit" (calculate "7" == 7.0) it "calculates many digits" (calculate "547" == 547.0) it "calculates addition" (calculate "54+78" == 54.0+78.0) it "calculates subtraction" (calculate "67-34" == 67.0-34.0) it "calculates multiplication" (calculate "45*4" == 45.0*4.0) it "calculates division" (calculate "657/34" == 657.0/34.0)
Alex-Diez/haskell-tdd-kata
old-katas/test/CalculatorKata/Day5Spec.hs
bsd-3-clause
612
0
11
202
160
78
82
17
1
{-# OPTIONS -Wall #-} module Language.Pck.Cpu.State ( -- * Evaluation monad (State monad) EvalCpu -- * Cpu state type , CpuState , pcFromCpuState , grFromCpuState , flFromCpuState , imemFromCpuState , dmemFromCpuState , dumpCpuState , initCpuState , initCpuStateMem -- * Result type , ResultStat(..) -- * access for the Cpu state -- ** PC(program counter) , readPc , updatePc , incPc -- ** General purpose registers , readGReg , readGReg2 , updateGReg -- ** Flags , readFlags , updateFlag -- ** Instruction memory , fetchInst -- ** Data memory , readDmem , updateDmem ) where import Control.Monad.State import Language.Pck.Cpu.Config import Language.Pck.Cpu.Instruction import Language.Pck.Cpu.Register import Language.Pck.Cpu.Memory ---------------------------------------- -- cpu state monad ---------------------------------------- -- | the cpu eval monad type EvalCpu a = State CpuState a -- | the result state data ResultStat = RsNormal -- ^ normal result | RsHalt -- ^ cpu halt(stop) | RsDbgBrk -- ^ debugger triggered | RsErr String -- ^ execution error deriving (Show, Eq) ---------------------------------------- -- cpu state type ---------------------------------------- -- | the cpu state (processor internal state) -- -- This is the result type from 'Language.Pck.Cpu.run' function. -- -- get each values by 'pcFromCpuState', 'grFromCpuState', 'flFromCpuState', -- 'imemFromCpuState', 'dmemFromCpuState', 'dumpCpuState' data CpuState = CpuState { state_pc :: Int , state_gr :: GRegArray , state_fl :: FlagArray , state_imem :: ImemArray , state_dmem :: DmemArray } deriving Eq -- accessor -- | -- > > pcFromCpuState $ run [(0,[MOVI R0 7, HALT])] [] -- > 1 -- pcFromCpuState :: CpuState -> Int pcFromCpuState = state_pc -- | -- > > grFromCpuState $ run [(0,[MOVI R0 7, HALT])] [] -- > [7,0,0,0,0,0,0,0] -- grFromCpuState :: CpuState -> [Int] grFromCpuState = getGRegs . state_gr -- | -- > > flFromCpuState $ run [(0,[MOVI R0 7, HALT])] [] -- > [False,False] -- flFromCpuState :: CpuState -> [Bool] flFromCpuState = getFlags . state_fl -- | -- > > imemFromCpuState $ run [(0,[MOVI R0 7, HALT])] [] -- > [(0,[MOVI R0 7,HALT,UNDEF,UNDEF,...])] -- imemFromCpuState :: CpuState -> InstImage imemFromCpuState = getInstImage . state_imem -- | -- > > dmemFromCpuState $ run [(0,[MOVI R0 0, MOVI R1 10, ST R0 R1, HALT])] [] -- > [(0,[10,0,0,0,0,...])] -- dmemFromCpuState :: CpuState -> DataImage dmemFromCpuState = getDataImage . state_dmem -- show instance Show CpuState where show = showCpuState showCpuState :: CpuState -> String showCpuState s = "pc : " ++ show (pcFromCpuState s) ++ "\ngr : " ++ show (grFromCpuState s) ++ "\nfl : " ++ show (flFromCpuState s) ++ "\nim : " ++ show (imemFromCpuState s) ++ "\ndm : " ++ show (dmemFromCpuState s) ++ "\n" -- | dump Cpu state (without instruction image) -- -- > > putStr $ dumpCpuState $ run [(0,[MOVI R0 7, HALT])] [] -- > pc : 1 -- > gr : [7,0,0,0,0,0,0,0] -- > fl : [False,False] -- > dm : [(0,[7,0,0,0,0,...])] -- dumpCpuState :: CpuState -> String dumpCpuState s = "pc : " ++ show (pcFromCpuState s) ++ "\ngr : " ++ show (grFromCpuState s) ++ "\nfl : " ++ show (flFromCpuState s) ++ "\ndm : " ++ show (dmemFromCpuState s) ++ "\n" ---------------------------------------- -- initial state ---------------------------------------- -- | a default CpuState initCpuState :: CpuState initCpuState = CpuState { state_pc = cfgStartPc cpuConfig , state_gr = initGReg , state_fl = initFlag , state_imem = initImem , state_dmem = initDmem } -- | initialize CpuState by inst and data image initCpuStateMem :: InstImage -> DataImage -> CpuState initCpuStateMem insts vals = initCpuState {state_imem = presetImem insts ,state_dmem = presetDmem vals} ---------------------------------------- -- state utility ---------------------------------------- -- | read the pc readPc :: EvalCpu Int readPc = gets state_pc -- | update the pc -- -- Example: -- -- > jumpRI :: Int -> EvalCpu ResultStat -- > jumpRI ad = do pc <- readPc -- > updatePc (pc + ad) -- updatePc :: Int -> EvalCpu ResultStat updatePc pc = do modify $ \s -> s { state_pc = pc } return RsNormal -- | increment the pc incPc :: EvalCpu ResultStat incPc = do pc <- readPc updatePc (pc + 1) -- | read a general purpose register -- -- Example: -- -- > jump :: GReg -> EvalCpu ResultStat -- > jump reg = do ad <- readGReg reg -- > updatePc ad -- readGReg :: GReg -> EvalCpu Int readGReg ra = do gr <- gets state_gr return $ getGReg gr ra -- | read general purpose register pair readGReg2 :: GReg -> GReg -> EvalCpu (Int, Int) readGReg2 ra rb = do gr <- gets state_gr return (getGReg gr ra, getGReg gr rb) -- | update a general purpose register -- -- Example: -- -- > movpc :: GReg -> EvalCpu ResultStat -- > movpc reg = do pc <- readPc -- > updateGReg reg pc -- updateGReg :: GReg -> Int -> EvalCpu () updateGReg reg val = do cpu <- get let gr' = modifyGReg (state_gr cpu) reg val put cpu { state_gr = gr' } -- | read flag registers -- -- Example: -- -- > branchRI :: FCond -> Int -> EvalCpu ResultStat -- > branchRI fcond ad = do flags <- readFlags -- > if judgeFCond flags fcond -- > then jumpRI ad -- > else incPc -- readFlags :: EvalCpu FlagArray readFlags = gets state_fl -- | update a flag -- -- Example: -- -- > cmpRR :: GReg -> GReg -> EvalCpu ResultStat -- > cmpRR ra rb = do (ra', rb') <- readGReg2 ra rb -- > updateFlag FLZ (ra' == rb') -- > updateFlag FLC (ra' < rb') -- updateFlag :: Flag -> Bool -> EvalCpu () updateFlag flag val = do cpu <- get let flags = state_fl cpu fl' = modifyFlag flags flag val put cpu { state_fl = fl' } -- | fetch an instruction from the instruction memory fetchInst :: EvalCpu Inst fetchInst = do imem <- gets state_imem pc <- readPc return $ fetchImem imem pc -- | read a data value from the data memory -- -- Example: -- -- > load :: GReg -> GReg -> EvalCpu ResultStat -- > load ra rb = do rb' <- readGReg rb -- > ra' <- readDmem rb' -- > updateGReg ra ra' -- readDmem :: Int -> EvalCpu Int readDmem ad = do cpu <- get return $ getDmem (state_dmem cpu) ad -- | update the data memory -- -- Example: -- -- > store :: GReg -> GReg -> EvalCpu ResultStat -- > store ra rb = do (ra', rb') <- readGReg2 ra rb -- > updateDmem ra' rb' -- updateDmem :: Int -> Int -> EvalCpu () updateDmem ad val = do cpu <- get let dmem' = modifyDmem (state_dmem cpu) ad val put cpu { state_dmem = dmem' }
takenobu-hs/processor-creative-kit
Language/Pck/Cpu/State.hs
bsd-3-clause
7,498
0
17
2,288
1,226
707
519
115
1
{-# LANGUAGE Rank2Types, FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} module NPNTool.PetriNet ( -- * Datatypes Net(..), Trans(..), SS, DynNet(..), PTNet, PTMark, PTTrans, PTPlace, -- * General and abstract functions, opertations HLArc, LLArc, annotate, -- * Additional functions fireSequence_, fireSequence, reachabilityGraph, reachabilityGraph', postP, preP ) where import Prelude import Data.Set (Set) import qualified Data.Set as Set import Data.MultiSet (MultiSet) import qualified Data.MultiSet as MSet import Data.Monoid import Data.Functor.Identity import Data.Functor.Compose import Data.Graph.Inductive (Gr) import qualified Data.Graph.Inductive as G --import Data.Graph.Inductive.NodeMap import NPNTool.NodeMap import qualified Data.Foldable as F newtype Trans = Trans { name :: String } deriving (Eq,Ord) instance Show Trans where show = name -- | A generalized net datatype data Net p t n m = Net { places :: Set p -- ^ A set of places , trans :: Set t -- ^ A set of transitions , pre :: t -> n p -- ^ The pre function , post :: t -> n p -- ^ The post function , initial :: m p -- ^ Initial marking } newtype HLArc a p = Arc { unArc :: (MultiSet (a p)) } type LLArc = HLArc Identity type PTNet = Net PTPlace Trans MultiSet MultiSet type PTMark = MultiSet PTPlace type PTTrans = Trans type PTPlace = Int -- | Annotate net using additional functors of place/transition relationship annotate :: (Functor a, Functor n) => Net p t n m -> (p -> t -> a p) -> (t -> p -> a p) -> Net p t (Compose n a) m annotate n f g = n { pre = \t -> Compose $ fmap (flip f t) (pre n t) , post = \t -> Compose $ fmap (g t) (post n t) } -- | A general dynamic net interface class DynNet net p t m | net -> p, net -> t, net -> m where -- | Whether a set of transitions is enabled. -- Note that this is different then checking whether each -- transition in the set is enabled enabledS :: net -> m p -> Set t -> Bool -- | Whether some transition is enabled enabled :: net -> m p -> t -> Bool enabled n mark tr = enabledS n mark (Set.singleton tr) -- | The marking after some transitions is fired fire :: net -> m p -> t -> m p instance DynNet PTNet PTPlace PTTrans MultiSet where enabledS = enabledSPT enabled = enabledPT fire = firePT enabledPT :: PTNet -> PTMark -> PTTrans -> Bool enabledPT (Net {pre=pre}) marking = (`MSet.isSubsetOf` marking) . pre enabledSPT :: PTNet -> PTMark -> Set PTTrans -> Bool enabledSPT (Net {pre=pre}) marking = (`MSet.isSubsetOf` marking) . (F.foldMap pre) firePT :: PTNet -> PTMark -> PTTrans -> PTMark firePT (Net {pre=pre, post=post}) mark t = (mark MSet.\\ pre t) <> post t fireSequence_ :: (DynNet net p t m) => net -> m p -> [t] -> m p fireSequence_ n = foldl (fire n) fireSequence :: (DynNet net p t m) => net -> m p -> [t] -> Maybe (m p) fireSequence n = F.foldlM (fire' n) where fire' n m t = if enabled n m t then Just (fire n m t) else Nothing -- reuse types from StateSpace module type SS = Gr PTMark PTTrans -- | The reachability graph of a Petri Net reachabilityGraph :: (DynNet (Net p t n m) p t m, Ord p, Ord (m p)) => (Net p t n m) -> Gr (m p) t reachabilityGraph = snd. reachabilityGraph' -- | The reachability graph of a Petri Net together with a 'NodeMap' reachabilityGraph' :: (DynNet (Net p t n m) p t m, Ord p, Ord (m p)) => (Net p t n m) -> (NodeMap (m p), Gr (m p) t) reachabilityGraph' net = snd $ run G.empty $ insMapNodeM (initial net) >> go (Set.singleton (initial net)) where go !work | Set.null work = return () | otherwise = do let m = (head . Set.toList) work --- Better way to pick an arbitrary M from the set Work? work' = Set.delete m work work'' <- F.foldrM (act net m) work' (trans net) go $! work'' act :: (G.DynGraph g, DynNet net p t m, Ord p, Ord (m p)) => net -> m p -> t -> Set (m p) -> NodeMapM (m p) t g (Set (m p)) act net m !t !w = if enabled net m t then do let m' = fire net m t present <- lookupNodeM m' w' <- case present of Just _ -> return w Nothing -> do insMapNodeM m' return (Set.insert m' w) insMapEdgeM (m,m',t) return $! w' else return w -- | Post-transitions of a place postP :: (Eq p, F.Foldable n) => p -> Net p t n m -> [t] postP p (Net {trans=trans, pre=preT, post=postT}) = F.foldMap (\x -> if F.any (== p) (preT x) then [x] else []) trans -- | Pre-transitions of a place preP :: (Eq p, F.Foldable n) => p -> Net p t n m -> [t] preP p (Net {trans=trans, pre=preT, post=postT}) = F.foldMap (\x -> if F.any (== p) (postT x) then [x] else []) trans
co-dan/NPNTool
src/NPNTool/PetriNet.hs
bsd-3-clause
5,064
0
17
1,391
1,852
999
853
102
3
{-| Module : AERN2.RealSpec Description : hspec tests for CauchyReal Copyright : (c) Michal Konecny License : BSD3 Maintainer : mikkonecny@gmail.com Stability : experimental Portability : portable -} module AERN2.PolySpec (spec) where -- import MixedTypesNumPrelude import AERN2.Poly.Cheb.Tests import Test.Hspec spec :: Spec spec = specChPoly
michalkonecny/aern2
aern2-fun-univariate/test/AERN2/PolySpec.hs
bsd-3-clause
398
0
4
99
35
23
12
5
1
{-# LANGUAGE OverloadedStrings #-} module Lib (app) where import SDL import Linear import Linear.Affine import Foreign.C.Types import Control.Monad (unless) import Data.Word import Control.Concurrent import System.Random import Control.Monad import Neural windowWidth = 500 :: CInt windowHeight = 500 :: CInt verticeRange = (-8.0,8.0) app :: IO () app = appInit appInit :: IO () appInit = do initializeAll window <- createWindow "Neural Network Test" defaultWindow { windowInitialSize = V2 windowWidth windowHeight } renderer <- createRenderer window (-1) defaultRenderer neural <- buildRandomNeuralNetwork verticeRange [2, 32, 16, 8, 3] appLoop neural renderer appLoop :: NeuralNetwork -> Renderer -> IO () appLoop neural renderer = do events <- pollEvents let eventIsKeyPress key event = case eventPayload event of KeyboardEvent keyboardEvent -> keyboardEventKeyMotion keyboardEvent == Pressed && keysymKeycode (keyboardEventKeysym keyboardEvent) == key _ -> False keyPressed key = not (null (filter (eventIsKeyPress key) events)) qPressed = keyPressed KeycodeQ rendererDrawColor renderer $= V4 0 0 0 255 clear renderer drawScene neural renderer present renderer neural' <- mutate verticeRange neural unless qPressed $ appLoop neural' renderer drawScene :: NeuralNetwork -> Renderer -> IO () drawScene neural renderer = do let generateAllPoints = [(P $ V2 (CInt (fromIntegral x)) (CInt (fromIntegral y))) | x <- [0..(fromIntegral windowWidth)] :: [Int], y <- [0..(fromIntegral windowHeight)]] allPoints <- return generateAllPoints mapM_ (\point -> drawAnalogOutputForPoint point neural renderer) allPoints drawAnalogOutputForPoint :: Point V2 CInt -> NeuralNetwork -> Renderer -> IO () drawAnalogOutputForPoint point@(P (V2 (CInt x) (CInt y))) neural renderer = do outputValues <- return (calculateOutputValues inputs neural) r <- getOutputValue 0 outputValues g <- getOutputValue 1 outputValues b <- getOutputValue 2 outputValues rendererDrawColor renderer $= V4 r g b 255 drawPoint renderer point where inputs = [normalizedX, normalizedY] normalizedX = normalizedDim x windowWidth normalizedY = normalizedDim y windowHeight normalizedDim a b = (((fromIntegral a) - (0.5 * (fromIntegral b))) / (fromIntegral b)) normalizeOutput a = floor (a * 256) getOutputValue n outputValues = return $ normalizeOutput $ outputValues !! n drawWinnerTakesAllForPoint :: Point V2 CInt -> NeuralNetwork -> Renderer -> IO () drawWinnerTakesAllForPoint point@(P (V2 (CInt x) (CInt y))) neural renderer = do let drawRed = do rendererDrawColor renderer $= V4 255 0 0 255 drawPoint renderer point let drawGreen = do rendererDrawColor renderer $= V4 0 255 0 255 drawPoint renderer point let drawBlue = do rendererDrawColor renderer $= V4 0 0 255 255 drawPoint renderer point winner <- return (calculateHighestOutputIndex inputs neural) when (winner == 0) drawRed when (winner == 1) drawGreen when (winner == 2) drawBlue where inputs = [normalizedX, normalizedY] normalizedX = normalizedDim x windowWidth normalizedY = normalizedDim y windowHeight normalizedDim a b = (((fromIntegral a) - (0.5 * (fromIntegral b))) / (fromIntegral b)) normalizeOutput a = floor (a * 256) getOutputValue n outputValues = return $ normalizeOutput $ outputValues !! n
KenseiMaedhros/neural-net-visual-test
src/Lib.hs
bsd-3-clause
3,730
0
17
958
1,186
582
604
82
2
module ImportBothUsedUnqualified where import Language.Haskell.Names (symbolName) import qualified Language.Haskell.Names as N main = symbolName
serokell/importify
test/test-data/haskell-names@records/02-ImportBothUsedUnqualified.hs
mit
157
0
5
26
29
20
9
4
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.OpsWorks.DisassociateElasticIP -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Disassociates an Elastic IP address from its instance. The address -- remains registered with the stack. For more information, see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/resources.html Resource Management>. -- -- __Required Permissions__: To use this action, an IAM user must have a -- Manage permissions level for the stack, or an attached policy that -- explicitly grants permissions. For more information on user permissions, -- see -- <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing User Permissions>. -- -- /See:/ <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_DisassociateElasticIP.html AWS API Reference> for DisassociateElasticIP. module Network.AWS.OpsWorks.DisassociateElasticIP ( -- * Creating a Request disassociateElasticIP , DisassociateElasticIP -- * Request Lenses , deiElasticIP -- * Destructuring the Response , disassociateElasticIPResponse , DisassociateElasticIPResponse ) where import Network.AWS.OpsWorks.Types import Network.AWS.OpsWorks.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'disassociateElasticIP' smart constructor. newtype DisassociateElasticIP = DisassociateElasticIP' { _deiElasticIP :: Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DisassociateElasticIP' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'deiElasticIP' disassociateElasticIP :: Text -- ^ 'deiElasticIP' -> DisassociateElasticIP disassociateElasticIP pElasticIP_ = DisassociateElasticIP' { _deiElasticIP = pElasticIP_ } -- | The Elastic IP address. deiElasticIP :: Lens' DisassociateElasticIP Text deiElasticIP = lens _deiElasticIP (\ s a -> s{_deiElasticIP = a}); instance AWSRequest DisassociateElasticIP where type Rs DisassociateElasticIP = DisassociateElasticIPResponse request = postJSON opsWorks response = receiveNull DisassociateElasticIPResponse' instance ToHeaders DisassociateElasticIP where toHeaders = const (mconcat ["X-Amz-Target" =# ("OpsWorks_20130218.DisassociateElasticIp" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON DisassociateElasticIP where toJSON DisassociateElasticIP'{..} = object (catMaybes [Just ("ElasticIp" .= _deiElasticIP)]) instance ToPath DisassociateElasticIP where toPath = const "/" instance ToQuery DisassociateElasticIP where toQuery = const mempty -- | /See:/ 'disassociateElasticIPResponse' smart constructor. data DisassociateElasticIPResponse = DisassociateElasticIPResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DisassociateElasticIPResponse' with the minimum fields required to make a request. -- disassociateElasticIPResponse :: DisassociateElasticIPResponse disassociateElasticIPResponse = DisassociateElasticIPResponse'
fmapfmapfmap/amazonka
amazonka-opsworks/gen/Network/AWS/OpsWorks/DisassociateElasticIP.hs
mpl-2.0
3,957
0
12
777
405
247
158
59
1
-- an eyeball test for unicode handling -- loads a file of UTF-8 encoded strings (hardcoded below) and displays widgets -- for each one of the strings -- Eric Kow 2006 {-# LANGUAGE FlexibleContexts #-} module Main where import UTF8 import Paths_samplesTest import Graphics.UI.WX import Graphics.UI.WXCore import System.IO import Control.Monad (liftM) import Data.Word (Word8) import Foreign.Marshal.Array main :: IO () main = start sampler sampler :: IO () sampler = do f <- frame [text := "UTF-8 viewer"] pnl <- panel f [] nb <- notebook pnl [] -- sLines <- liftM lines readTestFile let bunchOf lable thing = do p <- panel nb [] ws <- mapM (\t -> thing p [ text := t, tooltip := t ]) sLines return $ tab lable $ container p $ margin 10 $ column 1 $ map widget ws bunchOfSel lable thing = do p <- panel nb [] w <- thing p [on select ::= logSelect sLines] return $ tab lable $ container p $ margin 10 $ widget w -- manually created tabs p1 <- panel nb [] let for1 thing = do w <- thing p1 [ on select ::= logSelect sLines, items := sLines ] set w [ selection := 0 ] return w p1choice <- for1 choice p1combo <- for1 comboBox p1slist <- for1 singleListBox p1mlist <- multiListBox p1 [ items := sLines ] let t1 = tab "Selectors" $ container p1 $ margin 10 $ column 1 $ [ label "choice", widget p1choice , label "combo" , widget p1combo , label "s-list", widget p1slist , label "m-list", widget p1mlist ] p2 <- panel nb [] let t2 = tab "Labels" $ container p2 $ column 1 $ map label sLines -- textlog <- textCtrl pnl [enabled := False, wrap := WrapNone] textCtrlMakeLogActiveTarget textlog logMessage "logging enabled" -- ts <- sequence [ bunchOf "Static" staticText , bunchOf "TextEntry" textEntry , bunchOf "Checks" checkBox , bunchOf "Buttons" button , bunchOfSel "Radio" (\p -> radioBox p Vertical sLines) ] -- set f [layout := container pnl $ hfill $ column 0 [ hfill $ tabs nb $ t1:t2:ts , hfill $ widget textlog ] ] where logSelect _labels w = do i <- get w selection s <- get w (item i) logMessage ("selected index: " ++ show i ++ ": " ++ s) -- from the mailing list hGetBytes :: Handle -> Int -> IO [Word8] hGetBytes h c = allocaArray c $ \p -> do c' <- hGetBuf h p c peekArray c' p readTestFile :: IO String readTestFile = do testFilePath <- getDataFileName testFile h <- openBinaryFile testFilePath ReadMode hsize <- hFileSize h ws <- hGetBytes h $ fromIntegral hsize return . fst . decode $ ws testFile :: FilePath testFile = "utf-tests"
jacekszymanski/wxHaskell
samples/test/UTF8Sampler.hs
lgpl-2.1
2,945
0
18
958
985
467
518
71
1
{-# LANGUAGE TemplateHaskell #-} {-| PyType helper for Ganeti Haskell code. -} {- Copyright (C) 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.THH.PyType ( PyType(..) , pyType , pyOptionalType ) where import Control.Monad import Data.List (intercalate) import Language.Haskell.TH import Language.Haskell.TH.Syntax (Lift(..)) import Ganeti.PyValue -- | Represents a Python encoding of types. data PyType = PTMaybe PyType | PTApp PyType [PyType] | PTOther String | PTAny | PTDictOf | PTListOf | PTNone | PTObject | PTOr | PTSetOf | PTTupleOf deriving (Show, Eq, Ord) -- TODO: We could use th-lift to generate this instance automatically. instance Lift PyType where lift (PTMaybe x) = [| PTMaybe x |] lift (PTApp tf as) = [| PTApp tf as |] lift (PTOther i) = [| PTOther i |] lift PTAny = [| PTAny |] lift PTDictOf = [| PTDictOf |] lift PTListOf = [| PTListOf |] lift PTNone = [| PTNone |] lift PTObject = [| PTObject |] lift PTOr = [| PTOr |] lift PTSetOf = [| PTSetOf |] lift PTTupleOf = [| PTTupleOf |] instance PyValue PyType where -- Use lib/ht.py type aliases to avoid Python creating redundant -- new match functions for commonly used OpCode param types. showValue (PTMaybe (PTOther "NonEmptyString")) = ht "MaybeString" showValue (PTMaybe (PTOther "Bool")) = ht "MaybeBool" showValue (PTMaybe PTDictOf) = ht "MaybeDict" showValue (PTMaybe PTListOf) = ht "MaybeList" showValue (PTMaybe x) = ptApp (ht "Maybe") [x] showValue (PTApp tf as) = ptApp (showValue tf) as showValue (PTOther i) = ht i showValue PTAny = ht "Any" showValue PTDictOf = ht "DictOf" showValue PTListOf = ht "ListOf" showValue PTNone = ht "None" showValue PTObject = ht "Object" showValue PTOr = ht "Or" showValue PTSetOf = ht "SetOf" showValue PTTupleOf = ht "TupleOf" ht :: String -> String ht = ("ht.T" ++) ptApp :: String -> [PyType] -> String ptApp name ts = name ++ "(" ++ intercalate ", " (map showValue ts) ++ ")" -- | Converts a Haskell type name into a Python type name. pyTypeName :: Name -> PyType pyTypeName name = case nameBase name of "()" -> PTNone "Map" -> PTDictOf "Set" -> PTSetOf "ListSet" -> PTSetOf "Either" -> PTOr "GenericContainer" -> PTDictOf "JSValue" -> PTAny "JSObject" -> PTObject str -> PTOther str -- | Converts a Haskell type into a Python type. pyType :: Type -> Q PyType pyType t | not (null args) = PTApp `liftM` pyType fn `ap` mapM pyType args where (fn, args) = pyAppType t pyType (ConT name) = return $ pyTypeName name pyType ListT = return PTListOf pyType (TupleT 0) = return PTNone pyType (TupleT _) = return PTTupleOf pyType typ = fail $ "unhandled case for type " ++ show typ -- | Returns a type and its type arguments. pyAppType :: Type -> (Type, [Type]) pyAppType = g [] where g as (AppT typ1 typ2) = g (typ2 : as) typ1 g as typ = (typ, as) -- | @pyType opt typ@ converts Haskell type @typ@ into a Python type, -- where @opt@ determines if the converted type is optional (i.e., -- Maybe). pyOptionalType :: Bool -> Type -> Q PyType pyOptionalType True typ = PTMaybe <$> pyType typ pyOptionalType False typ = pyType typ
mbakke/ganeti
src/Ganeti/THH/PyType.hs
bsd-2-clause
4,849
0
10
1,287
966
517
449
82
9
module Optimization.LineSearch.SteepestDescent ( -- * Steepest descent method steepestDescent -- * Step size methods , module Optimization.LineSearch ) where import Optimization.LineSearch import Linear -- | Steepest descent method -- -- @steepestDescent search f df x0@ optimizes a function @f@ with gradient @df@ -- with step size schedule @search@ starting from initial point @x0@ -- -- The steepest descent method chooses the negative gradient of the function -- as its step direction. steepestDescent :: (Num a, Ord a, Additive f, Metric f) => LineSearch f a -- ^ line search method -> (f a -> f a) -- ^ gradient of function -> f a -- ^ starting point -> [f a] -- ^ iterates steepestDescent search df x0 = iterate go x0 where go x = let p = negated (df x) a = search df p x in x ^+^ a *^ p {-# INLINEABLE steepestDescent #-}
ocramz/optimization
src/Optimization/LineSearch/SteepestDescent.hs
bsd-3-clause
990
0
13
308
178
98
80
15
1
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "Data/HashMap/Base.hs" #-} {-# LANGUAGE BangPatterns, CPP, DeriveDataTypeable, MagicHash #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RoleAnnotations #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-full-laziness -funbox-strict-fields #-} module Data.HashMap.Base ( HashMap(..) , Leaf(..) -- * Construction , empty , singleton -- * Basic interface , null , size , member , lookup , lookupDefault , (!) , insert , insertWith , unsafeInsert , delete , adjust , update , alter -- * Combine -- ** Union , union , unionWith , unionWithKey , unions -- * Transformations , map , mapWithKey , traverseWithKey -- * Difference and intersection , difference , differenceWith , intersection , intersectionWith , intersectionWithKey -- * Folds , foldl' , foldlWithKey' , foldr , foldrWithKey -- * Filter , mapMaybe , mapMaybeWithKey , filter , filterWithKey -- * Conversions , keys , elems -- ** Lists , toList , fromList , fromListWith -- Internals used by the strict version , Hash , Bitmap , bitmapIndexedOrFull , collision , hash , mask , index , bitsPerSubkey , fullNodeMask , sparseIndex , two , unionArrayBy , update16 , update16M , update16With' , updateOrConcatWith , updateOrConcatWithKey , filterMapAux , equalKeys ) where import Data.Semigroup (Semigroup((<>))) import Control.DeepSeq (NFData(rnf)) import Control.Monad.ST (ST) import Data.Bits ((.&.), (.|.), complement) import Data.Data hiding (Typeable) import qualified Data.Foldable as Foldable import qualified Data.List as L import GHC.Exts ((==#), build, reallyUnsafePtrEquality#) import Prelude hiding (filter, foldr, lookup, map, null, pred) import Text.Read hiding (step) import qualified Data.HashMap.Array as A import qualified Data.Hashable as H import Data.Hashable (Hashable) import Data.HashMap.PopCount (popCount) import Data.HashMap.Unsafe (runST) import Data.HashMap.UnsafeShift (unsafeShiftL, unsafeShiftR) import Data.Typeable (Typeable) import GHC.Exts (isTrue#) import qualified GHC.Exts as Exts import Data.Functor.Classes import qualified Data.Hashable.Lifted as H -- | A set of values. A set cannot contain duplicate values. ------------------------------------------------------------------------ -- | Convenience function. Compute a hash value for the given value. hash :: H.Hashable a => a -> Hash hash = fromIntegral . H.hash data Leaf k v = L !k v deriving (Eq) instance (NFData k, NFData v) => NFData (Leaf k v) where rnf (L k v) = rnf k `seq` rnf v -- Invariant: The length of the 1st argument to 'Full' is -- 2^bitsPerSubkey -- | A map from keys to values. A map cannot contain duplicate keys; -- each key can map to at most one value. data HashMap k v = Empty | BitmapIndexed !Bitmap !(A.Array (HashMap k v)) | Leaf !Hash !(Leaf k v) | Full !(A.Array (HashMap k v)) | Collision !Hash !(A.Array (Leaf k v)) deriving (Typeable) type role HashMap nominal representational instance (NFData k, NFData v) => NFData (HashMap k v) where rnf Empty = () rnf (BitmapIndexed _ ary) = rnf ary rnf (Leaf _ l) = rnf l rnf (Full ary) = rnf ary rnf (Collision _ ary) = rnf ary instance Functor (HashMap k) where fmap = map instance Foldable.Foldable (HashMap k) where foldr f = foldrWithKey (const f) instance (Eq k, Hashable k) => Semigroup (HashMap k v) where (<>) = union {-# INLINE (<>) #-} instance (Eq k, Hashable k) => Monoid (HashMap k v) where mempty = empty {-# INLINE mempty #-} mappend = (<>) {-# INLINE mappend #-} instance (Data k, Data v, Eq k, Hashable k) => Data (HashMap k v) where gfoldl f z m = z fromList `f` toList m toConstr _ = fromListConstr gunfold k z c = case constrIndex c of 1 -> k (z fromList) _ -> error "gunfold" dataTypeOf _ = hashMapDataType dataCast2 f = gcast2 f fromListConstr :: Constr fromListConstr = mkConstr hashMapDataType "fromList" [] Prefix hashMapDataType :: DataType hashMapDataType = mkDataType "Data.HashMap.Base.HashMap" [fromListConstr] type Hash = Word type Bitmap = Word type Shift = Int instance Show2 HashMap where liftShowsPrec2 spk slk spv slv d m = showsUnaryWith (liftShowsPrec sp sl) "fromList" d (toList m) where sp = liftShowsPrec2 spk slk spv slv sl = liftShowList2 spk slk spv slv instance Show k => Show1 (HashMap k) where liftShowsPrec = liftShowsPrec2 showsPrec showList instance (Eq k, Hashable k, Read k) => Read1 (HashMap k) where liftReadsPrec rp rl = readsData $ readsUnaryWith (liftReadsPrec rp' rl') "fromList" fromList where rp' = liftReadsPrec rp rl rl' = liftReadList rp rl instance (Eq k, Hashable k, Read k, Read e) => Read (HashMap k e) where readPrec = parens $ prec 10 $ do Ident "fromList" <- lexP xs <- readPrec return (fromList xs) readListPrec = readListPrecDefault instance (Show k, Show v) => Show (HashMap k v) where showsPrec d m = showParen (d > 10) $ showString "fromList " . shows (toList m) instance Traversable (HashMap k) where traverse f = traverseWithKey (const f) instance Eq2 HashMap where liftEq2 = equal instance Eq k => Eq1 (HashMap k) where liftEq = equal (==) instance (Eq k, Eq v) => Eq (HashMap k v) where (==) = equal (==) (==) equal :: (k -> k' -> Bool) -> (v -> v' -> Bool) -> HashMap k v -> HashMap k' v' -> Bool equal eqk eqv t1 t2 = go (toList' t1 []) (toList' t2 []) where -- If the two trees are the same, then their lists of 'Leaf's and -- 'Collision's read from left to right should be the same (modulo the -- order of elements in 'Collision'). go (Leaf k1 l1 : tl1) (Leaf k2 l2 : tl2) | k1 == k2 && leafEq l1 l2 = go tl1 tl2 go (Collision k1 ary1 : tl1) (Collision k2 ary2 : tl2) | k1 == k2 && A.length ary1 == A.length ary2 && isPermutationBy leafEq (A.toList ary1) (A.toList ary2) = go tl1 tl2 go [] [] = True go _ _ = False leafEq (L k v) (L k' v') = eqk k k' && eqv v v' -- Note: previous implemenation isPermutation = null (as // bs) -- was O(n^2) too. -- -- This assumes lists are of equal length isPermutationBy :: (a -> b -> Bool) -> [a] -> [b] -> Bool isPermutationBy f = go where f' = flip f go [] [] = True go (x : xs) (y : ys) | f x y = go xs ys | otherwise = go (deleteBy f' y xs) (deleteBy f x ys) go [] (_ : _) = False go (_ : _) [] = False -- Data.List.deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a] deleteBy :: (a -> b -> Bool) -> a -> [b] -> [b] deleteBy _ _ [] = [] deleteBy eq x (y:ys) = if x `eq` y then ys else y : deleteBy eq x ys -- Same as 'equal' but doesn't compare the values. equalKeys :: (k -> k' -> Bool) -> HashMap k v -> HashMap k' v' -> Bool equalKeys eq t1 t2 = go (toList' t1 []) (toList' t2 []) where go (Leaf k1 l1 : tl1) (Leaf k2 l2 : tl2) | k1 == k2 && leafEq l1 l2 = go tl1 tl2 go (Collision k1 ary1 : tl1) (Collision k2 ary2 : tl2) | k1 == k2 && A.length ary1 == A.length ary2 && isPermutationBy leafEq (A.toList ary1) (A.toList ary2) = go tl1 tl2 go [] [] = True go _ _ = False leafEq (L k _) (L k' _) = eq k k' instance H.Hashable2 HashMap where liftHashWithSalt2 hk hv salt hm = go salt (toList' hm []) where -- go :: Int -> [HashMap k v] -> Int go s [] = s go s (Leaf _ l : tl) = s `hashLeafWithSalt` l `go` tl -- For collisions we hashmix hash value -- and then array of values' hashes sorted go s (Collision h a : tl) = (s `H.hashWithSalt` h) `hashCollisionWithSalt` a `go` tl go s (_ : tl) = s `go` tl -- hashLeafWithSalt :: Int -> Leaf k v -> Int hashLeafWithSalt s (L k v) = (s `hk` k) `hv` v -- hashCollisionWithSalt :: Int -> A.Array (Leaf k v) -> Int hashCollisionWithSalt s = L.foldl' H.hashWithSalt s . arrayHashesSorted s -- arrayHashesSorted :: Int -> A.Array (Leaf k v) -> [Int] arrayHashesSorted s = L.sort . L.map (hashLeafWithSalt s) . A.toList instance (Hashable k) => H.Hashable1 (HashMap k) where liftHashWithSalt = H.liftHashWithSalt2 H.hashWithSalt instance (Hashable k, Hashable v) => Hashable (HashMap k v) where hashWithSalt salt hm = go salt (toList' hm []) where go :: Int -> [HashMap k v] -> Int go s [] = s go s (Leaf _ l : tl) = s `hashLeafWithSalt` l `go` tl -- For collisions we hashmix hash value -- and then array of values' hashes sorted go s (Collision h a : tl) = (s `H.hashWithSalt` h) `hashCollisionWithSalt` a `go` tl go s (_ : tl) = s `go` tl hashLeafWithSalt :: Int -> Leaf k v -> Int hashLeafWithSalt s (L k v) = s `H.hashWithSalt` k `H.hashWithSalt` v hashCollisionWithSalt :: Int -> A.Array (Leaf k v) -> Int hashCollisionWithSalt s = L.foldl' H.hashWithSalt s . arrayHashesSorted s arrayHashesSorted :: Int -> A.Array (Leaf k v) -> [Int] arrayHashesSorted s = L.sort . L.map (hashLeafWithSalt s) . A.toList -- Helper to get 'Leaf's and 'Collision's as a list. toList' :: HashMap k v -> [HashMap k v] -> [HashMap k v] toList' (BitmapIndexed _ ary) a = A.foldr toList' a ary toList' (Full ary) a = A.foldr toList' a ary toList' l@(Leaf _ _) a = l : a toList' c@(Collision _ _) a = c : a toList' Empty a = a -- Helper function to detect 'Leaf's and 'Collision's. isLeafOrCollision :: HashMap k v -> Bool isLeafOrCollision (Leaf _ _) = True isLeafOrCollision (Collision _ _) = True isLeafOrCollision _ = False ------------------------------------------------------------------------ -- * Construction -- | /O(1)/ Construct an empty map. empty :: HashMap k v empty = Empty -- | /O(1)/ Construct a map with a single element. singleton :: (Hashable k) => k -> v -> HashMap k v singleton k v = Leaf (hash k) (L k v) ------------------------------------------------------------------------ -- * Basic interface -- | /O(1)/ Return 'True' if this map is empty, 'False' otherwise. null :: HashMap k v -> Bool null Empty = True null _ = False -- | /O(n)/ Return the number of key-value mappings in this map. size :: HashMap k v -> Int size t = go t 0 where go Empty !n = n go (Leaf _ _) n = n + 1 go (BitmapIndexed _ ary) n = A.foldl' (flip go) n ary go (Full ary) n = A.foldl' (flip go) n ary go (Collision _ ary) n = n + A.length ary -- | /O(log n)/ Return 'True' if the specified key is present in the -- map, 'False' otherwise. member :: (Eq k, Hashable k) => k -> HashMap k a -> Bool member k m = case lookup k m of Nothing -> False Just _ -> True {-# INLINABLE member #-} -- | /O(log n)/ Return the value to which the specified key is mapped, -- or 'Nothing' if this map contains no mapping for the key. lookup :: (Eq k, Hashable k) => k -> HashMap k v -> Maybe v lookup k0 m0 = go h0 k0 0 m0 where h0 = hash k0 go !_ !_ !_ Empty = Nothing go h k _ (Leaf hx (L kx x)) | h == hx && k == kx = Just x -- TODO: Split test in two | otherwise = Nothing go h k s (BitmapIndexed b v) | b .&. m == 0 = Nothing | otherwise = go h k (s+bitsPerSubkey) (A.index v (sparseIndex b m)) where m = mask h s go h k s (Full v) = go h k (s+bitsPerSubkey) (A.index v (index h s)) go h k _ (Collision hx v) | h == hx = lookupInArray k v | otherwise = Nothing {-# INLINABLE lookup #-} -- | /O(log n)/ Return the value to which the specified key is mapped, -- or the default value if this map contains no mapping for the key. lookupDefault :: (Eq k, Hashable k) => v -- ^ Default value to return. -> k -> HashMap k v -> v lookupDefault def k t = case lookup k t of Just v -> v _ -> def {-# INLINABLE lookupDefault #-} -- | /O(log n)/ Return the value to which the specified key is mapped. -- Calls 'error' if this map contains no mapping for the key. (!) :: (Eq k, Hashable k) => HashMap k v -> k -> v (!) m k = case lookup k m of Just v -> v Nothing -> error "Data.HashMap.Base.(!): key not found" {-# INLINABLE (!) #-} infixl 9 ! -- | Create a 'Collision' value with two 'Leaf' values. collision :: Hash -> Leaf k v -> Leaf k v -> HashMap k v collision h e1 e2 = let v = A.run $ do mary <- A.new 2 e1 A.write mary 1 e2 return mary in Collision h v {-# INLINE collision #-} -- | Create a 'BitmapIndexed' or 'Full' node. bitmapIndexedOrFull :: Bitmap -> A.Array (HashMap k v) -> HashMap k v bitmapIndexedOrFull b ary | b == fullNodeMask = Full ary | otherwise = BitmapIndexed b ary {-# INLINE bitmapIndexedOrFull #-} -- | /O(log n)/ Associate the specified value with the specified -- key in this map. If this map previously contained a mapping for -- the key, the old value is replaced. insert :: (Eq k, Hashable k) => k -> v -> HashMap k v -> HashMap k v insert k0 v0 m0 = go h0 k0 v0 0 m0 where h0 = hash k0 go !h !k x !_ Empty = Leaf h (L k x) go h k x s t@(Leaf hy l@(L ky y)) | hy == h = if ky == k then if x `ptrEq` y then t else Leaf h (L k x) else collision h l (L k x) | otherwise = runST (two s h k x hy ky y) go h k x s t@(BitmapIndexed b ary) | b .&. m == 0 = let !ary' = A.insert ary i $! Leaf h (L k x) in bitmapIndexedOrFull (b .|. m) ary' | otherwise = let !st = A.index ary i !st' = go h k x (s+bitsPerSubkey) st in if st' `ptrEq` st then t else BitmapIndexed b (A.update ary i st') where m = mask h s i = sparseIndex b m go h k x s t@(Full ary) = let !st = A.index ary i !st' = go h k x (s+bitsPerSubkey) st in if st' `ptrEq` st then t else Full (update16 ary i st') where i = index h s go h k x s t@(Collision hy v) | h == hy = Collision h (updateOrSnocWith const k x v) | otherwise = go h k x s $ BitmapIndexed (mask hy s) (A.singleton t) {-# INLINABLE insert #-} -- | In-place update version of insert unsafeInsert :: (Eq k, Hashable k) => k -> v -> HashMap k v -> HashMap k v unsafeInsert k0 v0 m0 = runST (go h0 k0 v0 0 m0) where h0 = hash k0 go !h !k x !_ Empty = return $! Leaf h (L k x) go h k x s t@(Leaf hy l@(L ky y)) | hy == h = if ky == k then if x `ptrEq` y then return t else return $! Leaf h (L k x) else return $! collision h l (L k x) | otherwise = two s h k x hy ky y go h k x s t@(BitmapIndexed b ary) | b .&. m == 0 = do ary' <- A.insertM ary i $! Leaf h (L k x) return $! bitmapIndexedOrFull (b .|. m) ary' | otherwise = do st <- A.indexM ary i st' <- go h k x (s+bitsPerSubkey) st A.unsafeUpdateM ary i st' return t where m = mask h s i = sparseIndex b m go h k x s t@(Full ary) = do st <- A.indexM ary i st' <- go h k x (s+bitsPerSubkey) st A.unsafeUpdateM ary i st' return t where i = index h s go h k x s t@(Collision hy v) | h == hy = return $! Collision h (updateOrSnocWith const k x v) | otherwise = go h k x s $ BitmapIndexed (mask hy s) (A.singleton t) {-# INLINABLE unsafeInsert #-} -- | Create a map from two key-value pairs which hashes don't collide. two :: Shift -> Hash -> k -> v -> Hash -> k -> v -> ST s (HashMap k v) two = go where go s h1 k1 v1 h2 k2 v2 | bp1 == bp2 = do st <- go (s+bitsPerSubkey) h1 k1 v1 h2 k2 v2 ary <- A.singletonM st return $! BitmapIndexed bp1 ary | otherwise = do mary <- A.new 2 $ Leaf h1 (L k1 v1) A.write mary idx2 $ Leaf h2 (L k2 v2) ary <- A.unsafeFreeze mary return $! BitmapIndexed (bp1 .|. bp2) ary where bp1 = mask h1 s bp2 = mask h2 s idx2 | index h1 s < index h2 s = 1 | otherwise = 0 {-# INLINE two #-} -- | /O(log n)/ Associate the value with the key in this map. If -- this map previously contained a mapping for the key, the old value -- is replaced by the result of applying the given function to the new -- and old value. Example: -- -- > insertWith f k v map -- > where f new old = new + old insertWith :: (Eq k, Hashable k) => (v -> v -> v) -> k -> v -> HashMap k v -> HashMap k v insertWith f k0 v0 m0 = go h0 k0 v0 0 m0 where h0 = hash k0 go !h !k x !_ Empty = Leaf h (L k x) go h k x s (Leaf hy l@(L ky y)) | hy == h = if ky == k then Leaf h (L k (f x y)) else collision h l (L k x) | otherwise = runST (two s h k x hy ky y) go h k x s (BitmapIndexed b ary) | b .&. m == 0 = let ary' = A.insert ary i $! Leaf h (L k x) in bitmapIndexedOrFull (b .|. m) ary' | otherwise = let st = A.index ary i st' = go h k x (s+bitsPerSubkey) st ary' = A.update ary i $! st' in BitmapIndexed b ary' where m = mask h s i = sparseIndex b m go h k x s (Full ary) = let st = A.index ary i st' = go h k x (s+bitsPerSubkey) st ary' = update16 ary i $! st' in Full ary' where i = index h s go h k x s t@(Collision hy v) | h == hy = Collision h (updateOrSnocWith f k x v) | otherwise = go h k x s $ BitmapIndexed (mask hy s) (A.singleton t) {-# INLINABLE insertWith #-} -- | In-place update version of insertWith unsafeInsertWith :: forall k v. (Eq k, Hashable k) => (v -> v -> v) -> k -> v -> HashMap k v -> HashMap k v unsafeInsertWith f k0 v0 m0 = runST (go h0 k0 v0 0 m0) where h0 = hash k0 go :: Hash -> k -> v -> Shift -> HashMap k v -> ST s (HashMap k v) go !h !k x !_ Empty = return $! Leaf h (L k x) go h k x s (Leaf hy l@(L ky y)) | hy == h = if ky == k then return $! Leaf h (L k (f x y)) else return $! collision h l (L k x) | otherwise = two s h k x hy ky y go h k x s t@(BitmapIndexed b ary) | b .&. m == 0 = do ary' <- A.insertM ary i $! Leaf h (L k x) return $! bitmapIndexedOrFull (b .|. m) ary' | otherwise = do st <- A.indexM ary i st' <- go h k x (s+bitsPerSubkey) st A.unsafeUpdateM ary i st' return t where m = mask h s i = sparseIndex b m go h k x s t@(Full ary) = do st <- A.indexM ary i st' <- go h k x (s+bitsPerSubkey) st A.unsafeUpdateM ary i st' return t where i = index h s go h k x s t@(Collision hy v) | h == hy = return $! Collision h (updateOrSnocWith f k x v) | otherwise = go h k x s $ BitmapIndexed (mask hy s) (A.singleton t) {-# INLINABLE unsafeInsertWith #-} -- | /O(log n)/ Remove the mapping for the specified key from this map -- if present. delete :: (Eq k, Hashable k) => k -> HashMap k v -> HashMap k v delete k0 m0 = go h0 k0 0 m0 where h0 = hash k0 go !_ !_ !_ Empty = Empty go h k _ t@(Leaf hy (L ky _)) | hy == h && ky == k = Empty | otherwise = t go h k s t@(BitmapIndexed b ary) | b .&. m == 0 = t | otherwise = let !st = A.index ary i !st' = go h k (s+bitsPerSubkey) st in if st' `ptrEq` st then t else case st' of Empty | A.length ary == 1 -> Empty | A.length ary == 2 -> case (i, A.index ary 0, A.index ary 1) of (0, _, l) | isLeafOrCollision l -> l (1, l, _) | isLeafOrCollision l -> l _ -> bIndexed | otherwise -> bIndexed where bIndexed = BitmapIndexed (b .&. complement m) (A.delete ary i) l | isLeafOrCollision l && A.length ary == 1 -> l _ -> BitmapIndexed b (A.update ary i st') where m = mask h s i = sparseIndex b m go h k s t@(Full ary) = let !st = A.index ary i !st' = go h k (s+bitsPerSubkey) st in if st' `ptrEq` st then t else case st' of Empty -> let ary' = A.delete ary i bm = fullNodeMask .&. complement (1 `unsafeShiftL` i) in BitmapIndexed bm ary' _ -> Full (A.update ary i st') where i = index h s go h k _ t@(Collision hy v) | h == hy = case indexOf k v of Just i | A.length v == 2 -> if i == 0 then Leaf h (A.index v 1) else Leaf h (A.index v 0) | otherwise -> Collision h (A.delete v i) Nothing -> t | otherwise = t {-# INLINABLE delete #-} -- | /O(log n)/ Adjust the value tied to a given key in this map only -- if it is present. Otherwise, leave the map alone. adjust :: (Eq k, Hashable k) => (v -> v) -> k -> HashMap k v -> HashMap k v adjust f k0 m0 = go h0 k0 0 m0 where h0 = hash k0 go !_ !_ !_ Empty = Empty go h k _ t@(Leaf hy (L ky y)) | hy == h && ky == k = Leaf h (L k (f y)) | otherwise = t go h k s t@(BitmapIndexed b ary) | b .&. m == 0 = t | otherwise = let st = A.index ary i st' = go h k (s+bitsPerSubkey) st ary' = A.update ary i $! st' in BitmapIndexed b ary' where m = mask h s i = sparseIndex b m go h k s (Full ary) = let i = index h s st = A.index ary i st' = go h k (s+bitsPerSubkey) st ary' = update16 ary i $! st' in Full ary' go h k _ t@(Collision hy v) | h == hy = Collision h (updateWith f k v) | otherwise = t {-# INLINABLE adjust #-} -- | /O(log n)/ The expression (@'update' f k map@) updates the value @x@ at @k@, -- (if it is in the map). If (f k x) is @'Nothing', the element is deleted. -- If it is (@'Just' y), the key k is bound to the new value y. update :: (Eq k, Hashable k) => (a -> Maybe a) -> k -> HashMap k a -> HashMap k a update f = alter (>>= f) {-# INLINABLE update #-} -- | /O(log n)/ The expression (@'alter' f k map@) alters the value @x@ at @k@, or -- absence thereof. @alter@ can be used to insert, delete, or update a value in a -- map. In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@. alter :: (Eq k, Hashable k) => (Maybe v -> Maybe v) -> k -> HashMap k v -> HashMap k v alter f k m = case f (lookup k m) of Nothing -> delete k m Just v -> insert k v m {-# INLINABLE alter #-} ------------------------------------------------------------------------ -- * Combine -- | /O(n+m)/ The union of two maps. If a key occurs in both maps, the -- mapping from the first will be the mapping in the result. union :: (Eq k, Hashable k) => HashMap k v -> HashMap k v -> HashMap k v union = unionWith const {-# INLINABLE union #-} -- | /O(n+m)/ The union of two maps. If a key occurs in both maps, -- the provided function (first argument) will be used to compute the -- result. unionWith :: (Eq k, Hashable k) => (v -> v -> v) -> HashMap k v -> HashMap k v -> HashMap k v unionWith f = unionWithKey (const f) {-# INLINE unionWith #-} -- | /O(n+m)/ The union of two maps. If a key occurs in both maps, -- the provided function (first argument) will be used to compute the -- result. unionWithKey :: (Eq k, Hashable k) => (k -> v -> v -> v) -> HashMap k v -> HashMap k v -> HashMap k v unionWithKey f = go 0 where -- empty vs. anything go !_ t1 Empty = t1 go _ Empty t2 = t2 -- leaf vs. leaf go s t1@(Leaf h1 l1@(L k1 v1)) t2@(Leaf h2 l2@(L k2 v2)) | h1 == h2 = if k1 == k2 then Leaf h1 (L k1 (f k1 v1 v2)) else collision h1 l1 l2 | otherwise = goDifferentHash s h1 h2 t1 t2 go s t1@(Leaf h1 (L k1 v1)) t2@(Collision h2 ls2) | h1 == h2 = Collision h1 (updateOrSnocWithKey f k1 v1 ls2) | otherwise = goDifferentHash s h1 h2 t1 t2 go s t1@(Collision h1 ls1) t2@(Leaf h2 (L k2 v2)) | h1 == h2 = Collision h1 (updateOrSnocWithKey (flip . f) k2 v2 ls1) | otherwise = goDifferentHash s h1 h2 t1 t2 go s t1@(Collision h1 ls1) t2@(Collision h2 ls2) | h1 == h2 = Collision h1 (updateOrConcatWithKey f ls1 ls2) | otherwise = goDifferentHash s h1 h2 t1 t2 -- branch vs. branch go s (BitmapIndexed b1 ary1) (BitmapIndexed b2 ary2) = let b' = b1 .|. b2 ary' = unionArrayBy (go (s+bitsPerSubkey)) b1 b2 ary1 ary2 in bitmapIndexedOrFull b' ary' go s (BitmapIndexed b1 ary1) (Full ary2) = let ary' = unionArrayBy (go (s+bitsPerSubkey)) b1 fullNodeMask ary1 ary2 in Full ary' go s (Full ary1) (BitmapIndexed b2 ary2) = let ary' = unionArrayBy (go (s+bitsPerSubkey)) fullNodeMask b2 ary1 ary2 in Full ary' go s (Full ary1) (Full ary2) = let ary' = unionArrayBy (go (s+bitsPerSubkey)) fullNodeMask fullNodeMask ary1 ary2 in Full ary' -- leaf vs. branch go s (BitmapIndexed b1 ary1) t2 | b1 .&. m2 == 0 = let ary' = A.insert ary1 i t2 b' = b1 .|. m2 in bitmapIndexedOrFull b' ary' | otherwise = let ary' = A.updateWith' ary1 i $ \st1 -> go (s+bitsPerSubkey) st1 t2 in BitmapIndexed b1 ary' where h2 = leafHashCode t2 m2 = mask h2 s i = sparseIndex b1 m2 go s t1 (BitmapIndexed b2 ary2) | b2 .&. m1 == 0 = let ary' = A.insert ary2 i $! t1 b' = b2 .|. m1 in bitmapIndexedOrFull b' ary' | otherwise = let ary' = A.updateWith' ary2 i $ \st2 -> go (s+bitsPerSubkey) t1 st2 in BitmapIndexed b2 ary' where h1 = leafHashCode t1 m1 = mask h1 s i = sparseIndex b2 m1 go s (Full ary1) t2 = let h2 = leafHashCode t2 i = index h2 s ary' = update16With' ary1 i $ \st1 -> go (s+bitsPerSubkey) st1 t2 in Full ary' go s t1 (Full ary2) = let h1 = leafHashCode t1 i = index h1 s ary' = update16With' ary2 i $ \st2 -> go (s+bitsPerSubkey) t1 st2 in Full ary' leafHashCode (Leaf h _) = h leafHashCode (Collision h _) = h leafHashCode _ = error "leafHashCode" goDifferentHash s h1 h2 t1 t2 | m1 == m2 = BitmapIndexed m1 (A.singleton $! go (s+bitsPerSubkey) t1 t2) | m1 < m2 = BitmapIndexed (m1 .|. m2) (A.pair t1 t2) | otherwise = BitmapIndexed (m1 .|. m2) (A.pair t2 t1) where m1 = mask h1 s m2 = mask h2 s {-# INLINE unionWithKey #-} -- | Strict in the result of @f@. unionArrayBy :: (a -> a -> a) -> Bitmap -> Bitmap -> A.Array a -> A.Array a -> A.Array a unionArrayBy f b1 b2 ary1 ary2 = A.run $ do let b' = b1 .|. b2 mary <- A.new_ (popCount b') -- iterate over nonzero bits of b1 .|. b2 -- it would be nice if we could shift m by more than 1 each time let ba = b1 .&. b2 go !i !i1 !i2 !m | m > b' = return () | b' .&. m == 0 = go i i1 i2 (m `unsafeShiftL` 1) | ba .&. m /= 0 = do A.write mary i $! f (A.index ary1 i1) (A.index ary2 i2) go (i+1) (i1+1) (i2+1) (m `unsafeShiftL` 1) | b1 .&. m /= 0 = do A.write mary i =<< A.indexM ary1 i1 go (i+1) (i1+1) (i2 ) (m `unsafeShiftL` 1) | otherwise = do A.write mary i =<< A.indexM ary2 i2 go (i+1) (i1 ) (i2+1) (m `unsafeShiftL` 1) go 0 0 0 (b' .&. negate b') -- XXX: b' must be non-zero return mary -- TODO: For the case where b1 .&. b2 == b1, i.e. when one is a -- subset of the other, we could use a slightly simpler algorithm, -- where we copy one array, and then update. {-# INLINE unionArrayBy #-} -- TODO: Figure out the time complexity of 'unions'. -- | Construct a set containing all elements from a list of sets. unions :: (Eq k, Hashable k) => [HashMap k v] -> HashMap k v unions = L.foldl' union empty {-# INLINE unions #-} ------------------------------------------------------------------------ -- * Transformations -- | /O(n)/ Transform this map by applying a function to every value. mapWithKey :: (k -> v1 -> v2) -> HashMap k v1 -> HashMap k v2 mapWithKey f = go where go Empty = Empty go (Leaf h (L k v)) = Leaf h $ L k (f k v) go (BitmapIndexed b ary) = BitmapIndexed b $ A.map' go ary go (Full ary) = Full $ A.map' go ary go (Collision h ary) = Collision h $ A.map' (\ (L k v) -> L k (f k v)) ary {-# INLINE mapWithKey #-} -- | /O(n)/ Transform this map by applying a function to every value. map :: (v1 -> v2) -> HashMap k v1 -> HashMap k v2 map f = mapWithKey (const f) {-# INLINE map #-} -- TODO: We should be able to use mutation to create the new -- 'HashMap'. -- | /O(n)/ Transform this map by accumulating an Applicative result -- from every value. traverseWithKey :: Applicative f => (k -> v1 -> f v2) -> HashMap k v1 -> f (HashMap k v2) traverseWithKey f = go where go Empty = pure Empty go (Leaf h (L k v)) = Leaf h . L k <$> f k v go (BitmapIndexed b ary) = BitmapIndexed b <$> A.traverse go ary go (Full ary) = Full <$> A.traverse go ary go (Collision h ary) = Collision h <$> A.traverse (\ (L k v) -> L k <$> f k v) ary {-# INLINE traverseWithKey #-} ------------------------------------------------------------------------ -- * Difference and intersection -- | /O(n*log m)/ Difference of two maps. Return elements of the first map -- not existing in the second. difference :: (Eq k, Hashable k) => HashMap k v -> HashMap k w -> HashMap k v difference a b = foldlWithKey' go empty a where go m k v = case lookup k b of Nothing -> insert k v m _ -> m {-# INLINABLE difference #-} -- | /O(n*log m)/ Difference with a combining function. When two equal keys are -- encountered, the combining function is applied to the values of these keys. -- If it returns 'Nothing', the element is discarded (proper set difference). If -- it returns (@'Just' y@), the element is updated with a new value @y@. differenceWith :: (Eq k, Hashable k) => (v -> w -> Maybe v) -> HashMap k v -> HashMap k w -> HashMap k v differenceWith f a b = foldlWithKey' go empty a where go m k v = case lookup k b of Nothing -> insert k v m Just w -> maybe m (\y -> insert k y m) (f v w) {-# INLINABLE differenceWith #-} -- | /O(n*log m)/ Intersection of two maps. Return elements of the first -- map for keys existing in the second. intersection :: (Eq k, Hashable k) => HashMap k v -> HashMap k w -> HashMap k v intersection a b = foldlWithKey' go empty a where go m k v = case lookup k b of Just _ -> insert k v m _ -> m {-# INLINABLE intersection #-} -- | /O(n+m)/ Intersection of two maps. If a key occurs in both maps -- the provided function is used to combine the values from the two -- maps. intersectionWith :: (Eq k, Hashable k) => (v1 -> v2 -> v3) -> HashMap k v1 -> HashMap k v2 -> HashMap k v3 intersectionWith f a b = foldlWithKey' go empty a where go m k v = case lookup k b of Just w -> insert k (f v w) m _ -> m {-# INLINABLE intersectionWith #-} -- | /O(n+m)/ Intersection of two maps. If a key occurs in both maps -- the provided function is used to combine the values from the two -- maps. intersectionWithKey :: (Eq k, Hashable k) => (k -> v1 -> v2 -> v3) -> HashMap k v1 -> HashMap k v2 -> HashMap k v3 intersectionWithKey f a b = foldlWithKey' go empty a where go m k v = case lookup k b of Just w -> insert k (f k v w) m _ -> m {-# INLINABLE intersectionWithKey #-} ------------------------------------------------------------------------ -- * Folds -- | /O(n)/ Reduce this map by applying a binary operator to all -- elements, using the given starting value (typically the -- left-identity of the operator). Each application of the operator -- is evaluated before before using the result in the next -- application. This function is strict in the starting value. foldl' :: (a -> v -> a) -> a -> HashMap k v -> a foldl' f = foldlWithKey' (\ z _ v -> f z v) {-# INLINE foldl' #-} -- | /O(n)/ Reduce this map by applying a binary operator to all -- elements, using the given starting value (typically the -- left-identity of the operator). Each application of the operator -- is evaluated before before using the result in the next -- application. This function is strict in the starting value. foldlWithKey' :: (a -> k -> v -> a) -> a -> HashMap k v -> a foldlWithKey' f = go where go !z Empty = z go z (Leaf _ (L k v)) = f z k v go z (BitmapIndexed _ ary) = A.foldl' go z ary go z (Full ary) = A.foldl' go z ary go z (Collision _ ary) = A.foldl' (\ z' (L k v) -> f z' k v) z ary {-# INLINE foldlWithKey' #-} -- | /O(n)/ Reduce this map by applying a binary operator to all -- elements, using the given starting value (typically the -- right-identity of the operator). foldr :: (v -> a -> a) -> a -> HashMap k v -> a foldr f = foldrWithKey (const f) {-# INLINE foldr #-} -- | /O(n)/ Reduce this map by applying a binary operator to all -- elements, using the given starting value (typically the -- right-identity of the operator). foldrWithKey :: (k -> v -> a -> a) -> a -> HashMap k v -> a foldrWithKey f = go where go z Empty = z go z (Leaf _ (L k v)) = f k v z go z (BitmapIndexed _ ary) = A.foldr (flip go) z ary go z (Full ary) = A.foldr (flip go) z ary go z (Collision _ ary) = A.foldr (\ (L k v) z' -> f k v z') z ary {-# INLINE foldrWithKey #-} ------------------------------------------------------------------------ -- * Filter -- | Create a new array of the @n@ first elements of @mary@. trim :: A.MArray s a -> Int -> ST s (A.Array a) trim mary n = do mary2 <- A.new_ n A.copyM mary 0 mary2 0 n A.unsafeFreeze mary2 {-# INLINE trim #-} -- | /O(n)/ Transform this map by applying a function to every value -- and retaining only some of them. mapMaybeWithKey :: (k -> v1 -> Maybe v2) -> HashMap k v1 -> HashMap k v2 mapMaybeWithKey f = filterMapAux onLeaf onColl where onLeaf (Leaf h (L k v)) | Just v' <- f k v = Just (Leaf h (L k v')) onLeaf _ = Nothing onColl (L k v) | Just v' <- f k v = Just (L k v') | otherwise = Nothing {-# INLINE mapMaybeWithKey #-} -- | /O(n)/ Transform this map by applying a function to every value -- and retaining only some of them. mapMaybe :: (v1 -> Maybe v2) -> HashMap k v1 -> HashMap k v2 mapMaybe f = mapMaybeWithKey (const f) {-# INLINE mapMaybe #-} -- | /O(n)/ Filter this map by retaining only elements satisfying a -- predicate. filterWithKey :: forall k v. (k -> v -> Bool) -> HashMap k v -> HashMap k v filterWithKey pred = filterMapAux onLeaf onColl where onLeaf t@(Leaf _ (L k v)) | pred k v = Just t onLeaf _ = Nothing onColl el@(L k v) | pred k v = Just el onColl _ = Nothing {-# INLINE filterWithKey #-} -- | Common implementation for 'filterWithKey' and 'mapMaybeWithKey', -- allowing the former to former to reuse terms. filterMapAux :: forall k v1 v2 . (HashMap k v1 -> Maybe (HashMap k v2)) -> (Leaf k v1 -> Maybe (Leaf k v2)) -> HashMap k v1 -> HashMap k v2 filterMapAux onLeaf onColl = go where go Empty = Empty go t@Leaf{} | Just t' <- onLeaf t = t' | otherwise = Empty go (BitmapIndexed b ary) = filterA ary b go (Full ary) = filterA ary fullNodeMask go (Collision h ary) = filterC ary h filterA ary0 b0 = let !n = A.length ary0 in runST $ do mary <- A.new_ n step ary0 mary b0 0 0 1 n where step :: A.Array (HashMap k v1) -> A.MArray s (HashMap k v2) -> Bitmap -> Int -> Int -> Bitmap -> Int -> ST s (HashMap k v2) step !ary !mary !b i !j !bi n | i >= n = case j of 0 -> return Empty 1 -> do ch <- A.read mary 0 case ch of t | isLeafOrCollision t -> return t _ -> BitmapIndexed b <$> trim mary 1 _ -> do ary2 <- trim mary j return $! if j == maxChildren then Full ary2 else BitmapIndexed b ary2 | bi .&. b == 0 = step ary mary b i j (bi `unsafeShiftL` 1) n | otherwise = case go (A.index ary i) of Empty -> step ary mary (b .&. complement bi) (i+1) j (bi `unsafeShiftL` 1) n t -> do A.write mary j t step ary mary b (i+1) (j+1) (bi `unsafeShiftL` 1) n filterC ary0 h = let !n = A.length ary0 in runST $ do mary <- A.new_ n step ary0 mary 0 0 n where step :: A.Array (Leaf k v1) -> A.MArray s (Leaf k v2) -> Int -> Int -> Int -> ST s (HashMap k v2) step !ary !mary i !j n | i >= n = case j of 0 -> return Empty 1 -> do l <- A.read mary 0 return $! Leaf h l _ | i == j -> do ary2 <- A.unsafeFreeze mary return $! Collision h ary2 | otherwise -> do ary2 <- trim mary j return $! Collision h ary2 | Just el <- onColl (A.index ary i) = A.write mary j el >> step ary mary (i+1) (j+1) n | otherwise = step ary mary (i+1) j n {-# INLINE filterMapAux #-} -- | /O(n)/ Filter this map by retaining only elements which values -- satisfy a predicate. filter :: (v -> Bool) -> HashMap k v -> HashMap k v filter p = filterWithKey (\_ v -> p v) {-# INLINE filter #-} ------------------------------------------------------------------------ -- * Conversions -- TODO: Improve fusion rules by modelled them after the Prelude ones -- on lists. -- | /O(n)/ Return a list of this map's keys. The list is produced -- lazily. keys :: HashMap k v -> [k] keys = L.map fst . toList {-# INLINE keys #-} -- | /O(n)/ Return a list of this map's values. The list is produced -- lazily. elems :: HashMap k v -> [v] elems = L.map snd . toList {-# INLINE elems #-} ------------------------------------------------------------------------ -- ** Lists -- | /O(n)/ Return a list of this map's elements. The list is -- produced lazily. The order of its elements is unspecified. toList :: HashMap k v -> [(k, v)] toList t = build (\ c z -> foldrWithKey (curry c) z t) {-# INLINE toList #-} -- | /O(n)/ Construct a map with the supplied mappings. If the list -- contains duplicate mappings, the later mappings take precedence. fromList :: (Eq k, Hashable k) => [(k, v)] -> HashMap k v fromList = L.foldl' (\ m (k, v) -> unsafeInsert k v m) empty {-# INLINABLE fromList #-} -- | /O(n*log n)/ Construct a map from a list of elements. Uses -- the provided function to merge duplicate entries. fromListWith :: (Eq k, Hashable k) => (v -> v -> v) -> [(k, v)] -> HashMap k v fromListWith f = L.foldl' (\ m (k, v) -> unsafeInsertWith f k v m) empty {-# INLINE fromListWith #-} ------------------------------------------------------------------------ -- Array operations -- | /O(n)/ Lookup the value associated with the given key in this -- array. Returns 'Nothing' if the key wasn't found. lookupInArray :: Eq k => k -> A.Array (Leaf k v) -> Maybe v lookupInArray k0 ary0 = go k0 ary0 0 (A.length ary0) where go !k !ary !i !n | i >= n = Nothing | otherwise = case A.index ary i of (L kx v) | k == kx -> Just v | otherwise -> go k ary (i+1) n {-# INLINABLE lookupInArray #-} -- | /O(n)/ Lookup the value associated with the given key in this -- array. Returns 'Nothing' if the key wasn't found. indexOf :: Eq k => k -> A.Array (Leaf k v) -> Maybe Int indexOf k0 ary0 = go k0 ary0 0 (A.length ary0) where go !k !ary !i !n | i >= n = Nothing | otherwise = case A.index ary i of (L kx _) | k == kx -> Just i | otherwise -> go k ary (i+1) n {-# INLINABLE indexOf #-} updateWith :: Eq k => (v -> v) -> k -> A.Array (Leaf k v) -> A.Array (Leaf k v) updateWith f k0 ary0 = go k0 ary0 0 (A.length ary0) where go !k !ary !i !n | i >= n = ary | otherwise = case A.index ary i of (L kx y) | k == kx -> A.update ary i (L k (f y)) | otherwise -> go k ary (i+1) n {-# INLINABLE updateWith #-} updateOrSnocWith :: Eq k => (v -> v -> v) -> k -> v -> A.Array (Leaf k v) -> A.Array (Leaf k v) updateOrSnocWith f = updateOrSnocWithKey (const f) {-# INLINABLE updateOrSnocWith #-} updateOrSnocWithKey :: Eq k => (k -> v -> v -> v) -> k -> v -> A.Array (Leaf k v) -> A.Array (Leaf k v) updateOrSnocWithKey f k0 v0 ary0 = go k0 v0 ary0 0 (A.length ary0) where go !k v !ary !i !n | i >= n = A.run $ do -- Not found, append to the end. mary <- A.new_ (n + 1) A.copy ary 0 mary 0 n A.write mary n (L k v) return mary | otherwise = case A.index ary i of (L kx y) | k == kx -> A.update ary i (L k (f k v y)) | otherwise -> go k v ary (i+1) n {-# INLINABLE updateOrSnocWithKey #-} updateOrConcatWith :: Eq k => (v -> v -> v) -> A.Array (Leaf k v) -> A.Array (Leaf k v) -> A.Array (Leaf k v) updateOrConcatWith f = updateOrConcatWithKey (const f) {-# INLINABLE updateOrConcatWith #-} updateOrConcatWithKey :: Eq k => (k -> v -> v -> v) -> A.Array (Leaf k v) -> A.Array (Leaf k v) -> A.Array (Leaf k v) updateOrConcatWithKey f ary1 ary2 = A.run $ do -- first: look up the position of each element of ary2 in ary1 let indices = A.map (\(L k _) -> indexOf k ary1) ary2 -- that tells us how large the overlap is: -- count number of Nothing constructors let nOnly2 = A.foldl' (\n -> maybe (n+1) (const n)) 0 indices let n1 = A.length ary1 let n2 = A.length ary2 -- copy over all elements from ary1 mary <- A.new_ (n1 + nOnly2) A.copy ary1 0 mary 0 n1 -- append or update all elements from ary2 let go !iEnd !i2 | i2 >= n2 = return () | otherwise = case A.index indices i2 of Just i1 -> do -- key occurs in both arrays, store combination in position i1 L k v1 <- A.indexM ary1 i1 L _ v2 <- A.indexM ary2 i2 A.write mary i1 (L k (f k v1 v2)) go iEnd (i2+1) Nothing -> do -- key is only in ary2, append to end A.write mary iEnd =<< A.indexM ary2 i2 go (iEnd+1) (i2+1) go n1 0 return mary {-# INLINABLE updateOrConcatWithKey #-} ------------------------------------------------------------------------ -- Manually unrolled loops -- | /O(n)/ Update the element at the given position in this array. update16 :: A.Array e -> Int -> e -> A.Array e update16 ary idx b = runST (update16M ary idx b) {-# INLINE update16 #-} -- | /O(n)/ Update the element at the given position in this array. update16M :: A.Array e -> Int -> e -> ST s (A.Array e) update16M ary idx b = do mary <- clone16 ary A.write mary idx b A.unsafeFreeze mary {-# INLINE update16M #-} -- | /O(n)/ Update the element at the given position in this array, by applying a function to it. update16With' :: A.Array e -> Int -> (e -> e) -> A.Array e update16With' ary idx f = update16 ary idx $! f (A.index ary idx) {-# INLINE update16With' #-} -- | Unsafely clone an array of 16 elements. The length of the input -- array is not checked. clone16 :: A.Array e -> ST s (A.MArray s e) clone16 ary = A.thaw ary 0 16 ------------------------------------------------------------------------ -- Bit twiddling bitsPerSubkey :: Int bitsPerSubkey = 4 maxChildren :: Int maxChildren = fromIntegral $ 1 `unsafeShiftL` bitsPerSubkey subkeyMask :: Bitmap subkeyMask = 1 `unsafeShiftL` bitsPerSubkey - 1 sparseIndex :: Bitmap -> Bitmap -> Int sparseIndex b m = popCount (b .&. (m - 1)) mask :: Word -> Shift -> Bitmap mask w s = 1 `unsafeShiftL` index w s {-# INLINE mask #-} -- | Mask out the 'bitsPerSubkey' bits used for indexing at this level -- of the tree. index :: Hash -> Shift -> Int index w s = fromIntegral $ (unsafeShiftR w s) .&. subkeyMask {-# INLINE index #-} -- | A bitmask with the 'bitsPerSubkey' least significant bits set. fullNodeMask :: Bitmap fullNodeMask = complement (complement 0 `unsafeShiftL` maxChildren) {-# INLINE fullNodeMask #-} -- | Check if two the two arguments are the same value. N.B. This -- function might give false negatives (due to GC moving objects.) ptrEq :: a -> a -> Bool ptrEq x y = isTrue# (reallyUnsafePtrEquality# x y ==# 1#) {-# INLINE ptrEq #-} ------------------------------------------------------------------------ -- IsList instance instance (Eq k, Hashable k) => Exts.IsList (HashMap k v) where type Item (HashMap k v) = (k, v) fromList = fromList toList = toList
phischu/fragnix
tests/packages/scotty/Data.HashMap.Base.hs
bsd-3-clause
47,372
0
21
15,435
16,300
8,148
8,152
915
17
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module DateParserSpec (spec) where import Test.Hspec import Test.QuickCheck import Control.Monad import Data.Either import Data.Text (Text) import qualified Data.Text as T import Data.Time import Data.Time.Calendar.WeekDate import DateParser spec :: Spec spec = do dateFormatTests dateTests dateCompletionTests printTests dateFormatTests :: Spec dateFormatTests = describe "date format parser" $ it "parses the german format correctly" $ parseDateFormat "%d[.[%m[.[%y]]]]" `shouldBe` Right german dateTests :: Spec dateTests = describe "date parser" $ do it "actually requires non-optional fields" $ shouldFail "%d-%m-%y" "05" describe "weekDay" $ do it "actually returns the right week day" $ property weekDayProp it "is always smaller than the current date" $ property weekDaySmallerProp dateCompletionTests :: Spec dateCompletionTests = describe "date completion" $ do it "today" $ parseGerman 2004 7 31 "31.7.2004" `shouldBe` Right (fromGregorian 2004 7 31) it "today is a leap day" $ parseGerman 2012 2 29 "29.2.2012" `shouldBe` Right (fromGregorian 2012 2 29) it "skips to previous month" $ parseGerman 2016 9 20 "21" `shouldBe` Right (fromGregorian 2016 08 21) it "stays in month if possible" $ parseGerman 2016 8 30 "21" `shouldBe` Right (fromGregorian 2016 08 21) it "skips to previous month to reach the 31st" $ parseGerman 2016 8 30 "31" `shouldBe` Right (fromGregorian 2016 07 31) it "skips to an earlier month to reach the 31st" $ parseGerman 2016 7 30 "31" `shouldBe` Right (fromGregorian 2016 05 31) it "skips to the previous year if necessary" $ parseGerman 2016 9 30 "2.12." `shouldBe` Right (fromGregorian 2015 12 2) it "skips to the previous years if after a leap year" $ parseGerman 2017 3 10 "29.2" `shouldBe` Right (fromGregorian 2016 02 29) it "even might skip to a leap year 8 years ago" $ parseGerman 2104 2 27 "29.2" `shouldBe` Right (fromGregorian 2096 02 29) it "some date in the near future" $ parseGerman 2016 2 20 "30.11.2016" `shouldBe` Right (fromGregorian 2016 11 30) it "some date in the far future" $ parseGerman 2016 2 20 "30.11.3348" `shouldBe` Right (fromGregorian 3348 11 30) it "last october" $ (do monthOnly <- parseDateFormat "%m" parseDate (fromGregorian 2016 9 15) monthOnly "10" ) `shouldBe` Right (fromGregorian 2015 10 31) it "last november" $ (do monthOnly <- parseDateFormat "%m" parseDate (fromGregorian 2016 9 15) monthOnly "11" ) `shouldBe` Right (fromGregorian 2015 11 30) it "next november" $ (do yearMonth <- parseDateFormat "%y.%m" parseDate (fromGregorian 2016 9 15) yearMonth "2016.11" ) `shouldBe` Right (fromGregorian 2016 11 1) it "next january" $ (do yearMonth <- parseDateFormat "%y.%m" parseDate (fromGregorian 2016 9 15) yearMonth "2017.1" ) `shouldBe` Right (fromGregorian 2017 1 1) it "last january" $ (do yearMonth <- parseDateFormat "%y.%m" parseDate (fromGregorian 2016 9 15) yearMonth "2016.1" ) `shouldBe` Right (fromGregorian 2016 1 31) it "literally yesterday" $ do parseGerman 2018 10 18 "yesterday" `shouldBe` Right (fromGregorian 2018 10 17) parseGerman 2018 10 18 "yest" `shouldBe` Right (fromGregorian 2018 10 17) it "literally today" $ do parseGerman 2018 10 18 "today" `shouldBe` Right (fromGregorian 2018 10 18) it "literally tomorrow" $ do parseGerman 2018 10 18 "tomorrow" `shouldBe` Right (fromGregorian 2018 10 19) it "literally monday" $ do parseGerman 2018 10 18 "monday" `shouldBe` Right (fromGregorian 2018 10 15) parseGerman 2018 10 18 "mon" `shouldBe` Right (fromGregorian 2018 10 15) it "literally tuesday" $ do parseGerman 2018 10 18 "tuesday" `shouldBe` Right (fromGregorian 2018 10 16) parseGerman 2018 10 18 "tues" `shouldBe` Right (fromGregorian 2018 10 16) parseGerman 2018 10 18 "tue" `shouldBe` Right (fromGregorian 2018 10 16) it "literally wednesday" $ do parseGerman 2018 10 18 "wednesday" `shouldBe` Right (fromGregorian 2018 10 17) parseGerman 2018 10 18 "wed" `shouldBe` Right (fromGregorian 2018 10 17) it "literally thursday" $ do parseGerman 2018 10 18 "thursday" `shouldBe` Right (fromGregorian 2018 10 18) parseGerman 2018 10 18 "thur" `shouldBe` Right (fromGregorian 2018 10 18) it "literally friday" $ do parseGerman 2018 10 18 "friday" `shouldBe` Right (fromGregorian 2018 10 12) parseGerman 2018 10 18 "fri" `shouldBe` Right (fromGregorian 2018 10 12) it "literally saturday" $ do parseGerman 2018 10 18 "saturday" `shouldBe` Right (fromGregorian 2018 10 13) parseGerman 2018 10 18 "sat" `shouldBe` Right (fromGregorian 2018 10 13) it "literally sunday" $ do parseGerman 2018 10 18 "sunday" `shouldBe` Right (fromGregorian 2018 10 14) parseGerman 2018 10 18 "sun" `shouldBe` Right (fromGregorian 2018 10 14) it "literally satan" $ do parseGerman 2018 10 18 "satan" `shouldSatisfy` isLeft where parseGerman :: Integer -> Int -> Int -> String -> Either Text Day parseGerman y m d str = parseDate (fromGregorian y m d) german (T.pack str) printTests :: Spec printTests = describe "date printer" $ do it "is inverse to reading" $ property $ printReadProp german it "handles short years correctly" $ do withDateFormat ("%d-[%m-[%y]]") $ \format -> printDate format (fromGregorian 2015 2 1) `shouldBe` "01-02-15" withDateFormat ("%d-[%m-[%y]]") $ \format -> printDate format (fromGregorian 1999 2 1) `shouldBe` "01-02-1999" it "handles long years correctly" $ withDateFormat ("%d-[%m-[%Y]]") $ \format -> printDate format (fromGregorian 2015 2 1) `shouldBe` "01-02-2015" withDateFormat :: Text -> (DateFormat -> Expectation) -> Expectation withDateFormat date action = case parseDateFormat date of Left err -> expectationFailure (show err) Right format -> action format shouldFail :: Text -> Text -> Expectation shouldFail format date = withDateFormat format $ \format' -> do res <- parseDateWithToday format' date unless (isLeft res) $ expectationFailure ("Should fail but parses: " ++ (T.unpack format) ++ " / " ++ (T.unpack date) ++ " as " ++ show res) weekDayProp :: Property weekDayProp = forAll (ModifiedJulianDay <$> (arbitrary `suchThat` (>= 7))) $ \current -> forAll (choose (1, 7)) $ \wday -> wday === getWDay (weekDay wday current) where getWDay :: Day -> Int getWDay d = let (_, _, w) = toWeekDate d in w weekDaySmallerProp :: Property weekDaySmallerProp = forAll (ModifiedJulianDay <$> (arbitrary `suchThat` (>= 7))) $ \current -> forAll (choose (1, 7)) $ \wday -> current >= weekDay wday current printReadProp :: DateFormat -> Day -> Property printReadProp format day = case parseDate day format (printDate format day) of Left err -> counterexample (T.unpack err) False Right res -> res === day instance Arbitrary Day where arbitrary = ModifiedJulianDay <$> arbitrary
rootzlevel/hledger-add
tests/DateParserSpec.hs
bsd-3-clause
7,247
0
19
1,592
2,355
1,144
1,211
153
2
module XMonad.Util.NoTaskbar (-- * Usage -- $usage noTaskbar ,markNoTaskbar) where import XMonad.Core import XMonad.ManageHook import Graphics.X11.Xlib (Window) import Graphics.X11.Xlib.Atom (aTOM) import Graphics.X11.Xlib.Extras (changeProperty32 ,propModePrepend) import Control.Monad.Reader (ask) -- $usage -- Utility functions to hide windows from pagers and taskbars. Mostly useful -- when EWMH doesn't do what you intend (e.g. for 'NamedScratchpad' windows you -- probably don't want to be dumped into the 'NSP' workspace). -- | A 'ManageHook' to mark a window to not be shown in pagers or taskbars. noTaskbar :: ManageHook noTaskbar = ask >>= (>> idHook) . liftX . markNoTaskbar -- | An 'X' action to mark a window to not be shown in pagers or taskbars. markNoTaskbar :: Window -> X () markNoTaskbar w = withDisplay $ \d -> do ws <- getAtom "_NET_WM_STATE" ntb <- getAtom "_NET_WM_STATE_SKIP_TASKBAR" npg <- getAtom "_NET_WM_STATE_SKIP_PAGER" io $ changeProperty32 d w ws aTOM propModePrepend [fi ntb,fi npg] -- sigh fi :: (Integral i, Num n) => i -> n fi = fromIntegral
f1u77y/xmonad-contrib
XMonad/Util/NoTaskbar.hs
bsd-3-clause
1,284
0
12
369
231
131
100
20
1
{-# OPTIONS_GHC -Wall #-} module Reporting.Render.Code ( render ) where import Control.Applicative ((<|>)) import Text.PrettyPrint.ANSI.Leijen (Doc, (<>), hardline, dullred, empty, text) import qualified Reporting.Region as R (|>) :: a -> (a -> b) -> b (|>) a f = f a (<==>) :: Doc -> Doc -> Doc (<==>) a b = a <> hardline <> b render :: Maybe R.Region -> R.Region -> String -> Doc render maybeSubRegion region@(R.Region start end) source = let (R.Position startLine startColumn) = start (R.Position endLine endColumn) = end relevantLines = lines source |> drop (startLine - 1) |> take (endLine - startLine + 1) in case relevantLines of [] -> empty [sourceLine] -> singleLineRegion startLine sourceLine $ case maybeSubRegion of Nothing -> (0, startColumn, endColumn, length sourceLine) Just (R.Region s e) -> (startColumn, R.column s, R.column e, endColumn) firstLine : rest -> let filteredFirstLine = replicate (startColumn - 1) ' ' ++ drop (startColumn - 1) firstLine filteredLastLine = take (endColumn) (last rest) focusedRelevantLines = filteredFirstLine : init rest ++ [filteredLastLine] lineNumbersWidth = length (show endLine) subregion = maybeSubRegion <|> Just region numberedLines = zipWith (addLineNumber subregion lineNumbersWidth) [startLine .. endLine] focusedRelevantLines in foldr (<==>) empty numberedLines addLineNumber :: Maybe R.Region -> Int -> Int -> String -> Doc addLineNumber maybeSubRegion width n line = let number = if n < 0 then " " else show n lineNumber = replicate (width - length number) ' ' ++ number ++ "│" spacer (R.Region start end) = if R.line start <= n && n <= R.line end then dullred (text ">") else text " " in text lineNumber <> maybe (text " ") spacer maybeSubRegion <> text line singleLineRegion :: Int -> String -> (Int, Int, Int, Int) -> Doc singleLineRegion lineNum sourceLine (start, innerStart, innerEnd, end) = let width = length (show lineNum) underline = text (replicate (innerStart + width + 1) ' ') <> dullred (text (replicate (max 1 (innerEnd - innerStart)) '^')) trimmedSourceLine = sourceLine |> drop (start - 1) |> take (end - start + 1) |> (++) (replicate (start - 1) ' ') in addLineNumber Nothing width lineNum trimmedSourceLine <==> underline
laszlopandy/elm-compiler
src/Reporting/Render/Code.hs
bsd-3-clause
2,842
0
18
987
896
471
425
81
4
module Blank () where {- qualif Gimme(v:[a], n:int, acc:[a]): (len v == n + 1 + len acc) -} {-@ gimme :: xs:[a] -> n:Int -> acc:[a] -> {v:[a] | len v = n + 1 + len acc} @-} gimme :: [a] -> Int -> [a] -> [a] gimme xs (-1) acc = acc gimme (x:xs) n acc = gimme xs (n-1) (x : acc) gimme _ _ _ = error "gimme" {-@ boober :: n:Int -> Int -> {v:[Int] | (len v) = n} @-} boober :: Int -> Int -> [Int] boober n y = gimme [y..] (n-1) []
abakst/liquidhaskell
tests/pos/gimme.hs
bsd-3-clause
438
0
8
113
153
84
69
7
1
module Aws.Sqs.Commands.Queue where import Aws.Core import Aws.Sqs.Core import Control.Applicative import Data.Maybe import Text.XML.Cursor (($//), (&/)) import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Text.XML.Cursor as Cu import qualified Data.ByteString.Char8 as B data CreateQueue = CreateQueue { cqDefaultVisibilityTimeout :: Maybe Int, cqQueueName :: T.Text } deriving (Show) data CreateQueueResponse = CreateQueueResponse { cqrQueueUrl :: T.Text } deriving (Show) instance ResponseConsumer r CreateQueueResponse where type ResponseMetadata CreateQueueResponse = SqsMetadata responseConsumer _ = sqsXmlResponseConsumer parse where parse el = do url <- force "Missing Queue Url" $ el $// Cu.laxElement "QueueUrl" &/ Cu.content return CreateQueueResponse{ cqrQueueUrl = url} -- | ServiceConfiguration: 'SqsConfiguration' instance SignQuery CreateQueue where type ServiceConfiguration CreateQueue = SqsConfiguration signQuery CreateQueue {..} = sqsSignQuery SqsQuery { sqsQueueName = Nothing, sqsQuery = [("Action", Just "CreateQueue"), ("QueueName", Just $ TE.encodeUtf8 cqQueueName)] ++ catMaybes [("DefaultVisibilityTimeout",) <$> case cqDefaultVisibilityTimeout of Just x -> Just $ Just $ B.pack $ show x Nothing -> Nothing]} instance Transaction CreateQueue CreateQueueResponse instance AsMemoryResponse CreateQueueResponse where type MemoryResponse CreateQueueResponse = CreateQueueResponse loadToMemory = return data DeleteQueue = DeleteQueue { dqQueueName :: QueueName } deriving (Show) data DeleteQueueResponse = DeleteQueueResponse deriving (Show) instance ResponseConsumer r DeleteQueueResponse where type ResponseMetadata DeleteQueueResponse = SqsMetadata responseConsumer _ = sqsXmlResponseConsumer parse where parse _ = do return DeleteQueueResponse{} -- | ServiceConfiguration: 'SqsConfiguration' instance SignQuery DeleteQueue where type ServiceConfiguration DeleteQueue = SqsConfiguration signQuery DeleteQueue {..} = sqsSignQuery SqsQuery { sqsQueueName = Just dqQueueName, sqsQuery = [("Action", Just "DeleteQueue")]} instance Transaction DeleteQueue DeleteQueueResponse instance AsMemoryResponse DeleteQueueResponse where type MemoryResponse DeleteQueueResponse = DeleteQueueResponse loadToMemory = return data ListQueues = ListQueues { lqQueueNamePrefix :: Maybe T.Text } deriving (Show) data ListQueuesResponse = ListQueuesResponse { lqrQueueUrls :: [T.Text] } deriving (Show) instance ResponseConsumer r ListQueuesResponse where type ResponseMetadata ListQueuesResponse = SqsMetadata responseConsumer _ = sqsXmlResponseConsumer parse where parse el = do let queues = el $// Cu.laxElement "QueueUrl" &/ Cu.content return ListQueuesResponse { lqrQueueUrls = queues } -- | ServiceConfiguration: 'SqsConfiguration' instance SignQuery ListQueues where type ServiceConfiguration ListQueues = SqsConfiguration signQuery ListQueues{..} = sqsSignQuery SqsQuery { sqsQueueName = Nothing, sqsQuery = [("Action", Just "ListQueues")] ++ catMaybes [ ("QueueNamePrefix",) <$> case lqQueueNamePrefix of Just x -> Just $ Just $ TE.encodeUtf8 x Nothing -> Nothing]} instance Transaction ListQueues ListQueuesResponse instance AsMemoryResponse ListQueuesResponse where type MemoryResponse ListQueuesResponse = ListQueuesResponse loadToMemory = return
frms-/aws
Aws/Sqs/Commands/Queue.hs
bsd-3-clause
4,393
0
18
1,467
843
460
383
-1
-1
module StrategoCmds where import Prelude hiding (print) import PFE0(pput,epput,getSubGraph) import PFE3(parseModule) import PFE4(rewriteAndTypeCheckModule) import PFE_Rewrites(fbRewrite,lcRewrite,flRewrite,pmRewrite,compRw,rwFun) import HsModule(hsModDecls) import PfeDepCmds(tdepgraph) import PfeParse import PfePropCmds(baseNames) import TiClasses(filterDefs,fromDefs) import PFEdeps(tdefinedNames,splitDecls,isDefaultDecl) import HsIdent(getHSName) import MapDeclMProp() -- ? import DefinedNames(addName) import TiPropInstances() import TiProp() -- for PFE, instance CheckRecursion ... import RemoveListCompProp() import SimpPatMatchProp() --import TiPropDecorate(TiDecls) --import PNT(PNT) import qualified Prop2Stratego2 as P2S --import qualified PropDecorate2Stratego2 as Ti2S import qualified TiProp2Stratego2 as Ti2S import AbstractIO(print) import MUtils(( # ),(@@),apSnd) import Sets(mkSet,elementOf) import PrettyPrint((<+>)) strategoCmds = [("stratego", (tModuleArg stratego,"translation of one module to Stratego")), ("strategoslice", (tQualId strategoSlice,"translate a slice to Stratego")){-, ("tstratego", (moduleArg tstratego,"resolve overloading and translate one module to Stratego")), ("tstrategoslice", (qualId tstrategoSlice,"resolve overloading and translate a slice to Stratego"))-}] tModuleArg = moduleArg' untyped tQualId cmd = f #@ untyped <@ arg "<M.x>" where f u = cmd u @@ parseQualId untyped = kwOption "-untyped" stratego untyped = if untyped then ustratego else tstratego strategoSlice untyped = if untyped then ustrategoSlice else tstrategoSlice -------------------------------------------------------------------------------- ustrategoSlice qn = slice' qn =<< transModule ustratego m = do transM <- transModule (print.transM.hsModDecls . snd) =<< parseModule m transModule = do simplify <- rwFun $ foldr1 compRw [fbRewrite,lcRewrite,flRewrite] let transM = P2S.rmIgnored . P2S.transDecs . simplify . addName return transM slice' q@(m,n) trans = do ms <- map (fst.snd) # getSubGraph (Just [m]) (_,(_,_,used)) <- tdepgraph [q] let needed = mkSet used print.concatMap trans =<< mapM (moduleSlice needed) ms moduleSlice needed m = filter (isNeeded needed m) . splitDecls . hsModDecls . snd # parseModule m -------------------------------------------------------------------------------- tstrategoSlice qn = tslice' qn ttransM ttransM = P2S.rmIgnored . Ti2S.transDecs' -- . addName tstratego m = print.ttransM.fromDefs.hsModDecls =<< rewriteAndTypeCheckModule rewrite m tslice' q@(m,n) trans = do ms <- map (fst.snd) # getSubGraph (Just [m]) (_,(_,_,used)) <- tdepgraph [q] let needed = mkSet used print.concatMap trans =<< mapM (tmoduleSlice needed) ms tmoduleSlice needed m = filter (isNeeded needed m) . splitDecls . fromDefs . hsModDecls # rewriteAndTypeCheckModule rewrite m -- where -- t = id :: TiDecls PNT -> TiDecls PNT -------------------------------------------------------------------------------- rewrite = pmRewrite `compRw` lcRewrite isNeeded needed m d = isDefaultDecl d || isNeeded' d where isNeeded' = any (`elementOf` needed) . map getHSName . tdefinedNames False m
forste/haReFork
tools/hs2stratego/StrategoCmds.hs
bsd-3-clause
3,239
0
13
482
894
493
401
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} -- | Implementation of the Futhark module system (at least most of it; -- some is scattered elsewhere in the type checker). module Language.Futhark.TypeChecker.Modules ( matchMTys, newNamesForMTy, refineEnv, applyFunctor, ) where import Control.Monad.Except import Control.Monad.Writer hiding (Sum) import Data.Either import Data.List (intersect) import qualified Data.Map.Strict as M import Data.Maybe import Data.Ord import qualified Data.Set as S import Futhark.Util.Pretty import Language.Futhark import Language.Futhark.Semantic import Language.Futhark.TypeChecker.Monad import Language.Futhark.TypeChecker.Types import Language.Futhark.TypeChecker.Unify (doUnification) import Prelude hiding (abs, mod) substituteTypesInMod :: TypeSubs -> Mod -> Mod substituteTypesInMod substs (ModEnv e) = ModEnv $ substituteTypesInEnv substs e substituteTypesInMod substs (ModFun (FunSig abs mod mty)) = ModFun $ FunSig abs (substituteTypesInMod substs mod) (substituteTypesInMTy substs mty) substituteTypesInMTy :: TypeSubs -> MTy -> MTy substituteTypesInMTy substs (MTy abs mod) = MTy abs $ substituteTypesInMod substs mod substituteTypesInEnv :: TypeSubs -> Env -> Env substituteTypesInEnv substs env = env { envVtable = M.map (substituteTypesInBoundV substs) $ envVtable env, envTypeTable = M.mapWithKey subT $ envTypeTable env, envModTable = M.map (substituteTypesInMod substs) $ envModTable env } where subT name (TypeAbbr l _ _) | Just (Subst ps rt) <- substs name = TypeAbbr l ps rt subT _ (TypeAbbr l ps (RetType dims t)) = TypeAbbr l ps $ applySubst substs $ RetType dims t substituteTypesInBoundV :: TypeSubs -> BoundV -> BoundV substituteTypesInBoundV substs (BoundV tps t) = let RetType dims t' = applySubst substs $ RetType [] t in BoundV (tps ++ map (`TypeParamDim` mempty) dims) t' -- | All names defined anywhere in the 'Env'. allNamesInEnv :: Env -> S.Set VName allNamesInEnv (Env vtable ttable stable modtable _names) = S.fromList ( M.keys vtable ++ M.keys ttable ++ M.keys stable ++ M.keys modtable ) <> mconcat ( map allNamesInMTy (M.elems stable) ++ map allNamesInMod (M.elems modtable) ++ map allNamesInType (M.elems ttable) ) where allNamesInType (TypeAbbr _ ps _) = S.fromList $ map typeParamName ps allNamesInMod :: Mod -> S.Set VName allNamesInMod (ModEnv env) = allNamesInEnv env allNamesInMod ModFun {} = mempty allNamesInMTy :: MTy -> S.Set VName allNamesInMTy (MTy abs mod) = S.fromList (map qualLeaf $ M.keys abs) <> allNamesInMod mod -- | Create unique renames for the module type. This is used for -- e.g. generative functor application. newNamesForMTy :: MTy -> TypeM (MTy, M.Map VName VName) newNamesForMTy orig_mty = do pairs <- forM (S.toList $ allNamesInMTy orig_mty) $ \v -> do v' <- newName v return (v, v') let substs = M.fromList pairs rev_substs = M.fromList $ map (uncurry $ flip (,)) pairs return (substituteInMTy substs orig_mty, rev_substs) where substituteInMTy :: M.Map VName VName -> MTy -> MTy substituteInMTy substs (MTy mty_abs mty_mod) = MTy (M.mapKeys (fmap substitute) mty_abs) (substituteInMod mty_mod) where substituteInEnv (Env vtable ttable _stable modtable names) = let vtable' = substituteInMap substituteInBinding vtable ttable' = substituteInMap substituteInTypeBinding ttable mtable' = substituteInMap substituteInMod modtable in Env { envVtable = vtable', envTypeTable = ttable', envSigTable = mempty, envModTable = mtable', envNameMap = M.map (fmap substitute) names } substitute v = fromMaybe v $ M.lookup v substs substituteInMap f m = let (ks, vs) = unzip $ M.toList m in M.fromList $ zip (map (\k -> fromMaybe k $ M.lookup k substs) ks) (map f vs) substituteInBinding (BoundV ps t) = BoundV (map substituteInTypeParam ps) (substituteInType t) substituteInMod (ModEnv env) = ModEnv $ substituteInEnv env substituteInMod (ModFun funsig) = ModFun $ substituteInFunSig funsig substituteInFunSig (FunSig abs mod mty) = FunSig (M.mapKeys (fmap substitute) abs) (substituteInMod mod) (substituteInMTy substs mty) substituteInTypeBinding (TypeAbbr l ps (RetType dims t)) = TypeAbbr l (map substituteInTypeParam ps) $ RetType dims $ substituteInType t substituteInTypeParam (TypeParamDim p loc) = TypeParamDim (substitute p) loc substituteInTypeParam (TypeParamType l p loc) = TypeParamType l (substitute p) loc substituteInType :: StructType -> StructType substituteInType (Scalar (TypeVar () u (TypeName qs v) targs)) = Scalar $ TypeVar () u (TypeName (map substitute qs) $ substitute v) $ map substituteInTypeArg targs substituteInType (Scalar (Prim t)) = Scalar $ Prim t substituteInType (Scalar (Record ts)) = Scalar $ Record $ fmap substituteInType ts substituteInType (Scalar (Sum ts)) = Scalar $ Sum $ (fmap . fmap) substituteInType ts substituteInType (Array () u t shape) = arrayOf (substituteInType $ Scalar t) (substituteInShape shape) u substituteInType (Scalar (Arrow als v t1 (RetType dims t2))) = Scalar $ Arrow als v (substituteInType t1) $ RetType dims $ substituteInType t2 substituteInShape (ShapeDecl ds) = ShapeDecl $ map substituteInDim ds substituteInDim (NamedDim (QualName qs v)) = NamedDim $ QualName (map substitute qs) $ substitute v substituteInDim d = d substituteInTypeArg (TypeArgDim (NamedDim (QualName qs v)) loc) = TypeArgDim (NamedDim $ QualName (map substitute qs) $ substitute v) loc substituteInTypeArg (TypeArgDim (ConstDim x) loc) = TypeArgDim (ConstDim x) loc substituteInTypeArg (TypeArgDim (AnyDim v) loc) = TypeArgDim (AnyDim v) loc substituteInTypeArg (TypeArgType t loc) = TypeArgType (substituteInType t) loc mtyTypeAbbrs :: MTy -> M.Map VName TypeBinding mtyTypeAbbrs (MTy _ mod) = modTypeAbbrs mod modTypeAbbrs :: Mod -> M.Map VName TypeBinding modTypeAbbrs (ModEnv env) = envTypeAbbrs env modTypeAbbrs (ModFun (FunSig _ mod mty)) = modTypeAbbrs mod <> mtyTypeAbbrs mty envTypeAbbrs :: Env -> M.Map VName TypeBinding envTypeAbbrs env = envTypeTable env <> (mconcat . map modTypeAbbrs . M.elems . envModTable) env -- | Refine the given type name in the given env. refineEnv :: SrcLoc -> TySet -> Env -> QualName Name -> [TypeParam] -> StructType -> TypeM (QualName VName, TySet, Env) refineEnv loc tset env tname ps t | Just (tname', TypeAbbr _ cur_ps (RetType _ (Scalar (TypeVar () _ (TypeName qs v) _)))) <- findTypeDef tname (ModEnv env), QualName (qualQuals tname') v `M.member` tset = if paramsMatch cur_ps ps then return ( tname', QualName qs v `M.delete` tset, substituteTypesInEnv ( flip M.lookup $ M.fromList [ (qualLeaf tname', Subst cur_ps $ RetType [] t), (v, Subst ps $ RetType [] t) ] ) env ) else typeError loc mempty $ "Cannot refine a type having" <+> tpMsg ps <> " with a type having " <> tpMsg cur_ps <> "." | otherwise = typeError loc mempty $ pquote (ppr tname) <+> "is not an abstract type in the module type." where tpMsg [] = "no type parameters" tpMsg xs = "type parameters" <+> spread (map ppr xs) paramsMatch :: [TypeParam] -> [TypeParam] -> Bool paramsMatch ps1 ps2 = length ps1 == length ps2 && all match (zip ps1 ps2) where match (TypeParamType l1 _ _, TypeParamType l2 _ _) = l1 <= l2 match (TypeParamDim _ _, TypeParamDim _ _) = True match _ = False findBinding :: (Env -> M.Map VName v) -> Namespace -> Name -> Env -> Maybe (VName, v) findBinding table namespace name the_env = do QualName _ name' <- M.lookup (namespace, name) $ envNameMap the_env (name',) <$> M.lookup name' (table the_env) findTypeDef :: QualName Name -> Mod -> Maybe (QualName VName, TypeBinding) findTypeDef _ ModFun {} = Nothing findTypeDef (QualName [] name) (ModEnv the_env) = do (name', tb) <- findBinding envTypeTable Type name the_env return (qualName name', tb) findTypeDef (QualName (q : qs) name) (ModEnv the_env) = do (q', q_mod) <- findBinding envModTable Term q the_env (QualName qs' name', tb) <- findTypeDef (QualName qs name) q_mod return (QualName (q' : qs') name', tb) resolveAbsTypes :: TySet -> Mod -> TySet -> SrcLoc -> Either TypeError (M.Map VName (QualName VName, TypeBinding)) resolveAbsTypes mod_abs mod sig_abs loc = do let abs_mapping = M.fromList $ zip (map (fmap baseName . fst) $ M.toList mod_abs) (M.toList mod_abs) fmap M.fromList . forM (M.toList sig_abs) $ \(name, name_l) -> case findTypeDef (fmap baseName name) mod of Just (name', TypeAbbr mod_l ps t) | mod_l > name_l -> mismatchedLiftedness name_l (map qualLeaf $ M.keys mod_abs) (qualLeaf name) (mod_l, ps, t) | name_l < SizeLifted, not $ null $ retDims t -> anonymousSizes (map qualLeaf $ M.keys mod_abs) (qualLeaf name) (mod_l, ps, t) | Just (abs_name, _) <- M.lookup (fmap baseName name) abs_mapping -> return (qualLeaf name, (abs_name, TypeAbbr name_l ps t)) | otherwise -> return (qualLeaf name, (name', TypeAbbr name_l ps t)) _ -> missingType loc $ fmap baseName name where mismatchedLiftedness name_l abs name mod_t = Left . TypeError loc mempty $ "Module defines" </> indent 2 (ppTypeAbbr abs name mod_t) </> "but module type requires" <+> text what <> "." where what = case name_l of Unlifted -> "a non-lifted type" SizeLifted -> "a size-lifted type" Lifted -> "a lifted type" anonymousSizes abs name mod_t = Left $ TypeError loc mempty $ "Module defines" </> indent 2 (ppTypeAbbr abs name mod_t) </> "which contains anonymous sizes, but module type requires non-lifted type." resolveMTyNames :: MTy -> MTy -> M.Map VName (QualName VName) resolveMTyNames = resolveMTyNames' where resolveMTyNames' (MTy _mod_abs mod) (MTy _sig_abs sig) = resolveModNames mod sig resolveModNames (ModEnv mod_env) (ModEnv sig_env) = resolveEnvNames mod_env sig_env resolveModNames (ModFun mod_fun) (ModFun sig_fun) = resolveModNames (funSigMod mod_fun) (funSigMod sig_fun) <> resolveMTyNames' (funSigMty mod_fun) (funSigMty sig_fun) resolveModNames _ _ = mempty resolveEnvNames mod_env sig_env = let mod_substs = resolve Term mod_env $ envModTable sig_env onMod (modname, mod_env_mod) = case M.lookup modname mod_substs of Just (QualName _ modname') | Just sig_env_mod <- M.lookup modname' $ envModTable mod_env -> resolveModNames sig_env_mod mod_env_mod _ -> mempty in mconcat [ resolve Term mod_env $ envVtable sig_env, resolve Type mod_env $ envVtable sig_env, resolve Signature mod_env $ envVtable sig_env, mod_substs, mconcat $ map onMod $ M.toList $ envModTable sig_env ] resolve namespace mod_env = M.mapMaybeWithKey resolve' where resolve' name _ = M.lookup (namespace, baseName name) $ envNameMap mod_env missingType :: Pretty a => SrcLoc -> a -> Either TypeError b missingType loc name = Left $ TypeError loc mempty $ "Module does not define a type named" <+> ppr name <> "." missingVal :: Pretty a => SrcLoc -> a -> Either TypeError b missingVal loc name = Left $ TypeError loc mempty $ "Module does not define a value named" <+> ppr name <> "." missingMod :: Pretty a => SrcLoc -> a -> Either TypeError b missingMod loc name = Left $ TypeError loc mempty $ "Module does not define a module named" <+> ppr name <> "." mismatchedType :: SrcLoc -> [VName] -> VName -> (Liftedness, [TypeParam], StructRetType) -> (Liftedness, [TypeParam], StructRetType) -> Either TypeError b mismatchedType loc abs name spec_t env_t = Left $ TypeError loc mempty $ "Module defines" </> indent 2 (ppTypeAbbr abs name env_t) </> "but module type requires" </> indent 2 (ppTypeAbbr abs name spec_t) ppTypeAbbr :: [VName] -> VName -> (Liftedness, [TypeParam], StructRetType) -> Doc ppTypeAbbr abs name (l, ps, RetType [] (Scalar (TypeVar () _ tn args))) | typeLeaf tn `elem` abs, map typeParamToArg ps == args = "type" <> ppr l <+> pprName name <+> spread (map ppr ps) ppTypeAbbr _ name (l, ps, t) = "type" <> ppr l <+> pprName name <+> spread (map ppr ps) <+> equals <+/> nest 2 (align (ppr t)) -- | Return new renamed/abstracted env, as well as a mapping from -- names in the signature to names in the new env. This is used for -- functor application. The first env is the module env, and the -- second the env it must match. matchMTys :: MTy -> MTy -> SrcLoc -> Either TypeError (M.Map VName VName) matchMTys orig_mty orig_mty_sig = matchMTys' (M.map (SizeSubst . NamedDim) $ resolveMTyNames orig_mty orig_mty_sig) orig_mty orig_mty_sig where matchMTys' :: M.Map VName (Subst StructRetType) -> MTy -> MTy -> SrcLoc -> Either TypeError (M.Map VName VName) matchMTys' _ (MTy _ ModFun {}) (MTy _ ModEnv {}) loc = Left $ TypeError loc mempty "Cannot match parametric module with non-parametric module type." matchMTys' _ (MTy _ ModEnv {}) (MTy _ ModFun {}) loc = Left $ TypeError loc mempty "Cannot match non-parametric module with paramatric module type." matchMTys' old_abs_subst_to_type (MTy mod_abs mod) (MTy sig_abs sig) loc = do -- Check that abstract types in 'sig' have an implementation in -- 'mod'. This also gives us a substitution that we use to check -- the types of values. abs_substs <- resolveAbsTypes mod_abs mod sig_abs loc let abs_subst_to_type = old_abs_subst_to_type <> M.map (substFromAbbr . snd) abs_substs abs_name_substs = M.map (qualLeaf . fst) abs_substs substs <- matchMods abs_subst_to_type mod sig loc return (substs <> abs_name_substs) matchMods :: M.Map VName (Subst StructRetType) -> Mod -> Mod -> SrcLoc -> Either TypeError (M.Map VName VName) matchMods _ ModEnv {} ModFun {} loc = Left $ TypeError loc mempty "Cannot match non-parametric module with parametric module type." matchMods _ ModFun {} ModEnv {} loc = Left $ TypeError loc mempty "Cannot match parametric module with non-parametric module type." matchMods abs_subst_to_type (ModEnv mod) (ModEnv sig) loc = matchEnvs abs_subst_to_type mod sig loc matchMods old_abs_subst_to_type (ModFun (FunSig mod_abs mod_pmod mod_mod)) (ModFun (FunSig sig_abs sig_pmod sig_mod)) loc = do abs_substs <- resolveAbsTypes mod_abs mod_pmod sig_abs loc let abs_subst_to_type = old_abs_subst_to_type <> M.map (substFromAbbr . snd) abs_substs abs_name_substs = M.map (qualLeaf . fst) abs_substs pmod_substs <- matchMods abs_subst_to_type mod_pmod sig_pmod loc mod_substs <- matchMTys' abs_subst_to_type mod_mod sig_mod loc return (pmod_substs <> mod_substs <> abs_name_substs) matchEnvs :: M.Map VName (Subst StructRetType) -> Env -> Env -> SrcLoc -> Either TypeError (M.Map VName VName) matchEnvs abs_subst_to_type env sig loc = do -- XXX: we only want to create substitutions for visible names. -- This must be wrong in some cases. Probably we need to -- rethink how we do shadowing for module types. let visible = S.fromList $ map qualLeaf $ M.elems $ envNameMap sig isVisible name = name `S.member` visible -- Check that all type abbreviations are correctly defined. abbr_name_substs <- fmap M.fromList $ forM (filter (isVisible . fst) $ M.toList $ envTypeTable sig) $ \(name, TypeAbbr spec_l spec_ps spec_t) -> case findBinding envTypeTable Type (baseName name) env of Just (name', TypeAbbr l ps t) -> matchTypeAbbr loc abs_subst_to_type name spec_l spec_ps spec_t name' l ps t Nothing -> missingType loc $ baseName name -- Check that all values are defined correctly, substituting the -- abstract types first. val_substs <- fmap M.fromList $ forM (M.toList $ envVtable sig) $ \(name, spec_bv) -> do let spec_bv' = substituteTypesInBoundV (`M.lookup` abs_subst_to_type) spec_bv case findBinding envVtable Term (baseName name) env of Just (name', bv) -> matchVal loc name spec_bv' name' bv _ -> missingVal loc (baseName name) -- Check for correct modules. mod_substs <- fmap M.unions $ forM (M.toList $ envModTable sig) $ \(name, modspec) -> case findBinding envModTable Term (baseName name) env of Just (name', mod) -> M.insert name name' <$> matchMods abs_subst_to_type mod modspec loc Nothing -> missingMod loc $ baseName name return $ val_substs <> mod_substs <> abbr_name_substs matchTypeAbbr :: SrcLoc -> M.Map VName (Subst StructRetType) -> VName -> Liftedness -> [TypeParam] -> StructRetType -> VName -> Liftedness -> [TypeParam] -> StructRetType -> Either TypeError (VName, VName) matchTypeAbbr loc abs_subst_to_type spec_name spec_l spec_ps spec_t name l ps t = do -- We have to create substitutions for the type parameters, too. unless (length spec_ps == length ps) $ nomatch spec_t param_substs <- mconcat <$> zipWithM (matchTypeParam (nomatch spec_t)) spec_ps ps -- Abstract types have a particular restriction to ensure that -- if we have a value of an abstract type 't [n]', then there is -- an array of size 'n' somewhere inside. when (M.member spec_name abs_subst_to_type) $ case S.toList (mustBeExplicitInType (retType t)) `intersect` map typeParamName ps of [] -> return () d : _ -> Left . TypeError loc mempty $ "Type" </> indent 2 (ppTypeAbbr [] name (l, ps, t)) </> textwrap "cannot be made abstract because size parameter" <+/> pquote (pprName d) <+/> textwrap "is not used as an array size in the definition." let spec_t' = applySubst (`M.lookup` (param_substs <> abs_subst_to_type)) spec_t if spec_t' == t then return (spec_name, name) else nomatch spec_t' where nomatch spec_t' = mismatchedType loc (M.keys abs_subst_to_type) spec_name (spec_l, spec_ps, spec_t') (l, ps, t) matchTypeParam _ (TypeParamDim x _) (TypeParamDim y _) = pure $ M.singleton x $ SizeSubst $ NamedDim $ qualName y matchTypeParam _ (TypeParamType spec_l x _) (TypeParamType l y _) | spec_l <= l = pure . M.singleton x . Subst [] . RetType [] $ Scalar $ TypeVar () Nonunique (typeName y) [] matchTypeParam nomatch _ _ = nomatch matchVal :: SrcLoc -> VName -> BoundV -> VName -> BoundV -> Either TypeError (VName, VName) matchVal loc spec_name spec_v name v = case matchValBinding loc spec_v v of Nothing -> return (spec_name, name) Just problem -> Left $ TypeError loc mempty $ "Module type specifies" </> indent 2 (ppValBind spec_name spec_v) </> "but module provides" </> indent 2 (ppValBind spec_name v) </> fromMaybe mempty problem matchValBinding :: SrcLoc -> BoundV -> BoundV -> Maybe (Maybe Doc) matchValBinding loc (BoundV _ orig_spec_t) (BoundV tps orig_t) = case doUnification loc tps (toStruct orig_spec_t) (toStruct orig_t) of Left (TypeError _ notes msg) -> Just $ Just $ msg <> ppr notes -- Even if they unify, we still have to verify the uniqueness -- properties. Right t | noSizes t `subtypeOf` noSizes orig_spec_t -> Nothing | otherwise -> Just Nothing ppValBind v (BoundV tps t) = "val" <+> pprName v <+> spread (map ppr tps) <+> colon </> indent 2 (align (ppr t)) -- | Apply a parametric module to an argument. applyFunctor :: SrcLoc -> FunSig -> MTy -> TypeM ( MTy, M.Map VName VName, M.Map VName VName ) applyFunctor applyloc (FunSig p_abs p_mod body_mty) a_mty = do p_subst <- badOnLeft $ matchMTys a_mty (MTy p_abs p_mod) applyloc -- Apply type abbreviations from a_mty to body_mty. let a_abbrs = mtyTypeAbbrs a_mty isSub v = case M.lookup v a_abbrs of Just abbr -> Just $ substFromAbbr abbr _ -> Just $ SizeSubst $ NamedDim $ qualName v type_subst = M.mapMaybe isSub p_subst body_mty' = substituteTypesInMTy (`M.lookup` type_subst) body_mty (body_mty'', body_subst) <- newNamesForMTy body_mty' return (body_mty'', p_subst, body_subst)
HIPERFIT/futhark
src/Language/Futhark/TypeChecker/Modules.hs
isc
22,422
0
20
6,456
6,798
3,365
3,433
508
15
{-# LANGUAGE Strict #-} -- | A usage-table is sort of a bottom-up symbol table, describing how -- (and if) a variable is used. module Futhark.Analysis.UsageTable ( UsageTable, without, lookup, used, expand, isConsumed, isInResult, isUsedDirectly, isSize, usages, usage, consumedUsage, inResultUsage, sizeUsage, sizeUsages, withoutU, Usages, consumedU, presentU, usageInStm, ) where import Data.Bits import qualified Data.Foldable as Foldable import qualified Data.IntMap.Strict as IM import Data.List (foldl') import Futhark.IR import Futhark.IR.Prop.Aliases import Prelude hiding (lookup) -- | A usage table. newtype UsageTable = UsageTable (IM.IntMap Usages) deriving (Eq, Show) instance Semigroup UsageTable where UsageTable table1 <> UsageTable table2 = UsageTable $ IM.unionWith (<>) table1 table2 instance Monoid UsageTable where mempty = UsageTable mempty -- | Remove these entries from the usage table. without :: UsageTable -> [VName] -> UsageTable without (UsageTable table) = UsageTable . Foldable.foldl (flip IM.delete) table . map baseTag -- | Look up a variable in the usage table. lookup :: VName -> UsageTable -> Maybe Usages lookup name (UsageTable table) = IM.lookup (baseTag name) table lookupPred :: (Usages -> Bool) -> VName -> UsageTable -> Bool lookupPred f name = maybe False f . lookup name -- | Is the variable present in the usage table? That is, has it been used? used :: VName -> UsageTable -> Bool used = lookupPred $ const True -- | Expand the usage table based on aliasing information. expand :: (VName -> Names) -> UsageTable -> UsageTable expand look (UsageTable m) = UsageTable $ foldl' grow m $ IM.toList m where grow m' (k, v) = foldl' (grow'' $ v `withoutU` presentU) m' $ namesIntMap $ look $ VName (nameFromString "") k grow'' v m'' k = IM.insertWith (<>) (baseTag k) v m'' is :: Usages -> VName -> UsageTable -> Bool is = lookupPred . matches -- | Has the variable been consumed? isConsumed :: VName -> UsageTable -> Bool isConsumed = is consumedU -- | Has the variable been used in the 'Result' of a body? isInResult :: VName -> UsageTable -> Bool isInResult = is inResultU -- | Has the given name been used directly (i.e. could we rename it or -- remove it without anyone noticing?) isUsedDirectly :: VName -> UsageTable -> Bool isUsedDirectly = is presentU -- | Is this name used as the size of something (array or memory block)? isSize :: VName -> UsageTable -> Bool isSize = is sizeU -- | Construct a usage table reflecting that these variables have been -- used. usages :: Names -> UsageTable usages = UsageTable . IM.map (const presentU) . namesIntMap -- | Construct a usage table where the given variable has been used in -- this specific way. usage :: VName -> Usages -> UsageTable usage name uses = UsageTable $ IM.singleton (baseTag name) uses -- | Construct a usage table where the given variable has been consumed. consumedUsage :: VName -> UsageTable consumedUsage name = UsageTable $ IM.singleton (baseTag name) consumedU -- | Construct a usage table where the given variable has been used in -- the 'Result' of a body. inResultUsage :: VName -> UsageTable inResultUsage name = UsageTable $ IM.singleton (baseTag name) inResultU -- | Construct a usage table where the given variable has been used as -- an array or memory size. sizeUsage :: VName -> UsageTable sizeUsage name = UsageTable $ IM.singleton (baseTag name) sizeU -- | Construct a usage table where the given names have been used as -- an array or memory size. sizeUsages :: Names -> UsageTable sizeUsages = UsageTable . IM.map (const sizeU) . namesIntMap -- | A description of how a single variable has been used. newtype Usages = Usages Int -- Bitmap representation for speed. deriving (Eq, Ord, Show) instance Semigroup Usages where Usages x <> Usages y = Usages $ x .|. y instance Monoid Usages where mempty = Usages 0 -- | A kind of usage. consumedU, inResultU, presentU, sizeU :: Usages consumedU = Usages 1 inResultU = Usages 2 presentU = Usages 4 sizeU = Usages 8 -- | Check whether the bits that are set in the first argument are -- also set in the second. matches :: Usages -> Usages -> Bool matches (Usages x) (Usages y) = x == (x .&. y) -- | x - y, but for 'Usages'. withoutU :: Usages -> Usages -> Usages withoutU (Usages x) (Usages y) = Usages $ x .&. complement y usageInBody :: Aliased rep => Body rep -> UsageTable usageInBody = foldMap consumedUsage . namesToList . consumedInBody -- | Produce a usage table reflecting the use of the free variables in -- a single statement. usageInStm :: (ASTRep rep, Aliased rep) => Stm rep -> UsageTable usageInStm (Let pat rep e) = mconcat [ usageInPat, usageInExpDec, usageInExp e, usages (freeIn e) ] where usageInPat = usages ( mconcat (map freeIn $ patElems pat) `namesSubtract` namesFromList (patNames pat) ) <> sizeUsages (foldMap (freeIn . patElemType) (patElems pat)) usageInExpDec = usages $ freeIn rep usageInExp :: Aliased rep => Exp rep -> UsageTable usageInExp (Apply _ args _ _) = mconcat [ mconcat $ map consumedUsage $ namesToList $ subExpAliases arg | (arg, d) <- args, d == Consume ] usageInExp e@DoLoop {} = foldMap consumedUsage $ namesToList $ consumedInExp e usageInExp (If _ tbranch fbranch _) = usageInBody tbranch <> usageInBody fbranch usageInExp (WithAcc inputs lam) = foldMap inputUsage inputs <> usageInBody (lambdaBody lam) where inputUsage (_, arrs, _) = foldMap consumedUsage arrs usageInExp (BasicOp (Update _ src _ _)) = consumedUsage src usageInExp (BasicOp (FlatUpdate src _ _)) = consumedUsage src usageInExp (Op op) = mconcat $ map consumedUsage (namesToList $ consumedInOp op) usageInExp (BasicOp _) = mempty
diku-dk/futhark
src/Futhark/Analysis/UsageTable.hs
isc
5,919
0
14
1,236
1,575
833
742
126
1
module Discussion.Converter (compact, unlambda) where import Control.Applicative ((<$>)) import Discussion.Data import Discussion.Bool -------------------------------------------------------------------------------- -- Termを本質的な構造は変えずに最小の構成にする compact :: Term -> Term compact v@(VarT _) = v compact (App ((App ts1) : ts2)) = compact $ App ((compact <$> ts1) ++ (compact <$> ts2)) compact (App ts) = App (compact <$> ts) compact (Lambda vs1 (Lambda vs2 t)) = compact $ Lambda (vs1 ++ vs2) (compact t) compact (Lambda vs t) = Lambda vs (compact t) -------------------------------------------------------------------------------- -- Termの中からLambda式を完全に取り除く -- Lambda式は同等の振る舞いをするSKIコンビネータ-の組に置き換えられる unlambda :: Term -> Term unlambda (App ts) = App $ fmap unlambda ts unlambda (Lambda vs t) = unabstract vs t unlambda t = t -- Termの中から[Var]を取り除く -- [Var]はLambdaの引数にあたるリストでunabstractは引数を内側から処理するため -- 引数のリストをreverseして、実際の処理はunabstract'に委託 unabstract :: [Var] -> Term -> Term unabstract vs t = compact $ unabstract' (reverse vs) t unabstract' :: [Var] -> Term -> Term unabstract' [] t = t unabstract' (v:vs) t = unabstract vs $ unabstractOnce v t unabstractOnce :: Var -> Term -> Term unabstractOnce v t@(App [t1, t2]) | v `isFreeIn` t = App [k, t] | v `isFreeIn` t1 && t2 == VarT v = t1 | otherwise = App [s, unabstractOnce v t1, unabstractOnce v t2] unabstractOnce v t@(App ts) | v `isFreeIn` t = App [k, t] | v `isFreeIn` App (init ts) && last ts == VarT v = App (init ts) | otherwise = App [s, unabstractOnce v $ App (init ts), unabstractOnce v $ last ts] unabstractOnce v (Lambda vs t) = unabstractOnce v $ unabstract vs t unabstractOnce v t@(VarT v') | v == v' = i | otherwise = App [k, t] -------------------------------------------------------------------------------- s = VarT $ Var "S_" k = VarT $ Var "K_" i = VarT $ Var "I_"
todays-mitsui/discussion
src/Discussion/Converter.hs
mit
2,223
0
13
445
745
383
362
38
1
-- | Create a bundle to be uploaded to Stackage Server. {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FlexibleContexts #-} module Stackage.ServerBundle ( bpAllPackages , docsListing , createBundleV2 , CreateBundleV2 (..) , SnapshotType (..) , writeIndexStyle , DocMap , PackageDocs (..) ) where import qualified Data.Yaml as Y import Stackage.BuildConstraints import Stackage.BuildPlan import Stackage.Prelude import qualified Text.XML as X import Text.XML.Cursor import System.Directory (canonicalizePath, doesDirectoryExist, doesFileExist) import System.FilePath (takeFileName) -- | All package/versions in a build plan, including core packages. -- -- Note that this may include packages not available on Hackage. bpAllPackages :: BuildPlan -> Map PackageName Version bpAllPackages BuildPlan {..} = siCorePackages bpSystemInfo ++ map ppVersion bpPackages docsListing :: BuildPlan -> FilePath -- ^ docs directory -> IO DocMap docsListing bp docsDir = fmap fold $ mapM go $ mapToList $ bpAllPackages bp where go :: (PackageName, Version) -> IO DocMap go (package, version) = do -- handleAny (const $ return mempty) $ do let dirname = unpack (concat [ display package , "-" , display version ]) indexFP = (docsDir </> dirname </> "index.html") ie <- doesFileExist indexFP if ie then do doc <- flip X.readFile indexFP X.def { X.psDecodeEntities = X.decodeHtmlEntities } let cursor = fromDocument doc getPair x = take 1 $ do href <- attribute "href" x let name = concat $ x $// content guard $ not $ null name return (href, name) pairs = cursor $// attributeIs "class" "module" &/ laxElement "a" >=> getPair m <- fmap fold $ forM pairs $ \(href, name) -> do let suffix = dirname </> unpack href e <- doesFileExist $ docsDir </> suffix return $ if e then asMap $ singletonMap name [pack dirname, href] else mempty return $ singletonMap (display package) $ PackageDocs { pdVersion = display version , pdModules = m } else return mempty data CreateBundleV2 = CreateBundleV2 { cb2Plan :: BuildPlan , cb2Type :: SnapshotType , cb2DocsDir :: FilePath , cb2DocmapFile :: !FilePath } -- | Create a V2 bundle, which contains the build plan, metadata, docs, and doc -- map. createBundleV2 :: CreateBundleV2 -> IO () createBundleV2 CreateBundleV2 {..} = do docsDir <- canonicalizePath cb2DocsDir docMap <- docsListing cb2Plan cb2DocsDir Y.encodeFile (docsDir </> "build-plan.yaml") cb2Plan Y.encodeFile (docsDir </> "build-type.yaml") cb2Type Y.encodeFile (docsDir </> "docs-map.yaml") docMap Y.encodeFile cb2DocmapFile docMap void $ writeIndexStyle Nothing cb2DocsDir writeIndexStyle :: Maybe Text -- ^ snapshot id -> FilePath -- ^ docs dir -> IO [String] writeIndexStyle msnapid dir = do dirs <- fmap sort $ runConduitRes $ sourceDirectory dir .| filterMC (liftIO . doesDirectoryExist) .| mapC takeFileName .| sinkList writeFile (dir </> "index.html") $ encodeUtf8 $ asText $ pack $ mkIndex (unpack <$> msnapid) dirs writeFile (dir </> "style.css") $ encodeUtf8 $ asText $ pack styleCss return dirs mkIndex :: Maybe String -> [String] -> String mkIndex msnapid dirs = concat [ "<!DOCTYPE html>\n<html lang='en'><head><title>Haddocks index</title>" , "<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css'>" , "<link rel='stylesheet' href='style.css'>" , "<link rel='shortcut icon' href='https://www.stackage.org/static/img/favicon.ico' />" , "</head>" , "<body><div class='container'>" , "<div class='row'><div class='span12 col-md-12'>" , "<h1>Haddock documentation index</h1>" , flip foldMap msnapid $ \snapid -> concat [ "<p class='return'><a href=\"https://www.stackage.org/stackage/" , snapid , "\">Return to snapshot</a></p>" ] , "<ul>" , concatMap toLI dirs , "</ul></div></div></div></body></html>" ] where toLI name = concat [ "<li><a href='" , name , "/index.html'>" , name , "</a></li>" ] styleCss :: String styleCss = concat [ "@media (min-width: 530px) {" , "ul { -webkit-column-count: 2; -moz-column-count: 2; column-count: 2 }" , "}" , "@media (min-width: 760px) {" , "ul { -webkit-column-count: 3; -moz-column-count: 3; column-count: 3 }" , "}" , "ul {" , " margin-left: 0;" , " padding-left: 0;" , " list-style-type: none;" , "}" , "body {" , " background: #f0f0f0;" , " font-family: 'Lato', sans-serif;" , " text-shadow: 1px 1px 1px #ffffff;" , " font-size: 20px;" , " line-height: 30px;" , " padding-bottom: 5em;" , "}" , "h1 {" , " font-weight: normal;" , " color: #06537d;" , " font-size: 45px;" , "}" , ".return a {" , " color: #06537d;" , " font-style: italic;" , "}" , ".return {" , " margin-bottom: 1em;" , "}"]
fpco/stackage-curator
src/Stackage/ServerBundle.hs
mit
5,807
0
22
1,847
1,128
601
527
146
3
{-# LANGUAGE OverloadedStrings #-} import Data.Aeson import Control.Applicative ((<$>), (<*>)) import Control.Monad (mzero) import qualified Data.Text as T data Ingredient = Ingredient { amount :: Float , unit :: String , item :: String } deriving (Eq) instance Show Ingredient where show (Ingredient a u i) = printf "%.2f" a ++ " " ++ u ++ " " ++ i instance FromJSON Ingredient where parseJSON (Object o) = Ingredient <$> o .: "amount" <*> o .: "measurement" <*> o .: "ingredient" parseJSON _ = mzero data Recipe = Recipe { name :: Maybe T.Text , current :: Maybe Float , desired :: Maybe Float , ingredients :: Maybe Array } deriving (Eq, Show) instance FromJSON Recipe where parseJSON (Object v) = Recipe <$> v .:? "recipeName" <*> v .:? "currentServings" <*> v .:? "desiredServings" <*> v .:? "ingredients" parseJSON _ = mzero
tpoulsen/RecipeScaler
RecipeJSON.hs
mit
1,249
0
13
560
297
162
135
29
0
module Main(main,hello) where import qualified Hello import qualified Hello as H import Hello(exported) hello = Hello.hello main = Hello.hello
sgtest/haskell-module-import
src/Main.hs
mit
156
0
5
32
44
29
15
6
1
{-# htermination keysFM :: FiniteMap a b -> [a] #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_keysFM_1.hs
mit
69
0
3
12
5
3
2
1
0
-- find the number of elements of a list -- too easy.. doesn't count myLength :: [x] -> Int myLength a = length a -- can't i use a fold and just add one for each element (regardless of what it is?) myLength' a = foldr (\x -> \y -> y + 1) 0 a -- here's what's going on.. the thing between parenthesis is a lambda.. it's the function used by fold to accumulate each element (\x) to the currently accumulated value (\y) -- here's a solution from the website itself:(isn't this a foldr?) myLength'' [] = 0 myLength'' (_:xs) = 1 + myLength'' xs
queirozfcom/haskell-99-problems
problem4.hs
mit
560
0
9
126
93
50
43
5
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Diagrams.RubiksCube.Model ( -- * Constructing cubes Side (..) , topLeft, topCenter, topRight , middleLeft, middleCenter, middleRight , bottomLeft, bottomCenter, bottomRight , rotateSideCW, rotateSideCCW , Cube (..), frontSide, backSide, leftSide, rightSide, upSide, downSide , RubiksCube (..), cube -- * Selecting rows and columns , Vec3 (..) , topRow, middleRow, bottomRow , leftCol, centerCol, rightCol -- * Traversing facets -- ** By layer , topLayerFacets, middleLayerFacets, bottomLayerFacets -- ** By position , centerFacets, cornerFacets, edgeFacets , sideCorners, sideEdges -- * Rotating the whole cube , Aut , rotateLeft, rotateRight , rotateDown, rotateUp , rotateCW, rotateCCW -- * Moving layers of the cube , move, doMoves, undoMoves ) where import Control.Lens import Diagrams.RubiksCube.Move (Move (..)) import Data.Foldable (Foldable) import Control.Applicative (Applicative (..), (<$>)) import Data.Distributive (Distributive (..)) import Data.Functor.Rep (Representable (..), distributeRep, tabulated) -- | The type of automorphisms type Aut a = Iso' a a -- Natural numbers data N = Z | S N -- Some type synonyms for natural numbers type Zero = 'Z type One = 'S Zero type Two = 'S One type Three = 'S Two type Four = 'S Three -- | Finite type with n inhabitants data Fin :: N -> * where FinZ :: Fin ('S n) FinS :: Fin n -> Fin ('S n) zero :: Fin ('S n) zero = FinZ one :: Fin ('S ('S n)) one = FinS zero two :: Fin ('S ('S ('S n))) two = FinS one three :: Fin ('S ('S ('S ('S n)))) three = FinS two -- | A list of fixed length 3. data Vec3 a = Vec3 a a a deriving (Show, Eq, Functor, Foldable, Traversable) instance Applicative Vec3 where pure v = Vec3 v v v Vec3 f1 f2 f3 <*> Vec3 v1 v2 v3 = Vec3 (f1 v1) (f2 v2) (f3 v3) instance Reversing (Vec3 a) where reversing (Vec3 a b c) = Vec3 c b a instance Distributive Vec3 where distribute = distributeRep instance Representable Vec3 where type Rep Vec3 = Fin Three tabulate f = Vec3 (f zero) (f one) (f two) index (Vec3 a b c) fin = case fin of FinZ -> a FinS FinZ -> b FinS (FinS FinZ) -> c _ -> error "index@Vec3: cannot happen" instance Field1 (Vec3 a) (Vec3 a) a a where _1 f (Vec3 a b c) = (\a' -> Vec3 a' b c) <$> f a instance Field2 (Vec3 a) (Vec3 a) a a where _2 f (Vec3 a b c) = (\b' -> Vec3 a b' c) <$> f b instance Field3 (Vec3 a) (Vec3 a) a a where _3 f (Vec3 a b c) = (\c' -> Vec3 a b c') <$> f c -- | A variant of 'inside' that works for insideRep :: Representable g => Lens s t a b -> Lens (g s) (g t) (g a) (g b) insideRep l = from tabulated . inside l . tabulated -- | A list of fixed length 4. data Vec4 a = Vec4 a a a a deriving (Show, Eq, Functor, Foldable, Traversable) instance Applicative Vec4 where pure v = Vec4 v v v v Vec4 f1 f2 f3 f4 <*> Vec4 v1 v2 v3 v4 = Vec4 (f1 v1) (f2 v2) (f3 v3) (f4 v4) instance Distributive Vec4 where distribute = distributeRep instance Representable Vec4 where type Rep Vec4 = Fin Four tabulate f = Vec4 (f zero) (f one) (f two) (f three) index (Vec4 a b c d) fin = case fin of FinZ -> a FinS FinZ -> b FinS (FinS FinZ) -> c FinS (FinS (FinS FinZ)) -> d _ -> error "index@Vec4: cannot happen" cycRight :: Vec4 a -> Vec4 a cycRight (Vec4 a b c d) = Vec4 d a b c cycLeft :: Vec4 a -> Vec4 a cycLeft (Vec4 a b c d) = Vec4 b c d a cycleLeft :: Aut (Vec4 a) cycleLeft = iso cycLeft cycRight cycleRight :: Aut (Vec4 a) cycleRight = iso cycRight cycLeft -- | One side of the Rubik's Cube with 3*3 facets. data Side a = Side { _topLeft :: a , _topCenter :: a , _topRight :: a , _middleLeft :: a , _middleCenter :: a , _middleRight :: a , _bottomLeft :: a , _bottomCenter :: a , _bottomRight :: a } deriving (Show, Eq, Functor, Foldable, Traversable) instance Applicative Side where pure v = Side v v v v v v v v v Side f1 f2 f3 f4 f5 f6 f7 f8 f9 <*> Side v1 v2 v3 v4 v5 v6 v7 v8 v9 = Side (f1 v1) (f2 v2) (f3 v3) (f4 v4) (f5 v5) (f6 v6) (f7 v7) (f8 v8) (f9 v9) makeLenses ''Side instance Reversing (Side a) where reversing (Side tl tc tr ml mc mr bl bc br) = Side br bc bl mr mc ml tr tc tl rotCW :: Side a -> Side a rotCW (Side tl tc tr ml mc mr bl bc br) = Side bl ml tl bc mc tc br mr tr rotCCW :: Side a -> Side a rotCCW (Side tl tc tr ml mc mr bl bc br) = Side tr mr br tc mc bc tl ml bl -- | Rotate the side clockwise. rotateSideCW :: Aut (Side a) rotateSideCW = iso rotCW rotCCW -- | Rotate the side counter-clockwise. rotateSideCCW :: Aut (Side a) rotateSideCCW = iso rotCCW rotCW -- | The top three facets (from left to right). topRow :: Lens' (Side a) (Vec3 a) topRow = lens getter setter where getter (Side tl tc tr _ _ _ _ _ _) = Vec3 tl tc tr setter (Side _ _ _ ml mc mr bl bc br) (Vec3 tl tc tr) = Side tl tc tr ml mc mr bl bc br -- | The middle three facets (from left to right). middleRow :: Lens' (Side a) (Vec3 a) middleRow = lens getter setter where getter (Side _ _ _ ml mc mr _ _ _) = Vec3 ml mc mr setter (Side tl tc tr _ _ _ bl bc br) (Vec3 ml mc mr) = Side tl tc tr ml mc mr bl bc br -- | The bottom three facets (from left to right). bottomRow :: Lens' (Side a) (Vec3 a) bottomRow = lens getter setter where getter (Side _ _ _ _ _ _ bl bc br) = Vec3 bl bc br setter (Side tl tc tr ml mc mr _ _ _) (Vec3 bl bc br) = Side tl tc tr ml mc mr bl bc br -- | The left column (from top to down). leftCol :: Lens' (Side a) (Vec3 a) leftCol = lens getter setter where getter (Side tl _ _ ml _ _ bl _ _) = Vec3 tl ml bl setter (Side _ tc tr _ mc mr _ bc br) (Vec3 tl ml bl) = Side tl tc tr ml mc mr bl bc br -- | The center column (from top to down). centerCol :: Lens' (Side a) (Vec3 a) centerCol = lens getter setter where getter (Side _ tc _ _ mc _ _ bc _) = Vec3 tc mc bc setter (Side tl _ tr ml _ mr bl _ br) (Vec3 tc mc bc) = Side tl tc tr ml mc mr bl bc br -- | The right column (from top to down). rightCol :: Lens' (Side a) (Vec3 a) rightCol = lens getter setter where getter (Side _ _ tr _ _ mr _ _ br) = Vec3 tr mr br setter (Side tl tc _ ml mc _ bl bc _) (Vec3 tr mr br) = Side tl tc tr ml mc mr bl bc br -- | The four corners of a side. sideCorners :: Traversal' (Side a) a sideCorners f (Side tl tc tr ml mc mr bl bc br) = (\tl' tr' bl' br' -> Side tl' tc tr' ml mc mr bl' bc br') <$> f tl <*> f tr <*> f bl <*> f br -- | The four edges of a side. sideEdges :: Traversal' (Side a) a sideEdges f (Side tl tc tr ml mc mr bl bc br) = (\tc' ml' mr' bc' -> Side tl tc' tr ml' mc mr' bl bc' br) <$> f tc <*> f ml <*> f mr <*> f bc -- | A cube with six sides. -- -- @ -- +---+ -- | u | -- +---+---+---+---+ -- | l | f | r | b | -- +---+---+---+---+ -- | d | -- +---+ -- @ data Cube a = Cube { _frontSide :: a , _backSide :: a , _leftSide :: a , _rightSide :: a , _upSide :: a , _downSide :: a } deriving (Show, Eq, Functor, Foldable, Traversable) instance Applicative Cube where pure v = Cube v v v v v v Cube ff fb fl fr fu fd <*> Cube vf vb vl vr vu vd = Cube (ff vf) (fb vb) (fl vl) (fr vr) (fu vu) (fd vd) rotRight' :: Cube a -> Cube a rotRight' (Cube f b l r u d) = Cube l r b f u d rotLeft' :: Cube a -> Cube a rotLeft' (Cube f b l r u d) = Cube r l f b u d rotateRight' :: Aut (Cube a) rotateRight' = iso rotRight' rotLeft' _rotateLeft' :: Aut (Cube a) _rotateLeft' = from rotateRight' rotDown' :: Reversing a => Cube a -> Cube a rotDown' (Cube f b l r u d) = Cube u (reversing d) l r (reversing b) f rotUp' :: Reversing a => Cube a -> Cube a rotUp' (Cube f b l r u d) = Cube d (reversing u) l r f (reversing b) rotateDown' :: Reversing a => Aut (Cube a) rotateDown' = iso rotDown' rotUp' _rotateUp' :: Reversing a => Aut (Cube a) _rotateUp' = from rotateDown' makeLenses ''Cube -- | A normal Rubik's cube with 6 sides with 9 facets each. newtype RubiksCube a = RubiksCube { _cube :: Cube (Side a) } deriving (Show, Eq, Functor) instance Applicative RubiksCube where pure = RubiksCube . pure . pure RubiksCube f <*> RubiksCube v = RubiksCube ((<*>) <$> f <*> v) makeLenses ''RubiksCube cong :: Traversal' s a -> Aut a -> Aut s cong t i = withIso i $ \f g -> iso (over t f) (over t g) -- | Rotate the whole Rubik's Cube such that the front side becomes the new -- right side and the top and bottom sides stay fixed. rotateRight :: Aut (RubiksCube a) rotateRight = cong cube $ rotateRight' . cong upSide rotateSideCCW . cong downSide rotateSideCW -- | Rotate the whole Rubik's Cube such that the front side becomes the new -- left side and the top and bottom sides stay fixed. rotateLeft :: Aut (RubiksCube a) rotateLeft = from rotateRight -- | Rotate the whole Rubik's Cube such that the front side becomes the new -- bottom side and the left and right sides stay fixed. rotateDown :: Aut (RubiksCube a) rotateDown = cong cube $ rotateDown' . cong leftSide rotateSideCW . cong rightSide rotateSideCCW -- | Rotate the whole Rubik's Cube such that the front side becomes the new -- top side and the left and right sides stay fixed. rotateUp :: Aut (RubiksCube a) rotateUp = from rotateDown -- | Rotate the whole Rubik's Cube such that the top side becomes the new -- right side and the front and back sides stay fixed. rotateCW :: Aut (RubiksCube a) rotateCW = rotateUp . rotateLeft . rotateDown -- | Rotate the whole Rubik's Cube such that the top side becomes the new -- left side and the front and back sides stay fixed. rotateCCW :: Aut (RubiksCube a) rotateCCW = from rotateCW type RowsLens a = Lens' (Cube (Side a)) (Vec4 (Vec3 a)) type ColsLens a = Lens' (Cube (Side a)) (Vec4 (Vec3 a)) horizontalSides :: Lens' (Cube a) (Vec4 a) horizontalSides = lens getter setter where getter (Cube f b l r _u _d) = Vec4 f r b l setter (Cube _f _b _l _r u d) (Vec4 f' r' b' l') = Cube f' b' l' r' u d horizontalRows :: Lens' (Side a) (Vec3 a) -> RowsLens a horizontalRows rowLens = horizontalSides . insideRep rowLens upRows :: RowsLens a upRows = horizontalRows topRow middleRows :: RowsLens a middleRows = horizontalRows middleRow downRows :: RowsLens a downRows = horizontalRows bottomRow moveU :: Aut (RubiksCube a) moveU = cong cube $ cong upRows cycleLeft . cong upSide rotateSideCW moveD :: Aut (RubiksCube a) moveD = cong cube $ cong downRows cycleRight . cong downSide rotateSideCW verticalCols :: Lens' (Side a) (Vec3 a) -> ColsLens a verticalCols colLens = lens getter setter where getter (Cube f b _l _r u d) = Vec4 (f ^. colLens) (u ^. colLens) (b ^. reversed . colLens) (d ^. colLens) setter (Cube f b l r u d) (Vec4 f' u' b' d') = Cube (set colLens f' f) (set (reversed . colLens) b' b) l r (set colLens u' u) (set colLens d' d) leftCols :: ColsLens a leftCols = verticalCols leftCol _centerCols :: ColsLens a _centerCols = verticalCols centerCol rightCols :: ColsLens a rightCols = verticalCols rightCol moveL :: Aut (RubiksCube a) moveL = cong cube $ cong leftCols cycleLeft . cong leftSide rotateSideCW moveR :: Aut (RubiksCube a) moveR = cong cube $ cong rightCols cycleRight . cong rightSide rotateSideCW ringCols :: Lens' (Side a) (Vec3 a) -> ColsLens a ringCols colLens = lens getter setter where getter (Cube _f _b l r u d) = Vec4 (r ^. colLens) (u ^. rotateSideCW . colLens) (l ^. reversed . colLens) (d ^. rotateSideCCW . colLens) setter (Cube f b l r u d) (Vec4 r' u' l' d') = Cube f b (set (reversed . colLens) l' l) (set colLens r' r) (set (rotateSideCW . colLens) u' u) (set (rotateSideCCW . colLens) d' d) frontCols :: ColsLens a frontCols = ringCols leftCol _betweenCols :: ColsLens a _betweenCols = ringCols centerCol backCols :: ColsLens a backCols = ringCols rightCol moveF :: Aut (RubiksCube a) moveF = cong cube $ cong frontCols cycleLeft . cong frontSide rotateSideCW moveB :: Aut (RubiksCube a) moveB = cong cube $ cong backCols cycleRight . cong backSide rotateSideCW -- | Perform a move. move :: Move -> Aut (RubiksCube a) move D = moveD move D' = from moveD move U = moveU move U' = from moveU move L = moveL move L' = from moveL move R = moveR move R' = from moveR move F = moveF move F' = from moveF move B = moveB move B' = from moveB -- | Perform a list of moves. doMoves :: [Move] -> Aut (RubiksCube a) doMoves [] = iso id id doMoves (m:ms) = move m . doMoves ms -- | Undo the actions of a list of moves. undoMoves :: [Move] -> Aut (RubiksCube a) undoMoves = from . doMoves -- | The 21=4*3+9 facets in the top layer. topLayerFacets :: Traversal' (RubiksCube a) a topLayerFacets f = cube $ \c -> (\upSide' upRows' -> c & upSide .~ upSide' & upRows .~ upRows') <$> (traverse f (c ^. upSide)) <*> (traverse (traverse f) (c ^. upRows)) -- | The 12=4*3 facets in the middle layer. middleLayerFacets :: Traversal' (RubiksCube a) a middleLayerFacets = cube.middleRows.traverse.traverse -- | The 21=4*3+9 facets in the bottom layer. bottomLayerFacets :: Traversal' (RubiksCube a) a bottomLayerFacets f = cube $ \c -> (\downSide' downRows' -> c & downSide .~ downSide' & downRows .~ downRows') <$> (traverse f (c ^. downSide)) <*> (traverse (traverse f) (c ^. downRows)) -- | The six facets that are the center of their side. centerFacets :: Traversal' (RubiksCube a) a centerFacets = cube.traverse.middleCenter -- | The 24=6*4=8*3 corner facets. cornerFacets :: Traversal' (RubiksCube a) a cornerFacets = cube.traverse.sideCorners -- | The 24=6*4=12*2 edge facets. edgeFacets :: Traversal' (RubiksCube a) a edgeFacets = cube.traverse.sideEdges
timjb/diagrams-rubiks-cube
src/Diagrams/RubiksCube/Model.hs
mit
14,358
0
14
3,614
5,547
2,839
2,708
-1
-1
{-# LANGUAGE RecordWildCards, NamedFieldPuns #-} -- Needed libraries: --cabal install bmp --cabal install parsec-numbers --cabal install vect import Codec.BMP import qualified Data.ByteString as BS import Raytrace import Types import Scene import SceneParser (loadSceneFile, rawScene) ---------------------------------------------------------------- main = do --scene@SceneConfig {width, height, output} <- loadSceneFile "./scenes/scene4-emission.test" --scene@SceneConfig {width, height, output} <- loadSceneFile "./scenes/scene4-diffuse.test" --scene@SceneConfig {width, height, output} <- loadSceneFile "./scenes/scene4-specular.test" --scene@SceneConfig {width, height, output} <- loadSceneFile "./scenes/scene5.test" scene@SceneConfig {width, height, output} <- loadSceneFile "./scenes/scene6.test" --scene@SceneConfig {width, height, output} <- loadSceneFile "./scenes/scene7.test" --s <- rawScene "./scenes/scene6.test" --print scene print "Ray tracing image..." let image = raytraceImage scene let rgba = imageToByteString image let bmp = packRGBA32ToBMP24 (fromIntegral width) (fromIntegral height) rgba let filename = (reverse $ drop 4 $ reverse output) ++ ".bmp" writeBMP filename bmp print "Done!" imageToByteString :: [Color] -> BS.ByteString imageToByteString image = BS.pack imageAsWord8Array where imageAsWord8Array = concatMap colorToWord8Array image colorToWord8Array (Color r g b) = [ fromIntegral (floor ((min 1 r)*255)), fromIntegral (floor ((min 1 g)*255)), fromIntegral (floor ((min 1 b)*255)), 255]
CanisLupus/haskell-raytracer
raytracer.hs
mit
1,563
6
14
205
326
171
155
23
1
{-# LANGUAGE DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : Language.Maude.Exec.Types -- Copyright : (c) David Lazar, 2012 -- License : MIT -- -- Maintainer : lazar6@illinois.edu -- Stability : experimental -- Portability : unknown -- -- Types shared between modules in the Language.Maude.Exec namespace ----------------------------------------------------------------------------- module Language.Maude.Exec.Types ( -- * Error handling MaudeException(..) -- * Configuring Maude's execution , MaudeCommand(..) , MaudeConf(..) -- * Result types , MaudeResult(..) , RewriteResult(..) , SearchResult(..) , SearchResults , Substitution(..) , MaudeStatistics(..) ) where import Control.Exception import Data.Data import Data.Text (Text) import System.Exit (ExitCode) import qualified Text.XML.Light as XML import Language.Maude.Syntax data MaudeException = MaudeFailure { maudeFailureExitCode :: ExitCode , maudeFailureStderr :: Text , maudeFailureStdout :: Text } -- ^ Thrown when the @maude@ executable fails | LogToXmlFailure -- ^ Thrown when the log produced by Maude is not parseable as XML | XmlToResultFailure String XML.Element -- ^ Thrown when the XML can't be parsed/translated to -- one of the result types below deriving (Typeable) instance Exception MaudeException instance Show MaudeException where showsPrec _ (MaudeFailure e err out) = showString "MaudeFailure (exitCode = " . showsPrec 0 e . showString ") (stderr = " . showsPrec 0 err . showString ") (stdout = " . showsPrec 0 out . showChar ')' showsPrec _ LogToXmlFailure = showString "LogToXmlFailure" showsPrec _ (XmlToResultFailure s e) = showString "XmlToResultFailure " . showsPrec 0 s . showString "\n" . showString (take n xml) . showString (if length xml > n then "..." else "") where n = 100 xml = XML.showElement e -- | Commands performed by Maude data MaudeCommand = Rewrite Text | Erewrite Text | Search Text Text deriving (Eq, Ord, Show, Data, Typeable) -- | Configuration of Maude's execution data MaudeConf = MaudeConf { maudeCmd :: FilePath -- ^ Path to the Maude executable , loadFiles :: [FilePath] -- ^ Files to load before running a command } deriving (Eq, Ord, Show, Data, Typeable) -- | Low-level Maude result data MaudeResult = MaudeResult { maudeStdout :: Text -- ^ Text printed to standard out during execution , maudeXmlLog :: Text -- ^ XML log obtained via Maude's @--xml-log@ option } deriving (Eq, Ord, Show, Data, Typeable) -- | High-level (e)rewrite result data RewriteResult = RewriteResult { resultTerm :: Term -- ^ The rewritten term , rewriteStatistics :: MaudeStatistics -- ^ Statistics about the rewrite performed } deriving (Eq, Ord, Show, Data, Typeable) -- | High-level search result data SearchResult = SearchResult { searchSolutionNumber :: Integer , searchStatistics :: MaudeStatistics , searchResult :: Substitution } deriving (Eq, Ord, Show, Data, Typeable) -- | Several search results type SearchResults = [SearchResult] -- | Search result substitution data Substitution = Substitution Term Term deriving (Eq, Ord, Show, Data, Typeable) -- | Statistics returned by Maude after a successful command data MaudeStatistics = MaudeStatistics { totalRewrites :: Integer -- ^ Total rewrites performed , realTime :: Integer -- ^ Real time (milliseconds) , cpuTime :: Integer -- ^ CPU time (milliseconds) } deriving (Eq, Ord, Show, Data, Typeable)
davidlazar/maude-hs
src/Language/Maude/Exec/Types.hs
mit
3,851
0
12
929
712
417
295
70
0
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeSynonymInstances #-} module TestUtility ( URIBuilder , uri , query , runTest , get , post , postRaw , put , putRaw , delete , jsonBody , simpleHeader ) where import Blaze.ByteString.Builder ( toByteString ) import Control.Monad.Trans ( liftIO ) import Control.Monad.Trans.Reader ( runReaderT ) import Data.Aeson ( ToJSON, FromJSON, encode, decode ) import qualified Data.ByteString as BS ( ByteString ) import qualified Data.ByteString.Lazy as BSL ( ByteString, toStrict, fromStrict ) import Data.List ( find ) import qualified Data.Text as T ( Text, pack ) import Data.Text.Encoding ( encodeUtf8 ) import Data.Maybe ( fromJust ) import Database.Persist.Sql ( runMigrationSilent ) import Network.Wai ( Application, Request(..) ) import Network.Wai.Test ( SRequest(..), SResponse , runSession, srequest, setPath, defaultRequest, simpleBody, simpleHeaders ) import Network.HTTP.Types.Header ( HeaderName, hAccept ) import Network.HTTP.Types.Method ( Method, methodGet, methodPost, methodPut, methodDelete ) import Network.HTTP.Types.URI ( Query, encodePath ) import System.IO.Temp ( withSystemTempFile ) import Web.Scotty.Trans ( scottyAppT ) import Core ( BrandyScottyM ) import Database ( runSql ) import Plugins ( mkPlugin ) import Routing ( routes ) import Schema ( migrate ) data URIBuilder = URIBuilder [T.Text] Query instance Monoid URIBuilder where mappend (URIBuilder p1 q1) (URIBuilder p2 q2) = URIBuilder (p1 ++ p2) (q1 ++ q2) mempty = URIBuilder [] [] instance Show URIBuilder where show (URIBuilder p q) = show $ toByteString $ encodePath p q uri :: [T.Text] -> URIBuilder uri path = URIBuilder path [] query :: BS.ByteString -> T.Text -> URIBuilder query q v = URIBuilder [] [(q, Just $ encodeUtf8 v)] runTest :: (Application -> IO ()) -> IO () runTest test = withSystemTempFile "brandytest.sqlite3" $ \f _ -> do let file = T.pack f _ <- runReaderT (runSql . runMigrationSilent $ migrate) file app <- liftIO $ scottyApp file $ routes mkPlugin test app scottyApp :: T.Text -> BrandyScottyM () -> IO Application scottyApp file = scottyAppT (`runReaderT` file) (`runReaderT` file) get :: Application -> URIBuilder -> IO SResponse get app path = actionWithoutBody (jsonRequest methodGet) app path post :: (ToJSON a) => Application -> URIBuilder -> a -> IO SResponse post app u v = actionWithBody (encode v) (jsonRequestWithBody methodPost) app u postRaw :: Application -> URIBuilder -> BS.ByteString -> IO SResponse postRaw app u v = actionWithBody (BSL.fromStrict v) (defaultRequestWithBody methodPost) app u put :: (ToJSON a) => Application -> URIBuilder -> a -> IO SResponse put app u v = actionWithBody (encode v) (jsonRequestWithBody methodPut) app u putRaw :: Application -> URIBuilder -> BS.ByteString -> IO SResponse putRaw app u v = actionWithBody (BSL.fromStrict v) (defaultRequestWithBody methodPut) app u delete :: Application -> URIBuilder -> IO SResponse delete app path = actionWithoutBody (jsonRequest methodDelete) app path jsonBody :: FromJSON a => SResponse -> a jsonBody = fromJust . decode . simpleBody actionWithBody :: BSL.ByteString -> (BS.ByteString -> Request) -> Application -> URIBuilder -> IO SResponse actionWithBody body request app uriBuilder = runSession (srequest sreq) app where req = setPath (request $ BSL.toStrict body) $ uriToByteString uriBuilder sreq = SRequest req body actionWithoutBody :: Request -> Application -> URIBuilder -> IO SResponse actionWithoutBody request app uriBuilder = runSession (srequest sreq) app where req = setPath request $ uriToByteString uriBuilder sreq = SRequest req "" jsonRequest :: Method -> Request jsonRequest method = defaultRequest { requestMethod = method , requestHeaders = [(hAccept, "application/json")] } jsonRequestWithBody :: Method -> BS.ByteString -> Request jsonRequestWithBody method payload = (jsonRequest method) { requestBody = return payload } defaultRequestWithBody :: Method -> BS.ByteString -> Request defaultRequestWithBody method payload = defaultRequest { requestMethod = method , requestBody = return payload } uriToByteString :: URIBuilder -> BS.ByteString uriToByteString (URIBuilder p q) = toByteString $ encodePath p q simpleHeader :: HeaderName -> SResponse -> BS.ByteString simpleHeader name = snd . fromJust . find ((name ==) . fst) . simpleHeaders
stu-smith/Brandy
tests/TestUtility.hs
mit
4,956
0
13
1,238
1,440
783
657
118
1
{-| TODO This has a bunch of stub logic that was intended for an architecture with a single Urbit daemon running multiple ships. Do it or strip it out. -} module Urbit.King.API ( King(..) , TermConn , TermConnAPI , kingAPI , readPortsFile ) where import RIO.Directory import Urbit.Prelude import Network.Socket (Socket) import Prelude (read) import Urbit.King.App (HasPierPath(..)) import qualified Network.HTTP.Types as H import qualified Network.Wai as W import qualified Network.Wai.Handler.Warp as W import qualified Network.Wai.Handler.WebSockets as WS import qualified Network.WebSockets as WS import qualified Urbit.Vere.NounServ as NounServ import qualified Urbit.Vere.Term.API as Term -- Types ----------------------------------------------------------------------- type TermConn = NounServ.Conn Term.ClientTake [Term.Ev] type TermConnAPI = TVar (Maybe (TermConn -> STM ())) {-| Daemon state. -} data King = King { kServer :: Async () , kTermConn :: TermConnAPI } -------------------------------------------------------------------------------- {-| Get the filepath of the urbit config directory and the ports file. -} portsFilePath :: HasPierPath e => RIO e (FilePath, FilePath) portsFilePath = do dir <- view pierPathL fil <- pure (dir </> ".king.ports") pure (dir, fil) {-| Write the ports file. -} portsFile :: HasPierPath e => Word -> RAcquire e (FilePath, FilePath) portsFile por = mkRAcquire mkFile (removeFile . snd) where mkFile = do (dir, fil) <- portsFilePath createDirectoryIfMissing True dir writeFile fil (encodeUtf8 $ tshow por) pure (dir, fil) {-| Get the HTTP port for the running Urbit daemon. -} readPortsFile :: HasPierPath e => RIO e (Maybe Word) readPortsFile = do (_, fil) <- portsFilePath bs <- readFile fil evaluate (readMay $ unpack $ decodeUtf8 bs) kingServer :: HasLogFunc e => (Int, Socket) -> RAcquire e King kingServer is = mkRAcquire (startKing is) (cancel . kServer) where startKing :: HasLogFunc e => (Int, Socket) -> RIO e King startKing (port, sock) = do api <- newTVarIO Nothing let opts = W.defaultSettings & W.setPort port env <- ask tid <- async $ io $ W.runSettingsSocket opts sock $ app env api pure (King tid api) {-| Start the HTTP server and write to the ports file. -} kingAPI :: (HasPierPath e, HasLogFunc e) => RAcquire e King kingAPI = do (port, sock) <- io $ W.openFreePort (dir, fil) <- portsFile (fromIntegral port) -- lockFile dir kingServer (port, sock) serveTerminal :: HasLogFunc e => e -> TermConnAPI -> Word -> W.Application serveTerminal env api word = WS.websocketsOr WS.defaultConnectionOptions wsApp fallback where fallback req respond = respond $ W.responseLBS H.status500 [] $ "This endpoint uses websockets" wsApp pen = atomically (readTVar api) >>= \case Nothing -> WS.rejectRequest pen "Ship not running" Just sp -> do wsc <- io $ WS.acceptRequest pen inp <- io $ newTBMChanIO 5 out <- io $ newTBMChanIO 5 atomically $ sp $ NounServ.mkConn inp out let doit = runRIO env $ NounServ.wsConn "NOUNSERV (wsServ) " inp out wsc -- If `wai` kills this thread for any reason, the TBMChans -- need to be closed. If they are not closed, the -- terminal will not know that they disconnected. finally doit $ atomically $ do closeTBMChan inp closeTBMChan out data BadShip = BadShip Text deriving (Show, Exception) app :: HasLogFunc e => e -> TermConnAPI -> W.Application app env api req respond = case W.pathInfo req of ["terminal", session] -> do session :: Word <- evaluate $ read $ unpack session serveTerminal env api session req respond ["status"] -> respond $ W.responseLBS H.status200 [] "{}" _ -> respond $ W.responseLBS H.status404 [] "No implemented"
urbit/urbit
pkg/hs/urbit-king/lib/Urbit/King/API.hs
mit
4,293
0
18
1,230
1,126
585
541
-1
-1
module Gshell.Command ( Command(..) , Options(..) ) where data Command = Init FilePath | Enter FilePath | EnterRevision FilePath | Clear FilePath | Commit String | Push | Pull | Rollback | Log | Makefile (Maybe FilePath) | GetGraph deriving ( Show ) data Options = Options Command FilePath deriving Show
ctlab/gShell
src/Gshell/Command.hs
mit
480
0
8
227
98
60
38
14
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} module Ogma.Server where import Control.Monad.Except import Control.Monad.Reader import Data.Maybe import Data.Text (Text) import Data.Time import Database.Persist.Sql import GHC.Int import Network.Wai import Network.Wai.Middleware.RequestLogger import Servant import Servant.Server.Experimental.Auth import Auth.Identity.Servant import Data.Auth.Identity import Data.Auth.Token import Ogma.Api.Definition import Ogma.Model.Model import Ogma.Model.Privilege data OgmaConfig = OgmaConfig { getPool :: ConnectionPool , accessSize :: TokenSize , refreshSize :: TokenSize , accessExpire :: NominalDiffTime , refreshExpire :: NominalDiffTime } type OgmaM = ReaderT OgmaConfig (ExceptT ServantErr IO) queryDb :: SqlPersistT OgmaM a -> OgmaM a queryDb backReq = do pool <- getPool <$> ask runSqlPool backReq pool accountNewH :: AccountNewPost -> OgmaM (Headers '[Header "resource-id" Int64] NoContent) accountNewH (AccountNewPost email login) = do userMaybe <- queryDb $ createNewUser login email case userMaybe of Just id -> return $ addHeader (fromSqlKey id) NoContent Nothing -> throwError $ err403 { errBody = "Login or email have already been taken" } authTokenToGetToken :: AuthToken -> GetTokenResponse authTokenToGetToken (AuthToken ac re exAc _ _) = GetTokenResponse (unToken ac) (unToken re) exAc getTokenH :: GetTokenPost -> OgmaM GetTokenResponse getTokenH (GetTokenPost login) = do logMaybe <- queryDb $ getUserByLogin login case logMaybe of Just (Entity _ usr) -> do acSize <- accessSize <$> ask reSize <- refreshSize <$> ask acExp <- accessExpire <$> ask reExp <- refreshExpire <$> ask authTok <- queryDb $ regenTokens (userIdentity usr) acExp reExp acSize reSize return $ authTokenToGetToken authTok Nothing -> throwError $ err403 { errBody = "Login unknown" } newDocumentH :: (Entity User) -> DocumentPost -> OgmaM (Headers '[Header "resource-id" Int64] NoContent) newDocumentH (Entity userId _) (DocumentPost title content) = do (docId, _) <- queryDb $ createNewDocument userId title content return $ addHeader (fromSqlKey docId) NoContent putDocumentH :: (Entity User) -> Int64 -> DocumentPost -> OgmaM NoContent putDocumentH _ _ _ = throwError err400 getDocumentH :: (Entity User) -> Int64 -> OgmaM GetDocument getDocumentH (Entity userId _) docInt = do let docId = toSqlKey docInt perm <- queryDb $ getPerm userId docId if perm >= ReadOnly then do doc <- fromJust <$> (queryDb $ get docId) -- getPerm ensures queryDb returns something return $ GetDocument (documentTitle doc) "not implemented" (documentModifiedon doc) (documentCreatedon doc) (stringify perm) else throwError err403 server :: ServerT OgmaAPI OgmaM server = accountNewH :<|> getTokenH :<|> (\user -> (newDocumentH user :<|> putDocumentH user :<|> getDocumentH user)) readerToExcept :: OgmaConfig -> OgmaM :~> ExceptT ServantErr IO readerToExcept cfg = Nat $ \x -> runReaderT x cfg readerServer :: OgmaConfig -> Server OgmaAPI readerServer cfg = enter (readerToExcept cfg) server ogmaIdentityHandler :: ConnectionPool -> IdentityId -> Handler (Entity User) ogmaIdentityHandler pool id = do userMaybe <- liftIO $ runSqlPool (getUserByIdentity id) pool case userMaybe of Just val -> return val Nothing -> throwError (err500 { errBody = "Orphan token" }) type instance AuthServerData (AuthProtect "ogma-identity") = Entity User ogmad :: OgmaConfig -> Application ogmad cfg = let pool = getPool cfg in logStdout $ serveWithContext ogmaAPI (authIdentityServerContext pool (ogmaIdentityHandler pool)) (readerServer cfg)
lgeorget/ogma
server/src/Ogma/Server.hs
mit
4,893
0
16
1,640
1,137
580
557
108
2
module Y2021.M03.D05.Exercise where {-- 'Shell scripting' Haskell is the name of the game for today. Today we're going to build a Haskell application that interacts with the shell, or 'command line,' if you prefer. Specifically, we're creating the application 'im' that has this interaction: $ im geophf Hello, geophf! How are you? $ im fine That's good to hear. I hope you have a lovely day! Apologies to all of you Haskellers who go by the name 'fine.' You can even name this module 'Eliza,' if you're feeling nostalgic. --} greet :: String -> IO () greet name = undefined -- greet, for 'fine' responds with the well-wishes for a good day, otherwise -- asks 'name' how they are. -- use the file im.hs in this directory to create your shell ... um: 'script.' -- BONUS ------------------------------------------------------- -- Now ... you can build a database to see if they were first asked and -- tailor (swift?) the response based upon that context, if you want to get -- fancy. -- BONUS-BONUS ------------------------------------------------- -- What if they don't enter anything? Add an errorHandler to guide them, -- gently, into this dialogue. {-- $ cd Y2021/M03/D05 $ ghc im ... [2 of 2] Compiling Main ( im.hs, im.o ) Linking im ... $ im Hi. What's your name? $ im geophf Hello, geophf! How are you? $ im fine That's good to hear. I hope you have a lovely day! --}
geophf/1HaskellADay
exercises/HAD/Y2021/M03/D05/Exercise.hs
mit
1,403
0
7
267
42
29
13
3
1
{-# LANGUAGE OverloadedStrings #-} import Web.Scotty import qualified Text.Blaze.Html5 as H import Text.Blaze.Html5 (toHtml, Html) import Text.Blaze.Html.Renderer.Text (renderHtml) greet :: String -> Html greet user = H.html $ do H.head $ H.title "Welcome!" H.body $ do H.h1 "Greetings!" H.p ("Hello " >> toHtml user >> "!") app = do get "/" $ text "Home Page" get "/greet/:name" $ do name <- param "name" html $ renderHtml (greet name) main :: IO () main = scotty 8000 app
riwsky/wiwinwlh
src/scotty.hs
mit
512
0
15
115
193
97
96
20
1
-- | Utils.Functions module {-# LANGUAGE CPP #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverlappingInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE UnicodeSyntax #-} #ifndef MIN_VERSION_base #define MIN_VERSION_base(a,b,c) 1 #endif -- Assume we are using the newest versions when using ghci without cabal module Utils.Functions ( -- * Spaced concatenation (▪) , (<>) , BShow(..) -- * Printing with indentation , printInd , putStrLnInd -- * List manipulation , swapPrefix , unique -- * Others , agdafy , checkIdScope , stdout2file ) where import Data.Foldable (toList) import Data.List (isPrefixOf) import Data.Set (Set, fromList) import qualified Data.Set as S import GHC.IO.Handle (hDuplicateTo) import System.IO (IOMode (WriteMode), openFile, stdout) #if MIN_VERSION_base(4,7,0) import Data.Foldable (any) import Prelude hiding (any) #endif infixr 4 ▪ -- | '"foo" ▪ "bar"' = '"foo bar"'. Its main use is to simplify the -- concatenation of printable types separated by spaces. (▪) ∷ forall a b. (BShow a, BShow b) ⇒ a → b → String (▪) α₁ α₂ = βshow α₁ ++ " " ++ βshow α₂ infixr 4 <> -- | '"foo" ▪ "bar"' = '"foo bar"'. Its main use is to simplify the -- concatenation of printable types separated by spaces. (<>) ∷ forall a b. (BShow a, BShow b) ⇒ a → b → String (<>) α₁ α₂ = βshow α₁ ++ βshow α₂ -- | 'BShow' fixes 'Show' 'String' instance behavior @length "foo" ≠ -- length (show "foo")@ with two new instances (and overlapped) -- instances for 'String' and 'Show' 'a'. class BShow a where βshow ∷ a → String -- TODO: fix overlapping mess #if MIN_VERSION_base(4,8,0) instance {-# OVERLAPPING #-} BShow String where #else instance BShow String where #endif βshow a = a #if MIN_VERSION_base(4,8,0) instance {-# OVERLAPPING #-} BShow Char where #else instance BShow Char where #endif βshow a = [a] #if MIN_VERSION_base(4,8,0) instance {-# OVERLAPPABLE #-} Show a ⇒ BShow a where #else instance Show a ⇒ BShow a where #endif βshow = show -- | Removes duplicate elements of a list. unique ∷ (Ord a) ⇒ [a] → [a] unique = toList . fromList -- | 'printInd' @i b@, prints a with @b@ level of indentation @i@. printInd ∷ (Show a) ⇒ Int → a → IO () printInd ind a = putStr spaces >> print a where spaces ∷ String spaces = replicate ind ' ' -- | 'printInd' @i str@, prints a with @str@ level of indentation @i@. putStrLnInd ∷ Int → String → IO () putStrLnInd ind a = putStr spaces >> putStrLn a where spaces ∷ String spaces = replicate ind ' ' -- | 'swapPrefix' @a b str@, replaces prefix @a@ in @str@ with @b@ -- checking that @a@ is a prefix of @str@. swapPrefix ∷ Eq a ⇒ [a] -- ^ Current prefix → [a] -- ^ Replacement → [a] -- ^ List to be replaced → [a] -- ^ Resulting list swapPrefix a b str | a `isPrefixOf`str = b ++ drop (length a) str | otherwise = str -- | <http://www.gilith.com/software/metis/ Metis> -- identifiers usually contain @_@ characters which are invalid in -- <http://wiki.portal.chalmers.se/agda/pmwiki.php Agda>, 'agdafy' -- replaces @normalize_0_0@ with @normalize-0-0@. This is -- mostly used inside the -- <https://www.haskell.org/happy/ Happy> -- parser every time an 'Data.TSTP.AtomicWord' is created. agdafy ∷ String → String agdafy = map repl where repl ∷ Char → Char repl '_' = '-' repl a = a -- | Redirect all stdout output into a file or do nothing (in case of -- 'Nothing') stdout2file ∷ Maybe FilePath → IO () stdout2file Nothing = return () stdout2file (Just o) = openFile o WriteMode >>= flip hDuplicateTo stdout -- | 'checkIdScope' @i t s@ check if any name in @s@ has a more -- general scope than @t@ with level @i@ checkIdScope ∷ Int → String → Set (Int, String) → Bool checkIdScope i f s = any (\(i₀,f₀) → f₀ == f && i₀ <= i ) (S.toList s)
agomezl/tstp2agda
src/Utils/Functions.hs
mit
4,218
26
10
997
829
478
351
68
2
{-# LANGUAGE TypeFamilies, TypeOperators, FlexibleInstances, UndecidableInstances #-} module Language.CL.C.HOAS.Sugar ((:->), Func, Proc, Procedure, RP, C ) where import Language.CL.C.HOAS.AST (Function, Expression) import Language.CL.C.Types.Classes class (ParamType a, RetType a) => RP a instance (ParamType a, RetType a) => RP a type C = Expression type Func a b = Expression a -> Expression b type Proc b = Func () b type Procedure b = Function () b type family a :-> b type instance () :-> a = () -> C a type instance (a, b) :-> c = (C a, C b) -> C c type instance (a, b, c) :-> d = (C a, C b, C c) -> C d type instance (a, b, c, d) :-> e = (C a, C b, C c, C d) -> C e type instance (a, b, c, d, e) :-> f = (C a, C b, C c, C d, C e) -> C f type instance (a, b, c, d, e, f) :-> g = (C a, C b, C c, C d, C e, C f) -> C g
pxqr/language-cl-c
Language/CL/C/HOAS/Sugar.hs
mit
847
12
7
205
464
265
199
-1
-1
-- Minimal implicational modal logic, PHOAS approach, initial encoding {-# LANGUAGE DataKinds, GADTs, KindSignatures, Rank2Types, Safe, TypeOperators #-} module Pi.BoxMp where import Lib (Nat (Suc)) -- Types infixr 0 :=> data Ty :: * where UNIT :: Ty (:=>) :: Ty -> Ty -> Ty BOX :: Ty -> Ty -- Context and truth judgement with modal depth -- NOTE: Haskell does not support kind synonyms -- type Cx = Ty -> * type IsTrue (a :: Ty) (d :: Nat) (tc :: Ty -> Nat -> *) = tc a d -- Terms infixl 1 :$ data Tm :: Nat -> (Ty -> Nat -> *) -> Ty -> * where Var :: IsTrue a d tc -> Tm d tc a Lam :: (IsTrue a d tc -> Tm d tc b) -> Tm d tc (a :=> b) (:$) :: Tm d tc (a :=> b) -> Tm d tc a -> Tm d tc b Box :: Tm (Suc d) tc a -> Tm d tc (BOX a) Unbox :: Tm d tc (BOX a) -> (IsTrue a gd tc -> Tm d tc b) -> Tm d tc b var :: IsTrue a d tc -> Tm d tc a var = Var lam :: (Tm d tc a -> Tm d tc b) -> Tm d tc (a :=> b) lam f = Lam $ \x -> f (var x) box :: Tm (Suc d) tc a -> Tm d tc (BOX a) box = Box unbox :: Tm d tc (BOX a) -> (Tm gd tc a -> Tm d tc b) -> Tm d tc b unbox x' f = Unbox x' $ \x -> f (var x) type Thm a = forall d tc. Tm d tc a -- Example theorems rNec :: Thm a -> Thm (BOX a) rNec x = box x aK :: Thm (BOX (a :=> b) :=> BOX a :=> BOX b) aK = lam $ \f' -> lam $ \x' -> unbox f' $ \f -> unbox x' $ \x -> box (f :$ x) aT :: Thm (BOX a :=> a) aT = lam $ \x' -> unbox x' $ \x -> x a4 :: Thm (BOX a :=> BOX (BOX a)) a4 = lam $ \x' -> unbox x' $ \x -> box (box x) t1 :: Thm (a :=> BOX (a :=> a)) t1 = lam $ \_ -> box (lam $ \y -> y)
mietek/formal-logic
src/Pi/BoxMp.hs
mit
1,664
0
15
554
866
455
411
45
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-vpcoptions.html module Stratosphere.ResourceProperties.ElasticsearchDomainVPCOptions where import Stratosphere.ResourceImports -- | Full data type definition for ElasticsearchDomainVPCOptions. See -- 'elasticsearchDomainVPCOptions' for a more convenient constructor. data ElasticsearchDomainVPCOptions = ElasticsearchDomainVPCOptions { _elasticsearchDomainVPCOptionsSecurityGroupIds :: Maybe (ValList Text) , _elasticsearchDomainVPCOptionsSubnetIds :: Maybe (ValList Text) } deriving (Show, Eq) instance ToJSON ElasticsearchDomainVPCOptions where toJSON ElasticsearchDomainVPCOptions{..} = object $ catMaybes [ fmap (("SecurityGroupIds",) . toJSON) _elasticsearchDomainVPCOptionsSecurityGroupIds , fmap (("SubnetIds",) . toJSON) _elasticsearchDomainVPCOptionsSubnetIds ] -- | Constructor for 'ElasticsearchDomainVPCOptions' containing required -- fields as arguments. elasticsearchDomainVPCOptions :: ElasticsearchDomainVPCOptions elasticsearchDomainVPCOptions = ElasticsearchDomainVPCOptions { _elasticsearchDomainVPCOptionsSecurityGroupIds = Nothing , _elasticsearchDomainVPCOptionsSubnetIds = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-vpcoptions.html#cfn-elasticsearch-domain-vpcoptions-securitygroupids edvpcoSecurityGroupIds :: Lens' ElasticsearchDomainVPCOptions (Maybe (ValList Text)) edvpcoSecurityGroupIds = lens _elasticsearchDomainVPCOptionsSecurityGroupIds (\s a -> s { _elasticsearchDomainVPCOptionsSecurityGroupIds = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-vpcoptions.html#cfn-elasticsearch-domain-vpcoptions-subnetids edvpcoSubnetIds :: Lens' ElasticsearchDomainVPCOptions (Maybe (ValList Text)) edvpcoSubnetIds = lens _elasticsearchDomainVPCOptionsSubnetIds (\s a -> s { _elasticsearchDomainVPCOptionsSubnetIds = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/ElasticsearchDomainVPCOptions.hs
mit
2,153
0
12
205
264
151
113
27
1
{-# LANGUAGE OverloadedStrings #-} module Homework.Week11.Reference where import Control.Monad (void) import Data.Int (Int64) import Data.Text (Text) import Database.SQLite.Simple (Connection, Only(..), query, execute_, execute, lastInsertRowId, query_, open, close) import Homework.Week11.Types dbName :: String dbName = "week11.sqlite" insertUser :: FullName -> EmailAddress -> IO UserId insertUser fn ea = do conn <- open dbName execute conn " INSERT INTO `users` \ \ (full_name, email_address) \ \ VALUES (?, ?)" (fn, ea) close conn lastInsertRowId conn >>= return . UserId getUsers :: IO [User] getUsers = do conn <- open dbName query_ conn " SELECT id, full_name, email_address \ \ FROM `users`" deleteUserById :: UserId -> IO () deleteUserById userId = do conn <- open dbName execute conn " DELETE FROM `users` \ \ WHERE id = ?" (Only userId) close conn getUserById :: UserId -> IO (Maybe User) getUserById userId = do conn <- open dbName rs <- query conn " SELECT id, full_name, email_address \ \ FROM `users` \ \ WHERE id = ?" (Only userId) close conn case rs of [] -> return Nothing [user] -> return (Just user) setupDB :: IO () setupDB = do conn <- open dbName execute_ conn "DROP TABLE IF EXISTS `users`" execute_ conn " CREATE TABLE IF NOT EXISTS `users` \ \ ( id INTEGER PRIMARY KEY \ \ , full_name VARCHAR NOT NULL \ \ , email_address VARCHAR NOT NULL) " close conn
laser/cis-194-winter-2016
src/Homework/Week11/Reference.hs
mit
1,503
0
12
352
398
198
200
47
2
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-} module SMCDEL.Explicit.K where import Control.Arrow ((&&&),second) import Data.Containers.ListUtils (nubInt,nubOrd) import Data.Dynamic import Data.List (sort,(\\),delete,intercalate,intersect) import qualified Data.Map.Strict as M import Data.Map.Strict ((!)) import Data.Maybe (isJust,isNothing) import Test.QuickCheck import SMCDEL.Language import SMCDEL.Explicit.S5 (Action,Bisimulation,HasWorlds,World,worldsOf) import SMCDEL.Internal.Help (alleqWith,lfp) import SMCDEL.Internal.TexDisplay newtype KripkeModel = KrM (M.Map World (M.Map Prp Bool, M.Map Agent [World])) deriving (Eq,Ord,Show) instance Pointed KripkeModel World type PointedModel = (KripkeModel, World) instance Pointed KripkeModel [World] type MultipointedModel = (KripkeModel,[World]) distinctVal :: KripkeModel -> Bool distinctVal (KrM m) = M.size m == length (nubOrd (map fst (M.elems m))) instance HasWorlds KripkeModel where worldsOf (KrM m) = M.keys m instance HasVocab KripkeModel where vocabOf (KrM m) = M.keys $ fst (head (M.elems m)) instance HasAgents KripkeModel where agentsOf (KrM m) = M.keys $ snd (head (M.elems m)) relOfIn :: Agent -> KripkeModel -> M.Map World [World] relOfIn i (KrM m) = M.map (\x -> snd x ! i) m truthsInAt :: KripkeModel -> World -> [Prp] truthsInAt (KrM m) w = M.keys (M.filter id (fst (m ! w))) instance KripkeLike KripkeModel where directed = const True getNodes m = map (show . fromEnum &&& labelOf) (worldsOf m) where labelOf w = "$" ++ tex (truthsInAt m w) ++ "$" getEdges m = concat [ [ (a, show $ fromEnum w, show $ fromEnum v) | v <- relOfIn a m ! w ] | w <- worldsOf m, a <- agentsOf m ] getActuals = const [] instance KripkeLike PointedModel where directed = directed . fst getNodes = getNodes . fst getEdges = getEdges . fst getActuals = return . show . fromEnum . snd instance KripkeLike MultipointedModel where directed = directed . fst getNodes = getNodes . fst getEdges = getEdges . fst getActuals = map (show . fromEnum) . snd instance TexAble KripkeModel where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot instance TexAble PointedModel where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot instance TexAble MultipointedModel where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot instance Arbitrary KripkeModel where arbitrary = do nonActualWorlds <- sublistOf [1..8] let worlds = 0 : nonActualWorlds m <- mapM (\w -> do myAssignment <- zip defaultVocabulary <$> infiniteListOf (choose (True,False)) myRelations <- mapM (\a -> do reachables <- sublistOf worlds return (a,reachables) ) defaultAgents return (w, (M.fromList myAssignment, M.fromList myRelations)) -- FIXME avoid fromList, build M.map directly? ) worlds return $ KrM $ M.fromList m shrink krm = [ krm `withoutWorld` w | length (worldsOf krm) > 1, w <- delete 0 (worldsOf krm) ] withoutWorld :: KripkeModel -> World -> KripkeModel withoutWorld (KrM m) w = KrM $ M.map (second (M.map (delete w))) $ M.delete w m eval :: PointedModel -> Form -> Bool eval _ Top = True eval _ Bot = False eval (m,w) (PrpF p) = p `elem` truthsInAt m w eval pm (Neg f) = not $ eval pm f eval pm (Conj fs) = all (eval pm) fs eval pm (Disj fs) = any (eval pm) fs eval pm (Xor fs) = odd $ length (filter id $ map (eval pm) fs) eval pm (Impl f g) = not (eval pm f) || eval pm g eval pm (Equi f g) = eval pm f == eval pm g eval pm (Forall ps f) = eval pm (foldl singleForall f ps) where singleForall g p = Conj [ substit p Top g, substit p Bot g ] eval pm (Exists ps f) = eval pm (foldl singleExists f ps) where singleExists g p = Disj [ substit p Top g, substit p Bot g ] eval (KrM m,w) (K i f) = all (\w' -> eval (KrM m,w') f) (snd (m ! w) ! i) eval (KrM m,w) (Kw i f) = alleqWith (\w' -> eval (KrM m,w') f) (snd (m ! w) ! i) eval (m,w) (Ck ags form) = all (\w' -> eval (m,w') form) (groupRel m ags w) eval (m,w) (Ckw ags form) = alleqWith (\w' -> eval (m,w') form) (groupRel m ags w) eval (m,w) (PubAnnounce f g) = not (eval (m,w) f) || eval (update (m,w) f) g eval (m,w) (PubAnnounceW f g) = eval (update m aform, w) g where aform | eval (m,w) f = f | otherwise = Neg f eval (m,w) (Announce listeners f g) = not (eval (m,w) f) || eval newm g where newm = (m,w) `update` announceAction (agentsOf m) listeners f eval (m,w) (AnnounceW listeners f g) = eval newm g where newm = (m,w) `update` announceAction (agentsOf m) listeners aform aform | eval (m,w) f = f | otherwise = Neg f eval pm (Dia (Dyn dynLabel d) f) = case fromDynamic d of Just pactm -> eval pm (preOf (pactm :: PointedActionModel)) && eval (pm `update` pactm) f Nothing -> error $ "cannot update Kripke model with '" ++ dynLabel ++ "':\n " ++ show d instance Semantics PointedModel where isTrue = eval instance Semantics KripkeModel where isTrue m = isTrue (m, worldsOf m) instance Semantics MultipointedModel where isTrue (m,ws) f = all (\w -> isTrue (m,w) f) ws groupRel :: KripkeModel -> [Agent] -> World -> [World] groupRel (KrM m) ags w = sort $ lfp extend (oneStepReachFrom w) where oneStepReachFrom x = concat [ snd (m ! x) ! a | a <- ags ] extend xs = nubInt $ xs ++ concatMap oneStepReachFrom xs instance Update KripkeModel Form where checks = [ ] -- unpointed models can always be updated with any formula unsafeUpdate (KrM m) f = KrM newm where newm = M.mapMaybeWithKey isin m isin w' (v,rs) | eval (KrM m,w') f = Just (v, M.map newr rs) | otherwise = Nothing newr = filter (`elem` M.keys newm) instance Update PointedModel Form where unsafeUpdate (m,w) f = (unsafeUpdate m f, w) instance Update MultipointedModel Form where unsafeUpdate (m,ws) f = let newm = unsafeUpdate m f in (newm, ws `intersect` worldsOf newm) announceAction :: [Agent] -> [Agent] -> Form -> PointedActionModel announceAction everyone listeners f = (ActM am, 1) where am = M.fromList [ (1, Act { pre = f, post = M.empty, rel = M.fromList $ [(i,[1]) | i <- listeners] ++ [(i,[2]) | i <- everyone \\ listeners] } ) , (2, Act { pre = Top, post = M.empty, rel = M.fromList [(i,[2]) | i <- everyone] } ) ] checkBisim :: Bisimulation -> KripkeModel -> KripkeModel -> Bool checkBisim [] _ _ = False checkBisim z m1 m2 = all (\(w1,w2) -> (truthsInAt m1 w1 == truthsInAt m2 w2) -- same valuation && and [ any (\v2 -> (v1,v2) `elem` z) (relOfIn ag m2 ! w2) -- forth | ag <- agentsOf m1, v1 <- relOfIn ag m1 ! w1 ] && and [ any (\v1 -> (v1,v2) `elem` z) (relOfIn ag m1 ! w1) -- back | ag <- agentsOf m2, v2 <- relOfIn ag m2 ! w2 ] ) z checkBisimPointed :: Bisimulation -> PointedModel -> PointedModel -> Bool checkBisimPointed z (m1,w1) (m2,w2) = (w1,w2) `elem` z && checkBisim z m1 m2 type Status = Maybe Form type StatusMap = M.Map (World,World) Status diff :: KripkeModel -> KripkeModel -> StatusMap diff m1 m2 = lfp step start where -- initialize using differences in atomic propositions given by valuation start = M.fromList [ ((w1,w2), propDiff (truthsInAt m1 w1) (truthsInAt m2 w2)) | w1 <- worldsOf m1, w2 <- worldsOf m2 ] propDiff ps qs | ps \\ qs /= [] = Just $ PrpF $ head (ps \\ qs) | qs \\ ps /= [] = Just $ Neg $ PrpF $ head (qs \\ ps) | otherwise = Nothing -- until a fixpoint is reached, update the map using all relations step curMap = M.mapWithKey (updateAt curMap) curMap updateAt _ _ (Just f) = Just f updateAt curMap (w1,w2) Nothing = case -- forth [ Neg . K i . Neg . Conj $ [ f | w2' <- w2's, let Just f = curMap ! (w1',w2') ] | i <- agentsOf m1 , let w2's = relOfIn i m2 ! w2 , w1' <- relOfIn i m1 ! w1 , all (\w2' -> isJust $ curMap ! (w1',w2')) w2's ] ++ -- back [ K i . Disj $ [ f | w1' <- w1's, let Just f = curMap ! (w1',w2') ] | i <- agentsOf m1 , let w1's = relOfIn i m1 ! w1 , w2' <- relOfIn i m2 ! w2 , all (\w1' -> isJust $ curMap ! (w1',w2')) w1's ] of [] -> Nothing (f:_) -> Just f diffPointed :: PointedModel -> PointedModel -> Either Bisimulation Form diffPointed (m1,w1) (m2,w2) = case diff m1 m2 ! (w1,w2) of Nothing -> Left $ M.keys $ M.filter isNothing (diff m1 m2) Just f -> Right f generatedSubmodel :: PointedModel -> PointedModel generatedSubmodel (KrM m, cur) = (KrM newm, cur) where newm = M.mapMaybeWithKey isin m isin w' (v,rs) | w' `elem` reachable = Just (v, M.map newr rs) | otherwise = Nothing newr = filter (`elem` M.keys newm) reachable = lfp follow [cur] where follow xs = sort . nubInt $ concat [ snd (m ! x) ! a | x <- xs, a <- agentsOf (KrM m) ] type PostCondition = M.Map Prp Form data Act = Act {pre :: Form, post :: PostCondition, rel :: M.Map Agent [Action]} deriving (Eq,Ord,Show) -- | Extend `post` to all propositions safepost :: Act -> Prp -> Form safepost ch p | p `elem` M.keys (post ch) = post ch ! p | otherwise = PrpF p newtype ActionModel = ActM (M.Map Action Act) deriving (Eq,Ord,Show) instance HasAgents ActionModel where agentsOf (ActM am) = M.keys $ rel (head (M.elems am)) instance HasPrecondition ActionModel where preOf _ = Top instance Pointed ActionModel Action type PointedActionModel = (ActionModel, Action) instance HasPrecondition PointedActionModel where preOf (ActM am, actual) = pre (am ! actual) instance Pointed ActionModel [Action] type MultipointedActionModel = (ActionModel, [Action]) instance HasPrecondition MultipointedActionModel where preOf (ActM am, as) = Disj [ pre (am ! a) | a <- as ] instance Update KripkeModel ActionModel where checks = [haveSameAgents] unsafeUpdate m (ActM am) = let (newModel,_) = unsafeUpdate (m, worldsOf m) (ActM am, M.keys am) in newModel instance Update PointedModel PointedActionModel where checks = [haveSameAgents,preCheck] unsafeUpdate (m, w) (actm, a) = let (newModel,[newWorld]) = unsafeUpdate (m, [w]) (actm, [a]) in (newModel,newWorld) instance Update PointedModel MultipointedActionModel where checks = [haveSameAgents,preCheck] unsafeUpdate (m, w) mpactm = let (newModel,[newWorld]) = unsafeUpdate (m, [w]) mpactm in (newModel,newWorld) instance Update MultipointedModel PointedActionModel where checks = [haveSameAgents] -- do not check precondition! unsafeUpdate mpm (actm, a) = unsafeUpdate mpm (actm, [a]) instance Update MultipointedModel MultipointedActionModel where checks = [haveSameAgents] unsafeUpdate (KrM m, ws) (ActM am, facts) = (KrM $ M.fromList (map annotate worldPairs), newActualWorlds) where worldPairs = zip (concat [ [ (s, a) | eval (KrM m, s) (pre $ am ! a) ] | s <- M.keys m, a <- M.keys am ]) [0..] newActualWorlds = [ k | ((w,a),k) <- worldPairs, w `elem` ws, a `elem` facts ] annotate ((s,a),news) = (news , (newval, M.fromList (map reachFor (agentsOf (KrM m))))) where newval = M.mapWithKey applyPC (fst $ m ! s) applyPC p oldbit | p `elem` M.keys (post (am ! a)) = eval (KrM m,s) (post (am ! a) ! p) | otherwise = oldbit reachFor i = (i, [ news' | ((s',a'),news') <- worldPairs, s' `elem` snd (m ! s) ! i, a' `elem` rel (am ! a) ! i ]) instance Arbitrary ActionModel where arbitrary = do let allactions = [0..3] BF f <- sized $ randomboolformWith defaultVocabulary BF g <- sized $ randomboolformWith defaultVocabulary BF h <- sized $ randomboolformWith defaultVocabulary let myPres = Top : map simplify [f,g,h] myPosts <- mapM (\_ -> do proptochange <- elements defaultVocabulary postconcon <- elements $ [Top,Bot] ++ map PrpF defaultVocabulary return $ M.fromList [ (proptochange, postconcon) ] ) allactions myRels <- mapM (\k -> do reachList <- sublistOf allactions return $ M.fromList $ ("1",[k]) : [ (ag,reachList) | ag <- tail defaultAgents ] ) allactions return $ ActM $ M.fromList [ (k::Action, Act (myPres !! k) (myPosts !! k) (myRels !! k)) | k <- allactions ] shrink (ActM am) = [ ActM $ removeFromRels k $ M.delete k am | k <- M.keys am, k /= 0 ] where removeFromRels = M.map . removeFrom where removeFrom k c = c { rel = M.map (delete k) (rel c) } instance KripkeLike ActionModel where directed = const True getNodes (ActM am) = map (show &&& labelOf) (M.keys am) where labelOf a = concat [ "$\\begin{array}{c} ? " , tex (pre (am ! a)) , "\\\\" , intercalate "\\\\" (map showPost (M.toList $ post (am ! a))) , "\\end{array}$" ] showPost (p,f) = tex p ++ " := " ++ tex f getEdges (ActM am) = concat [ [ (i, show a, show b) | b <- rel (am ! a) ! i ] | a <- M.keys am, i <- agentsOf (ActM am) ] getActuals = const [ ] instance TexAble ActionModel where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot instance KripkeLike PointedActionModel where directed = directed . fst getNodes = getNodes . fst getEdges = getEdges . fst getActuals (_, a) = [show a] instance TexAble PointedActionModel where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot instance KripkeLike MultipointedActionModel where directed = directed . fst getNodes = getNodes . fst getEdges = getEdges . fst getActuals (_, as) = map show as instance TexAble MultipointedActionModel where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot
jrclogic/SMCDEL
src/SMCDEL/Explicit/K.hs
gpl-2.0
13,818
18
21
3,268
6,109
3,197
2,912
-1
-1
{- | Module : $Header$ Description : Handpicked model of OMDoc subset Copyright : (c) Hendrik Iben, Uni Bremen 2005-2007 License : GPLv2 or higher, see LICENSE.txt Maintainer : hiben@informatik.uni-bremen.de Stability : provisional Portability : non-portable Model of a handpicked subset from OMDoc -} module OMDoc.OMDocInterface where import qualified Network.URI as URI import Data.Char import qualified Data.Word as Word import Common.Doc import Common.DocUtils import Common.Id omdocDefaultNamespace :: String omdocDefaultNamespace = "http://www.mathweb.org/omdoc" instance Pretty URI.URI where pretty u = text $ (URI.uriToString id u "") instance Ord URI.URI where compare u1 u2 = compare (showURI u1) (showURI u2) -- | OMDocRef is anyURI type OMDocRef = URI.URI -- | OMDocRefs modelled as a list type OMDocRefs = [OMDocRef] showURI :: URI.URI -> String showURI uri = (URI.uriToString id uri) "" -- Try to parse an URI (so Network.URI needs not be imported) mkOMDocRef :: String -> Maybe OMDocRef mkOMDocRef = URI.parseURIReference mkSymbolRef :: XmlId -> OMDocRef mkSymbolRef xid = case URI.parseURIReference ("#" ++ xid) of Nothing -> error ("Invalid Symbol-Id! (" ++ xid ++ ")") (Just u) -> u mkExtSymbolRef :: XmlId -> XmlId -> OMDocRef mkExtSymbolRef xcd xid = case URI.parseURIReference (xcd ++ "#" ++ xid) of Nothing -> error "Invalid Reference!" (Just u) -> u -- OMDoc -- | used for ids type XmlId = String -- | used for names, pcdata type XmlString = String -- | OMDoc data OMDoc = OMDoc { omdocId :: XmlId , omdocTheories :: [Theory] , omdocInclusions :: [Inclusion] } deriving (Show) addTheories :: OMDoc -> [Theory] -> OMDoc addTheories omdoc theories = omdoc { omdocTheories = (omdocTheories omdoc) ++ theories } addInclusions :: OMDoc -> [Inclusion] -> OMDoc addInclusions omdoc inclusions = omdoc { omdocInclusions = (omdocInclusions omdoc) ++ inclusions } -- Theory data Theory = Theory { theoryId :: XmlId , theoryConstitutives :: [Constitutive] , theoryPresentations :: [Presentation] , theoryComment :: Maybe String } deriving Show instance Pretty Theory where pretty t = text $ (show (theoryId t)) ++ case (theoryComment t) of Nothing -> "" (Just c) -> ": " ++ (show c) instance Eq Theory where t1 == t2 = (theoryId t1) == (theoryId t2) instance Ord Theory where t1 `compare` t2 = (theoryId t1) `compare` (theoryId t2) -- debug showTheory :: Theory -> String showTheory t = show (t { theoryPresentations = [] }) -- | Type (scope) of import data ImportsType = ITLocal | ITGlobal deriving Show -- | Imports (for Theory) data Imports = Imports { importsFrom :: OMDocRef , importsMorphism :: Maybe Morphism , importsId :: Maybe XmlId , importsType :: ImportsType , importsConservativity :: Conservativity } deriving Show -- | Presentation data Presentation = Presentation { presentationForId :: XmlId , presentationSystem :: Maybe XmlString , presentationUses :: [Use] } deriving (Show, Eq) mkPresentationS :: XmlId -> XmlString -> [Use] -> Presentation mkPresentationS forid presSystem = Presentation forid (Just presSystem) mkPresentation :: XmlId -> [Use] -> Presentation mkPresentation forid = Presentation forid Nothing addUse :: Presentation -> Use -> Presentation addUse pres use = pres { presentationUses = (presentationUses pres) ++ [use] } -- | Use for Presentation data Use = Use { useFormat :: XmlString , useValue :: String } deriving (Show, Eq) mkUse :: XmlString -> String -> Use mkUse = Use -- | SymbolRole for Symbol data SymbolRole = SRType | SRSort | SRObject | SRBinder | SRAttribution | SRSemanticAttribution | SRError deriving (Eq, Ord) instance Show SymbolRole where show SRType = "type" show SRSort = "sort" show SRObject = "object" show SRBinder = "binder" show SRAttribution = "attribution" show SRSemanticAttribution = "semantic-attribution" show SRError = "error" instance Read SymbolRole where readsPrec _ s = case map toLower s of "type" -> [(SRType, [])] "sort" -> [(SRSort, [])] "object" -> [(SRObject, [])] "binder" -> [(SRBinder, [])] "attribution" -> [(SRAttribution, [])] "semantic-attribution" -> [(SRSemanticAttribution, [])] "error" -> [(SRError, [])] _ -> [] -- | Symbol data Symbol = Symbol { symbolGeneratedFrom :: Maybe XmlId , symbolId :: XmlId , symbolRole :: SymbolRole , symbolType :: Maybe Type } deriving (Show, Eq, Ord) instance GetRange Symbol instance Pretty Symbol where pretty s = text $ show s mkSymbolE :: Maybe XmlId -> XmlId -> SymbolRole -> Maybe Type -> Symbol mkSymbolE = Symbol mkSymbol :: XmlId -> SymbolRole -> Symbol mkSymbol xid sr = mkSymbolE Nothing xid sr Nothing -- | Type data Type = Type { typeSystem :: Maybe URI.URI , typeOMDocMathObject :: OMDocMathObject } deriving (Show, Eq, Ord) mkType :: Maybe OMDocRef -> OMDocMathObject -> Type mkType = Type {- | OMDoc Theory constitutive elements + convenience additions (ADT) -} data Constitutive = CAx Axiom | CDe Definition | CSy Symbol | CIm Imports | CAd ADT | CCo { conComCmt :: String, conComCon :: Constitutive } deriving Show mkCAx :: Axiom -> Constitutive mkCAx = CAx mkCDe :: Definition -> Constitutive mkCDe = CDe mkCSy :: Symbol -> Constitutive mkCSy = CSy mkCIm :: Imports -> Constitutive mkCIm = CIm mkCAd :: ADT -> Constitutive mkCAd = CAd mkCCo :: String -> Constitutive -> Constitutive mkCCo = CCo isAxiom :: Constitutive -> Bool isAxiom (CAx {}) = True isAxiom _ = False isDefinition :: Constitutive -> Bool isDefinition (CDe {}) = True isDefinition _ = False isSymbol :: Constitutive -> Bool isSymbol (CSy {}) = True isSymbol _ = False isImports :: Constitutive -> Bool isImports (CIm {}) = True isImports _ = False isADT :: Constitutive -> Bool isADT (CAd {}) = True isADT _ = False isCommented :: Constitutive -> Bool isCommented (CCo {}) = True isCommented _ = False getIdsForPresentation :: Constitutive -> [XmlId] getIdsForPresentation (CAx a) = [axiomName a] getIdsForPresentation (CDe _) = [] getIdsForPresentation (CSy s) = [symbolId s] getIdsForPresentation (CIm _) = [] getIdsForPresentation (CAd a) = map sortDefName (adtSortDefs a) getIdsForPresentation (CCo {}) = [] -- | Axiom data Axiom = Axiom { axiomName :: XmlId , axiomCMPs :: [CMP] , axiomFMPs :: [FMP] } deriving Show mkAxiom :: XmlId -> [CMP] -> [FMP] -> Axiom mkAxiom = Axiom -- | CMP data CMP = CMP { cmpContent :: MText } deriving Show mkCMP :: MText -> CMP mkCMP = CMP -- | FMP data FMP = FMP { fmpLogic :: Maybe XmlString , fmpContent :: Either OMObject ([Assumption], [Conclusion]) } deriving Show -- | Assumption (incomplete) data Assumption = Assumption deriving Show data Conclusion = Conclusion deriving Show -- | Definition (incomplete) data Definition = Definition { definitionId :: XmlId , definitionCMPs :: [CMP] , definitionFMPs :: [FMP] } deriving Show mkDefinition :: XmlId -> [CMP] -> [FMP] -> Definition mkDefinition = Definition -- | ADT data ADT = ADT { adtId :: Maybe XmlId , adtSortDefs :: [SortDef] } deriving Show data SortType = STFree | STGenerated | STLoose mkADT :: [SortDef] -> ADT mkADT = ADT Nothing mkADTEx :: Maybe XmlId -> [SortDef] -> ADT mkADTEx = ADT instance Show SortType where show STFree = "free" show STGenerated = "generated" show STLoose = "loose" instance Read SortType where readsPrec _ s = if s == "free" then [(STFree, "")] else if s == "generated" then [(STGenerated, "")] else if s == "loose" then [(STLoose, "")] else [] -- | SortDef data SortDef = SortDef { sortDefName :: XmlId , sortDefRole :: SymbolRole , sortDefType :: SortType , sortDefConstructors :: [Constructor] , sortDefInsorts :: [Insort] , sortDefRecognizers :: [Recognizer] } deriving Show mkSortDefE :: XmlId -> SymbolRole -> SortType -> [Constructor] -> [Insort] -> [Recognizer] -> SortDef mkSortDefE = SortDef mkSortDef :: XmlId -> [Constructor] -> [Insort] -> [Recognizer] -> SortDef mkSortDef xid cons ins recs = mkSortDefE xid SRSort STFree cons ins recs -- | Constructor data Constructor = Constructor { constructorName :: XmlId , constructorRole :: SymbolRole , constructorArguments :: [Type] } deriving Show mkConstructorE :: XmlId -> SymbolRole -> [Type] -> Constructor mkConstructorE = Constructor mkConstructor :: XmlId -> [Type] -> Constructor mkConstructor xid types = Constructor xid SRObject types -- | Insort data Insort = Insort { insortFor :: OMDocRef } deriving Show mkInsort :: OMDocRef -> Insort mkInsort = Insort -- | Recognizer data Recognizer = Recognizer { recognizerName :: XmlId } deriving Show mkRecognizer :: XmlId -> Recognizer mkRecognizer = Recognizer -- | Inclusion-Conservativity data Conservativity = CNone | CMonomorphism | CDefinitional | CConservative deriving (Eq, Ord) instance Show Conservativity where show CNone = "none" show CMonomorphism = "monomorphism" show CDefinitional = "definitional" show CConservative = "conservative" instance Read Conservativity where readsPrec _ s = case s of "monomorphism" -> [(CMonomorphism, "")] "definitional" -> [(CDefinitional, "")] "conservative" -> [(CConservative, "")] "none" -> [(CNone, "")] _ -> [] -- | Inclusions data Inclusion = TheoryInclusion { inclusionFrom :: OMDocRef , inclusionTo :: OMDocRef , inclusionMorphism :: Maybe Morphism , inclusionId :: Maybe XmlId , inclusionConservativity :: Conservativity } | AxiomInclusion { inclusionFrom :: OMDocRef , inclusionTo :: OMDocRef , inclusionMorphism :: Maybe Morphism , inclusionId :: Maybe XmlId , inclusionConservativity :: Conservativity } deriving (Show, Eq, Ord) instance Pretty Inclusion where pretty = text . show -- | OMDoc Morphism data Morphism = Morphism { morphismId :: Maybe XmlId , morphismHiding :: [XmlId] , morphismBase :: [XmlId] , morphismRequations :: [ ( MText, MText ) ] } deriving (Show, Eq, Ord) instance Pretty Morphism where pretty m = text $ show m -- Mathematical Text (incomplete) data MText = MTextText String | MTextTerm String | MTextPhrase String | MTextOM OMObject deriving (Show, Eq, Ord) -- OMDoc Mathematical Object data OMDocMathObject = OMOMOBJ OMObject | OMLegacy String | OMMath String deriving (Show, Eq, Ord) -- | OMOBJ data OMObject = OMObject OMElement deriving (Show, Eq, Ord) mkOMOBJ :: OMElementClass e => e -> OMObject mkOMOBJ e = OMObject (toElement e) -- | OMS data OMSymbol = OMS { omsCDBase :: Maybe OMDocRef , omsCD :: XmlId , omsName :: XmlId } deriving (Show, Eq, Ord) mkOMS :: Maybe OMDocRef -> XmlId -> XmlId -> OMSymbol mkOMS = OMS mkOMSE :: Maybe OMDocRef -> XmlId -> XmlId -> OMElement mkOMSE mref xcd xid = toElement $ mkOMS mref xcd xid -- | OMI data OMInteger = OMI { omiInt :: Int } deriving (Show, Eq, Ord) mkOMI :: Int -> OMInteger mkOMI = OMI mkOMIE :: Int -> OMElement mkOMIE i = toElement $ mkOMI i -- | A Variable can be a OMV or an OMATTR data OMVariable = OMVS OMSimpleVariable | OMVA OMAttribution deriving (Show, Eq, Ord) -- | Class to use something as a Variable class OMVariableClass a where toVariable :: a -> OMVariable fromVariable :: OMVariable -> Maybe a instance OMVariableClass OMVariable where toVariable = id fromVariable = Just . id instance OMVariableClass OMSimpleVariable where toVariable = OMVS fromVariable (OMVS x) = Just x fromVariable _ = Nothing mkOMVar :: Either OMSimpleVariable OMAttribution -> OMVariable mkOMVar (Left oms) = OMVS oms mkOMVar (Right omattr) = OMVA omattr mkOMVarE :: Either OMSimpleVariable OMAttribution -> OMElement mkOMVarE v = toElement $ mkOMVar v -- | OMV data OMSimpleVariable = OMV { omvName :: XmlString } deriving (Show, Eq, Ord) mkOMSimpleVar :: XmlString -> OMSimpleVariable mkOMSimpleVar = OMV mkOMSimpleVarE :: XmlString -> OMElement mkOMSimpleVarE xid = toElement $ mkOMSimpleVar xid mkOMVSVar :: XmlString -> OMVariable mkOMVSVar = OMVS . mkOMSimpleVar mkOMVSVarE :: XmlString -> OMElement mkOMVSVarE xid = toElement $ OMVS $ mkOMSimpleVar xid -- | OMATTR data OMAttribution = OMATTR { omattrATP :: OMAttributionPart , omattrElem :: OMElement } deriving (Show, Eq, Ord) instance OMVariableClass OMAttribution where toVariable = OMVA fromVariable (OMVA x) = Just x fromVariable _ = Nothing mkOMATTR :: OMElementClass e => OMAttributionPart -> e -> OMAttribution mkOMATTR omatp ome = OMATTR { omattrATP = omatp , omattrElem = toElement ome } mkOMATTRE :: OMElementClass e => OMAttributionPart -> e -> OMElement mkOMATTRE omatp ome = toElement $ mkOMATTR omatp ome -- | OMATP data OMAttributionPart = OMATP { omatpAttribs :: [(OMSymbol, OMElement)] } deriving (Show, Eq, Ord) mkOMATP :: OMElementClass e => [(OMSymbol, e)] -> OMAttributionPart mkOMATP = OMATP . map (\ (s, e) -> (s, toElement e)) -- | OMBVAR data OMBindingVariables = OMBVAR { ombvarVars :: [OMVariable] } deriving (Show, Eq, Ord) mkOMBVAR :: OMVariableClass e => [e] -> OMBindingVariables mkOMBVAR = OMBVAR . map toVariable {- | OMB is actually just a bytearray for storing data. [Char] representation is forced by export from Codec.Base64 -} data OMBase64 = OMB { -- decoded Content ombContent :: [Word.Word8] } deriving (Show, Eq, Ord) mkOMB :: [Word.Word8] -> OMBase64 mkOMB = OMB mkOMBE :: [Word.Word8] -> OMElement mkOMBE = toElement . mkOMB mkOMBWords :: [Word.Word8] -> OMBase64 mkOMBWords = OMB mkOMBWordsE :: [Word.Word8] -> OMElement mkOMBWordsE = toElement . mkOMBWords getOMBWords :: OMBase64 -> [Word.Word8] getOMBWords omb = ombContent omb -- | OMSTR data OMString = OMSTR { omstrText :: String } deriving (Show, Eq, Ord) mkOMSTR :: String -> OMString mkOMSTR = OMSTR mkOMSTRE :: String -> OMElement mkOMSTRE = toElement . mkOMSTR -- | OMF data OMFloat = OMF { omfFloat :: Float } deriving (Show, Eq, Ord) mkOMF :: Float -> OMFloat mkOMF = OMF mkOMFE :: Float -> OMElement mkOMFE = toElement . mkOMF -- | OMA data OMApply = OMA { omaElements :: [OMElement] } deriving (Show, Eq, Ord) mkOMA :: OMElementClass e => [e] -> OMApply mkOMA [] = error "Empty list of elements for OMA!" mkOMA l = OMA (map toElement l) mkOMAE :: OMElementClass e => [e] -> OMElement mkOMAE = toElement . mkOMA -- | OME data OMError = OME { omeSymbol :: OMSymbol , omeExtra :: [OMElement] } deriving (Show, Eq, Ord) mkOME :: OMElementClass e => OMSymbol -> [e] -> OMError mkOME _ [] = error "Empty list of elements for OME!" mkOME s e = OME s (map toElement e) mkOMEE :: OMElementClass e => OMSymbol -> [e] -> OMElement mkOMEE s e = toElement $ mkOME s e -- | OMR data OMReference = OMR { omrHRef :: URI.URI } deriving (Show, Eq, Ord) mkOMR :: URI.URI -> OMReference mkOMR = OMR mkOMRE :: URI.URI -> OMElement mkOMRE = toElement . mkOMR -- | OMB data OMBind = OMBIND { ombindBinder :: OMElement , ombindVariables :: OMBindingVariables , ombindExpression :: OMElement } deriving (Show, Eq, Ord) mkOMBIND :: (OMElementClass e1, OMElementClass e2) => e1 -> OMBindingVariables -> e2 -> OMBind mkOMBIND binder bvars expr = OMBIND { ombindBinder = toElement binder , ombindVariables = bvars , ombindExpression = toElement expr } mkOMBINDE :: (OMElementClass e1, OMElementClass e2) => e1 -> OMBindingVariables -> e2 -> OMElement mkOMBINDE binder vars expr = toElement $ mkOMBIND binder vars expr -- | Elements for Open Math data OMElement = OMES OMSymbol | OMEV OMSimpleVariable | OMEI OMInteger | OMEB OMBase64 | OMESTR OMString | OMEF OMFloat | OMEA OMApply | OMEBIND OMBind | OMEE OMError | OMEATTR OMAttribution | OMER OMReference | OMEC (Maybe OMElement) String deriving (Show, Eq, Ord) -- | insert a comment into an open-math structure (use with caution...) mkOMComment :: String -> OMElement mkOMComment = OMEC Nothing mkOMCommented :: OMElementClass e => String -> e -> OMElement mkOMCommented cmt e = OMEC (Just (toElement e)) cmt -- | Class of Elements for Open Math class OMElementClass a where toElement :: a -> OMElement fromElement :: OMElement -> Maybe a instance OMElementClass OMSymbol where toElement = OMES fromElement (OMES oms) = Just oms fromElement _ = Nothing instance OMElementClass OMInteger where toElement = OMEI fromElement (OMEI x) = Just x fromElement _ = Nothing instance OMElementClass OMVariable where toElement (OMVS omv) = OMEV omv toElement (OMVA omattr) = OMEATTR omattr fromElement (OMEV omv) = Just (OMVS omv) fromElement (OMEATTR omattr) = Just (OMVA omattr) fromElement _ = Nothing instance OMElementClass OMSimpleVariable where toElement omv = OMEV omv fromElement (OMEV omv) = Just omv fromElement _ = Nothing instance OMElementClass OMAttribution where toElement = OMEATTR fromElement (OMEATTR x) = Just x fromElement _ = Nothing instance OMElementClass OMBase64 where toElement = OMEB fromElement (OMEB x) = Just x fromElement _ = Nothing instance OMElementClass OMString where toElement = OMESTR fromElement (OMESTR x) = Just x fromElement _ = Nothing instance OMElementClass OMFloat where toElement = OMEF fromElement (OMEF x) = Just x fromElement _ = Nothing instance OMElementClass OMApply where toElement = OMEA fromElement (OMEA x) = Just x fromElement _ = Nothing instance OMElementClass OMError where toElement = OMEE fromElement (OMEE x) = Just x fromElement _ = Nothing instance OMElementClass OMReference where toElement = OMER fromElement (OMER x) = Just x fromElement _ = Nothing instance OMElementClass OMBind where toElement = OMEBIND fromElement (OMEBIND x) = Just x fromElement _ = Nothing instance OMElementClass OMElement where toElement = id fromElement = Just . id
nevrenato/Hets_Fork
OMDoc/OMDocInterface.hs
gpl-2.0
18,827
0
12
4,480
5,453
2,996
2,457
545
2
module BioInf.RNAdesign.Graph where import Control.Arrow (first,second) import Data.Graph.Inductive.Basic import Data.Graph.Inductive.Graph import Data.Graph.Inductive.PatriciaTree import Data.Graph.Inductive.Query import Data.List (nub,partition) import Biobase.Secondary.Diagrams -- | Given the one to many structures, create the independent graphs, where -- each graph describes a set of dependent edges in the basepairing. independentGraphs xs | null xs = error "You should give at least one structure. If you did, you have found a bug, yeah!" | any ((/=lx).length) xs = error $ "At least one structure with different length was found" ++ show xs | otherwise = independentComponents g where lx = length $ head xs g = mkUnionGraph xs -- | Union of several graphs, created from secondary structure. mkUnionGraph = unions . map (pairlistToGraph . (mkD1S :: String -> D1Secondary)) -- | Given k graphs, each with nodes [1..n], provide the union of all edges. unions :: Eq b => [Gr a b] -> Gr a b unions [] = empty unions xs@(x:_) = mkGraph (labNodes x) (nub $ concatMap labEdges xs) where -- | Given a pairlist, generate the secondary structure graph. pairlistToGraph :: D1Secondary -> Gr () () pairlistToGraph d = let (len, ps) = fromD1S d in undir $ mkUGraph [0..len -1] ps -- | Split the graph into (simple, complex) components. The simple components -- can trivially be filled with any pair. The complex components require an Ear -- or Woffle decomposition. Simple components are acyclic. independentComponents :: DynGraph gr => gr () () -> [gr () ()] independentComponents g = map f $ components g where f ns = mkUGraph ns (edges g) -- | Tests if the given graph is bipartite, which is true if the even/odd BST -- trees contain no edges isBipartite :: DynGraph gr => gr a b -> Bool isBipartite g = e && o where -- True, if there are no edges (e,o) = both (null . edges) $ f g -- generate the (even,odd) distance graphs f g = both (flip delNodes g . map fst) . partition (even . snd) $ level (fst $ head $ labNodes g) g both f = second f . first f
choener/RNAdesign
BioInf/RNAdesign/Graph.hs
gpl-3.0
2,104
0
12
406
563
293
270
30
1
module Data.Conduit.Extra ( group ) where import Data.Conduit group :: Resource m => Int -> Conduit a m [a] group n = conduitState st0 push close where close (_, xs) = return [xs] push (m, xs) x = do let n' = m + 1 return $ if n' == n then StateProducing st0 [reverse $ x : xs] else StateProducing (n', x : xs) [] st0 = (0, [])
br0ns/hindsight
src/Data/Conduit/Extra.hs
gpl-3.0
418
0
14
160
174
93
81
15
2
{- Copyright 2013 Matthew Gordon. This file is part of Gramophone. Gramophone is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Gramophone is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Gramophone. If not, see <http://www.gnu.org/licenses/>. -} {-# LANGUAGE TemplateHaskell #-} module Gramophone.Core.MediaController.Types ( Track(..), PlayerState(..), GenericResult(..), PlayCommand(..), StopCommand(..), ShutDownCommand(..), StatusCommand(..), StatusResult(..), ReadTagsCommand(..), ReadTagsResult(..), MediaController(..) ) where import Gramophone.Core.MediaController.CommandMVar import Gramophone.Core.MediaController.Tags import Data.Time.Clock (DiffTime, UTCTime(..)) data ReadTagsCommand = ReadTags FilePath data ReadTagsResult = TagsSuccess Tags | TagsFail String data Track = Track { trackFilename :: FilePath, trackLength :: DiffTime, trackCurrentTime :: DiffTime } data PlayerState = Playing Track | Stopped data GenericResult = Success | ErrorMessage String data PlayCommand = Play FilePath data StopCommand = Stop data ShutDownCommand = ShutDown data StatusCommand = GetStatus data StatusResult = Status PlayerState UTCTime data MediaController = MediaController { playCommand :: CommandMVar PlayCommand GenericResult, stopCommand :: CommandMVar StopCommand GenericResult, shutDownCommand :: CommandMVar ShutDownCommand (), statusCommand :: CommandMVar StatusCommand StatusResult , readTagsCommand :: CommandMVar ReadTagsCommand ReadTagsResult }
matthewscottgordon/gramophone
src/Gramophone/Core/MediaController/Types.hs
gpl-3.0
2,131
0
10
477
302
189
113
36
0
{-| Module : Generator Description : Helpful functions for generating JSON from Clausewitz values Copyright : (c) Matthew Bauer, 2016 Maintainer : mjbauer95@gmail.com Stability : experimental Generate JSON data from parsed values within Clausewitz text assets. These provide commonly used methods for creating meaningful data from parsed values. -} module Generator where import qualified ClausewitzText import Data.Aeson import Data.Map hiding (null, foldr') import Data.Text hiding (empty, takeWhile, singleton, foldr, null) import qualified Data.HashMap.Lazy import Data.Foldable toMapO :: [ClausewitzText.Value] -> Value toMapO s = Object $ Data.HashMap.Lazy.fromList (Data.Map.toList (toMap s)) toMap :: [ClausewitzText.Value] -> Map Text Value toMap = foldr' (union . toMap') empty toMap' :: ClausewitzText.Value -> Map Text Value toMap' (ClausewitzText.Identifier a) = singleton (pack a) (String $ pack a) toMap' (ClausewitzText.Float a) = singleton (pack $ show a) (Number (fromRational (toRational a))) toMap' (ClausewitzText.Assignment a b) = singleton (pack a) (toMap'' b) toMap' _ = empty toMap'' :: ClausewitzText.Value -> Value toMap'' (ClausewitzText.Identifier s) = String (pack s) toMap'' (ClausewitzText.Float f) = Number (fromRational (toRational f)) toMap'' (ClausewitzText.Bool b) = Bool b toMap'' (ClausewitzText.String s) = String (pack s) toMap'' (ClausewitzText.List s) = toMapO s toMap'' _ = Null genmapForwards :: [ClausewitzText.Value] -> Map String Value genmapForwards = foldr' (union . genmapForwards') empty where genmapForwards' (ClausewitzText.Assignment n (ClausewitzText.List b)) = singleton n (toMapO b) genmapForwards' _ = empty genmap :: [ClausewitzText.Value] -> Map String String genmap = foldr' (union . genmap') empty where genmap' (ClausewitzText.Assignment n (ClausewitzText.List b)) = each n b genmap' _ = empty each n = foldr' (union . each' n) empty each' n (ClausewitzText.Float b) = singleton (show (truncate b :: Integer)) n each' _ _ = empty genmapS :: [ClausewitzText.Value] -> Map String String genmapS = foldr' (union . genmap') empty where genmap' (ClausewitzText.Assignment n (ClausewitzText.List b)) = each n b genmap' _ = empty each n = foldr' (union . each' n) empty each' n (ClausewitzText.String b) = singleton b n each' _ _ = empty genmapI :: [ClausewitzText.Value] -> Map String String genmapI = foldr' (union . genmap') empty where genmap' (ClausewitzText.Assignment n (ClausewitzText.List b)) = each n b genmap' _ = empty each n = foldr' (union . each' n) empty each' n (ClausewitzText.Identifier b) = singleton b n each' _ _ = empty
matthewbauer/eu4-parser
Generator.hs
gpl-3.0
2,710
0
12
484
927
473
454
51
3
module Main (main) where import qualified ReadConfig.Tests import qualified Test.Tasty as T import qualified Types.Tests import qualified UnitConversions.Tests import qualified Utils.Tests main :: IO () main = T.defaultMain $ T.testGroup "Tests" [ ReadConfig.Tests.tests, Types.Tests.tests, Utils.Tests.tests, UnitConversions.Tests.test ]
JackKiefer/herms
test/Main.hs
gpl-3.0
389
0
8
87
93
58
35
15
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -- | -- Module : Network.Google.Internal.Auth -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : provisional -- Portability : non-portable (GHC extensions) -- -- Internal types and helpers for constructing OAuth credentials. module Network.Google.Internal.Auth where import Control.Exception.Lens (exception) import Control.Lens (Prism', prism, (<&>)) import Control.Monad.Catch import Control.Monad.IO.Class (MonadIO (..)) import Crypto.PubKey.RSA.Types (PrivateKey) import Data.Aeson import Data.Aeson.Types (Pair) import Data.ByteArray (ByteArray) import Data.ByteArray.Encoding import Data.ByteString (ByteString) import Data.ByteString.Builder () import qualified Data.ByteString.Lazy as LBS import Data.String (IsString) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Data.Time import Data.X509 (PrivKey (..)) import Data.X509.Memory (readKeyFileFromMemory) import GHC.TypeLits (Symbol) import Network.Google.Internal.Logger import Network.Google.Prelude import Network.HTTP.Conduit (HttpException, Manager) import qualified Network.HTTP.Conduit as Client import Network.HTTP.Types (Status, hContentType) -- | The supported credential mechanisms. data Credentials (s :: [Symbol]) = FromMetadata !ServiceId -- ^ Obtain and refresh access tokens from the underlying GCE host metadata -- at @http:\/\/169.254.169.254@. | FromClient !OAuthClient !(OAuthCode s) -- ^ Obtain and refresh access tokens using the specified client secret -- and authorization code obtained from. -- -- See the <https://developers.google.com/accounts/docs/OAuth2InstalledApp OAuth2 Installed Application> -- documentation for more information. | FromAccount !ServiceAccount -- ^ Use the specified @service_account@ and scopes to sign and request -- an access token. The 'ServiceAccount' will also be used for subsequent -- token refreshes. -- -- A 'ServiceAccount' is typically generated through the -- Google Developer Console. | FromUser !AuthorizedUser -- ^ Use the specified @authorized_user@ to obtain and refresh access tokens. -- -- An 'AuthorizedUser' is typically created by the @gcloud init@ command -- of the Google CloudSDK Tools. {-| Service Account credentials which are typically generated/download from the Google Developer console of the following form: > { > \"type\": \"service_account\", > \"private_key_id\": \"303ad77e5efdf2ce952DFa\", > \"private_key\": \"-----BEGIN PRIVATE KEY-----\n...\n\", > \"client_email\": \"email@serviceaccount.com\", > \"client_id\": \"035-2-310.useraccount.com\" > } The private key is used to sign a JSON Web Token (JWT) of the grant_type @urn:ietf:params:oauth:grant-type:jwt-bearer@, which is sent to 'accountsURL' to obtain a valid 'OAuthToken'. This process requires explicitly specifying which 'Scope's the resulting 'OAuthToken' is authorized to access. /See:/ <https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority Delegating authority to your service account>. -} data ServiceAccount = ServiceAccount { _serviceId :: !ClientId , _serviceEmail :: !Text , _serviceKeyId :: !Text , _servicePrivateKey :: !PrivateKey , _serviceAccountUser :: !(Maybe Text) } deriving (Eq, Show) instance FromJSON ServiceAccount where parseJSON = withObject "service_account" $ \o -> do bs <- Text.encodeUtf8 <$> o .: "private_key" k <- case listToMaybe (readKeyFileFromMemory bs) of Just (PrivKeyRSA k) -> pure k _ -> fail "Unable to parse key contents from \"private_key\"" ServiceAccount <$> o .: "client_id" <*> o .: "client_email" <*> o .: "private_key_id" <*> pure k <*> pure Nothing {-| Authorized User credentials which are typically generated by the Cloud SDK Tools such as @gcloud init@, of the following form: > { > \"type\": \"authorized_user\", > \"client_id\": \"32555940559.apps.googleusercontent.com\", > \"client_secret\": \"Zms2qjJy2998hD4CTg2ejr2\", > \"refresh_token\": \"1/B3gM1x35v.VtqffS1n5w-rSJ\" > } The secret and refresh token are used to obtain a valid 'OAuthToken' from 'accountsURL' using grant_type @refresh_token@. -} data AuthorizedUser = AuthorizedUser { _userId :: !ClientId , _userRefresh :: !RefreshToken , _userSecret :: !GSecret } deriving (Eq, Show) instance ToJSON AuthorizedUser where toJSON (AuthorizedUser i r s) = object [ "client_id" .= i , "refresh_token" .= r , "client_secret" .= s ] instance FromJSON AuthorizedUser where parseJSON = withObject "authorized_user" $ \o -> AuthorizedUser <$> o .: "client_id" <*> o .: "refresh_token" <*> o .: "client_secret" -- | A client identifier and accompanying secret used to obtain/refresh a token. data OAuthClient = OAuthClient { _clientId :: !ClientId , _clientSecret :: !GSecret } deriving (Eq, Show) {-| An OAuth bearer type token of the following form: > { > \"token_type\": \"Bearer\", > \"access_token\": \"eyJhbGci...\", > \"refresh_token\": \"1/B3gq9K...\", > \"expires_in\": 3600, > ... > } The '_tokenAccess' field will be inserted verbatim into the @Authorization: Bearer ...@ header for all HTTP requests. -} data OAuthToken (s :: [Symbol]) = OAuthToken { _tokenAccess :: !AccessToken , _tokenRefresh :: !(Maybe RefreshToken) , _tokenExpiry :: !UTCTime } deriving (Eq, Show) instance FromJSON (UTCTime -> OAuthToken s) where parseJSON = withObject "bearer" $ \o -> do t <- o .: "access_token" r <- o .:? "refresh_token" e <- o .: "expires_in" <&> fromInteger pure (OAuthToken t r . addUTCTime e) -- | An OAuth client authorization code. newtype OAuthCode (s :: [Symbol]) = OAuthCode Text deriving (Eq, Ord, Show, Read, IsString, Generic, Typeable, FromJSON, ToJSON) instance ToHttpApiData (OAuthCode s) where toQueryParam (OAuthCode c) = c toHeader (OAuthCode c) = Text.encodeUtf8 c -- | An error thrown when attempting to read/write AuthN/AuthZ information. data AuthError = RetrievalError HttpException | MissingFileError FilePath | InvalidFileError FilePath Text | TokenRefreshError Status Text (Maybe Text) | FileExistError FilePath deriving (Show, Typeable) instance Exception AuthError class AsAuthError a where -- | A general authentication error. _AuthError :: Prism' a AuthError {-# MINIMAL _AuthError #-} -- | An error occured while communicating over HTTP with either then -- local metadata or remote accounts.google.com endpoints. _RetrievalError :: Prism' a HttpException -- | The specified default credentials file could not be found. _MissingFileError :: Prism' a FilePath -- | An error occured parsing the default credentials file. _InvalidFileError :: Prism' a (FilePath, Text) -- | An error occured when attempting to refresh a token. _TokenRefreshError :: Prism' a (Status, Text, Maybe Text) _RetrievalError = _AuthError . _RetrievalError _MissingFileError = _AuthError . _MissingFileError _InvalidFileError = _AuthError . _InvalidFileError _TokenRefreshError = _AuthError . _TokenRefreshError instance AsAuthError SomeException where _AuthError = exception instance AsAuthError AuthError where _AuthError = id _RetrievalError = prism RetrievalError $ \case RetrievalError e -> Right e x -> Left x _MissingFileError = prism MissingFileError $ \case MissingFileError f -> Right f x -> Left x _InvalidFileError = prism (uncurry InvalidFileError) (\case InvalidFileError f e -> Right (f, e) x -> Left x) _TokenRefreshError = prism (\(s, e, d) -> TokenRefreshError s e d) (\case TokenRefreshError s e d -> Right (s, e, d) x -> Left x) data RefreshError = RefreshError { _error :: !Text , _description :: !(Maybe Text) } instance FromJSON RefreshError where parseJSON = withObject "refresh_error" $ \o -> RefreshError <$> o .: "error" <*> o .:? "error_description" -- | @https://accounts.google.com/o/oauth2/v2/auth@. accountsURL :: Text accountsURL = "https://accounts.google.com/o/oauth2/v2/auth" accountsRequest :: Client.Request accountsRequest = Client.defaultRequest { Client.host = "accounts.google.com" , Client.port = 443 , Client.secure = True , Client.method = "POST" , Client.path = "/o/oauth2/v2/auth" , Client.requestHeaders = [ (hContentType, "application/x-www-form-urlencoded") ] } -- | @https://www.googleapis.com/oauth2/v4/token@. tokenURL :: Text tokenURL = "https://www.googleapis.com/oauth2/v4/token" tokenRequest :: Client.Request tokenRequest = Client.defaultRequest { Client.host = "www.googleapis.com" , Client.port = 443 , Client.secure = True , Client.method = "POST" , Client.path = "/oauth2/v4/token" , Client.requestHeaders = [ (hContentType, "application/x-www-form-urlencoded") ] } refreshRequest :: (MonadIO m, MonadCatch m) => Client.Request -> Logger -> Manager -> m (OAuthToken s) refreshRequest rq l m = do logDebug l rq -- debug:ClientRequest rs <- liftIO (Client.httpLbs rq m) `catch` (throwM . RetrievalError) let bs = Client.responseBody rs s = Client.responseStatus rs logDebug l rs -- debug:ClientResponse logTrace l $ "[Response Body]\n" <> bs -- trace:ResponseBody if fromEnum s == 200 then success s bs else failure s bs where success s bs = do f <- parseErr s bs ts <- liftIO getCurrentTime pure (f ts) failure s bs = do let e = "Failure refreshing token from " <> host <> path logError l $ "[Refresh Error] " <> build e case parseLBS bs of Right x -> refreshErr s (_error x) (_description x) Left _ -> refreshErr s e Nothing parseErr s bs = case parseLBS bs of Right !x -> pure x Left e -> do logError l $ "[Parse Error] Failure parsing token refresh " <> build e refreshErr s e Nothing refreshErr :: MonadThrow m => Status -> Text -> Maybe Text -> m a refreshErr s e = throwM . TokenRefreshError s e host = Text.decodeUtf8 (Client.host rq) path = Text.decodeUtf8 (Client.path rq) parseLBS :: FromJSON a => LBS.ByteString -> Either Text a parseLBS = either (Left . Text.pack) Right . eitherDecode' base64Encode :: [Pair] -> ByteString base64Encode = base64 . LBS.toStrict . encode . object base64 :: ByteArray a => a -> ByteString base64 = convertToBase Base64URLUnpadded textBody :: Text -> RequestBody textBody = Client.RequestBodyBS . Text.encodeUtf8
brendanhay/gogol
gogol/src/Network/Google/Internal/Auth.hs
mpl-2.0
12,403
0
17
3,462
2,184
1,184
1,000
247
4
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AppEngine.Apps.Services.Versions.Instances.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets instance information. -- -- /See:/ <https://cloud.google.com/appengine/docs/admin-api/ Google App Engine Admin API Reference> for @appengine.apps.services.versions.instances.get@. module Network.Google.Resource.AppEngine.Apps.Services.Versions.Instances.Get ( -- * REST Resource AppsServicesVersionsInstancesGetResource -- * Creating a Request , appsServicesVersionsInstancesGet , AppsServicesVersionsInstancesGet -- * Request Lenses , asvigXgafv , asvigInstancesId , asvigUploadProtocol , asvigPp , asvigAccessToken , asvigUploadType , asvigVersionsId , asvigBearerToken , asvigAppsId , asvigServicesId , asvigCallback ) where import Network.Google.AppEngine.Types import Network.Google.Prelude -- | A resource alias for @appengine.apps.services.versions.instances.get@ method which the -- 'AppsServicesVersionsInstancesGet' request conforms to. type AppsServicesVersionsInstancesGetResource = "v1" :> "apps" :> Capture "appsId" Text :> "services" :> Capture "servicesId" Text :> "versions" :> Capture "versionsId" Text :> "instances" :> Capture "instancesId" Text :> QueryParam "$.xgafv" Text :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Instance -- | Gets instance information. -- -- /See:/ 'appsServicesVersionsInstancesGet' smart constructor. data AppsServicesVersionsInstancesGet = AppsServicesVersionsInstancesGet' { _asvigXgafv :: !(Maybe Text) , _asvigInstancesId :: !Text , _asvigUploadProtocol :: !(Maybe Text) , _asvigPp :: !Bool , _asvigAccessToken :: !(Maybe Text) , _asvigUploadType :: !(Maybe Text) , _asvigVersionsId :: !Text , _asvigBearerToken :: !(Maybe Text) , _asvigAppsId :: !Text , _asvigServicesId :: !Text , _asvigCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AppsServicesVersionsInstancesGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'asvigXgafv' -- -- * 'asvigInstancesId' -- -- * 'asvigUploadProtocol' -- -- * 'asvigPp' -- -- * 'asvigAccessToken' -- -- * 'asvigUploadType' -- -- * 'asvigVersionsId' -- -- * 'asvigBearerToken' -- -- * 'asvigAppsId' -- -- * 'asvigServicesId' -- -- * 'asvigCallback' appsServicesVersionsInstancesGet :: Text -- ^ 'asvigInstancesId' -> Text -- ^ 'asvigVersionsId' -> Text -- ^ 'asvigAppsId' -> Text -- ^ 'asvigServicesId' -> AppsServicesVersionsInstancesGet appsServicesVersionsInstancesGet pAsvigInstancesId_ pAsvigVersionsId_ pAsvigAppsId_ pAsvigServicesId_ = AppsServicesVersionsInstancesGet' { _asvigXgafv = Nothing , _asvigInstancesId = pAsvigInstancesId_ , _asvigUploadProtocol = Nothing , _asvigPp = True , _asvigAccessToken = Nothing , _asvigUploadType = Nothing , _asvigVersionsId = pAsvigVersionsId_ , _asvigBearerToken = Nothing , _asvigAppsId = pAsvigAppsId_ , _asvigServicesId = pAsvigServicesId_ , _asvigCallback = Nothing } -- | V1 error format. asvigXgafv :: Lens' AppsServicesVersionsInstancesGet (Maybe Text) asvigXgafv = lens _asvigXgafv (\ s a -> s{_asvigXgafv = a}) -- | Part of \`name\`. See documentation of \`appsId\`. asvigInstancesId :: Lens' AppsServicesVersionsInstancesGet Text asvigInstancesId = lens _asvigInstancesId (\ s a -> s{_asvigInstancesId = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). asvigUploadProtocol :: Lens' AppsServicesVersionsInstancesGet (Maybe Text) asvigUploadProtocol = lens _asvigUploadProtocol (\ s a -> s{_asvigUploadProtocol = a}) -- | Pretty-print response. asvigPp :: Lens' AppsServicesVersionsInstancesGet Bool asvigPp = lens _asvigPp (\ s a -> s{_asvigPp = a}) -- | OAuth access token. asvigAccessToken :: Lens' AppsServicesVersionsInstancesGet (Maybe Text) asvigAccessToken = lens _asvigAccessToken (\ s a -> s{_asvigAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). asvigUploadType :: Lens' AppsServicesVersionsInstancesGet (Maybe Text) asvigUploadType = lens _asvigUploadType (\ s a -> s{_asvigUploadType = a}) -- | Part of \`name\`. See documentation of \`appsId\`. asvigVersionsId :: Lens' AppsServicesVersionsInstancesGet Text asvigVersionsId = lens _asvigVersionsId (\ s a -> s{_asvigVersionsId = a}) -- | OAuth bearer token. asvigBearerToken :: Lens' AppsServicesVersionsInstancesGet (Maybe Text) asvigBearerToken = lens _asvigBearerToken (\ s a -> s{_asvigBearerToken = a}) -- | Part of \`name\`. Name of the resource requested. Example: -- apps\/myapp\/services\/default\/versions\/v1\/instances\/instance-1. asvigAppsId :: Lens' AppsServicesVersionsInstancesGet Text asvigAppsId = lens _asvigAppsId (\ s a -> s{_asvigAppsId = a}) -- | Part of \`name\`. See documentation of \`appsId\`. asvigServicesId :: Lens' AppsServicesVersionsInstancesGet Text asvigServicesId = lens _asvigServicesId (\ s a -> s{_asvigServicesId = a}) -- | JSONP asvigCallback :: Lens' AppsServicesVersionsInstancesGet (Maybe Text) asvigCallback = lens _asvigCallback (\ s a -> s{_asvigCallback = a}) instance GoogleRequest AppsServicesVersionsInstancesGet where type Rs AppsServicesVersionsInstancesGet = Instance type Scopes AppsServicesVersionsInstancesGet = '["https://www.googleapis.com/auth/appengine.admin", "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only"] requestClient AppsServicesVersionsInstancesGet'{..} = go _asvigAppsId _asvigServicesId _asvigVersionsId _asvigInstancesId _asvigXgafv _asvigUploadProtocol (Just _asvigPp) _asvigAccessToken _asvigUploadType _asvigBearerToken _asvigCallback (Just AltJSON) appEngineService where go = buildClient (Proxy :: Proxy AppsServicesVersionsInstancesGetResource) mempty
rueshyna/gogol
gogol-appengine/gen/Network/Google/Resource/AppEngine/Apps/Services/Versions/Instances/Get.hs
mpl-2.0
7,655
0
24
1,888
1,099
637
462
167
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Dataflow.Types.Sum -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.Dataflow.Types.Sum where import Network.Google.Prelude
rueshyna/gogol
gogol-dataflow/gen/Network/Google/Dataflow/Types/Sum.hs
mpl-2.0
600
0
4
109
29
25
4
8
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.VideoIntelligence.Types.Product -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.VideoIntelligence.Types.Product where import Network.Google.Prelude import Network.Google.VideoIntelligence.Types.Sum -- -- /See:/ 'googleRpc_StatusDetailsItem' smart constructor. newtype GoogleRpc_StatusDetailsItem = GoogleRpc_StatusDetailsItem' { _grsdiAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleRpc_StatusDetailsItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'grsdiAddtional' googleRpc_StatusDetailsItem :: HashMap Text JSONValue -- ^ 'grsdiAddtional' -> GoogleRpc_StatusDetailsItem googleRpc_StatusDetailsItem pGrsdiAddtional_ = GoogleRpc_StatusDetailsItem' {_grsdiAddtional = _Coerce # pGrsdiAddtional_} -- | Properties of the object. Contains field \'type with type URL. grsdiAddtional :: Lens' GoogleRpc_StatusDetailsItem (HashMap Text JSONValue) grsdiAddtional = lens _grsdiAddtional (\ s a -> s{_grsdiAddtional = a}) . _Coerce instance FromJSON GoogleRpc_StatusDetailsItem where parseJSON = withObject "GoogleRpcStatusDetailsItem" (\ o -> GoogleRpc_StatusDetailsItem' <$> (parseJSONObject o)) instance ToJSON GoogleRpc_StatusDetailsItem where toJSON = toJSON . _grsdiAddtional -- | Explicit content annotation (based on per-frame visual signals only). If -- no explicit content has been detected in a frame, no annotations are -- present for that frame. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_ExplicitContentAnnotation' smart constructor. data GoogleCloudVideointelligenceV1beta2_ExplicitContentAnnotation = GoogleCloudVideointelligenceV1beta2_ExplicitContentAnnotation' { _gcvvecaFrames :: !(Maybe [GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame]) , _gcvvecaVersion :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_ExplicitContentAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvecaFrames' -- -- * 'gcvvecaVersion' googleCloudVideointelligenceV1beta2_ExplicitContentAnnotation :: GoogleCloudVideointelligenceV1beta2_ExplicitContentAnnotation googleCloudVideointelligenceV1beta2_ExplicitContentAnnotation = GoogleCloudVideointelligenceV1beta2_ExplicitContentAnnotation' {_gcvvecaFrames = Nothing, _gcvvecaVersion = Nothing} -- | All video frames where explicit content was detected. gcvvecaFrames :: Lens' GoogleCloudVideointelligenceV1beta2_ExplicitContentAnnotation [GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame] gcvvecaFrames = lens _gcvvecaFrames (\ s a -> s{_gcvvecaFrames = a}) . _Default . _Coerce -- | Feature version. gcvvecaVersion :: Lens' GoogleCloudVideointelligenceV1beta2_ExplicitContentAnnotation (Maybe Text) gcvvecaVersion = lens _gcvvecaVersion (\ s a -> s{_gcvvecaVersion = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_ExplicitContentAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2ExplicitContentAnnotation" (\ o -> GoogleCloudVideointelligenceV1beta2_ExplicitContentAnnotation' <$> (o .:? "frames" .!= mempty) <*> (o .:? "version")) instance ToJSON GoogleCloudVideointelligenceV1beta2_ExplicitContentAnnotation where toJSON GoogleCloudVideointelligenceV1beta2_ExplicitContentAnnotation'{..} = object (catMaybes [("frames" .=) <$> _gcvvecaFrames, ("version" .=) <$> _gcvvecaVersion]) -- | Alternative hypotheses (a.k.a. n-best list). -- -- /See:/ 'googleCloudVideointelligenceV1_SpeechRecognitionAlternative' smart constructor. data GoogleCloudVideointelligenceV1_SpeechRecognitionAlternative = GoogleCloudVideointelligenceV1_SpeechRecognitionAlternative' { _gcvvsraConfidence :: !(Maybe (Textual Double)) , _gcvvsraWords :: !(Maybe [GoogleCloudVideointelligenceV1_WordInfo]) , _gcvvsraTranscript :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_SpeechRecognitionAlternative' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvsraConfidence' -- -- * 'gcvvsraWords' -- -- * 'gcvvsraTranscript' googleCloudVideointelligenceV1_SpeechRecognitionAlternative :: GoogleCloudVideointelligenceV1_SpeechRecognitionAlternative googleCloudVideointelligenceV1_SpeechRecognitionAlternative = GoogleCloudVideointelligenceV1_SpeechRecognitionAlternative' { _gcvvsraConfidence = Nothing , _gcvvsraWords = Nothing , _gcvvsraTranscript = Nothing } -- | Output only. The confidence estimate between 0.0 and 1.0. A higher -- number indicates an estimated greater likelihood that the recognized -- words are correct. This field is set only for the top alternative. This -- field is not guaranteed to be accurate and users should not rely on it -- to be always provided. The default of 0.0 is a sentinel value indicating -- \`confidence\` was not set. gcvvsraConfidence :: Lens' GoogleCloudVideointelligenceV1_SpeechRecognitionAlternative (Maybe Double) gcvvsraConfidence = lens _gcvvsraConfidence (\ s a -> s{_gcvvsraConfidence = a}) . mapping _Coerce -- | Output only. A list of word-specific information for each recognized -- word. Note: When \`enable_speaker_diarization\` is set to true, you will -- see all the words from the beginning of the audio. gcvvsraWords :: Lens' GoogleCloudVideointelligenceV1_SpeechRecognitionAlternative [GoogleCloudVideointelligenceV1_WordInfo] gcvvsraWords = lens _gcvvsraWords (\ s a -> s{_gcvvsraWords = a}) . _Default . _Coerce -- | Transcript text representing the words that the user spoke. gcvvsraTranscript :: Lens' GoogleCloudVideointelligenceV1_SpeechRecognitionAlternative (Maybe Text) gcvvsraTranscript = lens _gcvvsraTranscript (\ s a -> s{_gcvvsraTranscript = a}) instance FromJSON GoogleCloudVideointelligenceV1_SpeechRecognitionAlternative where parseJSON = withObject "GoogleCloudVideointelligenceV1SpeechRecognitionAlternative" (\ o -> GoogleCloudVideointelligenceV1_SpeechRecognitionAlternative' <$> (o .:? "confidence") <*> (o .:? "words" .!= mempty) <*> (o .:? "transcript")) instance ToJSON GoogleCloudVideointelligenceV1_SpeechRecognitionAlternative where toJSON GoogleCloudVideointelligenceV1_SpeechRecognitionAlternative'{..} = object (catMaybes [("confidence" .=) <$> _gcvvsraConfidence, ("words" .=) <$> _gcvvsraWords, ("transcript" .=) <$> _gcvvsraTranscript]) -- | Video frame level annotation results for text annotation (OCR). Contains -- information regarding timestamp and bounding box locations for the -- frames containing detected OCR text snippets. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_TextFrame' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_TextFrame = GoogleCloudVideointelligenceV1p3beta1_TextFrame' { _gcvvtfRotatedBoundingBox :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly) , _gcvvtfTimeOffSet :: !(Maybe GDuration) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_TextFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvtfRotatedBoundingBox' -- -- * 'gcvvtfTimeOffSet' googleCloudVideointelligenceV1p3beta1_TextFrame :: GoogleCloudVideointelligenceV1p3beta1_TextFrame googleCloudVideointelligenceV1p3beta1_TextFrame = GoogleCloudVideointelligenceV1p3beta1_TextFrame' {_gcvvtfRotatedBoundingBox = Nothing, _gcvvtfTimeOffSet = Nothing} -- | Bounding polygon of the detected text for this frame. gcvvtfRotatedBoundingBox :: Lens' GoogleCloudVideointelligenceV1p3beta1_TextFrame (Maybe GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly) gcvvtfRotatedBoundingBox = lens _gcvvtfRotatedBoundingBox (\ s a -> s{_gcvvtfRotatedBoundingBox = a}) -- | Timestamp of this frame. gcvvtfTimeOffSet :: Lens' GoogleCloudVideointelligenceV1p3beta1_TextFrame (Maybe Scientific) gcvvtfTimeOffSet = lens _gcvvtfTimeOffSet (\ s a -> s{_gcvvtfTimeOffSet = a}) . mapping _GDuration instance FromJSON GoogleCloudVideointelligenceV1p3beta1_TextFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1TextFrame" (\ o -> GoogleCloudVideointelligenceV1p3beta1_TextFrame' <$> (o .:? "rotatedBoundingBox") <*> (o .:? "timeOffset")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_TextFrame where toJSON GoogleCloudVideointelligenceV1p3beta1_TextFrame'{..} = object (catMaybes [("rotatedBoundingBox" .=) <$> _gcvvtfRotatedBoundingBox, ("timeOffset" .=) <$> _gcvvtfTimeOffSet]) -- | Video segment level annotation results for face detection. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_FaceSegment' smart constructor. newtype GoogleCloudVideointelligenceV1p1beta1_FaceSegment = GoogleCloudVideointelligenceV1p1beta1_FaceSegment' { _gcvvfsSegment :: Maybe GoogleCloudVideointelligenceV1p1beta1_VideoSegment } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_FaceSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvfsSegment' googleCloudVideointelligenceV1p1beta1_FaceSegment :: GoogleCloudVideointelligenceV1p1beta1_FaceSegment googleCloudVideointelligenceV1p1beta1_FaceSegment = GoogleCloudVideointelligenceV1p1beta1_FaceSegment' {_gcvvfsSegment = Nothing} -- | Video segment where a face was detected. gcvvfsSegment :: Lens' GoogleCloudVideointelligenceV1p1beta1_FaceSegment (Maybe GoogleCloudVideointelligenceV1p1beta1_VideoSegment) gcvvfsSegment = lens _gcvvfsSegment (\ s a -> s{_gcvvfsSegment = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_FaceSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1FaceSegment" (\ o -> GoogleCloudVideointelligenceV1p1beta1_FaceSegment' <$> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_FaceSegment where toJSON GoogleCloudVideointelligenceV1p1beta1_FaceSegment'{..} = object (catMaybes [("segment" .=) <$> _gcvvfsSegment]) -- | Streaming annotation results corresponding to a portion of the video -- that is currently being processed. Only ONE type of annotation will be -- specified in the response. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults = GoogleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults' { _gcvvsvarShotAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_VideoSegment]) , _gcvvsvarLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation]) , _gcvvsvarFrameTimestamp :: !(Maybe GDuration) , _gcvvsvarObjectAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation]) , _gcvvsvarExplicitAnnotation :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvsvarShotAnnotations' -- -- * 'gcvvsvarLabelAnnotations' -- -- * 'gcvvsvarFrameTimestamp' -- -- * 'gcvvsvarObjectAnnotations' -- -- * 'gcvvsvarExplicitAnnotation' googleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults :: GoogleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults googleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults = GoogleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults' { _gcvvsvarShotAnnotations = Nothing , _gcvvsvarLabelAnnotations = Nothing , _gcvvsvarFrameTimestamp = Nothing , _gcvvsvarObjectAnnotations = Nothing , _gcvvsvarExplicitAnnotation = Nothing } -- | Shot annotation results. Each shot is represented as a video segment. gcvvsvarShotAnnotations :: Lens' GoogleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults [GoogleCloudVideointelligenceV1p3beta1_VideoSegment] gcvvsvarShotAnnotations = lens _gcvvsvarShotAnnotations (\ s a -> s{_gcvvsvarShotAnnotations = a}) . _Default . _Coerce -- | Label annotation results. gcvvsvarLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults [GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation] gcvvsvarLabelAnnotations = lens _gcvvsvarLabelAnnotations (\ s a -> s{_gcvvsvarLabelAnnotations = a}) . _Default . _Coerce -- | Timestamp of the processed frame in microseconds. gcvvsvarFrameTimestamp :: Lens' GoogleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults (Maybe Scientific) gcvvsvarFrameTimestamp = lens _gcvvsvarFrameTimestamp (\ s a -> s{_gcvvsvarFrameTimestamp = a}) . mapping _GDuration -- | Object tracking results. gcvvsvarObjectAnnotations :: Lens' GoogleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults [GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation] gcvvsvarObjectAnnotations = lens _gcvvsvarObjectAnnotations (\ s a -> s{_gcvvsvarObjectAnnotations = a}) . _Default . _Coerce -- | Explicit content annotation results. gcvvsvarExplicitAnnotation :: Lens' GoogleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults (Maybe GoogleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation) gcvvsvarExplicitAnnotation = lens _gcvvsvarExplicitAnnotation (\ s a -> s{_gcvvsvarExplicitAnnotation = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1StreamingVideoAnnotationResults" (\ o -> GoogleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults' <$> (o .:? "shotAnnotations" .!= mempty) <*> (o .:? "labelAnnotations" .!= mempty) <*> (o .:? "frameTimestamp") <*> (o .:? "objectAnnotations" .!= mempty) <*> (o .:? "explicitAnnotation")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults where toJSON GoogleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults'{..} = object (catMaybes [("shotAnnotations" .=) <$> _gcvvsvarShotAnnotations, ("labelAnnotations" .=) <$> _gcvvsvarLabelAnnotations, ("frameTimestamp" .=) <$> _gcvvsvarFrameTimestamp, ("objectAnnotations" .=) <$> _gcvvsvarObjectAnnotations, ("explicitAnnotation" .=) <$> _gcvvsvarExplicitAnnotation]) -- | Video annotation response. Included in the \`response\` field of the -- \`Operation\` returned by the \`GetOperation\` call of the -- \`google::longrunning::Operations\` service. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_AnnotateVideoResponse' smart constructor. newtype GoogleCloudVideointelligenceV1beta2_AnnotateVideoResponse = GoogleCloudVideointelligenceV1beta2_AnnotateVideoResponse' { _gcvvavrAnnotationResults :: Maybe [GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_AnnotateVideoResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvavrAnnotationResults' googleCloudVideointelligenceV1beta2_AnnotateVideoResponse :: GoogleCloudVideointelligenceV1beta2_AnnotateVideoResponse googleCloudVideointelligenceV1beta2_AnnotateVideoResponse = GoogleCloudVideointelligenceV1beta2_AnnotateVideoResponse' {_gcvvavrAnnotationResults = Nothing} -- | Annotation results for all videos specified in \`AnnotateVideoRequest\`. gcvvavrAnnotationResults :: Lens' GoogleCloudVideointelligenceV1beta2_AnnotateVideoResponse [GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults] gcvvavrAnnotationResults = lens _gcvvavrAnnotationResults (\ s a -> s{_gcvvavrAnnotationResults = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1beta2_AnnotateVideoResponse where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2AnnotateVideoResponse" (\ o -> GoogleCloudVideointelligenceV1beta2_AnnotateVideoResponse' <$> (o .:? "annotationResults" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1beta2_AnnotateVideoResponse where toJSON GoogleCloudVideointelligenceV1beta2_AnnotateVideoResponse'{..} = object (catMaybes [("annotationResults" .=) <$> _gcvvavrAnnotationResults]) -- | Word-specific information for recognized words. Word information is only -- included in the response when certain request parameters are set, such -- as \`enable_word_time_offsets\`. -- -- /See:/ 'googleCloudVideointelligenceV1_WordInfo' smart constructor. data GoogleCloudVideointelligenceV1_WordInfo = GoogleCloudVideointelligenceV1_WordInfo' { _gcvvwiStartTime :: !(Maybe GDuration) , _gcvvwiConfidence :: !(Maybe (Textual Double)) , _gcvvwiEndTime :: !(Maybe GDuration) , _gcvvwiWord :: !(Maybe Text) , _gcvvwiSpeakerTag :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_WordInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvwiStartTime' -- -- * 'gcvvwiConfidence' -- -- * 'gcvvwiEndTime' -- -- * 'gcvvwiWord' -- -- * 'gcvvwiSpeakerTag' googleCloudVideointelligenceV1_WordInfo :: GoogleCloudVideointelligenceV1_WordInfo googleCloudVideointelligenceV1_WordInfo = GoogleCloudVideointelligenceV1_WordInfo' { _gcvvwiStartTime = Nothing , _gcvvwiConfidence = Nothing , _gcvvwiEndTime = Nothing , _gcvvwiWord = Nothing , _gcvvwiSpeakerTag = Nothing } -- | Time offset relative to the beginning of the audio, and corresponding to -- the start of the spoken word. This field is only set if -- \`enable_word_time_offsets=true\` and only in the top hypothesis. This -- is an experimental feature and the accuracy of the time offset can vary. gcvvwiStartTime :: Lens' GoogleCloudVideointelligenceV1_WordInfo (Maybe Scientific) gcvvwiStartTime = lens _gcvvwiStartTime (\ s a -> s{_gcvvwiStartTime = a}) . mapping _GDuration -- | Output only. The confidence estimate between 0.0 and 1.0. A higher -- number indicates an estimated greater likelihood that the recognized -- words are correct. This field is set only for the top alternative. This -- field is not guaranteed to be accurate and users should not rely on it -- to be always provided. The default of 0.0 is a sentinel value indicating -- \`confidence\` was not set. gcvvwiConfidence :: Lens' GoogleCloudVideointelligenceV1_WordInfo (Maybe Double) gcvvwiConfidence = lens _gcvvwiConfidence (\ s a -> s{_gcvvwiConfidence = a}) . mapping _Coerce -- | Time offset relative to the beginning of the audio, and corresponding to -- the end of the spoken word. This field is only set if -- \`enable_word_time_offsets=true\` and only in the top hypothesis. This -- is an experimental feature and the accuracy of the time offset can vary. gcvvwiEndTime :: Lens' GoogleCloudVideointelligenceV1_WordInfo (Maybe Scientific) gcvvwiEndTime = lens _gcvvwiEndTime (\ s a -> s{_gcvvwiEndTime = a}) . mapping _GDuration -- | The word corresponding to this set of information. gcvvwiWord :: Lens' GoogleCloudVideointelligenceV1_WordInfo (Maybe Text) gcvvwiWord = lens _gcvvwiWord (\ s a -> s{_gcvvwiWord = a}) -- | Output only. A distinct integer value is assigned for every speaker -- within the audio. This field specifies which one of those speakers was -- detected to have spoken this word. Value ranges from 1 up to -- diarization_speaker_count, and is only set if speaker diarization is -- enabled. gcvvwiSpeakerTag :: Lens' GoogleCloudVideointelligenceV1_WordInfo (Maybe Int32) gcvvwiSpeakerTag = lens _gcvvwiSpeakerTag (\ s a -> s{_gcvvwiSpeakerTag = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1_WordInfo where parseJSON = withObject "GoogleCloudVideointelligenceV1WordInfo" (\ o -> GoogleCloudVideointelligenceV1_WordInfo' <$> (o .:? "startTime") <*> (o .:? "confidence") <*> (o .:? "endTime") <*> (o .:? "word") <*> (o .:? "speakerTag")) instance ToJSON GoogleCloudVideointelligenceV1_WordInfo where toJSON GoogleCloudVideointelligenceV1_WordInfo'{..} = object (catMaybes [("startTime" .=) <$> _gcvvwiStartTime, ("confidence" .=) <$> _gcvvwiConfidence, ("endTime" .=) <$> _gcvvwiEndTime, ("word" .=) <$> _gcvvwiWord, ("speakerTag" .=) <$> _gcvvwiSpeakerTag]) -- | Video frame level annotation results for explicit content. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_ExplicitContentFrame' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_ExplicitContentFrame = GoogleCloudVideointelligenceV1p1beta1_ExplicitContentFrame' { _gcvvecfTimeOffSet :: !(Maybe GDuration) , _gcvvecfPornographyLikelihood :: !(Maybe GoogleCloudVideointelligenceV1p1beta1_ExplicitContentFramePornographyLikelihood) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_ExplicitContentFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvecfTimeOffSet' -- -- * 'gcvvecfPornographyLikelihood' googleCloudVideointelligenceV1p1beta1_ExplicitContentFrame :: GoogleCloudVideointelligenceV1p1beta1_ExplicitContentFrame googleCloudVideointelligenceV1p1beta1_ExplicitContentFrame = GoogleCloudVideointelligenceV1p1beta1_ExplicitContentFrame' {_gcvvecfTimeOffSet = Nothing, _gcvvecfPornographyLikelihood = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this location. gcvvecfTimeOffSet :: Lens' GoogleCloudVideointelligenceV1p1beta1_ExplicitContentFrame (Maybe Scientific) gcvvecfTimeOffSet = lens _gcvvecfTimeOffSet (\ s a -> s{_gcvvecfTimeOffSet = a}) . mapping _GDuration -- | Likelihood of the pornography content.. gcvvecfPornographyLikelihood :: Lens' GoogleCloudVideointelligenceV1p1beta1_ExplicitContentFrame (Maybe GoogleCloudVideointelligenceV1p1beta1_ExplicitContentFramePornographyLikelihood) gcvvecfPornographyLikelihood = lens _gcvvecfPornographyLikelihood (\ s a -> s{_gcvvecfPornographyLikelihood = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_ExplicitContentFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1ExplicitContentFrame" (\ o -> GoogleCloudVideointelligenceV1p1beta1_ExplicitContentFrame' <$> (o .:? "timeOffset") <*> (o .:? "pornographyLikelihood")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_ExplicitContentFrame where toJSON GoogleCloudVideointelligenceV1p1beta1_ExplicitContentFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvecfTimeOffSet, ("pornographyLikelihood" .=) <$> _gcvvecfPornographyLikelihood]) -- | Config for OBJECT_TRACKING. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_ObjectTrackingConfig' smart constructor. newtype GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingConfig = GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingConfig' { _gcvvotcModel :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvotcModel' googleCloudVideointelligenceV1p3beta1_ObjectTrackingConfig :: GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingConfig googleCloudVideointelligenceV1p3beta1_ObjectTrackingConfig = GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingConfig' {_gcvvotcModel = Nothing} -- | Model to use for object tracking. Supported values: \"builtin\/stable\" -- (the default if unset) and \"builtin\/latest\". gcvvotcModel :: Lens' GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingConfig (Maybe Text) gcvvotcModel = lens _gcvvotcModel (\ s a -> s{_gcvvotcModel = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingConfig where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1ObjectTrackingConfig" (\ o -> GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingConfig' <$> (o .:? "model")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingConfig where toJSON GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingConfig'{..} = object (catMaybes [("model" .=) <$> _gcvvotcModel]) -- | Alternative hypotheses (a.k.a. n-best list). -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative = GoogleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative' { _gConfidence :: !(Maybe (Textual Double)) , _gWords :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_WordInfo]) , _gTranscript :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gConfidence' -- -- * 'gWords' -- -- * 'gTranscript' googleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative :: GoogleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative googleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative = GoogleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative' {_gConfidence = Nothing, _gWords = Nothing, _gTranscript = Nothing} -- | Output only. The confidence estimate between 0.0 and 1.0. A higher -- number indicates an estimated greater likelihood that the recognized -- words are correct. This field is set only for the top alternative. This -- field is not guaranteed to be accurate and users should not rely on it -- to be always provided. The default of 0.0 is a sentinel value indicating -- \`confidence\` was not set. gConfidence :: Lens' GoogleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative (Maybe Double) gConfidence = lens _gConfidence (\ s a -> s{_gConfidence = a}) . mapping _Coerce -- | Output only. A list of word-specific information for each recognized -- word. Note: When \`enable_speaker_diarization\` is set to true, you will -- see all the words from the beginning of the audio. gWords :: Lens' GoogleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative [GoogleCloudVideointelligenceV1p3beta1_WordInfo] gWords = lens _gWords (\ s a -> s{_gWords = a}) . _Default . _Coerce -- | Transcript text representing the words that the user spoke. gTranscript :: Lens' GoogleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative (Maybe Text) gTranscript = lens _gTranscript (\ s a -> s{_gTranscript = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1SpeechRecognitionAlternative" (\ o -> GoogleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative' <$> (o .:? "confidence") <*> (o .:? "words" .!= mempty) <*> (o .:? "transcript")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative where toJSON GoogleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative'{..} = object (catMaybes [("confidence" .=) <$> _gConfidence, ("words" .=) <$> _gWords, ("transcript" .=) <$> _gTranscript]) -- | Video frame level annotation results for text annotation (OCR). Contains -- information regarding timestamp and bounding box locations for the -- frames containing detected OCR text snippets. -- -- /See:/ 'googleCloudVideointelligenceV1_TextFrame' smart constructor. data GoogleCloudVideointelligenceV1_TextFrame = GoogleCloudVideointelligenceV1_TextFrame' { _gRotatedBoundingBox :: !(Maybe GoogleCloudVideointelligenceV1_NormalizedBoundingPoly) , _gTimeOffSet :: !(Maybe GDuration) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_TextFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gRotatedBoundingBox' -- -- * 'gTimeOffSet' googleCloudVideointelligenceV1_TextFrame :: GoogleCloudVideointelligenceV1_TextFrame googleCloudVideointelligenceV1_TextFrame = GoogleCloudVideointelligenceV1_TextFrame' {_gRotatedBoundingBox = Nothing, _gTimeOffSet = Nothing} -- | Bounding polygon of the detected text for this frame. gRotatedBoundingBox :: Lens' GoogleCloudVideointelligenceV1_TextFrame (Maybe GoogleCloudVideointelligenceV1_NormalizedBoundingPoly) gRotatedBoundingBox = lens _gRotatedBoundingBox (\ s a -> s{_gRotatedBoundingBox = a}) -- | Timestamp of this frame. gTimeOffSet :: Lens' GoogleCloudVideointelligenceV1_TextFrame (Maybe Scientific) gTimeOffSet = lens _gTimeOffSet (\ s a -> s{_gTimeOffSet = a}) . mapping _GDuration instance FromJSON GoogleCloudVideointelligenceV1_TextFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1TextFrame" (\ o -> GoogleCloudVideointelligenceV1_TextFrame' <$> (o .:? "rotatedBoundingBox") <*> (o .:? "timeOffset")) instance ToJSON GoogleCloudVideointelligenceV1_TextFrame where toJSON GoogleCloudVideointelligenceV1_TextFrame'{..} = object (catMaybes [("rotatedBoundingBox" .=) <$> _gRotatedBoundingBox, ("timeOffset" .=) <$> _gTimeOffSet]) -- | Word-specific information for recognized words. Word information is only -- included in the response when certain request parameters are set, such -- as \`enable_word_time_offsets\`. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_WordInfo' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_WordInfo = GoogleCloudVideointelligenceV1p3beta1_WordInfo' { _gooStartTime :: !(Maybe GDuration) , _gooConfidence :: !(Maybe (Textual Double)) , _gooEndTime :: !(Maybe GDuration) , _gooWord :: !(Maybe Text) , _gooSpeakerTag :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_WordInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gooStartTime' -- -- * 'gooConfidence' -- -- * 'gooEndTime' -- -- * 'gooWord' -- -- * 'gooSpeakerTag' googleCloudVideointelligenceV1p3beta1_WordInfo :: GoogleCloudVideointelligenceV1p3beta1_WordInfo googleCloudVideointelligenceV1p3beta1_WordInfo = GoogleCloudVideointelligenceV1p3beta1_WordInfo' { _gooStartTime = Nothing , _gooConfidence = Nothing , _gooEndTime = Nothing , _gooWord = Nothing , _gooSpeakerTag = Nothing } -- | Time offset relative to the beginning of the audio, and corresponding to -- the start of the spoken word. This field is only set if -- \`enable_word_time_offsets=true\` and only in the top hypothesis. This -- is an experimental feature and the accuracy of the time offset can vary. gooStartTime :: Lens' GoogleCloudVideointelligenceV1p3beta1_WordInfo (Maybe Scientific) gooStartTime = lens _gooStartTime (\ s a -> s{_gooStartTime = a}) . mapping _GDuration -- | Output only. The confidence estimate between 0.0 and 1.0. A higher -- number indicates an estimated greater likelihood that the recognized -- words are correct. This field is set only for the top alternative. This -- field is not guaranteed to be accurate and users should not rely on it -- to be always provided. The default of 0.0 is a sentinel value indicating -- \`confidence\` was not set. gooConfidence :: Lens' GoogleCloudVideointelligenceV1p3beta1_WordInfo (Maybe Double) gooConfidence = lens _gooConfidence (\ s a -> s{_gooConfidence = a}) . mapping _Coerce -- | Time offset relative to the beginning of the audio, and corresponding to -- the end of the spoken word. This field is only set if -- \`enable_word_time_offsets=true\` and only in the top hypothesis. This -- is an experimental feature and the accuracy of the time offset can vary. gooEndTime :: Lens' GoogleCloudVideointelligenceV1p3beta1_WordInfo (Maybe Scientific) gooEndTime = lens _gooEndTime (\ s a -> s{_gooEndTime = a}) . mapping _GDuration -- | The word corresponding to this set of information. gooWord :: Lens' GoogleCloudVideointelligenceV1p3beta1_WordInfo (Maybe Text) gooWord = lens _gooWord (\ s a -> s{_gooWord = a}) -- | Output only. A distinct integer value is assigned for every speaker -- within the audio. This field specifies which one of those speakers was -- detected to have spoken this word. Value ranges from 1 up to -- diarization_speaker_count, and is only set if speaker diarization is -- enabled. gooSpeakerTag :: Lens' GoogleCloudVideointelligenceV1p3beta1_WordInfo (Maybe Int32) gooSpeakerTag = lens _gooSpeakerTag (\ s a -> s{_gooSpeakerTag = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1p3beta1_WordInfo where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1WordInfo" (\ o -> GoogleCloudVideointelligenceV1p3beta1_WordInfo' <$> (o .:? "startTime") <*> (o .:? "confidence") <*> (o .:? "endTime") <*> (o .:? "word") <*> (o .:? "speakerTag")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_WordInfo where toJSON GoogleCloudVideointelligenceV1p3beta1_WordInfo'{..} = object (catMaybes [("startTime" .=) <$> _gooStartTime, ("confidence" .=) <$> _gooConfidence, ("endTime" .=) <$> _gooEndTime, ("word" .=) <$> _gooWord, ("speakerTag" .=) <$> _gooSpeakerTag]) -- | Config for LABEL_DETECTION. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_LabelDetectionConfig' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfig = GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfig' { _gcvvldcLabelDetectionMode :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfigLabelDetectionMode) , _gcvvldcStationaryCamera :: !(Maybe Bool) , _gcvvldcModel :: !(Maybe Text) , _gcvvldcVideoConfidenceThreshold :: !(Maybe (Textual Double)) , _gcvvldcFrameConfidenceThreshold :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvldcLabelDetectionMode' -- -- * 'gcvvldcStationaryCamera' -- -- * 'gcvvldcModel' -- -- * 'gcvvldcVideoConfidenceThreshold' -- -- * 'gcvvldcFrameConfidenceThreshold' googleCloudVideointelligenceV1p3beta1_LabelDetectionConfig :: GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfig googleCloudVideointelligenceV1p3beta1_LabelDetectionConfig = GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfig' { _gcvvldcLabelDetectionMode = Nothing , _gcvvldcStationaryCamera = Nothing , _gcvvldcModel = Nothing , _gcvvldcVideoConfidenceThreshold = Nothing , _gcvvldcFrameConfidenceThreshold = Nothing } -- | What labels should be detected with LABEL_DETECTION, in addition to -- video-level labels or segment-level labels. If unspecified, defaults to -- \`SHOT_MODE\`. gcvvldcLabelDetectionMode :: Lens' GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfig (Maybe GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfigLabelDetectionMode) gcvvldcLabelDetectionMode = lens _gcvvldcLabelDetectionMode (\ s a -> s{_gcvvldcLabelDetectionMode = a}) -- | Whether the video has been shot from a stationary (i.e., non-moving) -- camera. When set to true, might improve detection accuracy for moving -- objects. Should be used with \`SHOT_AND_FRAME_MODE\` enabled. gcvvldcStationaryCamera :: Lens' GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfig (Maybe Bool) gcvvldcStationaryCamera = lens _gcvvldcStationaryCamera (\ s a -> s{_gcvvldcStationaryCamera = a}) -- | Model to use for label detection. Supported values: \"builtin\/stable\" -- (the default if unset) and \"builtin\/latest\". gcvvldcModel :: Lens' GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfig (Maybe Text) gcvvldcModel = lens _gcvvldcModel (\ s a -> s{_gcvvldcModel = a}) -- | The confidence threshold we perform filtering on the labels from -- video-level and shot-level detections. If not set, it\'s set to 0.3 by -- default. The valid range for this threshold is [0.1, 0.9]. Any value set -- outside of this range will be clipped. Note: For best results, follow -- the default threshold. We will update the default threshold everytime -- when we release a new model. gcvvldcVideoConfidenceThreshold :: Lens' GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfig (Maybe Double) gcvvldcVideoConfidenceThreshold = lens _gcvvldcVideoConfidenceThreshold (\ s a -> s{_gcvvldcVideoConfidenceThreshold = a}) . mapping _Coerce -- | The confidence threshold we perform filtering on the labels from -- frame-level detection. If not set, it is set to 0.4 by default. The -- valid range for this threshold is [0.1, 0.9]. Any value set outside of -- this range will be clipped. Note: For best results, follow the default -- threshold. We will update the default threshold everytime when we -- release a new model. gcvvldcFrameConfidenceThreshold :: Lens' GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfig (Maybe Double) gcvvldcFrameConfidenceThreshold = lens _gcvvldcFrameConfidenceThreshold (\ s a -> s{_gcvvldcFrameConfidenceThreshold = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfig where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1LabelDetectionConfig" (\ o -> GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfig' <$> (o .:? "labelDetectionMode") <*> (o .:? "stationaryCamera") <*> (o .:? "model") <*> (o .:? "videoConfidenceThreshold") <*> (o .:? "frameConfidenceThreshold")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfig where toJSON GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfig'{..} = object (catMaybes [("labelDetectionMode" .=) <$> _gcvvldcLabelDetectionMode, ("stationaryCamera" .=) <$> _gcvvldcStationaryCamera, ("model" .=) <$> _gcvvldcModel, ("videoConfidenceThreshold" .=) <$> _gcvvldcVideoConfidenceThreshold, ("frameConfidenceThreshold" .=) <$> _gcvvldcFrameConfidenceThreshold]) -- | Detected entity from video analysis. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_Entity' smart constructor. data GoogleCloudVideointelligenceV1beta2_Entity = GoogleCloudVideointelligenceV1beta2_Entity' { _gcvveLanguageCode :: !(Maybe Text) , _gcvveEntityId :: !(Maybe Text) , _gcvveDescription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_Entity' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvveLanguageCode' -- -- * 'gcvveEntityId' -- -- * 'gcvveDescription' googleCloudVideointelligenceV1beta2_Entity :: GoogleCloudVideointelligenceV1beta2_Entity googleCloudVideointelligenceV1beta2_Entity = GoogleCloudVideointelligenceV1beta2_Entity' { _gcvveLanguageCode = Nothing , _gcvveEntityId = Nothing , _gcvveDescription = Nothing } -- | Language code for \`description\` in BCP-47 format. gcvveLanguageCode :: Lens' GoogleCloudVideointelligenceV1beta2_Entity (Maybe Text) gcvveLanguageCode = lens _gcvveLanguageCode (\ s a -> s{_gcvveLanguageCode = a}) -- | Opaque entity ID. Some IDs may be available in [Google Knowledge Graph -- Search API](https:\/\/developers.google.com\/knowledge-graph\/). gcvveEntityId :: Lens' GoogleCloudVideointelligenceV1beta2_Entity (Maybe Text) gcvveEntityId = lens _gcvveEntityId (\ s a -> s{_gcvveEntityId = a}) -- | Textual description, e.g., \`Fixed-gear bicycle\`. gcvveDescription :: Lens' GoogleCloudVideointelligenceV1beta2_Entity (Maybe Text) gcvveDescription = lens _gcvveDescription (\ s a -> s{_gcvveDescription = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_Entity where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2Entity" (\ o -> GoogleCloudVideointelligenceV1beta2_Entity' <$> (o .:? "languageCode") <*> (o .:? "entityId") <*> (o .:? "description")) instance ToJSON GoogleCloudVideointelligenceV1beta2_Entity where toJSON GoogleCloudVideointelligenceV1beta2_Entity'{..} = object (catMaybes [("languageCode" .=) <$> _gcvveLanguageCode, ("entityId" .=) <$> _gcvveEntityId, ("description" .=) <$> _gcvveDescription]) -- | Annotation corresponding to one detected, tracked and recognized logo -- class. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation' smart constructor. data GoogleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation = GoogleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation' { _gcvvlraTracks :: !(Maybe [GoogleCloudVideointelligenceV1beta2_Track]) , _gcvvlraSegments :: !(Maybe [GoogleCloudVideointelligenceV1beta2_VideoSegment]) , _gcvvlraEntity :: !(Maybe GoogleCloudVideointelligenceV1beta2_Entity) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvlraTracks' -- -- * 'gcvvlraSegments' -- -- * 'gcvvlraEntity' googleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation :: GoogleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation googleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation = GoogleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation' { _gcvvlraTracks = Nothing , _gcvvlraSegments = Nothing , _gcvvlraEntity = Nothing } -- | All logo tracks where the recognized logo appears. Each track -- corresponds to one logo instance appearing in consecutive frames. gcvvlraTracks :: Lens' GoogleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation [GoogleCloudVideointelligenceV1beta2_Track] gcvvlraTracks = lens _gcvvlraTracks (\ s a -> s{_gcvvlraTracks = a}) . _Default . _Coerce -- | All video segments where the recognized logo appears. There might be -- multiple instances of the same logo class appearing in one VideoSegment. gcvvlraSegments :: Lens' GoogleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation [GoogleCloudVideointelligenceV1beta2_VideoSegment] gcvvlraSegments = lens _gcvvlraSegments (\ s a -> s{_gcvvlraSegments = a}) . _Default . _Coerce -- | Entity category information to specify the logo class that all the logo -- tracks within this LogoRecognitionAnnotation are recognized as. gcvvlraEntity :: Lens' GoogleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation (Maybe GoogleCloudVideointelligenceV1beta2_Entity) gcvvlraEntity = lens _gcvvlraEntity (\ s a -> s{_gcvvlraEntity = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2LogoRecognitionAnnotation" (\ o -> GoogleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation' <$> (o .:? "tracks" .!= mempty) <*> (o .:? "segments" .!= mempty) <*> (o .:? "entity")) instance ToJSON GoogleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation where toJSON GoogleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation'{..} = object (catMaybes [("tracks" .=) <$> _gcvvlraTracks, ("segments" .=) <$> _gcvvlraSegments, ("entity" .=) <$> _gcvvlraEntity]) -- | The recognized celebrity with confidence score. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_RecognizedCelebrity' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_RecognizedCelebrity = GoogleCloudVideointelligenceV1p3beta1_RecognizedCelebrity' { _gcvvrcCelebrity :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_Celebrity) , _gcvvrcConfidence :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_RecognizedCelebrity' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvrcCelebrity' -- -- * 'gcvvrcConfidence' googleCloudVideointelligenceV1p3beta1_RecognizedCelebrity :: GoogleCloudVideointelligenceV1p3beta1_RecognizedCelebrity googleCloudVideointelligenceV1p3beta1_RecognizedCelebrity = GoogleCloudVideointelligenceV1p3beta1_RecognizedCelebrity' {_gcvvrcCelebrity = Nothing, _gcvvrcConfidence = Nothing} -- | The recognized celebrity. gcvvrcCelebrity :: Lens' GoogleCloudVideointelligenceV1p3beta1_RecognizedCelebrity (Maybe GoogleCloudVideointelligenceV1p3beta1_Celebrity) gcvvrcCelebrity = lens _gcvvrcCelebrity (\ s a -> s{_gcvvrcCelebrity = a}) -- | Recognition confidence. Range [0, 1]. gcvvrcConfidence :: Lens' GoogleCloudVideointelligenceV1p3beta1_RecognizedCelebrity (Maybe Double) gcvvrcConfidence = lens _gcvvrcConfidence (\ s a -> s{_gcvvrcConfidence = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1p3beta1_RecognizedCelebrity where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1RecognizedCelebrity" (\ o -> GoogleCloudVideointelligenceV1p3beta1_RecognizedCelebrity' <$> (o .:? "celebrity") <*> (o .:? "confidence")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_RecognizedCelebrity where toJSON GoogleCloudVideointelligenceV1p3beta1_RecognizedCelebrity'{..} = object (catMaybes [("celebrity" .=) <$> _gcvvrcCelebrity, ("confidence" .=) <$> _gcvvrcConfidence]) -- | Annotation progress for a single video. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress = GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress' { _gcvvvapFeature :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgressFeature) , _gcvvvapStartTime :: !(Maybe DateTime') , _gcvvvapInputURI :: !(Maybe Text) , _gcvvvapProgressPercent :: !(Maybe (Textual Int32)) , _gcvvvapUpdateTime :: !(Maybe DateTime') , _gcvvvapSegment :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_VideoSegment) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvvapFeature' -- -- * 'gcvvvapStartTime' -- -- * 'gcvvvapInputURI' -- -- * 'gcvvvapProgressPercent' -- -- * 'gcvvvapUpdateTime' -- -- * 'gcvvvapSegment' googleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress :: GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress googleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress = GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress' { _gcvvvapFeature = Nothing , _gcvvvapStartTime = Nothing , _gcvvvapInputURI = Nothing , _gcvvvapProgressPercent = Nothing , _gcvvvapUpdateTime = Nothing , _gcvvvapSegment = Nothing } -- | Specifies which feature is being tracked if the request contains more -- than one feature. gcvvvapFeature :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress (Maybe GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgressFeature) gcvvvapFeature = lens _gcvvvapFeature (\ s a -> s{_gcvvvapFeature = a}) -- | Time when the request was received. gcvvvapStartTime :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress (Maybe UTCTime) gcvvvapStartTime = lens _gcvvvapStartTime (\ s a -> s{_gcvvvapStartTime = a}) . mapping _DateTime -- | Video file location in [Cloud -- Storage](https:\/\/cloud.google.com\/storage\/). gcvvvapInputURI :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress (Maybe Text) gcvvvapInputURI = lens _gcvvvapInputURI (\ s a -> s{_gcvvvapInputURI = a}) -- | Approximate percentage processed thus far. Guaranteed to be 100 when -- fully processed. gcvvvapProgressPercent :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress (Maybe Int32) gcvvvapProgressPercent = lens _gcvvvapProgressPercent (\ s a -> s{_gcvvvapProgressPercent = a}) . mapping _Coerce -- | Time of the most recent update. gcvvvapUpdateTime :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress (Maybe UTCTime) gcvvvapUpdateTime = lens _gcvvvapUpdateTime (\ s a -> s{_gcvvvapUpdateTime = a}) . mapping _DateTime -- | Specifies which segment is being tracked if the request contains more -- than one segment. gcvvvapSegment :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress (Maybe GoogleCloudVideointelligenceV1p3beta1_VideoSegment) gcvvvapSegment = lens _gcvvvapSegment (\ s a -> s{_gcvvvapSegment = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1VideoAnnotationProgress" (\ o -> GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress' <$> (o .:? "feature") <*> (o .:? "startTime") <*> (o .:? "inputUri") <*> (o .:? "progressPercent") <*> (o .:? "updateTime") <*> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress where toJSON GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress'{..} = object (catMaybes [("feature" .=) <$> _gcvvvapFeature, ("startTime" .=) <$> _gcvvvapStartTime, ("inputUri" .=) <$> _gcvvvapInputURI, ("progressPercent" .=) <$> _gcvvvapProgressPercent, ("updateTime" .=) <$> _gcvvvapUpdateTime, ("segment" .=) <$> _gcvvvapSegment]) -- | Normalized bounding polygon for text (that might not be aligned with -- axis). Contains list of the corner points in clockwise order starting -- from top-left corner. For example, for a rectangular bounding box: When -- the text is horizontal it might look like: 0----1 | | 3----2 When it\'s -- clockwise rotated 180 degrees around the top-left corner it becomes: -- 2----3 | | 1----0 and the vertex order will still be (0, 1, 2, 3). Note -- that values can be less than 0, or greater than 1 due to trignometric -- calculations for location of the box. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_NormalizedBoundingPoly' smart constructor. newtype GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingPoly = GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingPoly' { _gcvvnbpVertices :: Maybe [GoogleCloudVideointelligenceV1p1beta1_NormalizedVertex] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingPoly' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvnbpVertices' googleCloudVideointelligenceV1p1beta1_NormalizedBoundingPoly :: GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingPoly googleCloudVideointelligenceV1p1beta1_NormalizedBoundingPoly = GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingPoly' {_gcvvnbpVertices = Nothing} -- | Normalized vertices of the bounding polygon. gcvvnbpVertices :: Lens' GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingPoly [GoogleCloudVideointelligenceV1p1beta1_NormalizedVertex] gcvvnbpVertices = lens _gcvvnbpVertices (\ s a -> s{_gcvvnbpVertices = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingPoly where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1NormalizedBoundingPoly" (\ o -> GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingPoly' <$> (o .:? "vertices" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingPoly where toJSON GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingPoly'{..} = object (catMaybes [("vertices" .=) <$> _gcvvnbpVertices]) -- | Celebrity recognition annotation per video. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_CelebrityRecognitionAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_CelebrityRecognitionAnnotation = GoogleCloudVideointelligenceV1p3beta1_CelebrityRecognitionAnnotation' { _gcvvcraCelebrityTracks :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_CelebrityTrack]) , _gcvvcraVersion :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_CelebrityRecognitionAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvcraCelebrityTracks' -- -- * 'gcvvcraVersion' googleCloudVideointelligenceV1p3beta1_CelebrityRecognitionAnnotation :: GoogleCloudVideointelligenceV1p3beta1_CelebrityRecognitionAnnotation googleCloudVideointelligenceV1p3beta1_CelebrityRecognitionAnnotation = GoogleCloudVideointelligenceV1p3beta1_CelebrityRecognitionAnnotation' {_gcvvcraCelebrityTracks = Nothing, _gcvvcraVersion = Nothing} -- | The tracks detected from the input video, including recognized -- celebrities and other detected faces in the video. gcvvcraCelebrityTracks :: Lens' GoogleCloudVideointelligenceV1p3beta1_CelebrityRecognitionAnnotation [GoogleCloudVideointelligenceV1p3beta1_CelebrityTrack] gcvvcraCelebrityTracks = lens _gcvvcraCelebrityTracks (\ s a -> s{_gcvvcraCelebrityTracks = a}) . _Default . _Coerce -- | Feature version. gcvvcraVersion :: Lens' GoogleCloudVideointelligenceV1p3beta1_CelebrityRecognitionAnnotation (Maybe Text) gcvvcraVersion = lens _gcvvcraVersion (\ s a -> s{_gcvvcraVersion = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_CelebrityRecognitionAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1CelebrityRecognitionAnnotation" (\ o -> GoogleCloudVideointelligenceV1p3beta1_CelebrityRecognitionAnnotation' <$> (o .:? "celebrityTracks" .!= mempty) <*> (o .:? "version")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_CelebrityRecognitionAnnotation where toJSON GoogleCloudVideointelligenceV1p3beta1_CelebrityRecognitionAnnotation'{..} = object (catMaybes [("celebrityTracks" .=) <$> _gcvvcraCelebrityTracks, ("version" .=) <$> _gcvvcraVersion]) -- | Annotations related to one detected OCR text snippet. This will contain -- the corresponding text, confidence value, and frame level information -- for each detection. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_TextAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_TextAnnotation = GoogleCloudVideointelligenceV1p2beta1_TextAnnotation' { _gcvvtaText :: !(Maybe Text) , _gcvvtaVersion :: !(Maybe Text) , _gcvvtaSegments :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_TextSegment]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_TextAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvtaText' -- -- * 'gcvvtaVersion' -- -- * 'gcvvtaSegments' googleCloudVideointelligenceV1p2beta1_TextAnnotation :: GoogleCloudVideointelligenceV1p2beta1_TextAnnotation googleCloudVideointelligenceV1p2beta1_TextAnnotation = GoogleCloudVideointelligenceV1p2beta1_TextAnnotation' {_gcvvtaText = Nothing, _gcvvtaVersion = Nothing, _gcvvtaSegments = Nothing} -- | The detected text. gcvvtaText :: Lens' GoogleCloudVideointelligenceV1p2beta1_TextAnnotation (Maybe Text) gcvvtaText = lens _gcvvtaText (\ s a -> s{_gcvvtaText = a}) -- | Feature version. gcvvtaVersion :: Lens' GoogleCloudVideointelligenceV1p2beta1_TextAnnotation (Maybe Text) gcvvtaVersion = lens _gcvvtaVersion (\ s a -> s{_gcvvtaVersion = a}) -- | All video segments where OCR detected text appears. gcvvtaSegments :: Lens' GoogleCloudVideointelligenceV1p2beta1_TextAnnotation [GoogleCloudVideointelligenceV1p2beta1_TextSegment] gcvvtaSegments = lens _gcvvtaSegments (\ s a -> s{_gcvvtaSegments = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p2beta1_TextAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1TextAnnotation" (\ o -> GoogleCloudVideointelligenceV1p2beta1_TextAnnotation' <$> (o .:? "text") <*> (o .:? "version") <*> (o .:? "segments" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_TextAnnotation where toJSON GoogleCloudVideointelligenceV1p2beta1_TextAnnotation'{..} = object (catMaybes [("text" .=) <$> _gcvvtaText, ("version" .=) <$> _gcvvtaVersion, ("segments" .=) <$> _gcvvtaSegments]) -- | Celebrity definition. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_Celebrity' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_Celebrity = GoogleCloudVideointelligenceV1p3beta1_Celebrity' { _gcvvcName :: !(Maybe Text) , _gcvvcDisplayName :: !(Maybe Text) , _gcvvcDescription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_Celebrity' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvcName' -- -- * 'gcvvcDisplayName' -- -- * 'gcvvcDescription' googleCloudVideointelligenceV1p3beta1_Celebrity :: GoogleCloudVideointelligenceV1p3beta1_Celebrity googleCloudVideointelligenceV1p3beta1_Celebrity = GoogleCloudVideointelligenceV1p3beta1_Celebrity' { _gcvvcName = Nothing , _gcvvcDisplayName = Nothing , _gcvvcDescription = Nothing } -- | The resource name of the celebrity. Have the format -- \`video-intelligence\/kg-mid\` indicates a celebrity from preloaded -- gallery. kg-mid is the id in Google knowledge graph, which is unique for -- the celebrity. gcvvcName :: Lens' GoogleCloudVideointelligenceV1p3beta1_Celebrity (Maybe Text) gcvvcName = lens _gcvvcName (\ s a -> s{_gcvvcName = a}) -- | The celebrity name. gcvvcDisplayName :: Lens' GoogleCloudVideointelligenceV1p3beta1_Celebrity (Maybe Text) gcvvcDisplayName = lens _gcvvcDisplayName (\ s a -> s{_gcvvcDisplayName = a}) -- | Textual description of additional information about the celebrity, if -- applicable. gcvvcDescription :: Lens' GoogleCloudVideointelligenceV1p3beta1_Celebrity (Maybe Text) gcvvcDescription = lens _gcvvcDescription (\ s a -> s{_gcvvcDescription = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_Celebrity where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1Celebrity" (\ o -> GoogleCloudVideointelligenceV1p3beta1_Celebrity' <$> (o .:? "name") <*> (o .:? "displayName") <*> (o .:? "description")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_Celebrity where toJSON GoogleCloudVideointelligenceV1p3beta1_Celebrity'{..} = object (catMaybes [("name" .=) <$> _gcvvcName, ("displayName" .=) <$> _gcvvcDisplayName, ("description" .=) <$> _gcvvcDescription]) -- | Video segment. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_VideoSegment' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_VideoSegment = GoogleCloudVideointelligenceV1p2beta1_VideoSegment' { _gcvvvsStartTimeOffSet :: !(Maybe GDuration) , _gcvvvsEndTimeOffSet :: !(Maybe GDuration) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_VideoSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvvsStartTimeOffSet' -- -- * 'gcvvvsEndTimeOffSet' googleCloudVideointelligenceV1p2beta1_VideoSegment :: GoogleCloudVideointelligenceV1p2beta1_VideoSegment googleCloudVideointelligenceV1p2beta1_VideoSegment = GoogleCloudVideointelligenceV1p2beta1_VideoSegment' {_gcvvvsStartTimeOffSet = Nothing, _gcvvvsEndTimeOffSet = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the start of the segment (inclusive). gcvvvsStartTimeOffSet :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoSegment (Maybe Scientific) gcvvvsStartTimeOffSet = lens _gcvvvsStartTimeOffSet (\ s a -> s{_gcvvvsStartTimeOffSet = a}) . mapping _GDuration -- | Time-offset, relative to the beginning of the video, corresponding to -- the end of the segment (inclusive). gcvvvsEndTimeOffSet :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoSegment (Maybe Scientific) gcvvvsEndTimeOffSet = lens _gcvvvsEndTimeOffSet (\ s a -> s{_gcvvvsEndTimeOffSet = a}) . mapping _GDuration instance FromJSON GoogleCloudVideointelligenceV1p2beta1_VideoSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1VideoSegment" (\ o -> GoogleCloudVideointelligenceV1p2beta1_VideoSegment' <$> (o .:? "startTimeOffset") <*> (o .:? "endTimeOffset")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_VideoSegment where toJSON GoogleCloudVideointelligenceV1p2beta1_VideoSegment'{..} = object (catMaybes [("startTimeOffset" .=) <$> _gcvvvsStartTimeOffSet, ("endTimeOffset" .=) <$> _gcvvvsEndTimeOffSet]) -- | Video segment level annotation results for face detection. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_FaceSegment' smart constructor. newtype GoogleCloudVideointelligenceV1p2beta1_FaceSegment = GoogleCloudVideointelligenceV1p2beta1_FaceSegment' { _gSegment :: Maybe GoogleCloudVideointelligenceV1p2beta1_VideoSegment } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_FaceSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gSegment' googleCloudVideointelligenceV1p2beta1_FaceSegment :: GoogleCloudVideointelligenceV1p2beta1_FaceSegment googleCloudVideointelligenceV1p2beta1_FaceSegment = GoogleCloudVideointelligenceV1p2beta1_FaceSegment' {_gSegment = Nothing} -- | Video segment where a face was detected. gSegment :: Lens' GoogleCloudVideointelligenceV1p2beta1_FaceSegment (Maybe GoogleCloudVideointelligenceV1p2beta1_VideoSegment) gSegment = lens _gSegment (\ s a -> s{_gSegment = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_FaceSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1FaceSegment" (\ o -> GoogleCloudVideointelligenceV1p2beta1_FaceSegment' <$> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_FaceSegment where toJSON GoogleCloudVideointelligenceV1p2beta1_FaceSegment'{..} = object (catMaybes [("segment" .=) <$> _gSegment]) -- | A vertex represents a 2D point in the image. NOTE: the normalized vertex -- coordinates are relative to the original image and range from 0 to 1. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_NormalizedVertex' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_NormalizedVertex = GoogleCloudVideointelligenceV1p1beta1_NormalizedVertex' { _gcvvnvX :: !(Maybe (Textual Double)) , _gcvvnvY :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_NormalizedVertex' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvnvX' -- -- * 'gcvvnvY' googleCloudVideointelligenceV1p1beta1_NormalizedVertex :: GoogleCloudVideointelligenceV1p1beta1_NormalizedVertex googleCloudVideointelligenceV1p1beta1_NormalizedVertex = GoogleCloudVideointelligenceV1p1beta1_NormalizedVertex' {_gcvvnvX = Nothing, _gcvvnvY = Nothing} -- | X coordinate. gcvvnvX :: Lens' GoogleCloudVideointelligenceV1p1beta1_NormalizedVertex (Maybe Double) gcvvnvX = lens _gcvvnvX (\ s a -> s{_gcvvnvX = a}) . mapping _Coerce -- | Y coordinate. gcvvnvY :: Lens' GoogleCloudVideointelligenceV1p1beta1_NormalizedVertex (Maybe Double) gcvvnvY = lens _gcvvnvY (\ s a -> s{_gcvvnvY = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1p1beta1_NormalizedVertex where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1NormalizedVertex" (\ o -> GoogleCloudVideointelligenceV1p1beta1_NormalizedVertex' <$> (o .:? "x") <*> (o .:? "y")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_NormalizedVertex where toJSON GoogleCloudVideointelligenceV1p1beta1_NormalizedVertex'{..} = object (catMaybes [("x" .=) <$> _gcvvnvX, ("y" .=) <$> _gcvvnvY]) -- | Annotation progress for a single video. -- -- /See:/ 'googleCloudVideointelligenceV1_VideoAnnotationProgress' smart constructor. data GoogleCloudVideointelligenceV1_VideoAnnotationProgress = GoogleCloudVideointelligenceV1_VideoAnnotationProgress' { _gcvvvapsFeature :: !(Maybe GoogleCloudVideointelligenceV1_VideoAnnotationProgressFeature) , _gcvvvapsStartTime :: !(Maybe DateTime') , _gcvvvapsInputURI :: !(Maybe Text) , _gcvvvapsProgressPercent :: !(Maybe (Textual Int32)) , _gcvvvapsUpdateTime :: !(Maybe DateTime') , _gcvvvapsSegment :: !(Maybe GoogleCloudVideointelligenceV1_VideoSegment) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_VideoAnnotationProgress' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvvapsFeature' -- -- * 'gcvvvapsStartTime' -- -- * 'gcvvvapsInputURI' -- -- * 'gcvvvapsProgressPercent' -- -- * 'gcvvvapsUpdateTime' -- -- * 'gcvvvapsSegment' googleCloudVideointelligenceV1_VideoAnnotationProgress :: GoogleCloudVideointelligenceV1_VideoAnnotationProgress googleCloudVideointelligenceV1_VideoAnnotationProgress = GoogleCloudVideointelligenceV1_VideoAnnotationProgress' { _gcvvvapsFeature = Nothing , _gcvvvapsStartTime = Nothing , _gcvvvapsInputURI = Nothing , _gcvvvapsProgressPercent = Nothing , _gcvvvapsUpdateTime = Nothing , _gcvvvapsSegment = Nothing } -- | Specifies which feature is being tracked if the request contains more -- than one feature. gcvvvapsFeature :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationProgress (Maybe GoogleCloudVideointelligenceV1_VideoAnnotationProgressFeature) gcvvvapsFeature = lens _gcvvvapsFeature (\ s a -> s{_gcvvvapsFeature = a}) -- | Time when the request was received. gcvvvapsStartTime :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationProgress (Maybe UTCTime) gcvvvapsStartTime = lens _gcvvvapsStartTime (\ s a -> s{_gcvvvapsStartTime = a}) . mapping _DateTime -- | Video file location in [Cloud -- Storage](https:\/\/cloud.google.com\/storage\/). gcvvvapsInputURI :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationProgress (Maybe Text) gcvvvapsInputURI = lens _gcvvvapsInputURI (\ s a -> s{_gcvvvapsInputURI = a}) -- | Approximate percentage processed thus far. Guaranteed to be 100 when -- fully processed. gcvvvapsProgressPercent :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationProgress (Maybe Int32) gcvvvapsProgressPercent = lens _gcvvvapsProgressPercent (\ s a -> s{_gcvvvapsProgressPercent = a}) . mapping _Coerce -- | Time of the most recent update. gcvvvapsUpdateTime :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationProgress (Maybe UTCTime) gcvvvapsUpdateTime = lens _gcvvvapsUpdateTime (\ s a -> s{_gcvvvapsUpdateTime = a}) . mapping _DateTime -- | Specifies which segment is being tracked if the request contains more -- than one segment. gcvvvapsSegment :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationProgress (Maybe GoogleCloudVideointelligenceV1_VideoSegment) gcvvvapsSegment = lens _gcvvvapsSegment (\ s a -> s{_gcvvvapsSegment = a}) instance FromJSON GoogleCloudVideointelligenceV1_VideoAnnotationProgress where parseJSON = withObject "GoogleCloudVideointelligenceV1VideoAnnotationProgress" (\ o -> GoogleCloudVideointelligenceV1_VideoAnnotationProgress' <$> (o .:? "feature") <*> (o .:? "startTime") <*> (o .:? "inputUri") <*> (o .:? "progressPercent") <*> (o .:? "updateTime") <*> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1_VideoAnnotationProgress where toJSON GoogleCloudVideointelligenceV1_VideoAnnotationProgress'{..} = object (catMaybes [("feature" .=) <$> _gcvvvapsFeature, ("startTime" .=) <$> _gcvvvapsStartTime, ("inputUri" .=) <$> _gcvvvapsInputURI, ("progressPercent" .=) <$> _gcvvvapsProgressPercent, ("updateTime" .=) <$> _gcvvvapsUpdateTime, ("segment" .=) <$> _gcvvvapsSegment]) -- | Video frame level annotation results for label detection. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_LabelFrame' smart constructor. data GoogleCloudVideointelligenceV1beta2_LabelFrame = GoogleCloudVideointelligenceV1beta2_LabelFrame' { _gcvvlfTimeOffSet :: !(Maybe GDuration) , _gcvvlfConfidence :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_LabelFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvlfTimeOffSet' -- -- * 'gcvvlfConfidence' googleCloudVideointelligenceV1beta2_LabelFrame :: GoogleCloudVideointelligenceV1beta2_LabelFrame googleCloudVideointelligenceV1beta2_LabelFrame = GoogleCloudVideointelligenceV1beta2_LabelFrame' {_gcvvlfTimeOffSet = Nothing, _gcvvlfConfidence = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this location. gcvvlfTimeOffSet :: Lens' GoogleCloudVideointelligenceV1beta2_LabelFrame (Maybe Scientific) gcvvlfTimeOffSet = lens _gcvvlfTimeOffSet (\ s a -> s{_gcvvlfTimeOffSet = a}) . mapping _GDuration -- | Confidence that the label is accurate. Range: [0, 1]. gcvvlfConfidence :: Lens' GoogleCloudVideointelligenceV1beta2_LabelFrame (Maybe Double) gcvvlfConfidence = lens _gcvvlfConfidence (\ s a -> s{_gcvvlfConfidence = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1beta2_LabelFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2LabelFrame" (\ o -> GoogleCloudVideointelligenceV1beta2_LabelFrame' <$> (o .:? "timeOffset") <*> (o .:? "confidence")) instance ToJSON GoogleCloudVideointelligenceV1beta2_LabelFrame where toJSON GoogleCloudVideointelligenceV1beta2_LabelFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvlfTimeOffSet, ("confidence" .=) <$> _gcvvlfConfidence]) -- | Deprecated. No effect. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_FaceAnnotation' smart constructor. data GoogleCloudVideointelligenceV1beta2_FaceAnnotation = GoogleCloudVideointelligenceV1beta2_FaceAnnotation' { _gcvvfaThumbnail :: !(Maybe Bytes) , _gcvvfaFrames :: !(Maybe [GoogleCloudVideointelligenceV1beta2_FaceFrame]) , _gcvvfaSegments :: !(Maybe [GoogleCloudVideointelligenceV1beta2_FaceSegment]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_FaceAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvfaThumbnail' -- -- * 'gcvvfaFrames' -- -- * 'gcvvfaSegments' googleCloudVideointelligenceV1beta2_FaceAnnotation :: GoogleCloudVideointelligenceV1beta2_FaceAnnotation googleCloudVideointelligenceV1beta2_FaceAnnotation = GoogleCloudVideointelligenceV1beta2_FaceAnnotation' { _gcvvfaThumbnail = Nothing , _gcvvfaFrames = Nothing , _gcvvfaSegments = Nothing } -- | Thumbnail of a representative face view (in JPEG format). gcvvfaThumbnail :: Lens' GoogleCloudVideointelligenceV1beta2_FaceAnnotation (Maybe ByteString) gcvvfaThumbnail = lens _gcvvfaThumbnail (\ s a -> s{_gcvvfaThumbnail = a}) . mapping _Bytes -- | All video frames where a face was detected. gcvvfaFrames :: Lens' GoogleCloudVideointelligenceV1beta2_FaceAnnotation [GoogleCloudVideointelligenceV1beta2_FaceFrame] gcvvfaFrames = lens _gcvvfaFrames (\ s a -> s{_gcvvfaFrames = a}) . _Default . _Coerce -- | All video segments where a face was detected. gcvvfaSegments :: Lens' GoogleCloudVideointelligenceV1beta2_FaceAnnotation [GoogleCloudVideointelligenceV1beta2_FaceSegment] gcvvfaSegments = lens _gcvvfaSegments (\ s a -> s{_gcvvfaSegments = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1beta2_FaceAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2FaceAnnotation" (\ o -> GoogleCloudVideointelligenceV1beta2_FaceAnnotation' <$> (o .:? "thumbnail") <*> (o .:? "frames" .!= mempty) <*> (o .:? "segments" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1beta2_FaceAnnotation where toJSON GoogleCloudVideointelligenceV1beta2_FaceAnnotation'{..} = object (catMaybes [("thumbnail" .=) <$> _gcvvfaThumbnail, ("frames" .=) <$> _gcvvfaFrames, ("segments" .=) <$> _gcvvfaSegments]) -- | Normalized bounding box. The normalized vertex coordinates are relative -- to the original image. Range: [0, 1]. -- -- /See:/ 'googleCloudVideointelligenceV1_NormalizedBoundingBox' smart constructor. data GoogleCloudVideointelligenceV1_NormalizedBoundingBox = GoogleCloudVideointelligenceV1_NormalizedBoundingBox' { _gcvvnbbBottom :: !(Maybe (Textual Double)) , _gcvvnbbLeft :: !(Maybe (Textual Double)) , _gcvvnbbRight :: !(Maybe (Textual Double)) , _gcvvnbbTop :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_NormalizedBoundingBox' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvnbbBottom' -- -- * 'gcvvnbbLeft' -- -- * 'gcvvnbbRight' -- -- * 'gcvvnbbTop' googleCloudVideointelligenceV1_NormalizedBoundingBox :: GoogleCloudVideointelligenceV1_NormalizedBoundingBox googleCloudVideointelligenceV1_NormalizedBoundingBox = GoogleCloudVideointelligenceV1_NormalizedBoundingBox' { _gcvvnbbBottom = Nothing , _gcvvnbbLeft = Nothing , _gcvvnbbRight = Nothing , _gcvvnbbTop = Nothing } -- | Bottom Y coordinate. gcvvnbbBottom :: Lens' GoogleCloudVideointelligenceV1_NormalizedBoundingBox (Maybe Double) gcvvnbbBottom = lens _gcvvnbbBottom (\ s a -> s{_gcvvnbbBottom = a}) . mapping _Coerce -- | Left X coordinate. gcvvnbbLeft :: Lens' GoogleCloudVideointelligenceV1_NormalizedBoundingBox (Maybe Double) gcvvnbbLeft = lens _gcvvnbbLeft (\ s a -> s{_gcvvnbbLeft = a}) . mapping _Coerce -- | Right X coordinate. gcvvnbbRight :: Lens' GoogleCloudVideointelligenceV1_NormalizedBoundingBox (Maybe Double) gcvvnbbRight = lens _gcvvnbbRight (\ s a -> s{_gcvvnbbRight = a}) . mapping _Coerce -- | Top Y coordinate. gcvvnbbTop :: Lens' GoogleCloudVideointelligenceV1_NormalizedBoundingBox (Maybe Double) gcvvnbbTop = lens _gcvvnbbTop (\ s a -> s{_gcvvnbbTop = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1_NormalizedBoundingBox where parseJSON = withObject "GoogleCloudVideointelligenceV1NormalizedBoundingBox" (\ o -> GoogleCloudVideointelligenceV1_NormalizedBoundingBox' <$> (o .:? "bottom") <*> (o .:? "left") <*> (o .:? "right") <*> (o .:? "top")) instance ToJSON GoogleCloudVideointelligenceV1_NormalizedBoundingBox where toJSON GoogleCloudVideointelligenceV1_NormalizedBoundingBox'{..} = object (catMaybes [("bottom" .=) <$> _gcvvnbbBottom, ("left" .=) <$> _gcvvnbbLeft, ("right" .=) <$> _gcvvnbbRight, ("top" .=) <$> _gcvvnbbTop]) -- | A speech recognition result corresponding to a portion of the audio. -- -- /See:/ 'googleCloudVideointelligenceV1_SpeechTranscription' smart constructor. data GoogleCloudVideointelligenceV1_SpeechTranscription = GoogleCloudVideointelligenceV1_SpeechTranscription' { _gcvvstAlternatives :: !(Maybe [GoogleCloudVideointelligenceV1_SpeechRecognitionAlternative]) , _gcvvstLanguageCode :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_SpeechTranscription' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvstAlternatives' -- -- * 'gcvvstLanguageCode' googleCloudVideointelligenceV1_SpeechTranscription :: GoogleCloudVideointelligenceV1_SpeechTranscription googleCloudVideointelligenceV1_SpeechTranscription = GoogleCloudVideointelligenceV1_SpeechTranscription' {_gcvvstAlternatives = Nothing, _gcvvstLanguageCode = Nothing} -- | May contain one or more recognition hypotheses (up to the maximum -- specified in \`max_alternatives\`). These alternatives are ordered in -- terms of accuracy, with the top (first) alternative being the most -- probable, as ranked by the recognizer. gcvvstAlternatives :: Lens' GoogleCloudVideointelligenceV1_SpeechTranscription [GoogleCloudVideointelligenceV1_SpeechRecognitionAlternative] gcvvstAlternatives = lens _gcvvstAlternatives (\ s a -> s{_gcvvstAlternatives = a}) . _Default . _Coerce -- | Output only. The -- [BCP-47](https:\/\/www.rfc-editor.org\/rfc\/bcp\/bcp47.txt) language tag -- of the language in this result. This language code was detected to have -- the most likelihood of being spoken in the audio. gcvvstLanguageCode :: Lens' GoogleCloudVideointelligenceV1_SpeechTranscription (Maybe Text) gcvvstLanguageCode = lens _gcvvstLanguageCode (\ s a -> s{_gcvvstLanguageCode = a}) instance FromJSON GoogleCloudVideointelligenceV1_SpeechTranscription where parseJSON = withObject "GoogleCloudVideointelligenceV1SpeechTranscription" (\ o -> GoogleCloudVideointelligenceV1_SpeechTranscription' <$> (o .:? "alternatives" .!= mempty) <*> (o .:? "languageCode")) instance ToJSON GoogleCloudVideointelligenceV1_SpeechTranscription where toJSON GoogleCloudVideointelligenceV1_SpeechTranscription'{..} = object (catMaybes [("alternatives" .=) <$> _gcvvstAlternatives, ("languageCode" .=) <$> _gcvvstLanguageCode]) -- | Video annotation progress. Included in the \`metadata\` field of the -- \`Operation\` returned by the \`GetOperation\` call of the -- \`google::longrunning::Operations\` service. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_AnnotateVideoProgress' smart constructor. newtype GoogleCloudVideointelligenceV1beta2_AnnotateVideoProgress = GoogleCloudVideointelligenceV1beta2_AnnotateVideoProgress' { _gcvvavpAnnotationProgress :: Maybe [GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_AnnotateVideoProgress' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvavpAnnotationProgress' googleCloudVideointelligenceV1beta2_AnnotateVideoProgress :: GoogleCloudVideointelligenceV1beta2_AnnotateVideoProgress googleCloudVideointelligenceV1beta2_AnnotateVideoProgress = GoogleCloudVideointelligenceV1beta2_AnnotateVideoProgress' {_gcvvavpAnnotationProgress = Nothing} -- | Progress metadata for all videos specified in \`AnnotateVideoRequest\`. gcvvavpAnnotationProgress :: Lens' GoogleCloudVideointelligenceV1beta2_AnnotateVideoProgress [GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress] gcvvavpAnnotationProgress = lens _gcvvavpAnnotationProgress (\ s a -> s{_gcvvavpAnnotationProgress = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1beta2_AnnotateVideoProgress where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2AnnotateVideoProgress" (\ o -> GoogleCloudVideointelligenceV1beta2_AnnotateVideoProgress' <$> (o .:? "annotationProgress" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1beta2_AnnotateVideoProgress where toJSON GoogleCloudVideointelligenceV1beta2_AnnotateVideoProgress'{..} = object (catMaybes [("annotationProgress" .=) <$> _gcvvavpAnnotationProgress]) -- | Video segment level annotation results for text detection. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_TextSegment' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_TextSegment = GoogleCloudVideointelligenceV1p3beta1_TextSegment' { _gcvvtsFrames :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_TextFrame]) , _gcvvtsConfidence :: !(Maybe (Textual Double)) , _gcvvtsSegment :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_VideoSegment) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_TextSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvtsFrames' -- -- * 'gcvvtsConfidence' -- -- * 'gcvvtsSegment' googleCloudVideointelligenceV1p3beta1_TextSegment :: GoogleCloudVideointelligenceV1p3beta1_TextSegment googleCloudVideointelligenceV1p3beta1_TextSegment = GoogleCloudVideointelligenceV1p3beta1_TextSegment' { _gcvvtsFrames = Nothing , _gcvvtsConfidence = Nothing , _gcvvtsSegment = Nothing } -- | Information related to the frames where OCR detected text appears. gcvvtsFrames :: Lens' GoogleCloudVideointelligenceV1p3beta1_TextSegment [GoogleCloudVideointelligenceV1p3beta1_TextFrame] gcvvtsFrames = lens _gcvvtsFrames (\ s a -> s{_gcvvtsFrames = a}) . _Default . _Coerce -- | Confidence for the track of detected text. It is calculated as the -- highest over all frames where OCR detected text appears. gcvvtsConfidence :: Lens' GoogleCloudVideointelligenceV1p3beta1_TextSegment (Maybe Double) gcvvtsConfidence = lens _gcvvtsConfidence (\ s a -> s{_gcvvtsConfidence = a}) . mapping _Coerce -- | Video segment where a text snippet was detected. gcvvtsSegment :: Lens' GoogleCloudVideointelligenceV1p3beta1_TextSegment (Maybe GoogleCloudVideointelligenceV1p3beta1_VideoSegment) gcvvtsSegment = lens _gcvvtsSegment (\ s a -> s{_gcvvtsSegment = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_TextSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1TextSegment" (\ o -> GoogleCloudVideointelligenceV1p3beta1_TextSegment' <$> (o .:? "frames" .!= mempty) <*> (o .:? "confidence") <*> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_TextSegment where toJSON GoogleCloudVideointelligenceV1p3beta1_TextSegment'{..} = object (catMaybes [("frames" .=) <$> _gcvvtsFrames, ("confidence" .=) <$> _gcvvtsConfidence, ("segment" .=) <$> _gcvvtsSegment]) -- | Deprecated. No effect. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_FaceFrame' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_FaceFrame = GoogleCloudVideointelligenceV1p1beta1_FaceFrame' { _gcvvffTimeOffSet :: !(Maybe GDuration) , _gcvvffNormalizedBoundingBoxes :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_FaceFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvffTimeOffSet' -- -- * 'gcvvffNormalizedBoundingBoxes' googleCloudVideointelligenceV1p1beta1_FaceFrame :: GoogleCloudVideointelligenceV1p1beta1_FaceFrame googleCloudVideointelligenceV1p1beta1_FaceFrame = GoogleCloudVideointelligenceV1p1beta1_FaceFrame' {_gcvvffTimeOffSet = Nothing, _gcvvffNormalizedBoundingBoxes = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this location. gcvvffTimeOffSet :: Lens' GoogleCloudVideointelligenceV1p1beta1_FaceFrame (Maybe Scientific) gcvvffTimeOffSet = lens _gcvvffTimeOffSet (\ s a -> s{_gcvvffTimeOffSet = a}) . mapping _GDuration -- | Normalized Bounding boxes in a frame. There can be more than one boxes -- if the same face is detected in multiple locations within the current -- frame. gcvvffNormalizedBoundingBoxes :: Lens' GoogleCloudVideointelligenceV1p1beta1_FaceFrame [GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox] gcvvffNormalizedBoundingBoxes = lens _gcvvffNormalizedBoundingBoxes (\ s a -> s{_gcvvffNormalizedBoundingBoxes = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p1beta1_FaceFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1FaceFrame" (\ o -> GoogleCloudVideointelligenceV1p1beta1_FaceFrame' <$> (o .:? "timeOffset") <*> (o .:? "normalizedBoundingBoxes" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_FaceFrame where toJSON GoogleCloudVideointelligenceV1p1beta1_FaceFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvffTimeOffSet, ("normalizedBoundingBoxes" .=) <$> _gcvvffNormalizedBoundingBoxes]) -- | Normalized bounding box. The normalized vertex coordinates are relative -- to the original image. Range: [0, 1]. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox = GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox' { _gBottom :: !(Maybe (Textual Double)) , _gLeft :: !(Maybe (Textual Double)) , _gRight :: !(Maybe (Textual Double)) , _gTop :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gBottom' -- -- * 'gLeft' -- -- * 'gRight' -- -- * 'gTop' googleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox :: GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox googleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox = GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox' {_gBottom = Nothing, _gLeft = Nothing, _gRight = Nothing, _gTop = Nothing} -- | Bottom Y coordinate. gBottom :: Lens' GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox (Maybe Double) gBottom = lens _gBottom (\ s a -> s{_gBottom = a}) . mapping _Coerce -- | Left X coordinate. gLeft :: Lens' GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox (Maybe Double) gLeft = lens _gLeft (\ s a -> s{_gLeft = a}) . mapping _Coerce -- | Right X coordinate. gRight :: Lens' GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox (Maybe Double) gRight = lens _gRight (\ s a -> s{_gRight = a}) . mapping _Coerce -- | Top Y coordinate. gTop :: Lens' GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox (Maybe Double) gTop = lens _gTop (\ s a -> s{_gTop = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1NormalizedBoundingBox" (\ o -> GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox' <$> (o .:? "bottom") <*> (o .:? "left") <*> (o .:? "right") <*> (o .:? "top")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox where toJSON GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox'{..} = object (catMaybes [("bottom" .=) <$> _gBottom, ("left" .=) <$> _gLeft, ("right" .=) <$> _gRight, ("top" .=) <$> _gTop]) -- | A speech recognition result corresponding to a portion of the audio. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_SpeechTranscription' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_SpeechTranscription = GoogleCloudVideointelligenceV1p3beta1_SpeechTranscription' { _gAlternatives :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative]) , _gLanguageCode :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_SpeechTranscription' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gAlternatives' -- -- * 'gLanguageCode' googleCloudVideointelligenceV1p3beta1_SpeechTranscription :: GoogleCloudVideointelligenceV1p3beta1_SpeechTranscription googleCloudVideointelligenceV1p3beta1_SpeechTranscription = GoogleCloudVideointelligenceV1p3beta1_SpeechTranscription' {_gAlternatives = Nothing, _gLanguageCode = Nothing} -- | May contain one or more recognition hypotheses (up to the maximum -- specified in \`max_alternatives\`). These alternatives are ordered in -- terms of accuracy, with the top (first) alternative being the most -- probable, as ranked by the recognizer. gAlternatives :: Lens' GoogleCloudVideointelligenceV1p3beta1_SpeechTranscription [GoogleCloudVideointelligenceV1p3beta1_SpeechRecognitionAlternative] gAlternatives = lens _gAlternatives (\ s a -> s{_gAlternatives = a}) . _Default . _Coerce -- | Output only. The -- [BCP-47](https:\/\/www.rfc-editor.org\/rfc\/bcp\/bcp47.txt) language tag -- of the language in this result. This language code was detected to have -- the most likelihood of being spoken in the audio. gLanguageCode :: Lens' GoogleCloudVideointelligenceV1p3beta1_SpeechTranscription (Maybe Text) gLanguageCode = lens _gLanguageCode (\ s a -> s{_gLanguageCode = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_SpeechTranscription where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1SpeechTranscription" (\ o -> GoogleCloudVideointelligenceV1p3beta1_SpeechTranscription' <$> (o .:? "alternatives" .!= mempty) <*> (o .:? "languageCode")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_SpeechTranscription where toJSON GoogleCloudVideointelligenceV1p3beta1_SpeechTranscription'{..} = object (catMaybes [("alternatives" .=) <$> _gAlternatives, ("languageCode" .=) <$> _gLanguageCode]) -- | Video segment level annotation results for text detection. -- -- /See:/ 'googleCloudVideointelligenceV1_TextSegment' smart constructor. data GoogleCloudVideointelligenceV1_TextSegment = GoogleCloudVideointelligenceV1_TextSegment' { _gcvvtscFrames :: !(Maybe [GoogleCloudVideointelligenceV1_TextFrame]) , _gcvvtscConfidence :: !(Maybe (Textual Double)) , _gcvvtscSegment :: !(Maybe GoogleCloudVideointelligenceV1_VideoSegment) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_TextSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvtscFrames' -- -- * 'gcvvtscConfidence' -- -- * 'gcvvtscSegment' googleCloudVideointelligenceV1_TextSegment :: GoogleCloudVideointelligenceV1_TextSegment googleCloudVideointelligenceV1_TextSegment = GoogleCloudVideointelligenceV1_TextSegment' { _gcvvtscFrames = Nothing , _gcvvtscConfidence = Nothing , _gcvvtscSegment = Nothing } -- | Information related to the frames where OCR detected text appears. gcvvtscFrames :: Lens' GoogleCloudVideointelligenceV1_TextSegment [GoogleCloudVideointelligenceV1_TextFrame] gcvvtscFrames = lens _gcvvtscFrames (\ s a -> s{_gcvvtscFrames = a}) . _Default . _Coerce -- | Confidence for the track of detected text. It is calculated as the -- highest over all frames where OCR detected text appears. gcvvtscConfidence :: Lens' GoogleCloudVideointelligenceV1_TextSegment (Maybe Double) gcvvtscConfidence = lens _gcvvtscConfidence (\ s a -> s{_gcvvtscConfidence = a}) . mapping _Coerce -- | Video segment where a text snippet was detected. gcvvtscSegment :: Lens' GoogleCloudVideointelligenceV1_TextSegment (Maybe GoogleCloudVideointelligenceV1_VideoSegment) gcvvtscSegment = lens _gcvvtscSegment (\ s a -> s{_gcvvtscSegment = a}) instance FromJSON GoogleCloudVideointelligenceV1_TextSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1TextSegment" (\ o -> GoogleCloudVideointelligenceV1_TextSegment' <$> (o .:? "frames" .!= mempty) <*> (o .:? "confidence") <*> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1_TextSegment where toJSON GoogleCloudVideointelligenceV1_TextSegment'{..} = object (catMaybes [("frames" .=) <$> _gcvvtscFrames, ("confidence" .=) <$> _gcvvtscConfidence, ("segment" .=) <$> _gcvvtscSegment]) -- | Video frame level annotations for object detection and tracking. This -- field stores per frame location, time offset, and confidence. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_ObjectTrackingFrame' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingFrame = GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingFrame' { _gcvvotfTimeOffSet :: !(Maybe GDuration) , _gcvvotfNormalizedBoundingBox :: !(Maybe GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvotfTimeOffSet' -- -- * 'gcvvotfNormalizedBoundingBox' googleCloudVideointelligenceV1p2beta1_ObjectTrackingFrame :: GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingFrame googleCloudVideointelligenceV1p2beta1_ObjectTrackingFrame = GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingFrame' {_gcvvotfTimeOffSet = Nothing, _gcvvotfNormalizedBoundingBox = Nothing} -- | The timestamp of the frame in microseconds. gcvvotfTimeOffSet :: Lens' GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingFrame (Maybe Scientific) gcvvotfTimeOffSet = lens _gcvvotfTimeOffSet (\ s a -> s{_gcvvotfTimeOffSet = a}) . mapping _GDuration -- | The normalized bounding box location of this object track for the frame. gcvvotfNormalizedBoundingBox :: Lens' GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingFrame (Maybe GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox) gcvvotfNormalizedBoundingBox = lens _gcvvotfNormalizedBoundingBox (\ s a -> s{_gcvvotfNormalizedBoundingBox = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1ObjectTrackingFrame" (\ o -> GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingFrame' <$> (o .:? "timeOffset") <*> (o .:? "normalizedBoundingBox")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingFrame where toJSON GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvotfTimeOffSet, ("normalizedBoundingBox" .=) <$> _gcvvotfNormalizedBoundingBox]) -- | Label annotation. -- -- /See:/ 'googleCloudVideointelligenceV1_LabelAnnotation' smart constructor. data GoogleCloudVideointelligenceV1_LabelAnnotation = GoogleCloudVideointelligenceV1_LabelAnnotation' { _gcvvlaCategoryEntities :: !(Maybe [GoogleCloudVideointelligenceV1_Entity]) , _gcvvlaFrames :: !(Maybe [GoogleCloudVideointelligenceV1_LabelFrame]) , _gcvvlaVersion :: !(Maybe Text) , _gcvvlaSegments :: !(Maybe [GoogleCloudVideointelligenceV1_LabelSegment]) , _gcvvlaEntity :: !(Maybe GoogleCloudVideointelligenceV1_Entity) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_LabelAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvlaCategoryEntities' -- -- * 'gcvvlaFrames' -- -- * 'gcvvlaVersion' -- -- * 'gcvvlaSegments' -- -- * 'gcvvlaEntity' googleCloudVideointelligenceV1_LabelAnnotation :: GoogleCloudVideointelligenceV1_LabelAnnotation googleCloudVideointelligenceV1_LabelAnnotation = GoogleCloudVideointelligenceV1_LabelAnnotation' { _gcvvlaCategoryEntities = Nothing , _gcvvlaFrames = Nothing , _gcvvlaVersion = Nothing , _gcvvlaSegments = Nothing , _gcvvlaEntity = Nothing } -- | Common categories for the detected entity. For example, when the label -- is \`Terrier\`, the category is likely \`dog\`. And in some cases there -- might be more than one categories e.g., \`Terrier\` could also be a -- \`pet\`. gcvvlaCategoryEntities :: Lens' GoogleCloudVideointelligenceV1_LabelAnnotation [GoogleCloudVideointelligenceV1_Entity] gcvvlaCategoryEntities = lens _gcvvlaCategoryEntities (\ s a -> s{_gcvvlaCategoryEntities = a}) . _Default . _Coerce -- | All video frames where a label was detected. gcvvlaFrames :: Lens' GoogleCloudVideointelligenceV1_LabelAnnotation [GoogleCloudVideointelligenceV1_LabelFrame] gcvvlaFrames = lens _gcvvlaFrames (\ s a -> s{_gcvvlaFrames = a}) . _Default . _Coerce -- | Feature version. gcvvlaVersion :: Lens' GoogleCloudVideointelligenceV1_LabelAnnotation (Maybe Text) gcvvlaVersion = lens _gcvvlaVersion (\ s a -> s{_gcvvlaVersion = a}) -- | All video segments where a label was detected. gcvvlaSegments :: Lens' GoogleCloudVideointelligenceV1_LabelAnnotation [GoogleCloudVideointelligenceV1_LabelSegment] gcvvlaSegments = lens _gcvvlaSegments (\ s a -> s{_gcvvlaSegments = a}) . _Default . _Coerce -- | Detected entity. gcvvlaEntity :: Lens' GoogleCloudVideointelligenceV1_LabelAnnotation (Maybe GoogleCloudVideointelligenceV1_Entity) gcvvlaEntity = lens _gcvvlaEntity (\ s a -> s{_gcvvlaEntity = a}) instance FromJSON GoogleCloudVideointelligenceV1_LabelAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1LabelAnnotation" (\ o -> GoogleCloudVideointelligenceV1_LabelAnnotation' <$> (o .:? "categoryEntities" .!= mempty) <*> (o .:? "frames" .!= mempty) <*> (o .:? "version") <*> (o .:? "segments" .!= mempty) <*> (o .:? "entity")) instance ToJSON GoogleCloudVideointelligenceV1_LabelAnnotation where toJSON GoogleCloudVideointelligenceV1_LabelAnnotation'{..} = object (catMaybes [("categoryEntities" .=) <$> _gcvvlaCategoryEntities, ("frames" .=) <$> _gcvvlaFrames, ("version" .=) <$> _gcvvlaVersion, ("segments" .=) <$> _gcvvlaSegments, ("entity" .=) <$> _gcvvlaEntity]) -- | Normalized bounding polygon for text (that might not be aligned with -- axis). Contains list of the corner points in clockwise order starting -- from top-left corner. For example, for a rectangular bounding box: When -- the text is horizontal it might look like: 0----1 | | 3----2 When it\'s -- clockwise rotated 180 degrees around the top-left corner it becomes: -- 2----3 | | 1----0 and the vertex order will still be (0, 1, 2, 3). Note -- that values can be less than 0, or greater than 1 due to trignometric -- calculations for location of the box. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_NormalizedBoundingPoly' smart constructor. newtype GoogleCloudVideointelligenceV1beta2_NormalizedBoundingPoly = GoogleCloudVideointelligenceV1beta2_NormalizedBoundingPoly' { _gVertices :: Maybe [GoogleCloudVideointelligenceV1beta2_NormalizedVertex] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_NormalizedBoundingPoly' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gVertices' googleCloudVideointelligenceV1beta2_NormalizedBoundingPoly :: GoogleCloudVideointelligenceV1beta2_NormalizedBoundingPoly googleCloudVideointelligenceV1beta2_NormalizedBoundingPoly = GoogleCloudVideointelligenceV1beta2_NormalizedBoundingPoly' {_gVertices = Nothing} -- | Normalized vertices of the bounding polygon. gVertices :: Lens' GoogleCloudVideointelligenceV1beta2_NormalizedBoundingPoly [GoogleCloudVideointelligenceV1beta2_NormalizedVertex] gVertices = lens _gVertices (\ s a -> s{_gVertices = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1beta2_NormalizedBoundingPoly where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2NormalizedBoundingPoly" (\ o -> GoogleCloudVideointelligenceV1beta2_NormalizedBoundingPoly' <$> (o .:? "vertices" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1beta2_NormalizedBoundingPoly where toJSON GoogleCloudVideointelligenceV1beta2_NormalizedBoundingPoly'{..} = object (catMaybes [("vertices" .=) <$> _gVertices]) -- | Alternative hypotheses (a.k.a. n-best list). -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative = GoogleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative' { _gcvvsracConfidence :: !(Maybe (Textual Double)) , _gcvvsracWords :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_WordInfo]) , _gcvvsracTranscript :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvsracConfidence' -- -- * 'gcvvsracWords' -- -- * 'gcvvsracTranscript' googleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative :: GoogleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative googleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative = GoogleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative' { _gcvvsracConfidence = Nothing , _gcvvsracWords = Nothing , _gcvvsracTranscript = Nothing } -- | Output only. The confidence estimate between 0.0 and 1.0. A higher -- number indicates an estimated greater likelihood that the recognized -- words are correct. This field is set only for the top alternative. This -- field is not guaranteed to be accurate and users should not rely on it -- to be always provided. The default of 0.0 is a sentinel value indicating -- \`confidence\` was not set. gcvvsracConfidence :: Lens' GoogleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative (Maybe Double) gcvvsracConfidence = lens _gcvvsracConfidence (\ s a -> s{_gcvvsracConfidence = a}) . mapping _Coerce -- | Output only. A list of word-specific information for each recognized -- word. Note: When \`enable_speaker_diarization\` is set to true, you will -- see all the words from the beginning of the audio. gcvvsracWords :: Lens' GoogleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative [GoogleCloudVideointelligenceV1p2beta1_WordInfo] gcvvsracWords = lens _gcvvsracWords (\ s a -> s{_gcvvsracWords = a}) . _Default . _Coerce -- | Transcript text representing the words that the user spoke. gcvvsracTranscript :: Lens' GoogleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative (Maybe Text) gcvvsracTranscript = lens _gcvvsracTranscript (\ s a -> s{_gcvvsracTranscript = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1SpeechRecognitionAlternative" (\ o -> GoogleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative' <$> (o .:? "confidence") <*> (o .:? "words" .!= mempty) <*> (o .:? "transcript")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative where toJSON GoogleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative'{..} = object (catMaybes [("confidence" .=) <$> _gcvvsracConfidence, ("words" .=) <$> _gcvvsracWords, ("transcript" .=) <$> _gcvvsracTranscript]) -- | Word-specific information for recognized words. Word information is only -- included in the response when certain request parameters are set, such -- as \`enable_word_time_offsets\`. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_WordInfo' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_WordInfo = GoogleCloudVideointelligenceV1p2beta1_WordInfo' { _gcvvwicStartTime :: !(Maybe GDuration) , _gcvvwicConfidence :: !(Maybe (Textual Double)) , _gcvvwicEndTime :: !(Maybe GDuration) , _gcvvwicWord :: !(Maybe Text) , _gcvvwicSpeakerTag :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_WordInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvwicStartTime' -- -- * 'gcvvwicConfidence' -- -- * 'gcvvwicEndTime' -- -- * 'gcvvwicWord' -- -- * 'gcvvwicSpeakerTag' googleCloudVideointelligenceV1p2beta1_WordInfo :: GoogleCloudVideointelligenceV1p2beta1_WordInfo googleCloudVideointelligenceV1p2beta1_WordInfo = GoogleCloudVideointelligenceV1p2beta1_WordInfo' { _gcvvwicStartTime = Nothing , _gcvvwicConfidence = Nothing , _gcvvwicEndTime = Nothing , _gcvvwicWord = Nothing , _gcvvwicSpeakerTag = Nothing } -- | Time offset relative to the beginning of the audio, and corresponding to -- the start of the spoken word. This field is only set if -- \`enable_word_time_offsets=true\` and only in the top hypothesis. This -- is an experimental feature and the accuracy of the time offset can vary. gcvvwicStartTime :: Lens' GoogleCloudVideointelligenceV1p2beta1_WordInfo (Maybe Scientific) gcvvwicStartTime = lens _gcvvwicStartTime (\ s a -> s{_gcvvwicStartTime = a}) . mapping _GDuration -- | Output only. The confidence estimate between 0.0 and 1.0. A higher -- number indicates an estimated greater likelihood that the recognized -- words are correct. This field is set only for the top alternative. This -- field is not guaranteed to be accurate and users should not rely on it -- to be always provided. The default of 0.0 is a sentinel value indicating -- \`confidence\` was not set. gcvvwicConfidence :: Lens' GoogleCloudVideointelligenceV1p2beta1_WordInfo (Maybe Double) gcvvwicConfidence = lens _gcvvwicConfidence (\ s a -> s{_gcvvwicConfidence = a}) . mapping _Coerce -- | Time offset relative to the beginning of the audio, and corresponding to -- the end of the spoken word. This field is only set if -- \`enable_word_time_offsets=true\` and only in the top hypothesis. This -- is an experimental feature and the accuracy of the time offset can vary. gcvvwicEndTime :: Lens' GoogleCloudVideointelligenceV1p2beta1_WordInfo (Maybe Scientific) gcvvwicEndTime = lens _gcvvwicEndTime (\ s a -> s{_gcvvwicEndTime = a}) . mapping _GDuration -- | The word corresponding to this set of information. gcvvwicWord :: Lens' GoogleCloudVideointelligenceV1p2beta1_WordInfo (Maybe Text) gcvvwicWord = lens _gcvvwicWord (\ s a -> s{_gcvvwicWord = a}) -- | Output only. A distinct integer value is assigned for every speaker -- within the audio. This field specifies which one of those speakers was -- detected to have spoken this word. Value ranges from 1 up to -- diarization_speaker_count, and is only set if speaker diarization is -- enabled. gcvvwicSpeakerTag :: Lens' GoogleCloudVideointelligenceV1p2beta1_WordInfo (Maybe Int32) gcvvwicSpeakerTag = lens _gcvvwicSpeakerTag (\ s a -> s{_gcvvwicSpeakerTag = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1p2beta1_WordInfo where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1WordInfo" (\ o -> GoogleCloudVideointelligenceV1p2beta1_WordInfo' <$> (o .:? "startTime") <*> (o .:? "confidence") <*> (o .:? "endTime") <*> (o .:? "word") <*> (o .:? "speakerTag")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_WordInfo where toJSON GoogleCloudVideointelligenceV1p2beta1_WordInfo'{..} = object (catMaybes [("startTime" .=) <$> _gcvvwicStartTime, ("confidence" .=) <$> _gcvvwicConfidence, ("endTime" .=) <$> _gcvvwicEndTime, ("word" .=) <$> _gcvvwicWord, ("speakerTag" .=) <$> _gcvvwicSpeakerTag]) -- | Video frame level annotation results for label detection. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_LabelFrame' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_LabelFrame = GoogleCloudVideointelligenceV1p1beta1_LabelFrame' { _gcvvlfcTimeOffSet :: !(Maybe GDuration) , _gcvvlfcConfidence :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_LabelFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvlfcTimeOffSet' -- -- * 'gcvvlfcConfidence' googleCloudVideointelligenceV1p1beta1_LabelFrame :: GoogleCloudVideointelligenceV1p1beta1_LabelFrame googleCloudVideointelligenceV1p1beta1_LabelFrame = GoogleCloudVideointelligenceV1p1beta1_LabelFrame' {_gcvvlfcTimeOffSet = Nothing, _gcvvlfcConfidence = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this location. gcvvlfcTimeOffSet :: Lens' GoogleCloudVideointelligenceV1p1beta1_LabelFrame (Maybe Scientific) gcvvlfcTimeOffSet = lens _gcvvlfcTimeOffSet (\ s a -> s{_gcvvlfcTimeOffSet = a}) . mapping _GDuration -- | Confidence that the label is accurate. Range: [0, 1]. gcvvlfcConfidence :: Lens' GoogleCloudVideointelligenceV1p1beta1_LabelFrame (Maybe Double) gcvvlfcConfidence = lens _gcvvlfcConfidence (\ s a -> s{_gcvvlfcConfidence = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1p1beta1_LabelFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1LabelFrame" (\ o -> GoogleCloudVideointelligenceV1p1beta1_LabelFrame' <$> (o .:? "timeOffset") <*> (o .:? "confidence")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_LabelFrame where toJSON GoogleCloudVideointelligenceV1p1beta1_LabelFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvlfcTimeOffSet, ("confidence" .=) <$> _gcvvlfcConfidence]) -- | A vertex represents a 2D point in the image. NOTE: the normalized vertex -- coordinates are relative to the original image and range from 0 to 1. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_NormalizedVertex' smart constructor. data GoogleCloudVideointelligenceV1beta2_NormalizedVertex = GoogleCloudVideointelligenceV1beta2_NormalizedVertex' { _gX :: !(Maybe (Textual Double)) , _gY :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_NormalizedVertex' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gX' -- -- * 'gY' googleCloudVideointelligenceV1beta2_NormalizedVertex :: GoogleCloudVideointelligenceV1beta2_NormalizedVertex googleCloudVideointelligenceV1beta2_NormalizedVertex = GoogleCloudVideointelligenceV1beta2_NormalizedVertex' {_gX = Nothing, _gY = Nothing} -- | X coordinate. gX :: Lens' GoogleCloudVideointelligenceV1beta2_NormalizedVertex (Maybe Double) gX = lens _gX (\ s a -> s{_gX = a}) . mapping _Coerce -- | Y coordinate. gY :: Lens' GoogleCloudVideointelligenceV1beta2_NormalizedVertex (Maybe Double) gY = lens _gY (\ s a -> s{_gY = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1beta2_NormalizedVertex where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2NormalizedVertex" (\ o -> GoogleCloudVideointelligenceV1beta2_NormalizedVertex' <$> (o .:? "x") <*> (o .:? "y")) instance ToJSON GoogleCloudVideointelligenceV1beta2_NormalizedVertex where toJSON GoogleCloudVideointelligenceV1beta2_NormalizedVertex'{..} = object (catMaybes [("x" .=) <$> _gX, ("y" .=) <$> _gY]) -- | Face detection annotation. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation = GoogleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation' { _gcvvfdaThumbnail :: !(Maybe Bytes) , _gcvvfdaTracks :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_Track]) , _gcvvfdaVersion :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvfdaThumbnail' -- -- * 'gcvvfdaTracks' -- -- * 'gcvvfdaVersion' googleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation :: GoogleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation googleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation = GoogleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation' { _gcvvfdaThumbnail = Nothing , _gcvvfdaTracks = Nothing , _gcvvfdaVersion = Nothing } -- | The thumbnail of a person\'s face. gcvvfdaThumbnail :: Lens' GoogleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation (Maybe ByteString) gcvvfdaThumbnail = lens _gcvvfdaThumbnail (\ s a -> s{_gcvvfdaThumbnail = a}) . mapping _Bytes -- | The face tracks with attributes. gcvvfdaTracks :: Lens' GoogleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation [GoogleCloudVideointelligenceV1p3beta1_Track] gcvvfdaTracks = lens _gcvvfdaTracks (\ s a -> s{_gcvvfdaTracks = a}) . _Default . _Coerce -- | Feature version. gcvvfdaVersion :: Lens' GoogleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation (Maybe Text) gcvvfdaVersion = lens _gcvvfdaVersion (\ s a -> s{_gcvvfdaVersion = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1FaceDetectionAnnotation" (\ o -> GoogleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation' <$> (o .:? "thumbnail") <*> (o .:? "tracks" .!= mempty) <*> (o .:? "version")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation where toJSON GoogleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation'{..} = object (catMaybes [("thumbnail" .=) <$> _gcvvfdaThumbnail, ("tracks" .=) <$> _gcvvfdaTracks, ("version" .=) <$> _gcvvfdaVersion]) -- | Label annotation. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_LabelAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation = GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation' { _gCategoryEntities :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_Entity]) , _gFrames :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_LabelFrame]) , _gVersion :: !(Maybe Text) , _gSegments :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_LabelSegment]) , _gEntity :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_Entity) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gCategoryEntities' -- -- * 'gFrames' -- -- * 'gVersion' -- -- * 'gSegments' -- -- * 'gEntity' googleCloudVideointelligenceV1p3beta1_LabelAnnotation :: GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation googleCloudVideointelligenceV1p3beta1_LabelAnnotation = GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation' { _gCategoryEntities = Nothing , _gFrames = Nothing , _gVersion = Nothing , _gSegments = Nothing , _gEntity = Nothing } -- | Common categories for the detected entity. For example, when the label -- is \`Terrier\`, the category is likely \`dog\`. And in some cases there -- might be more than one categories e.g., \`Terrier\` could also be a -- \`pet\`. gCategoryEntities :: Lens' GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation [GoogleCloudVideointelligenceV1p3beta1_Entity] gCategoryEntities = lens _gCategoryEntities (\ s a -> s{_gCategoryEntities = a}) . _Default . _Coerce -- | All video frames where a label was detected. gFrames :: Lens' GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation [GoogleCloudVideointelligenceV1p3beta1_LabelFrame] gFrames = lens _gFrames (\ s a -> s{_gFrames = a}) . _Default . _Coerce -- | Feature version. gVersion :: Lens' GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation (Maybe Text) gVersion = lens _gVersion (\ s a -> s{_gVersion = a}) -- | All video segments where a label was detected. gSegments :: Lens' GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation [GoogleCloudVideointelligenceV1p3beta1_LabelSegment] gSegments = lens _gSegments (\ s a -> s{_gSegments = a}) . _Default . _Coerce -- | Detected entity. gEntity :: Lens' GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation (Maybe GoogleCloudVideointelligenceV1p3beta1_Entity) gEntity = lens _gEntity (\ s a -> s{_gEntity = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1LabelAnnotation" (\ o -> GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation' <$> (o .:? "categoryEntities" .!= mempty) <*> (o .:? "frames" .!= mempty) <*> (o .:? "version") <*> (o .:? "segments" .!= mempty) <*> (o .:? "entity")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation where toJSON GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation'{..} = object (catMaybes [("categoryEntities" .=) <$> _gCategoryEntities, ("frames" .=) <$> _gFrames, ("version" .=) <$> _gVersion, ("segments" .=) <$> _gSegments, ("entity" .=) <$> _gEntity]) -- | Explicit content annotation (based on per-frame visual signals only). If -- no explicit content has been detected in a frame, no annotations are -- present for that frame. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation = GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation' { _gooFrames :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFrame]) , _gooVersion :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gooFrames' -- -- * 'gooVersion' googleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation :: GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation googleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation = GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation' {_gooFrames = Nothing, _gooVersion = Nothing} -- | All video frames where explicit content was detected. gooFrames :: Lens' GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation [GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFrame] gooFrames = lens _gooFrames (\ s a -> s{_gooFrames = a}) . _Default . _Coerce -- | Feature version. gooVersion :: Lens' GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation (Maybe Text) gooVersion = lens _gooVersion (\ s a -> s{_gooVersion = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1ExplicitContentAnnotation" (\ o -> GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation' <$> (o .:? "frames" .!= mempty) <*> (o .:? "version")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation where toJSON GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation'{..} = object (catMaybes [("frames" .=) <$> _gooFrames, ("version" .=) <$> _gooVersion]) -- | Annotation corresponding to one detected, tracked and recognized logo -- class. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation = GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation' { _gooTracks :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_Track]) , _gooSegments :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_VideoSegment]) , _gooEntity :: !(Maybe GoogleCloudVideointelligenceV1p1beta1_Entity) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gooTracks' -- -- * 'gooSegments' -- -- * 'gooEntity' googleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation :: GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation googleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation = GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation' {_gooTracks = Nothing, _gooSegments = Nothing, _gooEntity = Nothing} -- | All logo tracks where the recognized logo appears. Each track -- corresponds to one logo instance appearing in consecutive frames. gooTracks :: Lens' GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation [GoogleCloudVideointelligenceV1p1beta1_Track] gooTracks = lens _gooTracks (\ s a -> s{_gooTracks = a}) . _Default . _Coerce -- | All video segments where the recognized logo appears. There might be -- multiple instances of the same logo class appearing in one VideoSegment. gooSegments :: Lens' GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation [GoogleCloudVideointelligenceV1p1beta1_VideoSegment] gooSegments = lens _gooSegments (\ s a -> s{_gooSegments = a}) . _Default . _Coerce -- | Entity category information to specify the logo class that all the logo -- tracks within this LogoRecognitionAnnotation are recognized as. gooEntity :: Lens' GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation (Maybe GoogleCloudVideointelligenceV1p1beta1_Entity) gooEntity = lens _gooEntity (\ s a -> s{_gooEntity = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1LogoRecognitionAnnotation" (\ o -> GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation' <$> (o .:? "tracks" .!= mempty) <*> (o .:? "segments" .!= mempty) <*> (o .:? "entity")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation where toJSON GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation'{..} = object (catMaybes [("tracks" .=) <$> _gooTracks, ("segments" .=) <$> _gooSegments, ("entity" .=) <$> _gooEntity]) -- | Face detection annotation. -- -- /See:/ 'googleCloudVideointelligenceV1_FaceDetectionAnnotation' smart constructor. data GoogleCloudVideointelligenceV1_FaceDetectionAnnotation = GoogleCloudVideointelligenceV1_FaceDetectionAnnotation' { _gcvvfdacThumbnail :: !(Maybe Bytes) , _gcvvfdacTracks :: !(Maybe [GoogleCloudVideointelligenceV1_Track]) , _gcvvfdacVersion :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_FaceDetectionAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvfdacThumbnail' -- -- * 'gcvvfdacTracks' -- -- * 'gcvvfdacVersion' googleCloudVideointelligenceV1_FaceDetectionAnnotation :: GoogleCloudVideointelligenceV1_FaceDetectionAnnotation googleCloudVideointelligenceV1_FaceDetectionAnnotation = GoogleCloudVideointelligenceV1_FaceDetectionAnnotation' { _gcvvfdacThumbnail = Nothing , _gcvvfdacTracks = Nothing , _gcvvfdacVersion = Nothing } -- | The thumbnail of a person\'s face. gcvvfdacThumbnail :: Lens' GoogleCloudVideointelligenceV1_FaceDetectionAnnotation (Maybe ByteString) gcvvfdacThumbnail = lens _gcvvfdacThumbnail (\ s a -> s{_gcvvfdacThumbnail = a}) . mapping _Bytes -- | The face tracks with attributes. gcvvfdacTracks :: Lens' GoogleCloudVideointelligenceV1_FaceDetectionAnnotation [GoogleCloudVideointelligenceV1_Track] gcvvfdacTracks = lens _gcvvfdacTracks (\ s a -> s{_gcvvfdacTracks = a}) . _Default . _Coerce -- | Feature version. gcvvfdacVersion :: Lens' GoogleCloudVideointelligenceV1_FaceDetectionAnnotation (Maybe Text) gcvvfdacVersion = lens _gcvvfdacVersion (\ s a -> s{_gcvvfdacVersion = a}) instance FromJSON GoogleCloudVideointelligenceV1_FaceDetectionAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1FaceDetectionAnnotation" (\ o -> GoogleCloudVideointelligenceV1_FaceDetectionAnnotation' <$> (o .:? "thumbnail") <*> (o .:? "tracks" .!= mempty) <*> (o .:? "version")) instance ToJSON GoogleCloudVideointelligenceV1_FaceDetectionAnnotation where toJSON GoogleCloudVideointelligenceV1_FaceDetectionAnnotation'{..} = object (catMaybes [("thumbnail" .=) <$> _gcvvfdacThumbnail, ("tracks" .=) <$> _gcvvfdacTracks, ("version" .=) <$> _gcvvfdacVersion]) -- | Detected entity from video analysis. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_Entity' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_Entity = GoogleCloudVideointelligenceV1p1beta1_Entity' { _gooLanguageCode :: !(Maybe Text) , _gooEntityId :: !(Maybe Text) , _gooDescription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_Entity' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gooLanguageCode' -- -- * 'gooEntityId' -- -- * 'gooDescription' googleCloudVideointelligenceV1p1beta1_Entity :: GoogleCloudVideointelligenceV1p1beta1_Entity googleCloudVideointelligenceV1p1beta1_Entity = GoogleCloudVideointelligenceV1p1beta1_Entity' { _gooLanguageCode = Nothing , _gooEntityId = Nothing , _gooDescription = Nothing } -- | Language code for \`description\` in BCP-47 format. gooLanguageCode :: Lens' GoogleCloudVideointelligenceV1p1beta1_Entity (Maybe Text) gooLanguageCode = lens _gooLanguageCode (\ s a -> s{_gooLanguageCode = a}) -- | Opaque entity ID. Some IDs may be available in [Google Knowledge Graph -- Search API](https:\/\/developers.google.com\/knowledge-graph\/). gooEntityId :: Lens' GoogleCloudVideointelligenceV1p1beta1_Entity (Maybe Text) gooEntityId = lens _gooEntityId (\ s a -> s{_gooEntityId = a}) -- | Textual description, e.g., \`Fixed-gear bicycle\`. gooDescription :: Lens' GoogleCloudVideointelligenceV1p1beta1_Entity (Maybe Text) gooDescription = lens _gooDescription (\ s a -> s{_gooDescription = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_Entity where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1Entity" (\ o -> GoogleCloudVideointelligenceV1p1beta1_Entity' <$> (o .:? "languageCode") <*> (o .:? "entityId") <*> (o .:? "description")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_Entity where toJSON GoogleCloudVideointelligenceV1p1beta1_Entity'{..} = object (catMaybes [("languageCode" .=) <$> _gooLanguageCode, ("entityId" .=) <$> _gooEntityId, ("description" .=) <$> _gooDescription]) -- | Video annotation response. Included in the \`response\` field of the -- \`Operation\` returned by the \`GetOperation\` call of the -- \`google::longrunning::Operations\` service. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_AnnotateVideoResponse' smart constructor. newtype GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoResponse = GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoResponse' { _gAnnotationResults :: Maybe [GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gAnnotationResults' googleCloudVideointelligenceV1p2beta1_AnnotateVideoResponse :: GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoResponse googleCloudVideointelligenceV1p2beta1_AnnotateVideoResponse = GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoResponse' {_gAnnotationResults = Nothing} -- | Annotation results for all videos specified in \`AnnotateVideoRequest\`. gAnnotationResults :: Lens' GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoResponse [GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults] gAnnotationResults = lens _gAnnotationResults (\ s a -> s{_gAnnotationResults = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoResponse where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1AnnotateVideoResponse" (\ o -> GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoResponse' <$> (o .:? "annotationResults" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoResponse where toJSON GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoResponse'{..} = object (catMaybes [("annotationResults" .=) <$> _gAnnotationResults]) -- | Video annotation progress. Included in the \`metadata\` field of the -- \`Operation\` returned by the \`GetOperation\` call of the -- \`google::longrunning::Operations\` service. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_AnnotateVideoProgress' smart constructor. newtype GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoProgress = GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoProgress' { _gAnnotationProgress :: Maybe [GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoProgress' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gAnnotationProgress' googleCloudVideointelligenceV1p1beta1_AnnotateVideoProgress :: GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoProgress googleCloudVideointelligenceV1p1beta1_AnnotateVideoProgress = GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoProgress' {_gAnnotationProgress = Nothing} -- | Progress metadata for all videos specified in \`AnnotateVideoRequest\`. gAnnotationProgress :: Lens' GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoProgress [GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress] gAnnotationProgress = lens _gAnnotationProgress (\ s a -> s{_gAnnotationProgress = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoProgress where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1AnnotateVideoProgress" (\ o -> GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoProgress' <$> (o .:? "annotationProgress" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoProgress where toJSON GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoProgress'{..} = object (catMaybes [("annotationProgress" .=) <$> _gAnnotationProgress]) -- | Deprecated. No effect. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_FaceAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_FaceAnnotation = GoogleCloudVideointelligenceV1p1beta1_FaceAnnotation' { _gcvvfacThumbnail :: !(Maybe Bytes) , _gcvvfacFrames :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_FaceFrame]) , _gcvvfacSegments :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_FaceSegment]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_FaceAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvfacThumbnail' -- -- * 'gcvvfacFrames' -- -- * 'gcvvfacSegments' googleCloudVideointelligenceV1p1beta1_FaceAnnotation :: GoogleCloudVideointelligenceV1p1beta1_FaceAnnotation googleCloudVideointelligenceV1p1beta1_FaceAnnotation = GoogleCloudVideointelligenceV1p1beta1_FaceAnnotation' { _gcvvfacThumbnail = Nothing , _gcvvfacFrames = Nothing , _gcvvfacSegments = Nothing } -- | Thumbnail of a representative face view (in JPEG format). gcvvfacThumbnail :: Lens' GoogleCloudVideointelligenceV1p1beta1_FaceAnnotation (Maybe ByteString) gcvvfacThumbnail = lens _gcvvfacThumbnail (\ s a -> s{_gcvvfacThumbnail = a}) . mapping _Bytes -- | All video frames where a face was detected. gcvvfacFrames :: Lens' GoogleCloudVideointelligenceV1p1beta1_FaceAnnotation [GoogleCloudVideointelligenceV1p1beta1_FaceFrame] gcvvfacFrames = lens _gcvvfacFrames (\ s a -> s{_gcvvfacFrames = a}) . _Default . _Coerce -- | All video segments where a face was detected. gcvvfacSegments :: Lens' GoogleCloudVideointelligenceV1p1beta1_FaceAnnotation [GoogleCloudVideointelligenceV1p1beta1_FaceSegment] gcvvfacSegments = lens _gcvvfacSegments (\ s a -> s{_gcvvfacSegments = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p1beta1_FaceAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1FaceAnnotation" (\ o -> GoogleCloudVideointelligenceV1p1beta1_FaceAnnotation' <$> (o .:? "thumbnail") <*> (o .:? "frames" .!= mempty) <*> (o .:? "segments" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_FaceAnnotation where toJSON GoogleCloudVideointelligenceV1p1beta1_FaceAnnotation'{..} = object (catMaybes [("thumbnail" .=) <$> _gcvvfacThumbnail, ("frames" .=) <$> _gcvvfacFrames, ("segments" .=) <$> _gcvvfacSegments]) -- | Annotation results for a single video. -- -- /See:/ 'googleCloudVideointelligenceV1_VideoAnnotationResults' smart constructor. data GoogleCloudVideointelligenceV1_VideoAnnotationResults = GoogleCloudVideointelligenceV1_VideoAnnotationResults' { _gcvvvarShotAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1_VideoSegment]) , _gcvvvarShotLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1_LabelAnnotation]) , _gcvvvarFaceDetectionAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1_FaceDetectionAnnotation]) , _gcvvvarFaceAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1_FaceAnnotation]) , _gcvvvarInputURI :: !(Maybe Text) , _gcvvvarError :: !(Maybe GoogleRpc_Status) , _gcvvvarShotPresenceLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1_LabelAnnotation]) , _gcvvvarPersonDetectionAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1_PersonDetectionAnnotation]) , _gcvvvarObjectAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation]) , _gcvvvarFrameLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1_LabelAnnotation]) , _gcvvvarSpeechTranscriptions :: !(Maybe [GoogleCloudVideointelligenceV1_SpeechTranscription]) , _gcvvvarSegmentPresenceLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1_LabelAnnotation]) , _gcvvvarLogoRecognitionAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1_LogoRecognitionAnnotation]) , _gcvvvarSegment :: !(Maybe GoogleCloudVideointelligenceV1_VideoSegment) , _gcvvvarTextAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1_TextAnnotation]) , _gcvvvarSegmentLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1_LabelAnnotation]) , _gcvvvarExplicitAnnotation :: !(Maybe GoogleCloudVideointelligenceV1_ExplicitContentAnnotation) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_VideoAnnotationResults' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvvarShotAnnotations' -- -- * 'gcvvvarShotLabelAnnotations' -- -- * 'gcvvvarFaceDetectionAnnotations' -- -- * 'gcvvvarFaceAnnotations' -- -- * 'gcvvvarInputURI' -- -- * 'gcvvvarError' -- -- * 'gcvvvarShotPresenceLabelAnnotations' -- -- * 'gcvvvarPersonDetectionAnnotations' -- -- * 'gcvvvarObjectAnnotations' -- -- * 'gcvvvarFrameLabelAnnotations' -- -- * 'gcvvvarSpeechTranscriptions' -- -- * 'gcvvvarSegmentPresenceLabelAnnotations' -- -- * 'gcvvvarLogoRecognitionAnnotations' -- -- * 'gcvvvarSegment' -- -- * 'gcvvvarTextAnnotations' -- -- * 'gcvvvarSegmentLabelAnnotations' -- -- * 'gcvvvarExplicitAnnotation' googleCloudVideointelligenceV1_VideoAnnotationResults :: GoogleCloudVideointelligenceV1_VideoAnnotationResults googleCloudVideointelligenceV1_VideoAnnotationResults = GoogleCloudVideointelligenceV1_VideoAnnotationResults' { _gcvvvarShotAnnotations = Nothing , _gcvvvarShotLabelAnnotations = Nothing , _gcvvvarFaceDetectionAnnotations = Nothing , _gcvvvarFaceAnnotations = Nothing , _gcvvvarInputURI = Nothing , _gcvvvarError = Nothing , _gcvvvarShotPresenceLabelAnnotations = Nothing , _gcvvvarPersonDetectionAnnotations = Nothing , _gcvvvarObjectAnnotations = Nothing , _gcvvvarFrameLabelAnnotations = Nothing , _gcvvvarSpeechTranscriptions = Nothing , _gcvvvarSegmentPresenceLabelAnnotations = Nothing , _gcvvvarLogoRecognitionAnnotations = Nothing , _gcvvvarSegment = Nothing , _gcvvvarTextAnnotations = Nothing , _gcvvvarSegmentLabelAnnotations = Nothing , _gcvvvarExplicitAnnotation = Nothing } -- | Shot annotations. Each shot is represented as a video segment. gcvvvarShotAnnotations :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults [GoogleCloudVideointelligenceV1_VideoSegment] gcvvvarShotAnnotations = lens _gcvvvarShotAnnotations (\ s a -> s{_gcvvvarShotAnnotations = a}) . _Default . _Coerce -- | Topical label annotations on shot level. There is exactly one element -- for each unique label. gcvvvarShotLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults [GoogleCloudVideointelligenceV1_LabelAnnotation] gcvvvarShotLabelAnnotations = lens _gcvvvarShotLabelAnnotations (\ s a -> s{_gcvvvarShotLabelAnnotations = a}) . _Default . _Coerce -- | Face detection annotations. gcvvvarFaceDetectionAnnotations :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults [GoogleCloudVideointelligenceV1_FaceDetectionAnnotation] gcvvvarFaceDetectionAnnotations = lens _gcvvvarFaceDetectionAnnotations (\ s a -> s{_gcvvvarFaceDetectionAnnotations = a}) . _Default . _Coerce -- | Deprecated. Please use \`face_detection_annotations\` instead. gcvvvarFaceAnnotations :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults [GoogleCloudVideointelligenceV1_FaceAnnotation] gcvvvarFaceAnnotations = lens _gcvvvarFaceAnnotations (\ s a -> s{_gcvvvarFaceAnnotations = a}) . _Default . _Coerce -- | Video file location in [Cloud -- Storage](https:\/\/cloud.google.com\/storage\/). gcvvvarInputURI :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults (Maybe Text) gcvvvarInputURI = lens _gcvvvarInputURI (\ s a -> s{_gcvvvarInputURI = a}) -- | If set, indicates an error. Note that for a single -- \`AnnotateVideoRequest\` some videos may succeed and some may fail. gcvvvarError :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults (Maybe GoogleRpc_Status) gcvvvarError = lens _gcvvvarError (\ s a -> s{_gcvvvarError = a}) -- | Presence label annotations on shot level. There is exactly one element -- for each unique label. Compared to the existing topical -- \`shot_label_annotations\`, this field presents more fine-grained, -- shot-level labels detected in video content and is made available only -- when the client sets \`LabelDetectionConfig.model\` to -- \"builtin\/latest\" in the request. gcvvvarShotPresenceLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults [GoogleCloudVideointelligenceV1_LabelAnnotation] gcvvvarShotPresenceLabelAnnotations = lens _gcvvvarShotPresenceLabelAnnotations (\ s a -> s{_gcvvvarShotPresenceLabelAnnotations = a}) . _Default . _Coerce -- | Person detection annotations. gcvvvarPersonDetectionAnnotations :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults [GoogleCloudVideointelligenceV1_PersonDetectionAnnotation] gcvvvarPersonDetectionAnnotations = lens _gcvvvarPersonDetectionAnnotations (\ s a -> s{_gcvvvarPersonDetectionAnnotations = a}) . _Default . _Coerce -- | Annotations for list of objects detected and tracked in video. gcvvvarObjectAnnotations :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults [GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation] gcvvvarObjectAnnotations = lens _gcvvvarObjectAnnotations (\ s a -> s{_gcvvvarObjectAnnotations = a}) . _Default . _Coerce -- | Label annotations on frame level. There is exactly one element for each -- unique label. gcvvvarFrameLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults [GoogleCloudVideointelligenceV1_LabelAnnotation] gcvvvarFrameLabelAnnotations = lens _gcvvvarFrameLabelAnnotations (\ s a -> s{_gcvvvarFrameLabelAnnotations = a}) . _Default . _Coerce -- | Speech transcription. gcvvvarSpeechTranscriptions :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults [GoogleCloudVideointelligenceV1_SpeechTranscription] gcvvvarSpeechTranscriptions = lens _gcvvvarSpeechTranscriptions (\ s a -> s{_gcvvvarSpeechTranscriptions = a}) . _Default . _Coerce -- | Presence label annotations on video level or user-specified segment -- level. There is exactly one element for each unique label. Compared to -- the existing topical \`segment_label_annotations\`, this field presents -- more fine-grained, segment-level labels detected in video content and is -- made available only when the client sets \`LabelDetectionConfig.model\` -- to \"builtin\/latest\" in the request. gcvvvarSegmentPresenceLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults [GoogleCloudVideointelligenceV1_LabelAnnotation] gcvvvarSegmentPresenceLabelAnnotations = lens _gcvvvarSegmentPresenceLabelAnnotations (\ s a -> s{_gcvvvarSegmentPresenceLabelAnnotations = a}) . _Default . _Coerce -- | Annotations for list of logos detected, tracked and recognized in video. gcvvvarLogoRecognitionAnnotations :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults [GoogleCloudVideointelligenceV1_LogoRecognitionAnnotation] gcvvvarLogoRecognitionAnnotations = lens _gcvvvarLogoRecognitionAnnotations (\ s a -> s{_gcvvvarLogoRecognitionAnnotations = a}) . _Default . _Coerce -- | Video segment on which the annotation is run. gcvvvarSegment :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults (Maybe GoogleCloudVideointelligenceV1_VideoSegment) gcvvvarSegment = lens _gcvvvarSegment (\ s a -> s{_gcvvvarSegment = a}) -- | OCR text detection and tracking. Annotations for list of detected text -- snippets. Each will have list of frame information associated with it. gcvvvarTextAnnotations :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults [GoogleCloudVideointelligenceV1_TextAnnotation] gcvvvarTextAnnotations = lens _gcvvvarTextAnnotations (\ s a -> s{_gcvvvarTextAnnotations = a}) . _Default . _Coerce -- | Topical label annotations on video level or user-specified segment -- level. There is exactly one element for each unique label. gcvvvarSegmentLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults [GoogleCloudVideointelligenceV1_LabelAnnotation] gcvvvarSegmentLabelAnnotations = lens _gcvvvarSegmentLabelAnnotations (\ s a -> s{_gcvvvarSegmentLabelAnnotations = a}) . _Default . _Coerce -- | Explicit content annotation. gcvvvarExplicitAnnotation :: Lens' GoogleCloudVideointelligenceV1_VideoAnnotationResults (Maybe GoogleCloudVideointelligenceV1_ExplicitContentAnnotation) gcvvvarExplicitAnnotation = lens _gcvvvarExplicitAnnotation (\ s a -> s{_gcvvvarExplicitAnnotation = a}) instance FromJSON GoogleCloudVideointelligenceV1_VideoAnnotationResults where parseJSON = withObject "GoogleCloudVideointelligenceV1VideoAnnotationResults" (\ o -> GoogleCloudVideointelligenceV1_VideoAnnotationResults' <$> (o .:? "shotAnnotations" .!= mempty) <*> (o .:? "shotLabelAnnotations" .!= mempty) <*> (o .:? "faceDetectionAnnotations" .!= mempty) <*> (o .:? "faceAnnotations" .!= mempty) <*> (o .:? "inputUri") <*> (o .:? "error") <*> (o .:? "shotPresenceLabelAnnotations" .!= mempty) <*> (o .:? "personDetectionAnnotations" .!= mempty) <*> (o .:? "objectAnnotations" .!= mempty) <*> (o .:? "frameLabelAnnotations" .!= mempty) <*> (o .:? "speechTranscriptions" .!= mempty) <*> (o .:? "segmentPresenceLabelAnnotations" .!= mempty) <*> (o .:? "logoRecognitionAnnotations" .!= mempty) <*> (o .:? "segment") <*> (o .:? "textAnnotations" .!= mempty) <*> (o .:? "segmentLabelAnnotations" .!= mempty) <*> (o .:? "explicitAnnotation")) instance ToJSON GoogleCloudVideointelligenceV1_VideoAnnotationResults where toJSON GoogleCloudVideointelligenceV1_VideoAnnotationResults'{..} = object (catMaybes [("shotAnnotations" .=) <$> _gcvvvarShotAnnotations, ("shotLabelAnnotations" .=) <$> _gcvvvarShotLabelAnnotations, ("faceDetectionAnnotations" .=) <$> _gcvvvarFaceDetectionAnnotations, ("faceAnnotations" .=) <$> _gcvvvarFaceAnnotations, ("inputUri" .=) <$> _gcvvvarInputURI, ("error" .=) <$> _gcvvvarError, ("shotPresenceLabelAnnotations" .=) <$> _gcvvvarShotPresenceLabelAnnotations, ("personDetectionAnnotations" .=) <$> _gcvvvarPersonDetectionAnnotations, ("objectAnnotations" .=) <$> _gcvvvarObjectAnnotations, ("frameLabelAnnotations" .=) <$> _gcvvvarFrameLabelAnnotations, ("speechTranscriptions" .=) <$> _gcvvvarSpeechTranscriptions, ("segmentPresenceLabelAnnotations" .=) <$> _gcvvvarSegmentPresenceLabelAnnotations, ("logoRecognitionAnnotations" .=) <$> _gcvvvarLogoRecognitionAnnotations, ("segment" .=) <$> _gcvvvarSegment, ("textAnnotations" .=) <$> _gcvvvarTextAnnotations, ("segmentLabelAnnotations" .=) <$> _gcvvvarSegmentLabelAnnotations, ("explicitAnnotation" .=) <$> _gcvvvarExplicitAnnotation]) -- | Config for SPEECH_TRANSCRIPTION. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig = GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig' { _gcvvstcSpeechContexts :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_SpeechContext]) , _gcvvstcLanguageCode :: !(Maybe Text) , _gcvvstcAudioTracks :: !(Maybe [Textual Int32]) , _gcvvstcEnableAutomaticPunctuation :: !(Maybe Bool) , _gcvvstcMaxAlternatives :: !(Maybe (Textual Int32)) , _gcvvstcEnableSpeakerDiarization :: !(Maybe Bool) , _gcvvstcFilterProfanity :: !(Maybe Bool) , _gcvvstcDiarizationSpeakerCount :: !(Maybe (Textual Int32)) , _gcvvstcEnableWordConfidence :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvstcSpeechContexts' -- -- * 'gcvvstcLanguageCode' -- -- * 'gcvvstcAudioTracks' -- -- * 'gcvvstcEnableAutomaticPunctuation' -- -- * 'gcvvstcMaxAlternatives' -- -- * 'gcvvstcEnableSpeakerDiarization' -- -- * 'gcvvstcFilterProfanity' -- -- * 'gcvvstcDiarizationSpeakerCount' -- -- * 'gcvvstcEnableWordConfidence' googleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig :: GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig googleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig = GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig' { _gcvvstcSpeechContexts = Nothing , _gcvvstcLanguageCode = Nothing , _gcvvstcAudioTracks = Nothing , _gcvvstcEnableAutomaticPunctuation = Nothing , _gcvvstcMaxAlternatives = Nothing , _gcvvstcEnableSpeakerDiarization = Nothing , _gcvvstcFilterProfanity = Nothing , _gcvvstcDiarizationSpeakerCount = Nothing , _gcvvstcEnableWordConfidence = Nothing } -- | Optional. A means to provide context to assist the speech recognition. gcvvstcSpeechContexts :: Lens' GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig [GoogleCloudVideointelligenceV1p3beta1_SpeechContext] gcvvstcSpeechContexts = lens _gcvvstcSpeechContexts (\ s a -> s{_gcvvstcSpeechContexts = a}) . _Default . _Coerce -- | Required. *Required* The language of the supplied audio as a -- [BCP-47](https:\/\/www.rfc-editor.org\/rfc\/bcp\/bcp47.txt) language -- tag. Example: \"en-US\". See [Language -- Support](https:\/\/cloud.google.com\/speech\/docs\/languages) for a list -- of the currently supported language codes. gcvvstcLanguageCode :: Lens' GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig (Maybe Text) gcvvstcLanguageCode = lens _gcvvstcLanguageCode (\ s a -> s{_gcvvstcLanguageCode = a}) -- | Optional. For file formats, such as MXF or MKV, supporting multiple -- audio tracks, specify up to two tracks. Default: track 0. gcvvstcAudioTracks :: Lens' GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig [Int32] gcvvstcAudioTracks = lens _gcvvstcAudioTracks (\ s a -> s{_gcvvstcAudioTracks = a}) . _Default . _Coerce -- | Optional. If \'true\', adds punctuation to recognition result -- hypotheses. This feature is only available in select languages. Setting -- this for requests in other languages has no effect at all. The default -- \'false\' value does not add punctuation to result hypotheses. NOTE: -- \"This is currently offered as an experimental service, complimentary to -- all users. In the future this may be exclusively available as a premium -- feature.\" gcvvstcEnableAutomaticPunctuation :: Lens' GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig (Maybe Bool) gcvvstcEnableAutomaticPunctuation = lens _gcvvstcEnableAutomaticPunctuation (\ s a -> s{_gcvvstcEnableAutomaticPunctuation = a}) -- | Optional. Maximum number of recognition hypotheses to be returned. -- Specifically, the maximum number of \`SpeechRecognitionAlternative\` -- messages within each \`SpeechTranscription\`. The server may return -- fewer than \`max_alternatives\`. Valid values are \`0\`-\`30\`. A value -- of \`0\` or \`1\` will return a maximum of one. If omitted, will return -- a maximum of one. gcvvstcMaxAlternatives :: Lens' GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig (Maybe Int32) gcvvstcMaxAlternatives = lens _gcvvstcMaxAlternatives (\ s a -> s{_gcvvstcMaxAlternatives = a}) . mapping _Coerce -- | Optional. If \'true\', enables speaker detection for each recognized -- word in the top alternative of the recognition result using a -- speaker_tag provided in the WordInfo. Note: When this is true, we send -- all the words from the beginning of the audio for the top alternative in -- every consecutive response. This is done in order to improve our speaker -- tags as our models learn to identify the speakers in the conversation -- over time. gcvvstcEnableSpeakerDiarization :: Lens' GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig (Maybe Bool) gcvvstcEnableSpeakerDiarization = lens _gcvvstcEnableSpeakerDiarization (\ s a -> s{_gcvvstcEnableSpeakerDiarization = a}) -- | Optional. If set to \`true\`, the server will attempt to filter out -- profanities, replacing all but the initial character in each filtered -- word with asterisks, e.g. \"f***\". If set to \`false\` or omitted, -- profanities won\'t be filtered out. gcvvstcFilterProfanity :: Lens' GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig (Maybe Bool) gcvvstcFilterProfanity = lens _gcvvstcFilterProfanity (\ s a -> s{_gcvvstcFilterProfanity = a}) -- | Optional. If set, specifies the estimated number of speakers in the -- conversation. If not set, defaults to \'2\'. Ignored unless -- enable_speaker_diarization is set to true. gcvvstcDiarizationSpeakerCount :: Lens' GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig (Maybe Int32) gcvvstcDiarizationSpeakerCount = lens _gcvvstcDiarizationSpeakerCount (\ s a -> s{_gcvvstcDiarizationSpeakerCount = a}) . mapping _Coerce -- | Optional. If \`true\`, the top result includes a list of words and the -- confidence for those words. If \`false\`, no word-level confidence -- information is returned. The default is \`false\`. gcvvstcEnableWordConfidence :: Lens' GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig (Maybe Bool) gcvvstcEnableWordConfidence = lens _gcvvstcEnableWordConfidence (\ s a -> s{_gcvvstcEnableWordConfidence = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1SpeechTranscriptionConfig" (\ o -> GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig' <$> (o .:? "speechContexts" .!= mempty) <*> (o .:? "languageCode") <*> (o .:? "audioTracks" .!= mempty) <*> (o .:? "enableAutomaticPunctuation") <*> (o .:? "maxAlternatives") <*> (o .:? "enableSpeakerDiarization") <*> (o .:? "filterProfanity") <*> (o .:? "diarizationSpeakerCount") <*> (o .:? "enableWordConfidence")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig where toJSON GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig'{..} = object (catMaybes [("speechContexts" .=) <$> _gcvvstcSpeechContexts, ("languageCode" .=) <$> _gcvvstcLanguageCode, ("audioTracks" .=) <$> _gcvvstcAudioTracks, ("enableAutomaticPunctuation" .=) <$> _gcvvstcEnableAutomaticPunctuation, ("maxAlternatives" .=) <$> _gcvvstcMaxAlternatives, ("enableSpeakerDiarization" .=) <$> _gcvvstcEnableSpeakerDiarization, ("filterProfanity" .=) <$> _gcvvstcFilterProfanity, ("diarizationSpeakerCount" .=) <$> _gcvvstcDiarizationSpeakerCount, ("enableWordConfidence" .=) <$> _gcvvstcEnableWordConfidence]) -- | A generic detected landmark represented by name in string format and a -- 2D location. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_DetectedLandmark' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_DetectedLandmark = GoogleCloudVideointelligenceV1p3beta1_DetectedLandmark' { _gcvvdlConfidence :: !(Maybe (Textual Double)) , _gcvvdlPoint :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_NormalizedVertex) , _gcvvdlName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_DetectedLandmark' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvdlConfidence' -- -- * 'gcvvdlPoint' -- -- * 'gcvvdlName' googleCloudVideointelligenceV1p3beta1_DetectedLandmark :: GoogleCloudVideointelligenceV1p3beta1_DetectedLandmark googleCloudVideointelligenceV1p3beta1_DetectedLandmark = GoogleCloudVideointelligenceV1p3beta1_DetectedLandmark' {_gcvvdlConfidence = Nothing, _gcvvdlPoint = Nothing, _gcvvdlName = Nothing} -- | The confidence score of the detected landmark. Range [0, 1]. gcvvdlConfidence :: Lens' GoogleCloudVideointelligenceV1p3beta1_DetectedLandmark (Maybe Double) gcvvdlConfidence = lens _gcvvdlConfidence (\ s a -> s{_gcvvdlConfidence = a}) . mapping _Coerce -- | The 2D point of the detected landmark using the normalized image -- coordindate system. The normalized coordinates have the range from 0 to -- 1. gcvvdlPoint :: Lens' GoogleCloudVideointelligenceV1p3beta1_DetectedLandmark (Maybe GoogleCloudVideointelligenceV1p3beta1_NormalizedVertex) gcvvdlPoint = lens _gcvvdlPoint (\ s a -> s{_gcvvdlPoint = a}) -- | The name of this landmark, for example, left_hand, right_shoulder. gcvvdlName :: Lens' GoogleCloudVideointelligenceV1p3beta1_DetectedLandmark (Maybe Text) gcvvdlName = lens _gcvvdlName (\ s a -> s{_gcvvdlName = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_DetectedLandmark where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1DetectedLandmark" (\ o -> GoogleCloudVideointelligenceV1p3beta1_DetectedLandmark' <$> (o .:? "confidence") <*> (o .:? "point") <*> (o .:? "name")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_DetectedLandmark where toJSON GoogleCloudVideointelligenceV1p3beta1_DetectedLandmark'{..} = object (catMaybes [("confidence" .=) <$> _gcvvdlConfidence, ("point" .=) <$> _gcvvdlPoint, ("name" .=) <$> _gcvvdlName]) -- | Deprecated. No effect. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_FaceFrame' smart constructor. data GoogleCloudVideointelligenceV1beta2_FaceFrame = GoogleCloudVideointelligenceV1beta2_FaceFrame' { _gooTimeOffSet :: !(Maybe GDuration) , _gooNormalizedBoundingBoxes :: !(Maybe [GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_FaceFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gooTimeOffSet' -- -- * 'gooNormalizedBoundingBoxes' googleCloudVideointelligenceV1beta2_FaceFrame :: GoogleCloudVideointelligenceV1beta2_FaceFrame googleCloudVideointelligenceV1beta2_FaceFrame = GoogleCloudVideointelligenceV1beta2_FaceFrame' {_gooTimeOffSet = Nothing, _gooNormalizedBoundingBoxes = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this location. gooTimeOffSet :: Lens' GoogleCloudVideointelligenceV1beta2_FaceFrame (Maybe Scientific) gooTimeOffSet = lens _gooTimeOffSet (\ s a -> s{_gooTimeOffSet = a}) . mapping _GDuration -- | Normalized Bounding boxes in a frame. There can be more than one boxes -- if the same face is detected in multiple locations within the current -- frame. gooNormalizedBoundingBoxes :: Lens' GoogleCloudVideointelligenceV1beta2_FaceFrame [GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox] gooNormalizedBoundingBoxes = lens _gooNormalizedBoundingBoxes (\ s a -> s{_gooNormalizedBoundingBoxes = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1beta2_FaceFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2FaceFrame" (\ o -> GoogleCloudVideointelligenceV1beta2_FaceFrame' <$> (o .:? "timeOffset") <*> (o .:? "normalizedBoundingBoxes" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1beta2_FaceFrame where toJSON GoogleCloudVideointelligenceV1beta2_FaceFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _gooTimeOffSet, ("normalizedBoundingBoxes" .=) <$> _gooNormalizedBoundingBoxes]) -- | Annotations corresponding to one tracked object. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation = GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation' { _gcvvotaFrames :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingFrame]) , _gcvvotaConfidence :: !(Maybe (Textual Double)) , _gcvvotaVersion :: !(Maybe Text) , _gcvvotaTrackId :: !(Maybe (Textual Int64)) , _gcvvotaSegment :: !(Maybe GoogleCloudVideointelligenceV1p2beta1_VideoSegment) , _gcvvotaEntity :: !(Maybe GoogleCloudVideointelligenceV1p2beta1_Entity) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvotaFrames' -- -- * 'gcvvotaConfidence' -- -- * 'gcvvotaVersion' -- -- * 'gcvvotaTrackId' -- -- * 'gcvvotaSegment' -- -- * 'gcvvotaEntity' googleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation :: GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation googleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation = GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation' { _gcvvotaFrames = Nothing , _gcvvotaConfidence = Nothing , _gcvvotaVersion = Nothing , _gcvvotaTrackId = Nothing , _gcvvotaSegment = Nothing , _gcvvotaEntity = Nothing } -- | Information corresponding to all frames where this object track appears. -- Non-streaming batch mode: it may be one or multiple ObjectTrackingFrame -- messages in frames. Streaming mode: it can only be one -- ObjectTrackingFrame message in frames. gcvvotaFrames :: Lens' GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation [GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingFrame] gcvvotaFrames = lens _gcvvotaFrames (\ s a -> s{_gcvvotaFrames = a}) . _Default . _Coerce -- | Object category\'s labeling confidence of this track. gcvvotaConfidence :: Lens' GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation (Maybe Double) gcvvotaConfidence = lens _gcvvotaConfidence (\ s a -> s{_gcvvotaConfidence = a}) . mapping _Coerce -- | Feature version. gcvvotaVersion :: Lens' GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation (Maybe Text) gcvvotaVersion = lens _gcvvotaVersion (\ s a -> s{_gcvvotaVersion = a}) -- | Streaming mode ONLY. In streaming mode, we do not know the end time of a -- tracked object before it is completed. Hence, there is no VideoSegment -- info returned. Instead, we provide a unique identifiable integer -- track_id so that the customers can correlate the results of the ongoing -- ObjectTrackAnnotation of the same track_id over time. gcvvotaTrackId :: Lens' GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation (Maybe Int64) gcvvotaTrackId = lens _gcvvotaTrackId (\ s a -> s{_gcvvotaTrackId = a}) . mapping _Coerce -- | Non-streaming batch mode ONLY. Each object track corresponds to one -- video segment where it appears. gcvvotaSegment :: Lens' GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation (Maybe GoogleCloudVideointelligenceV1p2beta1_VideoSegment) gcvvotaSegment = lens _gcvvotaSegment (\ s a -> s{_gcvvotaSegment = a}) -- | Entity to specify the object category that this track is labeled as. gcvvotaEntity :: Lens' GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation (Maybe GoogleCloudVideointelligenceV1p2beta1_Entity) gcvvotaEntity = lens _gcvvotaEntity (\ s a -> s{_gcvvotaEntity = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1ObjectTrackingAnnotation" (\ o -> GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation' <$> (o .:? "frames" .!= mempty) <*> (o .:? "confidence") <*> (o .:? "version") <*> (o .:? "trackId") <*> (o .:? "segment") <*> (o .:? "entity")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation where toJSON GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation'{..} = object (catMaybes [("frames" .=) <$> _gcvvotaFrames, ("confidence" .=) <$> _gcvvotaConfidence, ("version" .=) <$> _gcvvotaVersion, ("trackId" .=) <$> _gcvvotaTrackId, ("segment" .=) <$> _gcvvotaSegment, ("entity" .=) <$> _gcvvotaEntity]) -- | Annotation results for a single video. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_VideoAnnotationResults' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults = GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults' { _gcvvvarsShotAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_VideoSegment]) , _gcvvvarsShotLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation]) , _gcvvvarsFaceDetectionAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation]) , _gcvvvarsFaceAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_FaceAnnotation]) , _gcvvvarsCelebrityRecognitionAnnotations :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_CelebrityRecognitionAnnotation) , _gcvvvarsInputURI :: !(Maybe Text) , _gcvvvarsError :: !(Maybe GoogleRpc_Status) , _gcvvvarsShotPresenceLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation]) , _gcvvvarsPersonDetectionAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_PersonDetectionAnnotation]) , _gcvvvarsObjectAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation]) , _gcvvvarsFrameLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation]) , _gcvvvarsSpeechTranscriptions :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_SpeechTranscription]) , _gcvvvarsSegmentPresenceLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation]) , _gcvvvarsLogoRecognitionAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation]) , _gcvvvarsSegment :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_VideoSegment) , _gcvvvarsTextAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_TextAnnotation]) , _gcvvvarsSegmentLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation]) , _gcvvvarsExplicitAnnotation :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvvarsShotAnnotations' -- -- * 'gcvvvarsShotLabelAnnotations' -- -- * 'gcvvvarsFaceDetectionAnnotations' -- -- * 'gcvvvarsFaceAnnotations' -- -- * 'gcvvvarsCelebrityRecognitionAnnotations' -- -- * 'gcvvvarsInputURI' -- -- * 'gcvvvarsError' -- -- * 'gcvvvarsShotPresenceLabelAnnotations' -- -- * 'gcvvvarsPersonDetectionAnnotations' -- -- * 'gcvvvarsObjectAnnotations' -- -- * 'gcvvvarsFrameLabelAnnotations' -- -- * 'gcvvvarsSpeechTranscriptions' -- -- * 'gcvvvarsSegmentPresenceLabelAnnotations' -- -- * 'gcvvvarsLogoRecognitionAnnotations' -- -- * 'gcvvvarsSegment' -- -- * 'gcvvvarsTextAnnotations' -- -- * 'gcvvvarsSegmentLabelAnnotations' -- -- * 'gcvvvarsExplicitAnnotation' googleCloudVideointelligenceV1p3beta1_VideoAnnotationResults :: GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults googleCloudVideointelligenceV1p3beta1_VideoAnnotationResults = GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults' { _gcvvvarsShotAnnotations = Nothing , _gcvvvarsShotLabelAnnotations = Nothing , _gcvvvarsFaceDetectionAnnotations = Nothing , _gcvvvarsFaceAnnotations = Nothing , _gcvvvarsCelebrityRecognitionAnnotations = Nothing , _gcvvvarsInputURI = Nothing , _gcvvvarsError = Nothing , _gcvvvarsShotPresenceLabelAnnotations = Nothing , _gcvvvarsPersonDetectionAnnotations = Nothing , _gcvvvarsObjectAnnotations = Nothing , _gcvvvarsFrameLabelAnnotations = Nothing , _gcvvvarsSpeechTranscriptions = Nothing , _gcvvvarsSegmentPresenceLabelAnnotations = Nothing , _gcvvvarsLogoRecognitionAnnotations = Nothing , _gcvvvarsSegment = Nothing , _gcvvvarsTextAnnotations = Nothing , _gcvvvarsSegmentLabelAnnotations = Nothing , _gcvvvarsExplicitAnnotation = Nothing } -- | Shot annotations. Each shot is represented as a video segment. gcvvvarsShotAnnotations :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p3beta1_VideoSegment] gcvvvarsShotAnnotations = lens _gcvvvarsShotAnnotations (\ s a -> s{_gcvvvarsShotAnnotations = a}) . _Default . _Coerce -- | Topical label annotations on shot level. There is exactly one element -- for each unique label. gcvvvarsShotLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation] gcvvvarsShotLabelAnnotations = lens _gcvvvarsShotLabelAnnotations (\ s a -> s{_gcvvvarsShotLabelAnnotations = a}) . _Default . _Coerce -- | Face detection annotations. gcvvvarsFaceDetectionAnnotations :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p3beta1_FaceDetectionAnnotation] gcvvvarsFaceDetectionAnnotations = lens _gcvvvarsFaceDetectionAnnotations (\ s a -> s{_gcvvvarsFaceDetectionAnnotations = a}) . _Default . _Coerce -- | Deprecated. Please use \`face_detection_annotations\` instead. gcvvvarsFaceAnnotations :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p3beta1_FaceAnnotation] gcvvvarsFaceAnnotations = lens _gcvvvarsFaceAnnotations (\ s a -> s{_gcvvvarsFaceAnnotations = a}) . _Default . _Coerce -- | Celebrity recognition annotations. gcvvvarsCelebrityRecognitionAnnotations :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults (Maybe GoogleCloudVideointelligenceV1p3beta1_CelebrityRecognitionAnnotation) gcvvvarsCelebrityRecognitionAnnotations = lens _gcvvvarsCelebrityRecognitionAnnotations (\ s a -> s{_gcvvvarsCelebrityRecognitionAnnotations = a}) -- | Video file location in [Cloud -- Storage](https:\/\/cloud.google.com\/storage\/). gcvvvarsInputURI :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults (Maybe Text) gcvvvarsInputURI = lens _gcvvvarsInputURI (\ s a -> s{_gcvvvarsInputURI = a}) -- | If set, indicates an error. Note that for a single -- \`AnnotateVideoRequest\` some videos may succeed and some may fail. gcvvvarsError :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults (Maybe GoogleRpc_Status) gcvvvarsError = lens _gcvvvarsError (\ s a -> s{_gcvvvarsError = a}) -- | Presence label annotations on shot level. There is exactly one element -- for each unique label. Compared to the existing topical -- \`shot_label_annotations\`, this field presents more fine-grained, -- shot-level labels detected in video content and is made available only -- when the client sets \`LabelDetectionConfig.model\` to -- \"builtin\/latest\" in the request. gcvvvarsShotPresenceLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation] gcvvvarsShotPresenceLabelAnnotations = lens _gcvvvarsShotPresenceLabelAnnotations (\ s a -> s{_gcvvvarsShotPresenceLabelAnnotations = a}) . _Default . _Coerce -- | Person detection annotations. gcvvvarsPersonDetectionAnnotations :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p3beta1_PersonDetectionAnnotation] gcvvvarsPersonDetectionAnnotations = lens _gcvvvarsPersonDetectionAnnotations (\ s a -> s{_gcvvvarsPersonDetectionAnnotations = a}) . _Default . _Coerce -- | Annotations for list of objects detected and tracked in video. gcvvvarsObjectAnnotations :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation] gcvvvarsObjectAnnotations = lens _gcvvvarsObjectAnnotations (\ s a -> s{_gcvvvarsObjectAnnotations = a}) . _Default . _Coerce -- | Label annotations on frame level. There is exactly one element for each -- unique label. gcvvvarsFrameLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation] gcvvvarsFrameLabelAnnotations = lens _gcvvvarsFrameLabelAnnotations (\ s a -> s{_gcvvvarsFrameLabelAnnotations = a}) . _Default . _Coerce -- | Speech transcription. gcvvvarsSpeechTranscriptions :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p3beta1_SpeechTranscription] gcvvvarsSpeechTranscriptions = lens _gcvvvarsSpeechTranscriptions (\ s a -> s{_gcvvvarsSpeechTranscriptions = a}) . _Default . _Coerce -- | Presence label annotations on video level or user-specified segment -- level. There is exactly one element for each unique label. Compared to -- the existing topical \`segment_label_annotations\`, this field presents -- more fine-grained, segment-level labels detected in video content and is -- made available only when the client sets \`LabelDetectionConfig.model\` -- to \"builtin\/latest\" in the request. gcvvvarsSegmentPresenceLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation] gcvvvarsSegmentPresenceLabelAnnotations = lens _gcvvvarsSegmentPresenceLabelAnnotations (\ s a -> s{_gcvvvarsSegmentPresenceLabelAnnotations = a}) . _Default . _Coerce -- | Annotations for list of logos detected, tracked and recognized in video. gcvvvarsLogoRecognitionAnnotations :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation] gcvvvarsLogoRecognitionAnnotations = lens _gcvvvarsLogoRecognitionAnnotations (\ s a -> s{_gcvvvarsLogoRecognitionAnnotations = a}) . _Default . _Coerce -- | Video segment on which the annotation is run. gcvvvarsSegment :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults (Maybe GoogleCloudVideointelligenceV1p3beta1_VideoSegment) gcvvvarsSegment = lens _gcvvvarsSegment (\ s a -> s{_gcvvvarsSegment = a}) -- | OCR text detection and tracking. Annotations for list of detected text -- snippets. Each will have list of frame information associated with it. gcvvvarsTextAnnotations :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p3beta1_TextAnnotation] gcvvvarsTextAnnotations = lens _gcvvvarsTextAnnotations (\ s a -> s{_gcvvvarsTextAnnotations = a}) . _Default . _Coerce -- | Topical label annotations on video level or user-specified segment -- level. There is exactly one element for each unique label. gcvvvarsSegmentLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p3beta1_LabelAnnotation] gcvvvarsSegmentLabelAnnotations = lens _gcvvvarsSegmentLabelAnnotations (\ s a -> s{_gcvvvarsSegmentLabelAnnotations = a}) . _Default . _Coerce -- | Explicit content annotation. gcvvvarsExplicitAnnotation :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults (Maybe GoogleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation) gcvvvarsExplicitAnnotation = lens _gcvvvarsExplicitAnnotation (\ s a -> s{_gcvvvarsExplicitAnnotation = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1VideoAnnotationResults" (\ o -> GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults' <$> (o .:? "shotAnnotations" .!= mempty) <*> (o .:? "shotLabelAnnotations" .!= mempty) <*> (o .:? "faceDetectionAnnotations" .!= mempty) <*> (o .:? "faceAnnotations" .!= mempty) <*> (o .:? "celebrityRecognitionAnnotations") <*> (o .:? "inputUri") <*> (o .:? "error") <*> (o .:? "shotPresenceLabelAnnotations" .!= mempty) <*> (o .:? "personDetectionAnnotations" .!= mempty) <*> (o .:? "objectAnnotations" .!= mempty) <*> (o .:? "frameLabelAnnotations" .!= mempty) <*> (o .:? "speechTranscriptions" .!= mempty) <*> (o .:? "segmentPresenceLabelAnnotations" .!= mempty) <*> (o .:? "logoRecognitionAnnotations" .!= mempty) <*> (o .:? "segment") <*> (o .:? "textAnnotations" .!= mempty) <*> (o .:? "segmentLabelAnnotations" .!= mempty) <*> (o .:? "explicitAnnotation")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults where toJSON GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults'{..} = object (catMaybes [("shotAnnotations" .=) <$> _gcvvvarsShotAnnotations, ("shotLabelAnnotations" .=) <$> _gcvvvarsShotLabelAnnotations, ("faceDetectionAnnotations" .=) <$> _gcvvvarsFaceDetectionAnnotations, ("faceAnnotations" .=) <$> _gcvvvarsFaceAnnotations, ("celebrityRecognitionAnnotations" .=) <$> _gcvvvarsCelebrityRecognitionAnnotations, ("inputUri" .=) <$> _gcvvvarsInputURI, ("error" .=) <$> _gcvvvarsError, ("shotPresenceLabelAnnotations" .=) <$> _gcvvvarsShotPresenceLabelAnnotations, ("personDetectionAnnotations" .=) <$> _gcvvvarsPersonDetectionAnnotations, ("objectAnnotations" .=) <$> _gcvvvarsObjectAnnotations, ("frameLabelAnnotations" .=) <$> _gcvvvarsFrameLabelAnnotations, ("speechTranscriptions" .=) <$> _gcvvvarsSpeechTranscriptions, ("segmentPresenceLabelAnnotations" .=) <$> _gcvvvarsSegmentPresenceLabelAnnotations, ("logoRecognitionAnnotations" .=) <$> _gcvvvarsLogoRecognitionAnnotations, ("segment" .=) <$> _gcvvvarsSegment, ("textAnnotations" .=) <$> _gcvvvarsTextAnnotations, ("segmentLabelAnnotations" .=) <$> _gcvvvarsSegmentLabelAnnotations, ("explicitAnnotation" .=) <$> _gcvvvarsExplicitAnnotation]) -- | Person detection annotation per video. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_PersonDetectionAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_PersonDetectionAnnotation = GoogleCloudVideointelligenceV1p2beta1_PersonDetectionAnnotation' { _gcvvpdaTracks :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_Track]) , _gcvvpdaVersion :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_PersonDetectionAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvpdaTracks' -- -- * 'gcvvpdaVersion' googleCloudVideointelligenceV1p2beta1_PersonDetectionAnnotation :: GoogleCloudVideointelligenceV1p2beta1_PersonDetectionAnnotation googleCloudVideointelligenceV1p2beta1_PersonDetectionAnnotation = GoogleCloudVideointelligenceV1p2beta1_PersonDetectionAnnotation' {_gcvvpdaTracks = Nothing, _gcvvpdaVersion = Nothing} -- | The detected tracks of a person. gcvvpdaTracks :: Lens' GoogleCloudVideointelligenceV1p2beta1_PersonDetectionAnnotation [GoogleCloudVideointelligenceV1p2beta1_Track] gcvvpdaTracks = lens _gcvvpdaTracks (\ s a -> s{_gcvvpdaTracks = a}) . _Default . _Coerce -- | Feature version. gcvvpdaVersion :: Lens' GoogleCloudVideointelligenceV1p2beta1_PersonDetectionAnnotation (Maybe Text) gcvvpdaVersion = lens _gcvvpdaVersion (\ s a -> s{_gcvvpdaVersion = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_PersonDetectionAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1PersonDetectionAnnotation" (\ o -> GoogleCloudVideointelligenceV1p2beta1_PersonDetectionAnnotation' <$> (o .:? "tracks" .!= mempty) <*> (o .:? "version")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_PersonDetectionAnnotation where toJSON GoogleCloudVideointelligenceV1p2beta1_PersonDetectionAnnotation'{..} = object (catMaybes [("tracks" .=) <$> _gcvvpdaTracks, ("version" .=) <$> _gcvvpdaVersion]) -- | A generic detected landmark represented by name in string format and a -- 2D location. -- -- /See:/ 'googleCloudVideointelligenceV1_DetectedLandmark' smart constructor. data GoogleCloudVideointelligenceV1_DetectedLandmark = GoogleCloudVideointelligenceV1_DetectedLandmark' { _gcvvdlcConfidence :: !(Maybe (Textual Double)) , _gcvvdlcPoint :: !(Maybe GoogleCloudVideointelligenceV1_NormalizedVertex) , _gcvvdlcName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_DetectedLandmark' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvdlcConfidence' -- -- * 'gcvvdlcPoint' -- -- * 'gcvvdlcName' googleCloudVideointelligenceV1_DetectedLandmark :: GoogleCloudVideointelligenceV1_DetectedLandmark googleCloudVideointelligenceV1_DetectedLandmark = GoogleCloudVideointelligenceV1_DetectedLandmark' { _gcvvdlcConfidence = Nothing , _gcvvdlcPoint = Nothing , _gcvvdlcName = Nothing } -- | The confidence score of the detected landmark. Range [0, 1]. gcvvdlcConfidence :: Lens' GoogleCloudVideointelligenceV1_DetectedLandmark (Maybe Double) gcvvdlcConfidence = lens _gcvvdlcConfidence (\ s a -> s{_gcvvdlcConfidence = a}) . mapping _Coerce -- | The 2D point of the detected landmark using the normalized image -- coordindate system. The normalized coordinates have the range from 0 to -- 1. gcvvdlcPoint :: Lens' GoogleCloudVideointelligenceV1_DetectedLandmark (Maybe GoogleCloudVideointelligenceV1_NormalizedVertex) gcvvdlcPoint = lens _gcvvdlcPoint (\ s a -> s{_gcvvdlcPoint = a}) -- | The name of this landmark, for example, left_hand, right_shoulder. gcvvdlcName :: Lens' GoogleCloudVideointelligenceV1_DetectedLandmark (Maybe Text) gcvvdlcName = lens _gcvvdlcName (\ s a -> s{_gcvvdlcName = a}) instance FromJSON GoogleCloudVideointelligenceV1_DetectedLandmark where parseJSON = withObject "GoogleCloudVideointelligenceV1DetectedLandmark" (\ o -> GoogleCloudVideointelligenceV1_DetectedLandmark' <$> (o .:? "confidence") <*> (o .:? "point") <*> (o .:? "name")) instance ToJSON GoogleCloudVideointelligenceV1_DetectedLandmark where toJSON GoogleCloudVideointelligenceV1_DetectedLandmark'{..} = object (catMaybes [("confidence" .=) <$> _gcvvdlcConfidence, ("point" .=) <$> _gcvvdlcPoint, ("name" .=) <$> _gcvvdlcName]) -- | Config for FACE_DETECTION. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_FaceDetectionConfig' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_FaceDetectionConfig = GoogleCloudVideointelligenceV1p3beta1_FaceDetectionConfig' { _gcvvfdcModel :: !(Maybe Text) , _gcvvfdcIncludeBoundingBoxes :: !(Maybe Bool) , _gcvvfdcIncludeAttributes :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_FaceDetectionConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvfdcModel' -- -- * 'gcvvfdcIncludeBoundingBoxes' -- -- * 'gcvvfdcIncludeAttributes' googleCloudVideointelligenceV1p3beta1_FaceDetectionConfig :: GoogleCloudVideointelligenceV1p3beta1_FaceDetectionConfig googleCloudVideointelligenceV1p3beta1_FaceDetectionConfig = GoogleCloudVideointelligenceV1p3beta1_FaceDetectionConfig' { _gcvvfdcModel = Nothing , _gcvvfdcIncludeBoundingBoxes = Nothing , _gcvvfdcIncludeAttributes = Nothing } -- | Model to use for face detection. Supported values: \"builtin\/stable\" -- (the default if unset) and \"builtin\/latest\". gcvvfdcModel :: Lens' GoogleCloudVideointelligenceV1p3beta1_FaceDetectionConfig (Maybe Text) gcvvfdcModel = lens _gcvvfdcModel (\ s a -> s{_gcvvfdcModel = a}) -- | Whether bounding boxes are included in the face annotation output. gcvvfdcIncludeBoundingBoxes :: Lens' GoogleCloudVideointelligenceV1p3beta1_FaceDetectionConfig (Maybe Bool) gcvvfdcIncludeBoundingBoxes = lens _gcvvfdcIncludeBoundingBoxes (\ s a -> s{_gcvvfdcIncludeBoundingBoxes = a}) -- | Whether to enable face attributes detection, such as glasses, -- dark_glasses, mouth_open etc. Ignored if \'include_bounding_boxes\' is -- set to false. gcvvfdcIncludeAttributes :: Lens' GoogleCloudVideointelligenceV1p3beta1_FaceDetectionConfig (Maybe Bool) gcvvfdcIncludeAttributes = lens _gcvvfdcIncludeAttributes (\ s a -> s{_gcvvfdcIncludeAttributes = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_FaceDetectionConfig where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1FaceDetectionConfig" (\ o -> GoogleCloudVideointelligenceV1p3beta1_FaceDetectionConfig' <$> (o .:? "model") <*> (o .:? "includeBoundingBoxes") <*> (o .:? "includeAttributes")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_FaceDetectionConfig where toJSON GoogleCloudVideointelligenceV1p3beta1_FaceDetectionConfig'{..} = object (catMaybes [("model" .=) <$> _gcvvfdcModel, ("includeBoundingBoxes" .=) <$> _gcvvfdcIncludeBoundingBoxes, ("includeAttributes" .=) <$> _gcvvfdcIncludeAttributes]) -- | Person detection annotation per video. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_PersonDetectionAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_PersonDetectionAnnotation = GoogleCloudVideointelligenceV1p1beta1_PersonDetectionAnnotation' { _gcvvpdacTracks :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_Track]) , _gcvvpdacVersion :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_PersonDetectionAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvpdacTracks' -- -- * 'gcvvpdacVersion' googleCloudVideointelligenceV1p1beta1_PersonDetectionAnnotation :: GoogleCloudVideointelligenceV1p1beta1_PersonDetectionAnnotation googleCloudVideointelligenceV1p1beta1_PersonDetectionAnnotation = GoogleCloudVideointelligenceV1p1beta1_PersonDetectionAnnotation' {_gcvvpdacTracks = Nothing, _gcvvpdacVersion = Nothing} -- | The detected tracks of a person. gcvvpdacTracks :: Lens' GoogleCloudVideointelligenceV1p1beta1_PersonDetectionAnnotation [GoogleCloudVideointelligenceV1p1beta1_Track] gcvvpdacTracks = lens _gcvvpdacTracks (\ s a -> s{_gcvvpdacTracks = a}) . _Default . _Coerce -- | Feature version. gcvvpdacVersion :: Lens' GoogleCloudVideointelligenceV1p1beta1_PersonDetectionAnnotation (Maybe Text) gcvvpdacVersion = lens _gcvvpdacVersion (\ s a -> s{_gcvvpdacVersion = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_PersonDetectionAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1PersonDetectionAnnotation" (\ o -> GoogleCloudVideointelligenceV1p1beta1_PersonDetectionAnnotation' <$> (o .:? "tracks" .!= mempty) <*> (o .:? "version")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_PersonDetectionAnnotation where toJSON GoogleCloudVideointelligenceV1p1beta1_PersonDetectionAnnotation'{..} = object (catMaybes [("tracks" .=) <$> _gcvvpdacTracks, ("version" .=) <$> _gcvvpdacVersion]) -- | Video annotation progress. Included in the \`metadata\` field of the -- \`Operation\` returned by the \`GetOperation\` call of the -- \`google::longrunning::Operations\` service. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_AnnotateVideoProgress' smart constructor. newtype GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoProgress = GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoProgress' { _gcvvavpsAnnotationProgress :: Maybe [GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoProgress' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvavpsAnnotationProgress' googleCloudVideointelligenceV1p2beta1_AnnotateVideoProgress :: GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoProgress googleCloudVideointelligenceV1p2beta1_AnnotateVideoProgress = GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoProgress' {_gcvvavpsAnnotationProgress = Nothing} -- | Progress metadata for all videos specified in \`AnnotateVideoRequest\`. gcvvavpsAnnotationProgress :: Lens' GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoProgress [GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress] gcvvavpsAnnotationProgress = lens _gcvvavpsAnnotationProgress (\ s a -> s{_gcvvavpsAnnotationProgress = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoProgress where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1AnnotateVideoProgress" (\ o -> GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoProgress' <$> (o .:? "annotationProgress" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoProgress where toJSON GoogleCloudVideointelligenceV1p2beta1_AnnotateVideoProgress'{..} = object (catMaybes [("annotationProgress" .=) <$> _gcvvavpsAnnotationProgress]) -- | Service-specific metadata associated with the operation. It typically -- contains progress information and common metadata such as create time. -- Some services might not provide such metadata. Any method that returns a -- long-running operation should document the metadata type, if any. -- -- /See:/ 'googleLongrunning_OperationMetadata' smart constructor. newtype GoogleLongrunning_OperationMetadata = GoogleLongrunning_OperationMetadata' { _glomAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleLongrunning_OperationMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'glomAddtional' googleLongrunning_OperationMetadata :: HashMap Text JSONValue -- ^ 'glomAddtional' -> GoogleLongrunning_OperationMetadata googleLongrunning_OperationMetadata pGlomAddtional_ = GoogleLongrunning_OperationMetadata' {_glomAddtional = _Coerce # pGlomAddtional_} -- | Properties of the object. Contains field \'type with type URL. glomAddtional :: Lens' GoogleLongrunning_OperationMetadata (HashMap Text JSONValue) glomAddtional = lens _glomAddtional (\ s a -> s{_glomAddtional = a}) . _Coerce instance FromJSON GoogleLongrunning_OperationMetadata where parseJSON = withObject "GoogleLongrunningOperationMetadata" (\ o -> GoogleLongrunning_OperationMetadata' <$> (parseJSONObject o)) instance ToJSON GoogleLongrunning_OperationMetadata where toJSON = toJSON . _glomAddtional -- | Video frame level annotations for object detection and tracking. This -- field stores per frame location, time offset, and confidence. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_ObjectTrackingFrame' smart constructor. data GoogleCloudVideointelligenceV1beta2_ObjectTrackingFrame = GoogleCloudVideointelligenceV1beta2_ObjectTrackingFrame' { _gcvvotfcTimeOffSet :: !(Maybe GDuration) , _gcvvotfcNormalizedBoundingBox :: !(Maybe GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_ObjectTrackingFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvotfcTimeOffSet' -- -- * 'gcvvotfcNormalizedBoundingBox' googleCloudVideointelligenceV1beta2_ObjectTrackingFrame :: GoogleCloudVideointelligenceV1beta2_ObjectTrackingFrame googleCloudVideointelligenceV1beta2_ObjectTrackingFrame = GoogleCloudVideointelligenceV1beta2_ObjectTrackingFrame' {_gcvvotfcTimeOffSet = Nothing, _gcvvotfcNormalizedBoundingBox = Nothing} -- | The timestamp of the frame in microseconds. gcvvotfcTimeOffSet :: Lens' GoogleCloudVideointelligenceV1beta2_ObjectTrackingFrame (Maybe Scientific) gcvvotfcTimeOffSet = lens _gcvvotfcTimeOffSet (\ s a -> s{_gcvvotfcTimeOffSet = a}) . mapping _GDuration -- | The normalized bounding box location of this object track for the frame. gcvvotfcNormalizedBoundingBox :: Lens' GoogleCloudVideointelligenceV1beta2_ObjectTrackingFrame (Maybe GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox) gcvvotfcNormalizedBoundingBox = lens _gcvvotfcNormalizedBoundingBox (\ s a -> s{_gcvvotfcNormalizedBoundingBox = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_ObjectTrackingFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2ObjectTrackingFrame" (\ o -> GoogleCloudVideointelligenceV1beta2_ObjectTrackingFrame' <$> (o .:? "timeOffset") <*> (o .:? "normalizedBoundingBox")) instance ToJSON GoogleCloudVideointelligenceV1beta2_ObjectTrackingFrame where toJSON GoogleCloudVideointelligenceV1beta2_ObjectTrackingFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvotfcTimeOffSet, ("normalizedBoundingBox" .=) <$> _gcvvotfcNormalizedBoundingBox]) -- | A track of an object instance. -- -- /See:/ 'googleCloudVideointelligenceV1_Track' smart constructor. data GoogleCloudVideointelligenceV1_Track = GoogleCloudVideointelligenceV1_Track' { _gcvvtConfidence :: !(Maybe (Textual Double)) , _gcvvtAttributes :: !(Maybe [GoogleCloudVideointelligenceV1_DetectedAttribute]) , _gcvvtSegment :: !(Maybe GoogleCloudVideointelligenceV1_VideoSegment) , _gcvvtTimestampedObjects :: !(Maybe [GoogleCloudVideointelligenceV1_TimestampedObject]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_Track' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvtConfidence' -- -- * 'gcvvtAttributes' -- -- * 'gcvvtSegment' -- -- * 'gcvvtTimestampedObjects' googleCloudVideointelligenceV1_Track :: GoogleCloudVideointelligenceV1_Track googleCloudVideointelligenceV1_Track = GoogleCloudVideointelligenceV1_Track' { _gcvvtConfidence = Nothing , _gcvvtAttributes = Nothing , _gcvvtSegment = Nothing , _gcvvtTimestampedObjects = Nothing } -- | Optional. The confidence score of the tracked object. gcvvtConfidence :: Lens' GoogleCloudVideointelligenceV1_Track (Maybe Double) gcvvtConfidence = lens _gcvvtConfidence (\ s a -> s{_gcvvtConfidence = a}) . mapping _Coerce -- | Optional. Attributes in the track level. gcvvtAttributes :: Lens' GoogleCloudVideointelligenceV1_Track [GoogleCloudVideointelligenceV1_DetectedAttribute] gcvvtAttributes = lens _gcvvtAttributes (\ s a -> s{_gcvvtAttributes = a}) . _Default . _Coerce -- | Video segment of a track. gcvvtSegment :: Lens' GoogleCloudVideointelligenceV1_Track (Maybe GoogleCloudVideointelligenceV1_VideoSegment) gcvvtSegment = lens _gcvvtSegment (\ s a -> s{_gcvvtSegment = a}) -- | The object with timestamp and attributes per frame in the track. gcvvtTimestampedObjects :: Lens' GoogleCloudVideointelligenceV1_Track [GoogleCloudVideointelligenceV1_TimestampedObject] gcvvtTimestampedObjects = lens _gcvvtTimestampedObjects (\ s a -> s{_gcvvtTimestampedObjects = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1_Track where parseJSON = withObject "GoogleCloudVideointelligenceV1Track" (\ o -> GoogleCloudVideointelligenceV1_Track' <$> (o .:? "confidence") <*> (o .:? "attributes" .!= mempty) <*> (o .:? "segment") <*> (o .:? "timestampedObjects" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1_Track where toJSON GoogleCloudVideointelligenceV1_Track'{..} = object (catMaybes [("confidence" .=) <$> _gcvvtConfidence, ("attributes" .=) <$> _gcvvtAttributes, ("segment" .=) <$> _gcvvtSegment, ("timestampedObjects" .=) <$> _gcvvtTimestampedObjects]) -- | Video segment level annotation results for label detection. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_LabelSegment' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_LabelSegment = GoogleCloudVideointelligenceV1p1beta1_LabelSegment' { _gcvvlsConfidence :: !(Maybe (Textual Double)) , _gcvvlsSegment :: !(Maybe GoogleCloudVideointelligenceV1p1beta1_VideoSegment) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_LabelSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvlsConfidence' -- -- * 'gcvvlsSegment' googleCloudVideointelligenceV1p1beta1_LabelSegment :: GoogleCloudVideointelligenceV1p1beta1_LabelSegment googleCloudVideointelligenceV1p1beta1_LabelSegment = GoogleCloudVideointelligenceV1p1beta1_LabelSegment' {_gcvvlsConfidence = Nothing, _gcvvlsSegment = Nothing} -- | Confidence that the label is accurate. Range: [0, 1]. gcvvlsConfidence :: Lens' GoogleCloudVideointelligenceV1p1beta1_LabelSegment (Maybe Double) gcvvlsConfidence = lens _gcvvlsConfidence (\ s a -> s{_gcvvlsConfidence = a}) . mapping _Coerce -- | Video segment where a label was detected. gcvvlsSegment :: Lens' GoogleCloudVideointelligenceV1p1beta1_LabelSegment (Maybe GoogleCloudVideointelligenceV1p1beta1_VideoSegment) gcvvlsSegment = lens _gcvvlsSegment (\ s a -> s{_gcvvlsSegment = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_LabelSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1LabelSegment" (\ o -> GoogleCloudVideointelligenceV1p1beta1_LabelSegment' <$> (o .:? "confidence") <*> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_LabelSegment where toJSON GoogleCloudVideointelligenceV1p1beta1_LabelSegment'{..} = object (catMaybes [("confidence" .=) <$> _gcvvlsConfidence, ("segment" .=) <$> _gcvvlsSegment]) -- | Provides \"hints\" to the speech recognizer to favor specific words and -- phrases in the results. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_SpeechContext' smart constructor. newtype GoogleCloudVideointelligenceV1p3beta1_SpeechContext = GoogleCloudVideointelligenceV1p3beta1_SpeechContext' { _gcvvscPhrases :: Maybe [Text] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_SpeechContext' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvscPhrases' googleCloudVideointelligenceV1p3beta1_SpeechContext :: GoogleCloudVideointelligenceV1p3beta1_SpeechContext googleCloudVideointelligenceV1p3beta1_SpeechContext = GoogleCloudVideointelligenceV1p3beta1_SpeechContext' {_gcvvscPhrases = Nothing} -- | Optional. A list of strings containing words and phrases \"hints\" so -- that the speech recognition is more likely to recognize them. This can -- be used to improve the accuracy for specific words and phrases, for -- example, if specific commands are typically spoken by the user. This can -- also be used to add additional words to the vocabulary of the -- recognizer. See [usage -- limits](https:\/\/cloud.google.com\/speech\/limits#content). gcvvscPhrases :: Lens' GoogleCloudVideointelligenceV1p3beta1_SpeechContext [Text] gcvvscPhrases = lens _gcvvscPhrases (\ s a -> s{_gcvvscPhrases = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p3beta1_SpeechContext where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1SpeechContext" (\ o -> GoogleCloudVideointelligenceV1p3beta1_SpeechContext' <$> (o .:? "phrases" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_SpeechContext where toJSON GoogleCloudVideointelligenceV1p3beta1_SpeechContext'{..} = object (catMaybes [("phrases" .=) <$> _gcvvscPhrases]) -- | A track of an object instance. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_Track' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_Track = GoogleCloudVideointelligenceV1p3beta1_Track' { _gcvvtcConfidence :: !(Maybe (Textual Double)) , _gcvvtcAttributes :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_DetectedAttribute]) , _gcvvtcSegment :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_VideoSegment) , _gcvvtcTimestampedObjects :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_TimestampedObject]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_Track' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvtcConfidence' -- -- * 'gcvvtcAttributes' -- -- * 'gcvvtcSegment' -- -- * 'gcvvtcTimestampedObjects' googleCloudVideointelligenceV1p3beta1_Track :: GoogleCloudVideointelligenceV1p3beta1_Track googleCloudVideointelligenceV1p3beta1_Track = GoogleCloudVideointelligenceV1p3beta1_Track' { _gcvvtcConfidence = Nothing , _gcvvtcAttributes = Nothing , _gcvvtcSegment = Nothing , _gcvvtcTimestampedObjects = Nothing } -- | Optional. The confidence score of the tracked object. gcvvtcConfidence :: Lens' GoogleCloudVideointelligenceV1p3beta1_Track (Maybe Double) gcvvtcConfidence = lens _gcvvtcConfidence (\ s a -> s{_gcvvtcConfidence = a}) . mapping _Coerce -- | Optional. Attributes in the track level. gcvvtcAttributes :: Lens' GoogleCloudVideointelligenceV1p3beta1_Track [GoogleCloudVideointelligenceV1p3beta1_DetectedAttribute] gcvvtcAttributes = lens _gcvvtcAttributes (\ s a -> s{_gcvvtcAttributes = a}) . _Default . _Coerce -- | Video segment of a track. gcvvtcSegment :: Lens' GoogleCloudVideointelligenceV1p3beta1_Track (Maybe GoogleCloudVideointelligenceV1p3beta1_VideoSegment) gcvvtcSegment = lens _gcvvtcSegment (\ s a -> s{_gcvvtcSegment = a}) -- | The object with timestamp and attributes per frame in the track. gcvvtcTimestampedObjects :: Lens' GoogleCloudVideointelligenceV1p3beta1_Track [GoogleCloudVideointelligenceV1p3beta1_TimestampedObject] gcvvtcTimestampedObjects = lens _gcvvtcTimestampedObjects (\ s a -> s{_gcvvtcTimestampedObjects = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p3beta1_Track where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1Track" (\ o -> GoogleCloudVideointelligenceV1p3beta1_Track' <$> (o .:? "confidence") <*> (o .:? "attributes" .!= mempty) <*> (o .:? "segment") <*> (o .:? "timestampedObjects" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_Track where toJSON GoogleCloudVideointelligenceV1p3beta1_Track'{..} = object (catMaybes [("confidence" .=) <$> _gcvvtcConfidence, ("attributes" .=) <$> _gcvvtcAttributes, ("segment" .=) <$> _gcvvtcSegment, ("timestampedObjects" .=) <$> _gcvvtcTimestampedObjects]) -- | Video frame level annotation results for label detection. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_LabelFrame' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_LabelFrame = GoogleCloudVideointelligenceV1p2beta1_LabelFrame' { _ggTimeOffSet :: !(Maybe GDuration) , _ggConfidence :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_LabelFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ggTimeOffSet' -- -- * 'ggConfidence' googleCloudVideointelligenceV1p2beta1_LabelFrame :: GoogleCloudVideointelligenceV1p2beta1_LabelFrame googleCloudVideointelligenceV1p2beta1_LabelFrame = GoogleCloudVideointelligenceV1p2beta1_LabelFrame' {_ggTimeOffSet = Nothing, _ggConfidence = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this location. ggTimeOffSet :: Lens' GoogleCloudVideointelligenceV1p2beta1_LabelFrame (Maybe Scientific) ggTimeOffSet = lens _ggTimeOffSet (\ s a -> s{_ggTimeOffSet = a}) . mapping _GDuration -- | Confidence that the label is accurate. Range: [0, 1]. ggConfidence :: Lens' GoogleCloudVideointelligenceV1p2beta1_LabelFrame (Maybe Double) ggConfidence = lens _ggConfidence (\ s a -> s{_ggConfidence = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1p2beta1_LabelFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1LabelFrame" (\ o -> GoogleCloudVideointelligenceV1p2beta1_LabelFrame' <$> (o .:? "timeOffset") <*> (o .:? "confidence")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_LabelFrame where toJSON GoogleCloudVideointelligenceV1p2beta1_LabelFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _ggTimeOffSet, ("confidence" .=) <$> _ggConfidence]) -- | A generic detected attribute represented by name in string format. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_DetectedAttribute' smart constructor. data GoogleCloudVideointelligenceV1beta2_DetectedAttribute = GoogleCloudVideointelligenceV1beta2_DetectedAttribute' { _gcvvdaValue :: !(Maybe Text) , _gcvvdaConfidence :: !(Maybe (Textual Double)) , _gcvvdaName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_DetectedAttribute' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvdaValue' -- -- * 'gcvvdaConfidence' -- -- * 'gcvvdaName' googleCloudVideointelligenceV1beta2_DetectedAttribute :: GoogleCloudVideointelligenceV1beta2_DetectedAttribute googleCloudVideointelligenceV1beta2_DetectedAttribute = GoogleCloudVideointelligenceV1beta2_DetectedAttribute' {_gcvvdaValue = Nothing, _gcvvdaConfidence = Nothing, _gcvvdaName = Nothing} -- | Text value of the detection result. For example, the value for -- \"HairColor\" can be \"black\", \"blonde\", etc. gcvvdaValue :: Lens' GoogleCloudVideointelligenceV1beta2_DetectedAttribute (Maybe Text) gcvvdaValue = lens _gcvvdaValue (\ s a -> s{_gcvvdaValue = a}) -- | Detected attribute confidence. Range [0, 1]. gcvvdaConfidence :: Lens' GoogleCloudVideointelligenceV1beta2_DetectedAttribute (Maybe Double) gcvvdaConfidence = lens _gcvvdaConfidence (\ s a -> s{_gcvvdaConfidence = a}) . mapping _Coerce -- | The name of the attribute, for example, glasses, dark_glasses, -- mouth_open. A full list of supported type names will be provided in the -- document. gcvvdaName :: Lens' GoogleCloudVideointelligenceV1beta2_DetectedAttribute (Maybe Text) gcvvdaName = lens _gcvvdaName (\ s a -> s{_gcvvdaName = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_DetectedAttribute where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2DetectedAttribute" (\ o -> GoogleCloudVideointelligenceV1beta2_DetectedAttribute' <$> (o .:? "value") <*> (o .:? "confidence") <*> (o .:? "name")) instance ToJSON GoogleCloudVideointelligenceV1beta2_DetectedAttribute where toJSON GoogleCloudVideointelligenceV1beta2_DetectedAttribute'{..} = object (catMaybes [("value" .=) <$> _gcvvdaValue, ("confidence" .=) <$> _gcvvdaConfidence, ("name" .=) <$> _gcvvdaName]) -- | Annotation progress for a single video. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress = GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress' { _gcvvvapcFeature :: !(Maybe GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgressFeature) , _gcvvvapcStartTime :: !(Maybe DateTime') , _gcvvvapcInputURI :: !(Maybe Text) , _gcvvvapcProgressPercent :: !(Maybe (Textual Int32)) , _gcvvvapcUpdateTime :: !(Maybe DateTime') , _gcvvvapcSegment :: !(Maybe GoogleCloudVideointelligenceV1p2beta1_VideoSegment) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvvapcFeature' -- -- * 'gcvvvapcStartTime' -- -- * 'gcvvvapcInputURI' -- -- * 'gcvvvapcProgressPercent' -- -- * 'gcvvvapcUpdateTime' -- -- * 'gcvvvapcSegment' googleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress :: GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress googleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress = GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress' { _gcvvvapcFeature = Nothing , _gcvvvapcStartTime = Nothing , _gcvvvapcInputURI = Nothing , _gcvvvapcProgressPercent = Nothing , _gcvvvapcUpdateTime = Nothing , _gcvvvapcSegment = Nothing } -- | Specifies which feature is being tracked if the request contains more -- than one feature. gcvvvapcFeature :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress (Maybe GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgressFeature) gcvvvapcFeature = lens _gcvvvapcFeature (\ s a -> s{_gcvvvapcFeature = a}) -- | Time when the request was received. gcvvvapcStartTime :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress (Maybe UTCTime) gcvvvapcStartTime = lens _gcvvvapcStartTime (\ s a -> s{_gcvvvapcStartTime = a}) . mapping _DateTime -- | Video file location in [Cloud -- Storage](https:\/\/cloud.google.com\/storage\/). gcvvvapcInputURI :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress (Maybe Text) gcvvvapcInputURI = lens _gcvvvapcInputURI (\ s a -> s{_gcvvvapcInputURI = a}) -- | Approximate percentage processed thus far. Guaranteed to be 100 when -- fully processed. gcvvvapcProgressPercent :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress (Maybe Int32) gcvvvapcProgressPercent = lens _gcvvvapcProgressPercent (\ s a -> s{_gcvvvapcProgressPercent = a}) . mapping _Coerce -- | Time of the most recent update. gcvvvapcUpdateTime :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress (Maybe UTCTime) gcvvvapcUpdateTime = lens _gcvvvapcUpdateTime (\ s a -> s{_gcvvvapcUpdateTime = a}) . mapping _DateTime -- | Specifies which segment is being tracked if the request contains more -- than one segment. gcvvvapcSegment :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress (Maybe GoogleCloudVideointelligenceV1p2beta1_VideoSegment) gcvvvapcSegment = lens _gcvvvapcSegment (\ s a -> s{_gcvvvapcSegment = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1VideoAnnotationProgress" (\ o -> GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress' <$> (o .:? "feature") <*> (o .:? "startTime") <*> (o .:? "inputUri") <*> (o .:? "progressPercent") <*> (o .:? "updateTime") <*> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress where toJSON GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationProgress'{..} = object (catMaybes [("feature" .=) <$> _gcvvvapcFeature, ("startTime" .=) <$> _gcvvvapcStartTime, ("inputUri" .=) <$> _gcvvvapcInputURI, ("progressPercent" .=) <$> _gcvvvapcProgressPercent, ("updateTime" .=) <$> _gcvvvapcUpdateTime, ("segment" .=) <$> _gcvvvapcSegment]) -- | Video frame level annotation results for explicit content. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_ExplicitContentFrame' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_ExplicitContentFrame = GoogleCloudVideointelligenceV1p3beta1_ExplicitContentFrame' { _gcvvecfcTimeOffSet :: !(Maybe GDuration) , _gcvvecfcPornographyLikelihood :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_ExplicitContentFramePornographyLikelihood) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_ExplicitContentFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvecfcTimeOffSet' -- -- * 'gcvvecfcPornographyLikelihood' googleCloudVideointelligenceV1p3beta1_ExplicitContentFrame :: GoogleCloudVideointelligenceV1p3beta1_ExplicitContentFrame googleCloudVideointelligenceV1p3beta1_ExplicitContentFrame = GoogleCloudVideointelligenceV1p3beta1_ExplicitContentFrame' {_gcvvecfcTimeOffSet = Nothing, _gcvvecfcPornographyLikelihood = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this location. gcvvecfcTimeOffSet :: Lens' GoogleCloudVideointelligenceV1p3beta1_ExplicitContentFrame (Maybe Scientific) gcvvecfcTimeOffSet = lens _gcvvecfcTimeOffSet (\ s a -> s{_gcvvecfcTimeOffSet = a}) . mapping _GDuration -- | Likelihood of the pornography content.. gcvvecfcPornographyLikelihood :: Lens' GoogleCloudVideointelligenceV1p3beta1_ExplicitContentFrame (Maybe GoogleCloudVideointelligenceV1p3beta1_ExplicitContentFramePornographyLikelihood) gcvvecfcPornographyLikelihood = lens _gcvvecfcPornographyLikelihood (\ s a -> s{_gcvvecfcPornographyLikelihood = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_ExplicitContentFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1ExplicitContentFrame" (\ o -> GoogleCloudVideointelligenceV1p3beta1_ExplicitContentFrame' <$> (o .:? "timeOffset") <*> (o .:? "pornographyLikelihood")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_ExplicitContentFrame where toJSON GoogleCloudVideointelligenceV1p3beta1_ExplicitContentFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvecfcTimeOffSet, ("pornographyLikelihood" .=) <$> _gcvvecfcPornographyLikelihood]) -- | Video segment level annotation results for face detection. -- -- /See:/ 'googleCloudVideointelligenceV1_FaceSegment' smart constructor. newtype GoogleCloudVideointelligenceV1_FaceSegment = GoogleCloudVideointelligenceV1_FaceSegment' { _gooSegment :: Maybe GoogleCloudVideointelligenceV1_VideoSegment } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_FaceSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gooSegment' googleCloudVideointelligenceV1_FaceSegment :: GoogleCloudVideointelligenceV1_FaceSegment googleCloudVideointelligenceV1_FaceSegment = GoogleCloudVideointelligenceV1_FaceSegment' {_gooSegment = Nothing} -- | Video segment where a face was detected. gooSegment :: Lens' GoogleCloudVideointelligenceV1_FaceSegment (Maybe GoogleCloudVideointelligenceV1_VideoSegment) gooSegment = lens _gooSegment (\ s a -> s{_gooSegment = a}) instance FromJSON GoogleCloudVideointelligenceV1_FaceSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1FaceSegment" (\ o -> GoogleCloudVideointelligenceV1_FaceSegment' <$> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1_FaceSegment where toJSON GoogleCloudVideointelligenceV1_FaceSegment'{..} = object (catMaybes [("segment" .=) <$> _gooSegment]) -- | Annotations related to one detected OCR text snippet. This will contain -- the corresponding text, confidence value, and frame level information -- for each detection. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_TextAnnotation' smart constructor. data GoogleCloudVideointelligenceV1beta2_TextAnnotation = GoogleCloudVideointelligenceV1beta2_TextAnnotation' { _gcvvtacText :: !(Maybe Text) , _gcvvtacVersion :: !(Maybe Text) , _gcvvtacSegments :: !(Maybe [GoogleCloudVideointelligenceV1beta2_TextSegment]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_TextAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvtacText' -- -- * 'gcvvtacVersion' -- -- * 'gcvvtacSegments' googleCloudVideointelligenceV1beta2_TextAnnotation :: GoogleCloudVideointelligenceV1beta2_TextAnnotation googleCloudVideointelligenceV1beta2_TextAnnotation = GoogleCloudVideointelligenceV1beta2_TextAnnotation' { _gcvvtacText = Nothing , _gcvvtacVersion = Nothing , _gcvvtacSegments = Nothing } -- | The detected text. gcvvtacText :: Lens' GoogleCloudVideointelligenceV1beta2_TextAnnotation (Maybe Text) gcvvtacText = lens _gcvvtacText (\ s a -> s{_gcvvtacText = a}) -- | Feature version. gcvvtacVersion :: Lens' GoogleCloudVideointelligenceV1beta2_TextAnnotation (Maybe Text) gcvvtacVersion = lens _gcvvtacVersion (\ s a -> s{_gcvvtacVersion = a}) -- | All video segments where OCR detected text appears. gcvvtacSegments :: Lens' GoogleCloudVideointelligenceV1beta2_TextAnnotation [GoogleCloudVideointelligenceV1beta2_TextSegment] gcvvtacSegments = lens _gcvvtacSegments (\ s a -> s{_gcvvtacSegments = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1beta2_TextAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2TextAnnotation" (\ o -> GoogleCloudVideointelligenceV1beta2_TextAnnotation' <$> (o .:? "text") <*> (o .:? "version") <*> (o .:? "segments" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1beta2_TextAnnotation where toJSON GoogleCloudVideointelligenceV1beta2_TextAnnotation'{..} = object (catMaybes [("text" .=) <$> _gcvvtacText, ("version" .=) <$> _gcvvtacVersion, ("segments" .=) <$> _gcvvtacSegments]) -- | Detected entity from video analysis. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_Entity' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_Entity = GoogleCloudVideointelligenceV1p2beta1_Entity' { _gcvvecLanguageCode :: !(Maybe Text) , _gcvvecEntityId :: !(Maybe Text) , _gcvvecDescription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_Entity' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvecLanguageCode' -- -- * 'gcvvecEntityId' -- -- * 'gcvvecDescription' googleCloudVideointelligenceV1p2beta1_Entity :: GoogleCloudVideointelligenceV1p2beta1_Entity googleCloudVideointelligenceV1p2beta1_Entity = GoogleCloudVideointelligenceV1p2beta1_Entity' { _gcvvecLanguageCode = Nothing , _gcvvecEntityId = Nothing , _gcvvecDescription = Nothing } -- | Language code for \`description\` in BCP-47 format. gcvvecLanguageCode :: Lens' GoogleCloudVideointelligenceV1p2beta1_Entity (Maybe Text) gcvvecLanguageCode = lens _gcvvecLanguageCode (\ s a -> s{_gcvvecLanguageCode = a}) -- | Opaque entity ID. Some IDs may be available in [Google Knowledge Graph -- Search API](https:\/\/developers.google.com\/knowledge-graph\/). gcvvecEntityId :: Lens' GoogleCloudVideointelligenceV1p2beta1_Entity (Maybe Text) gcvvecEntityId = lens _gcvvecEntityId (\ s a -> s{_gcvvecEntityId = a}) -- | Textual description, e.g., \`Fixed-gear bicycle\`. gcvvecDescription :: Lens' GoogleCloudVideointelligenceV1p2beta1_Entity (Maybe Text) gcvvecDescription = lens _gcvvecDescription (\ s a -> s{_gcvvecDescription = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_Entity where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1Entity" (\ o -> GoogleCloudVideointelligenceV1p2beta1_Entity' <$> (o .:? "languageCode") <*> (o .:? "entityId") <*> (o .:? "description")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_Entity where toJSON GoogleCloudVideointelligenceV1p2beta1_Entity'{..} = object (catMaybes [("languageCode" .=) <$> _gcvvecLanguageCode, ("entityId" .=) <$> _gcvvecEntityId, ("description" .=) <$> _gcvvecDescription]) -- | Video frame level annotation results for text annotation (OCR). Contains -- information regarding timestamp and bounding box locations for the -- frames containing detected OCR text snippets. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_TextFrame' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_TextFrame = GoogleCloudVideointelligenceV1p1beta1_TextFrame' { _gcvvtfcRotatedBoundingBox :: !(Maybe GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingPoly) , _gcvvtfcTimeOffSet :: !(Maybe GDuration) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_TextFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvtfcRotatedBoundingBox' -- -- * 'gcvvtfcTimeOffSet' googleCloudVideointelligenceV1p1beta1_TextFrame :: GoogleCloudVideointelligenceV1p1beta1_TextFrame googleCloudVideointelligenceV1p1beta1_TextFrame = GoogleCloudVideointelligenceV1p1beta1_TextFrame' {_gcvvtfcRotatedBoundingBox = Nothing, _gcvvtfcTimeOffSet = Nothing} -- | Bounding polygon of the detected text for this frame. gcvvtfcRotatedBoundingBox :: Lens' GoogleCloudVideointelligenceV1p1beta1_TextFrame (Maybe GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingPoly) gcvvtfcRotatedBoundingBox = lens _gcvvtfcRotatedBoundingBox (\ s a -> s{_gcvvtfcRotatedBoundingBox = a}) -- | Timestamp of this frame. gcvvtfcTimeOffSet :: Lens' GoogleCloudVideointelligenceV1p1beta1_TextFrame (Maybe Scientific) gcvvtfcTimeOffSet = lens _gcvvtfcTimeOffSet (\ s a -> s{_gcvvtfcTimeOffSet = a}) . mapping _GDuration instance FromJSON GoogleCloudVideointelligenceV1p1beta1_TextFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1TextFrame" (\ o -> GoogleCloudVideointelligenceV1p1beta1_TextFrame' <$> (o .:? "rotatedBoundingBox") <*> (o .:? "timeOffset")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_TextFrame where toJSON GoogleCloudVideointelligenceV1p1beta1_TextFrame'{..} = object (catMaybes [("rotatedBoundingBox" .=) <$> _gcvvtfcRotatedBoundingBox, ("timeOffset" .=) <$> _gcvvtfcTimeOffSet]) -- | Word-specific information for recognized words. Word information is only -- included in the response when certain request parameters are set, such -- as \`enable_word_time_offsets\`. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_WordInfo' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_WordInfo = GoogleCloudVideointelligenceV1p1beta1_WordInfo' { _goooStartTime :: !(Maybe GDuration) , _goooConfidence :: !(Maybe (Textual Double)) , _goooEndTime :: !(Maybe GDuration) , _goooWord :: !(Maybe Text) , _goooSpeakerTag :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_WordInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'goooStartTime' -- -- * 'goooConfidence' -- -- * 'goooEndTime' -- -- * 'goooWord' -- -- * 'goooSpeakerTag' googleCloudVideointelligenceV1p1beta1_WordInfo :: GoogleCloudVideointelligenceV1p1beta1_WordInfo googleCloudVideointelligenceV1p1beta1_WordInfo = GoogleCloudVideointelligenceV1p1beta1_WordInfo' { _goooStartTime = Nothing , _goooConfidence = Nothing , _goooEndTime = Nothing , _goooWord = Nothing , _goooSpeakerTag = Nothing } -- | Time offset relative to the beginning of the audio, and corresponding to -- the start of the spoken word. This field is only set if -- \`enable_word_time_offsets=true\` and only in the top hypothesis. This -- is an experimental feature and the accuracy of the time offset can vary. goooStartTime :: Lens' GoogleCloudVideointelligenceV1p1beta1_WordInfo (Maybe Scientific) goooStartTime = lens _goooStartTime (\ s a -> s{_goooStartTime = a}) . mapping _GDuration -- | Output only. The confidence estimate between 0.0 and 1.0. A higher -- number indicates an estimated greater likelihood that the recognized -- words are correct. This field is set only for the top alternative. This -- field is not guaranteed to be accurate and users should not rely on it -- to be always provided. The default of 0.0 is a sentinel value indicating -- \`confidence\` was not set. goooConfidence :: Lens' GoogleCloudVideointelligenceV1p1beta1_WordInfo (Maybe Double) goooConfidence = lens _goooConfidence (\ s a -> s{_goooConfidence = a}) . mapping _Coerce -- | Time offset relative to the beginning of the audio, and corresponding to -- the end of the spoken word. This field is only set if -- \`enable_word_time_offsets=true\` and only in the top hypothesis. This -- is an experimental feature and the accuracy of the time offset can vary. goooEndTime :: Lens' GoogleCloudVideointelligenceV1p1beta1_WordInfo (Maybe Scientific) goooEndTime = lens _goooEndTime (\ s a -> s{_goooEndTime = a}) . mapping _GDuration -- | The word corresponding to this set of information. goooWord :: Lens' GoogleCloudVideointelligenceV1p1beta1_WordInfo (Maybe Text) goooWord = lens _goooWord (\ s a -> s{_goooWord = a}) -- | Output only. A distinct integer value is assigned for every speaker -- within the audio. This field specifies which one of those speakers was -- detected to have spoken this word. Value ranges from 1 up to -- diarization_speaker_count, and is only set if speaker diarization is -- enabled. goooSpeakerTag :: Lens' GoogleCloudVideointelligenceV1p1beta1_WordInfo (Maybe Int32) goooSpeakerTag = lens _goooSpeakerTag (\ s a -> s{_goooSpeakerTag = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1p1beta1_WordInfo where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1WordInfo" (\ o -> GoogleCloudVideointelligenceV1p1beta1_WordInfo' <$> (o .:? "startTime") <*> (o .:? "confidence") <*> (o .:? "endTime") <*> (o .:? "word") <*> (o .:? "speakerTag")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_WordInfo where toJSON GoogleCloudVideointelligenceV1p1beta1_WordInfo'{..} = object (catMaybes [("startTime" .=) <$> _goooStartTime, ("confidence" .=) <$> _goooConfidence, ("endTime" .=) <$> _goooEndTime, ("word" .=) <$> _goooWord, ("speakerTag" .=) <$> _goooSpeakerTag]) -- | For tracking related features. An object at time_offset with attributes, -- and located with normalized_bounding_box. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_TimestampedObject' smart constructor. data GoogleCloudVideointelligenceV1beta2_TimestampedObject = GoogleCloudVideointelligenceV1beta2_TimestampedObject' { _gcvvtoTimeOffSet :: !(Maybe GDuration) , _gcvvtoAttributes :: !(Maybe [GoogleCloudVideointelligenceV1beta2_DetectedAttribute]) , _gcvvtoNormalizedBoundingBox :: !(Maybe GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox) , _gcvvtoLandmarks :: !(Maybe [GoogleCloudVideointelligenceV1beta2_DetectedLandmark]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_TimestampedObject' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvtoTimeOffSet' -- -- * 'gcvvtoAttributes' -- -- * 'gcvvtoNormalizedBoundingBox' -- -- * 'gcvvtoLandmarks' googleCloudVideointelligenceV1beta2_TimestampedObject :: GoogleCloudVideointelligenceV1beta2_TimestampedObject googleCloudVideointelligenceV1beta2_TimestampedObject = GoogleCloudVideointelligenceV1beta2_TimestampedObject' { _gcvvtoTimeOffSet = Nothing , _gcvvtoAttributes = Nothing , _gcvvtoNormalizedBoundingBox = Nothing , _gcvvtoLandmarks = Nothing } -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this object. gcvvtoTimeOffSet :: Lens' GoogleCloudVideointelligenceV1beta2_TimestampedObject (Maybe Scientific) gcvvtoTimeOffSet = lens _gcvvtoTimeOffSet (\ s a -> s{_gcvvtoTimeOffSet = a}) . mapping _GDuration -- | Optional. The attributes of the object in the bounding box. gcvvtoAttributes :: Lens' GoogleCloudVideointelligenceV1beta2_TimestampedObject [GoogleCloudVideointelligenceV1beta2_DetectedAttribute] gcvvtoAttributes = lens _gcvvtoAttributes (\ s a -> s{_gcvvtoAttributes = a}) . _Default . _Coerce -- | Normalized Bounding box in a frame, where the object is located. gcvvtoNormalizedBoundingBox :: Lens' GoogleCloudVideointelligenceV1beta2_TimestampedObject (Maybe GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox) gcvvtoNormalizedBoundingBox = lens _gcvvtoNormalizedBoundingBox (\ s a -> s{_gcvvtoNormalizedBoundingBox = a}) -- | Optional. The detected landmarks. gcvvtoLandmarks :: Lens' GoogleCloudVideointelligenceV1beta2_TimestampedObject [GoogleCloudVideointelligenceV1beta2_DetectedLandmark] gcvvtoLandmarks = lens _gcvvtoLandmarks (\ s a -> s{_gcvvtoLandmarks = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1beta2_TimestampedObject where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2TimestampedObject" (\ o -> GoogleCloudVideointelligenceV1beta2_TimestampedObject' <$> (o .:? "timeOffset") <*> (o .:? "attributes" .!= mempty) <*> (o .:? "normalizedBoundingBox") <*> (o .:? "landmarks" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1beta2_TimestampedObject where toJSON GoogleCloudVideointelligenceV1beta2_TimestampedObject'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvtoTimeOffSet, ("attributes" .=) <$> _gcvvtoAttributes, ("normalizedBoundingBox" .=) <$> _gcvvtoNormalizedBoundingBox, ("landmarks" .=) <$> _gcvvtoLandmarks]) -- | This resource represents a long-running operation that is the result of -- a network API call. -- -- /See:/ 'googleLongrunning_Operation' smart constructor. data GoogleLongrunning_Operation = GoogleLongrunning_Operation' { _gloDone :: !(Maybe Bool) , _gloError :: !(Maybe GoogleRpc_Status) , _gloResponse :: !(Maybe GoogleLongrunning_OperationResponse) , _gloName :: !(Maybe Text) , _gloMetadata :: !(Maybe GoogleLongrunning_OperationMetadata) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleLongrunning_Operation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gloDone' -- -- * 'gloError' -- -- * 'gloResponse' -- -- * 'gloName' -- -- * 'gloMetadata' googleLongrunning_Operation :: GoogleLongrunning_Operation googleLongrunning_Operation = GoogleLongrunning_Operation' { _gloDone = Nothing , _gloError = Nothing , _gloResponse = Nothing , _gloName = Nothing , _gloMetadata = Nothing } -- | If the value is \`false\`, it means the operation is still in progress. -- If \`true\`, the operation is completed, and either \`error\` or -- \`response\` is available. gloDone :: Lens' GoogleLongrunning_Operation (Maybe Bool) gloDone = lens _gloDone (\ s a -> s{_gloDone = a}) -- | The error result of the operation in case of failure or cancellation. gloError :: Lens' GoogleLongrunning_Operation (Maybe GoogleRpc_Status) gloError = lens _gloError (\ s a -> s{_gloError = a}) -- | The normal response of the operation in case of success. If the original -- method returns no data on success, such as \`Delete\`, the response is -- \`google.protobuf.Empty\`. If the original method is standard -- \`Get\`\/\`Create\`\/\`Update\`, the response should be the resource. -- For other methods, the response should have the type \`XxxResponse\`, -- where \`Xxx\` is the original method name. For example, if the original -- method name is \`TakeSnapshot()\`, the inferred response type is -- \`TakeSnapshotResponse\`. gloResponse :: Lens' GoogleLongrunning_Operation (Maybe GoogleLongrunning_OperationResponse) gloResponse = lens _gloResponse (\ s a -> s{_gloResponse = a}) -- | The server-assigned name, which is only unique within the same service -- that originally returns it. If you use the default HTTP mapping, the -- \`name\` should be a resource name ending with -- \`operations\/{unique_id}\`. gloName :: Lens' GoogleLongrunning_Operation (Maybe Text) gloName = lens _gloName (\ s a -> s{_gloName = a}) -- | Service-specific metadata associated with the operation. It typically -- contains progress information and common metadata such as create time. -- Some services might not provide such metadata. Any method that returns a -- long-running operation should document the metadata type, if any. gloMetadata :: Lens' GoogleLongrunning_Operation (Maybe GoogleLongrunning_OperationMetadata) gloMetadata = lens _gloMetadata (\ s a -> s{_gloMetadata = a}) instance FromJSON GoogleLongrunning_Operation where parseJSON = withObject "GoogleLongrunningOperation" (\ o -> GoogleLongrunning_Operation' <$> (o .:? "done") <*> (o .:? "error") <*> (o .:? "response") <*> (o .:? "name") <*> (o .:? "metadata")) instance ToJSON GoogleLongrunning_Operation where toJSON GoogleLongrunning_Operation'{..} = object (catMaybes [("done" .=) <$> _gloDone, ("error" .=) <$> _gloError, ("response" .=) <$> _gloResponse, ("name" .=) <$> _gloName, ("metadata" .=) <$> _gloMetadata]) -- | Alternative hypotheses (a.k.a. n-best list). -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative = GoogleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative' { _gcvvsra1Confidence :: !(Maybe (Textual Double)) , _gcvvsra1Words :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_WordInfo]) , _gcvvsra1Transcript :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvsra1Confidence' -- -- * 'gcvvsra1Words' -- -- * 'gcvvsra1Transcript' googleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative :: GoogleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative googleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative = GoogleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative' { _gcvvsra1Confidence = Nothing , _gcvvsra1Words = Nothing , _gcvvsra1Transcript = Nothing } -- | Output only. The confidence estimate between 0.0 and 1.0. A higher -- number indicates an estimated greater likelihood that the recognized -- words are correct. This field is set only for the top alternative. This -- field is not guaranteed to be accurate and users should not rely on it -- to be always provided. The default of 0.0 is a sentinel value indicating -- \`confidence\` was not set. gcvvsra1Confidence :: Lens' GoogleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative (Maybe Double) gcvvsra1Confidence = lens _gcvvsra1Confidence (\ s a -> s{_gcvvsra1Confidence = a}) . mapping _Coerce -- | Output only. A list of word-specific information for each recognized -- word. Note: When \`enable_speaker_diarization\` is set to true, you will -- see all the words from the beginning of the audio. gcvvsra1Words :: Lens' GoogleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative [GoogleCloudVideointelligenceV1p1beta1_WordInfo] gcvvsra1Words = lens _gcvvsra1Words (\ s a -> s{_gcvvsra1Words = a}) . _Default . _Coerce -- | Transcript text representing the words that the user spoke. gcvvsra1Transcript :: Lens' GoogleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative (Maybe Text) gcvvsra1Transcript = lens _gcvvsra1Transcript (\ s a -> s{_gcvvsra1Transcript = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1SpeechRecognitionAlternative" (\ o -> GoogleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative' <$> (o .:? "confidence") <*> (o .:? "words" .!= mempty) <*> (o .:? "transcript")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative where toJSON GoogleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative'{..} = object (catMaybes [("confidence" .=) <$> _gcvvsra1Confidence, ("words" .=) <$> _gcvvsra1Words, ("transcript" .=) <$> _gcvvsra1Transcript]) -- | Video frame level annotation results for explicit content. -- -- /See:/ 'googleCloudVideointelligenceV1_ExplicitContentFrame' smart constructor. data GoogleCloudVideointelligenceV1_ExplicitContentFrame = GoogleCloudVideointelligenceV1_ExplicitContentFrame' { _goooTimeOffSet :: !(Maybe GDuration) , _goooPornographyLikelihood :: !(Maybe GoogleCloudVideointelligenceV1_ExplicitContentFramePornographyLikelihood) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_ExplicitContentFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'goooTimeOffSet' -- -- * 'goooPornographyLikelihood' googleCloudVideointelligenceV1_ExplicitContentFrame :: GoogleCloudVideointelligenceV1_ExplicitContentFrame googleCloudVideointelligenceV1_ExplicitContentFrame = GoogleCloudVideointelligenceV1_ExplicitContentFrame' {_goooTimeOffSet = Nothing, _goooPornographyLikelihood = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this location. goooTimeOffSet :: Lens' GoogleCloudVideointelligenceV1_ExplicitContentFrame (Maybe Scientific) goooTimeOffSet = lens _goooTimeOffSet (\ s a -> s{_goooTimeOffSet = a}) . mapping _GDuration -- | Likelihood of the pornography content.. goooPornographyLikelihood :: Lens' GoogleCloudVideointelligenceV1_ExplicitContentFrame (Maybe GoogleCloudVideointelligenceV1_ExplicitContentFramePornographyLikelihood) goooPornographyLikelihood = lens _goooPornographyLikelihood (\ s a -> s{_goooPornographyLikelihood = a}) instance FromJSON GoogleCloudVideointelligenceV1_ExplicitContentFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1ExplicitContentFrame" (\ o -> GoogleCloudVideointelligenceV1_ExplicitContentFrame' <$> (o .:? "timeOffset") <*> (o .:? "pornographyLikelihood")) instance ToJSON GoogleCloudVideointelligenceV1_ExplicitContentFrame where toJSON GoogleCloudVideointelligenceV1_ExplicitContentFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _goooTimeOffSet, ("pornographyLikelihood" .=) <$> _goooPornographyLikelihood]) -- | Video annotation request. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest = GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest' { _gcvvavrInputURI :: !(Maybe Text) , _gcvvavrVideoContext :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_VideoContext) , _gcvvavrInputContent :: !(Maybe Bytes) , _gcvvavrFeatures :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequestFeaturesItem]) , _gcvvavrLocationId :: !(Maybe Text) , _gcvvavrOutputURI :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvavrInputURI' -- -- * 'gcvvavrVideoContext' -- -- * 'gcvvavrInputContent' -- -- * 'gcvvavrFeatures' -- -- * 'gcvvavrLocationId' -- -- * 'gcvvavrOutputURI' googleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest :: GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest googleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest = GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest' { _gcvvavrInputURI = Nothing , _gcvvavrVideoContext = Nothing , _gcvvavrInputContent = Nothing , _gcvvavrFeatures = Nothing , _gcvvavrLocationId = Nothing , _gcvvavrOutputURI = Nothing } -- | Input video location. Currently, only [Cloud -- Storage](https:\/\/cloud.google.com\/storage\/) URIs are supported. URIs -- must be specified in the following format: -- \`gs:\/\/bucket-id\/object-id\` (other URI formats return -- google.rpc.Code.INVALID_ARGUMENT). For more information, see [Request -- URIs](https:\/\/cloud.google.com\/storage\/docs\/request-endpoints). To -- identify multiple videos, a video URI may include wildcards in the -- \`object-id\`. Supported wildcards: \'*\' to match 0 or more characters; -- \'?\' to match 1 character. If unset, the input video should be embedded -- in the request as \`input_content\`. If set, \`input_content\` must be -- unset. gcvvavrInputURI :: Lens' GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest (Maybe Text) gcvvavrInputURI = lens _gcvvavrInputURI (\ s a -> s{_gcvvavrInputURI = a}) -- | Additional video context and\/or feature-specific parameters. gcvvavrVideoContext :: Lens' GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest (Maybe GoogleCloudVideointelligenceV1p3beta1_VideoContext) gcvvavrVideoContext = lens _gcvvavrVideoContext (\ s a -> s{_gcvvavrVideoContext = a}) -- | The video data bytes. If unset, the input video(s) should be specified -- via the \`input_uri\`. If set, \`input_uri\` must be unset. gcvvavrInputContent :: Lens' GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest (Maybe ByteString) gcvvavrInputContent = lens _gcvvavrInputContent (\ s a -> s{_gcvvavrInputContent = a}) . mapping _Bytes -- | Required. Requested video annotation features. gcvvavrFeatures :: Lens' GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest [GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequestFeaturesItem] gcvvavrFeatures = lens _gcvvavrFeatures (\ s a -> s{_gcvvavrFeatures = a}) . _Default . _Coerce -- | Optional. Cloud region where annotation should take place. Supported -- cloud regions are: \`us-east1\`, \`us-west1\`, \`europe-west1\`, -- \`asia-east1\`. If no region is specified, the region will be determined -- based on video file location. gcvvavrLocationId :: Lens' GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest (Maybe Text) gcvvavrLocationId = lens _gcvvavrLocationId (\ s a -> s{_gcvvavrLocationId = a}) -- | Optional. Location where the output (in JSON format) should be stored. -- Currently, only [Cloud Storage](https:\/\/cloud.google.com\/storage\/) -- URIs are supported. These must be specified in the following format: -- \`gs:\/\/bucket-id\/object-id\` (other URI formats return -- google.rpc.Code.INVALID_ARGUMENT). For more information, see [Request -- URIs](https:\/\/cloud.google.com\/storage\/docs\/request-endpoints). gcvvavrOutputURI :: Lens' GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest (Maybe Text) gcvvavrOutputURI = lens _gcvvavrOutputURI (\ s a -> s{_gcvvavrOutputURI = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1AnnotateVideoRequest" (\ o -> GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest' <$> (o .:? "inputUri") <*> (o .:? "videoContext") <*> (o .:? "inputContent") <*> (o .:? "features" .!= mempty) <*> (o .:? "locationId") <*> (o .:? "outputUri")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest where toJSON GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoRequest'{..} = object (catMaybes [("inputUri" .=) <$> _gcvvavrInputURI, ("videoContext" .=) <$> _gcvvavrVideoContext, ("inputContent" .=) <$> _gcvvavrInputContent, ("features" .=) <$> _gcvvavrFeatures, ("locationId" .=) <$> _gcvvavrLocationId, ("outputUri" .=) <$> _gcvvavrOutputURI]) -- | Video segment. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_VideoSegment' smart constructor. data GoogleCloudVideointelligenceV1beta2_VideoSegment = GoogleCloudVideointelligenceV1beta2_VideoSegment' { _gStartTimeOffSet :: !(Maybe GDuration) , _gEndTimeOffSet :: !(Maybe GDuration) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_VideoSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gStartTimeOffSet' -- -- * 'gEndTimeOffSet' googleCloudVideointelligenceV1beta2_VideoSegment :: GoogleCloudVideointelligenceV1beta2_VideoSegment googleCloudVideointelligenceV1beta2_VideoSegment = GoogleCloudVideointelligenceV1beta2_VideoSegment' {_gStartTimeOffSet = Nothing, _gEndTimeOffSet = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the start of the segment (inclusive). gStartTimeOffSet :: Lens' GoogleCloudVideointelligenceV1beta2_VideoSegment (Maybe Scientific) gStartTimeOffSet = lens _gStartTimeOffSet (\ s a -> s{_gStartTimeOffSet = a}) . mapping _GDuration -- | Time-offset, relative to the beginning of the video, corresponding to -- the end of the segment (inclusive). gEndTimeOffSet :: Lens' GoogleCloudVideointelligenceV1beta2_VideoSegment (Maybe Scientific) gEndTimeOffSet = lens _gEndTimeOffSet (\ s a -> s{_gEndTimeOffSet = a}) . mapping _GDuration instance FromJSON GoogleCloudVideointelligenceV1beta2_VideoSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2VideoSegment" (\ o -> GoogleCloudVideointelligenceV1beta2_VideoSegment' <$> (o .:? "startTimeOffset") <*> (o .:? "endTimeOffset")) instance ToJSON GoogleCloudVideointelligenceV1beta2_VideoSegment where toJSON GoogleCloudVideointelligenceV1beta2_VideoSegment'{..} = object (catMaybes [("startTimeOffset" .=) <$> _gStartTimeOffSet, ("endTimeOffset" .=) <$> _gEndTimeOffSet]) -- | Video segment level annotation results for face detection. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_FaceSegment' smart constructor. newtype GoogleCloudVideointelligenceV1p3beta1_FaceSegment = GoogleCloudVideointelligenceV1p3beta1_FaceSegment' { _gcvvfscSegment :: Maybe GoogleCloudVideointelligenceV1p3beta1_VideoSegment } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_FaceSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvfscSegment' googleCloudVideointelligenceV1p3beta1_FaceSegment :: GoogleCloudVideointelligenceV1p3beta1_FaceSegment googleCloudVideointelligenceV1p3beta1_FaceSegment = GoogleCloudVideointelligenceV1p3beta1_FaceSegment' {_gcvvfscSegment = Nothing} -- | Video segment where a face was detected. gcvvfscSegment :: Lens' GoogleCloudVideointelligenceV1p3beta1_FaceSegment (Maybe GoogleCloudVideointelligenceV1p3beta1_VideoSegment) gcvvfscSegment = lens _gcvvfscSegment (\ s a -> s{_gcvvfscSegment = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_FaceSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1FaceSegment" (\ o -> GoogleCloudVideointelligenceV1p3beta1_FaceSegment' <$> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_FaceSegment where toJSON GoogleCloudVideointelligenceV1p3beta1_FaceSegment'{..} = object (catMaybes [("segment" .=) <$> _gcvvfscSegment]) -- | Annotation results for a single video. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_VideoAnnotationResults' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults = GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults' { _gcvvvarcShotAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_VideoSegment]) , _gcvvvarcShotLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation]) , _gcvvvarcFaceDetectionAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation]) , _gcvvvarcFaceAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_FaceAnnotation]) , _gcvvvarcInputURI :: !(Maybe Text) , _gcvvvarcError :: !(Maybe GoogleRpc_Status) , _gcvvvarcShotPresenceLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation]) , _gcvvvarcPersonDetectionAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_PersonDetectionAnnotation]) , _gcvvvarcObjectAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation]) , _gcvvvarcFrameLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation]) , _gcvvvarcSpeechTranscriptions :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_SpeechTranscription]) , _gcvvvarcSegmentPresenceLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation]) , _gcvvvarcLogoRecognitionAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation]) , _gcvvvarcSegment :: !(Maybe GoogleCloudVideointelligenceV1p2beta1_VideoSegment) , _gcvvvarcTextAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_TextAnnotation]) , _gcvvvarcSegmentLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation]) , _gcvvvarcExplicitAnnotation :: !(Maybe GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvvarcShotAnnotations' -- -- * 'gcvvvarcShotLabelAnnotations' -- -- * 'gcvvvarcFaceDetectionAnnotations' -- -- * 'gcvvvarcFaceAnnotations' -- -- * 'gcvvvarcInputURI' -- -- * 'gcvvvarcError' -- -- * 'gcvvvarcShotPresenceLabelAnnotations' -- -- * 'gcvvvarcPersonDetectionAnnotations' -- -- * 'gcvvvarcObjectAnnotations' -- -- * 'gcvvvarcFrameLabelAnnotations' -- -- * 'gcvvvarcSpeechTranscriptions' -- -- * 'gcvvvarcSegmentPresenceLabelAnnotations' -- -- * 'gcvvvarcLogoRecognitionAnnotations' -- -- * 'gcvvvarcSegment' -- -- * 'gcvvvarcTextAnnotations' -- -- * 'gcvvvarcSegmentLabelAnnotations' -- -- * 'gcvvvarcExplicitAnnotation' googleCloudVideointelligenceV1p2beta1_VideoAnnotationResults :: GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults googleCloudVideointelligenceV1p2beta1_VideoAnnotationResults = GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults' { _gcvvvarcShotAnnotations = Nothing , _gcvvvarcShotLabelAnnotations = Nothing , _gcvvvarcFaceDetectionAnnotations = Nothing , _gcvvvarcFaceAnnotations = Nothing , _gcvvvarcInputURI = Nothing , _gcvvvarcError = Nothing , _gcvvvarcShotPresenceLabelAnnotations = Nothing , _gcvvvarcPersonDetectionAnnotations = Nothing , _gcvvvarcObjectAnnotations = Nothing , _gcvvvarcFrameLabelAnnotations = Nothing , _gcvvvarcSpeechTranscriptions = Nothing , _gcvvvarcSegmentPresenceLabelAnnotations = Nothing , _gcvvvarcLogoRecognitionAnnotations = Nothing , _gcvvvarcSegment = Nothing , _gcvvvarcTextAnnotations = Nothing , _gcvvvarcSegmentLabelAnnotations = Nothing , _gcvvvarcExplicitAnnotation = Nothing } -- | Shot annotations. Each shot is represented as a video segment. gcvvvarcShotAnnotations :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p2beta1_VideoSegment] gcvvvarcShotAnnotations = lens _gcvvvarcShotAnnotations (\ s a -> s{_gcvvvarcShotAnnotations = a}) . _Default . _Coerce -- | Topical label annotations on shot level. There is exactly one element -- for each unique label. gcvvvarcShotLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation] gcvvvarcShotLabelAnnotations = lens _gcvvvarcShotLabelAnnotations (\ s a -> s{_gcvvvarcShotLabelAnnotations = a}) . _Default . _Coerce -- | Face detection annotations. gcvvvarcFaceDetectionAnnotations :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation] gcvvvarcFaceDetectionAnnotations = lens _gcvvvarcFaceDetectionAnnotations (\ s a -> s{_gcvvvarcFaceDetectionAnnotations = a}) . _Default . _Coerce -- | Deprecated. Please use \`face_detection_annotations\` instead. gcvvvarcFaceAnnotations :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p2beta1_FaceAnnotation] gcvvvarcFaceAnnotations = lens _gcvvvarcFaceAnnotations (\ s a -> s{_gcvvvarcFaceAnnotations = a}) . _Default . _Coerce -- | Video file location in [Cloud -- Storage](https:\/\/cloud.google.com\/storage\/). gcvvvarcInputURI :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults (Maybe Text) gcvvvarcInputURI = lens _gcvvvarcInputURI (\ s a -> s{_gcvvvarcInputURI = a}) -- | If set, indicates an error. Note that for a single -- \`AnnotateVideoRequest\` some videos may succeed and some may fail. gcvvvarcError :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults (Maybe GoogleRpc_Status) gcvvvarcError = lens _gcvvvarcError (\ s a -> s{_gcvvvarcError = a}) -- | Presence label annotations on shot level. There is exactly one element -- for each unique label. Compared to the existing topical -- \`shot_label_annotations\`, this field presents more fine-grained, -- shot-level labels detected in video content and is made available only -- when the client sets \`LabelDetectionConfig.model\` to -- \"builtin\/latest\" in the request. gcvvvarcShotPresenceLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation] gcvvvarcShotPresenceLabelAnnotations = lens _gcvvvarcShotPresenceLabelAnnotations (\ s a -> s{_gcvvvarcShotPresenceLabelAnnotations = a}) . _Default . _Coerce -- | Person detection annotations. gcvvvarcPersonDetectionAnnotations :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p2beta1_PersonDetectionAnnotation] gcvvvarcPersonDetectionAnnotations = lens _gcvvvarcPersonDetectionAnnotations (\ s a -> s{_gcvvvarcPersonDetectionAnnotations = a}) . _Default . _Coerce -- | Annotations for list of objects detected and tracked in video. gcvvvarcObjectAnnotations :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p2beta1_ObjectTrackingAnnotation] gcvvvarcObjectAnnotations = lens _gcvvvarcObjectAnnotations (\ s a -> s{_gcvvvarcObjectAnnotations = a}) . _Default . _Coerce -- | Label annotations on frame level. There is exactly one element for each -- unique label. gcvvvarcFrameLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation] gcvvvarcFrameLabelAnnotations = lens _gcvvvarcFrameLabelAnnotations (\ s a -> s{_gcvvvarcFrameLabelAnnotations = a}) . _Default . _Coerce -- | Speech transcription. gcvvvarcSpeechTranscriptions :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p2beta1_SpeechTranscription] gcvvvarcSpeechTranscriptions = lens _gcvvvarcSpeechTranscriptions (\ s a -> s{_gcvvvarcSpeechTranscriptions = a}) . _Default . _Coerce -- | Presence label annotations on video level or user-specified segment -- level. There is exactly one element for each unique label. Compared to -- the existing topical \`segment_label_annotations\`, this field presents -- more fine-grained, segment-level labels detected in video content and is -- made available only when the client sets \`LabelDetectionConfig.model\` -- to \"builtin\/latest\" in the request. gcvvvarcSegmentPresenceLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation] gcvvvarcSegmentPresenceLabelAnnotations = lens _gcvvvarcSegmentPresenceLabelAnnotations (\ s a -> s{_gcvvvarcSegmentPresenceLabelAnnotations = a}) . _Default . _Coerce -- | Annotations for list of logos detected, tracked and recognized in video. gcvvvarcLogoRecognitionAnnotations :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation] gcvvvarcLogoRecognitionAnnotations = lens _gcvvvarcLogoRecognitionAnnotations (\ s a -> s{_gcvvvarcLogoRecognitionAnnotations = a}) . _Default . _Coerce -- | Video segment on which the annotation is run. gcvvvarcSegment :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults (Maybe GoogleCloudVideointelligenceV1p2beta1_VideoSegment) gcvvvarcSegment = lens _gcvvvarcSegment (\ s a -> s{_gcvvvarcSegment = a}) -- | OCR text detection and tracking. Annotations for list of detected text -- snippets. Each will have list of frame information associated with it. gcvvvarcTextAnnotations :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p2beta1_TextAnnotation] gcvvvarcTextAnnotations = lens _gcvvvarcTextAnnotations (\ s a -> s{_gcvvvarcTextAnnotations = a}) . _Default . _Coerce -- | Topical label annotations on video level or user-specified segment -- level. There is exactly one element for each unique label. gcvvvarcSegmentLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation] gcvvvarcSegmentLabelAnnotations = lens _gcvvvarcSegmentLabelAnnotations (\ s a -> s{_gcvvvarcSegmentLabelAnnotations = a}) . _Default . _Coerce -- | Explicit content annotation. gcvvvarcExplicitAnnotation :: Lens' GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults (Maybe GoogleCloudVideointelligenceV1p2beta1_ExplicitContentAnnotation) gcvvvarcExplicitAnnotation = lens _gcvvvarcExplicitAnnotation (\ s a -> s{_gcvvvarcExplicitAnnotation = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1VideoAnnotationResults" (\ o -> GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults' <$> (o .:? "shotAnnotations" .!= mempty) <*> (o .:? "shotLabelAnnotations" .!= mempty) <*> (o .:? "faceDetectionAnnotations" .!= mempty) <*> (o .:? "faceAnnotations" .!= mempty) <*> (o .:? "inputUri") <*> (o .:? "error") <*> (o .:? "shotPresenceLabelAnnotations" .!= mempty) <*> (o .:? "personDetectionAnnotations" .!= mempty) <*> (o .:? "objectAnnotations" .!= mempty) <*> (o .:? "frameLabelAnnotations" .!= mempty) <*> (o .:? "speechTranscriptions" .!= mempty) <*> (o .:? "segmentPresenceLabelAnnotations" .!= mempty) <*> (o .:? "logoRecognitionAnnotations" .!= mempty) <*> (o .:? "segment") <*> (o .:? "textAnnotations" .!= mempty) <*> (o .:? "segmentLabelAnnotations" .!= mempty) <*> (o .:? "explicitAnnotation")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults where toJSON GoogleCloudVideointelligenceV1p2beta1_VideoAnnotationResults'{..} = object (catMaybes [("shotAnnotations" .=) <$> _gcvvvarcShotAnnotations, ("shotLabelAnnotations" .=) <$> _gcvvvarcShotLabelAnnotations, ("faceDetectionAnnotations" .=) <$> _gcvvvarcFaceDetectionAnnotations, ("faceAnnotations" .=) <$> _gcvvvarcFaceAnnotations, ("inputUri" .=) <$> _gcvvvarcInputURI, ("error" .=) <$> _gcvvvarcError, ("shotPresenceLabelAnnotations" .=) <$> _gcvvvarcShotPresenceLabelAnnotations, ("personDetectionAnnotations" .=) <$> _gcvvvarcPersonDetectionAnnotations, ("objectAnnotations" .=) <$> _gcvvvarcObjectAnnotations, ("frameLabelAnnotations" .=) <$> _gcvvvarcFrameLabelAnnotations, ("speechTranscriptions" .=) <$> _gcvvvarcSpeechTranscriptions, ("segmentPresenceLabelAnnotations" .=) <$> _gcvvvarcSegmentPresenceLabelAnnotations, ("logoRecognitionAnnotations" .=) <$> _gcvvvarcLogoRecognitionAnnotations, ("segment" .=) <$> _gcvvvarcSegment, ("textAnnotations" .=) <$> _gcvvvarcTextAnnotations, ("segmentLabelAnnotations" .=) <$> _gcvvvarcSegmentLabelAnnotations, ("explicitAnnotation" .=) <$> _gcvvvarcExplicitAnnotation]) -- | Annotations corresponding to one tracked object. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation = GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation' { _gcvvotacFrames :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingFrame]) , _gcvvotacConfidence :: !(Maybe (Textual Double)) , _gcvvotacVersion :: !(Maybe Text) , _gcvvotacTrackId :: !(Maybe (Textual Int64)) , _gcvvotacSegment :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_VideoSegment) , _gcvvotacEntity :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_Entity) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvotacFrames' -- -- * 'gcvvotacConfidence' -- -- * 'gcvvotacVersion' -- -- * 'gcvvotacTrackId' -- -- * 'gcvvotacSegment' -- -- * 'gcvvotacEntity' googleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation :: GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation googleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation = GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation' { _gcvvotacFrames = Nothing , _gcvvotacConfidence = Nothing , _gcvvotacVersion = Nothing , _gcvvotacTrackId = Nothing , _gcvvotacSegment = Nothing , _gcvvotacEntity = Nothing } -- | Information corresponding to all frames where this object track appears. -- Non-streaming batch mode: it may be one or multiple ObjectTrackingFrame -- messages in frames. Streaming mode: it can only be one -- ObjectTrackingFrame message in frames. gcvvotacFrames :: Lens' GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation [GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingFrame] gcvvotacFrames = lens _gcvvotacFrames (\ s a -> s{_gcvvotacFrames = a}) . _Default . _Coerce -- | Object category\'s labeling confidence of this track. gcvvotacConfidence :: Lens' GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation (Maybe Double) gcvvotacConfidence = lens _gcvvotacConfidence (\ s a -> s{_gcvvotacConfidence = a}) . mapping _Coerce -- | Feature version. gcvvotacVersion :: Lens' GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation (Maybe Text) gcvvotacVersion = lens _gcvvotacVersion (\ s a -> s{_gcvvotacVersion = a}) -- | Streaming mode ONLY. In streaming mode, we do not know the end time of a -- tracked object before it is completed. Hence, there is no VideoSegment -- info returned. Instead, we provide a unique identifiable integer -- track_id so that the customers can correlate the results of the ongoing -- ObjectTrackAnnotation of the same track_id over time. gcvvotacTrackId :: Lens' GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation (Maybe Int64) gcvvotacTrackId = lens _gcvvotacTrackId (\ s a -> s{_gcvvotacTrackId = a}) . mapping _Coerce -- | Non-streaming batch mode ONLY. Each object track corresponds to one -- video segment where it appears. gcvvotacSegment :: Lens' GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation (Maybe GoogleCloudVideointelligenceV1p3beta1_VideoSegment) gcvvotacSegment = lens _gcvvotacSegment (\ s a -> s{_gcvvotacSegment = a}) -- | Entity to specify the object category that this track is labeled as. gcvvotacEntity :: Lens' GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation (Maybe GoogleCloudVideointelligenceV1p3beta1_Entity) gcvvotacEntity = lens _gcvvotacEntity (\ s a -> s{_gcvvotacEntity = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1ObjectTrackingAnnotation" (\ o -> GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation' <$> (o .:? "frames" .!= mempty) <*> (o .:? "confidence") <*> (o .:? "version") <*> (o .:? "trackId") <*> (o .:? "segment") <*> (o .:? "entity")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation where toJSON GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingAnnotation'{..} = object (catMaybes [("frames" .=) <$> _gcvvotacFrames, ("confidence" .=) <$> _gcvvotacConfidence, ("version" .=) <$> _gcvvotacVersion, ("trackId" .=) <$> _gcvvotacTrackId, ("segment" .=) <$> _gcvvotacSegment, ("entity" .=) <$> _gcvvotacEntity]) -- | Deprecated. No effect. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_FaceFrame' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_FaceFrame = GoogleCloudVideointelligenceV1p2beta1_FaceFrame' { _gcvvffcTimeOffSet :: !(Maybe GDuration) , _gcvvffcNormalizedBoundingBoxes :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_FaceFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvffcTimeOffSet' -- -- * 'gcvvffcNormalizedBoundingBoxes' googleCloudVideointelligenceV1p2beta1_FaceFrame :: GoogleCloudVideointelligenceV1p2beta1_FaceFrame googleCloudVideointelligenceV1p2beta1_FaceFrame = GoogleCloudVideointelligenceV1p2beta1_FaceFrame' {_gcvvffcTimeOffSet = Nothing, _gcvvffcNormalizedBoundingBoxes = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this location. gcvvffcTimeOffSet :: Lens' GoogleCloudVideointelligenceV1p2beta1_FaceFrame (Maybe Scientific) gcvvffcTimeOffSet = lens _gcvvffcTimeOffSet (\ s a -> s{_gcvvffcTimeOffSet = a}) . mapping _GDuration -- | Normalized Bounding boxes in a frame. There can be more than one boxes -- if the same face is detected in multiple locations within the current -- frame. gcvvffcNormalizedBoundingBoxes :: Lens' GoogleCloudVideointelligenceV1p2beta1_FaceFrame [GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox] gcvvffcNormalizedBoundingBoxes = lens _gcvvffcNormalizedBoundingBoxes (\ s a -> s{_gcvvffcNormalizedBoundingBoxes = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p2beta1_FaceFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1FaceFrame" (\ o -> GoogleCloudVideointelligenceV1p2beta1_FaceFrame' <$> (o .:? "timeOffset") <*> (o .:? "normalizedBoundingBoxes" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_FaceFrame where toJSON GoogleCloudVideointelligenceV1p2beta1_FaceFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvffcTimeOffSet, ("normalizedBoundingBoxes" .=) <$> _gcvvffcNormalizedBoundingBoxes]) -- | Video segment level annotation results for label detection. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_LabelSegment' smart constructor. data GoogleCloudVideointelligenceV1beta2_LabelSegment = GoogleCloudVideointelligenceV1beta2_LabelSegment' { _gcvvlscConfidence :: !(Maybe (Textual Double)) , _gcvvlscSegment :: !(Maybe GoogleCloudVideointelligenceV1beta2_VideoSegment) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_LabelSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvlscConfidence' -- -- * 'gcvvlscSegment' googleCloudVideointelligenceV1beta2_LabelSegment :: GoogleCloudVideointelligenceV1beta2_LabelSegment googleCloudVideointelligenceV1beta2_LabelSegment = GoogleCloudVideointelligenceV1beta2_LabelSegment' {_gcvvlscConfidence = Nothing, _gcvvlscSegment = Nothing} -- | Confidence that the label is accurate. Range: [0, 1]. gcvvlscConfidence :: Lens' GoogleCloudVideointelligenceV1beta2_LabelSegment (Maybe Double) gcvvlscConfidence = lens _gcvvlscConfidence (\ s a -> s{_gcvvlscConfidence = a}) . mapping _Coerce -- | Video segment where a label was detected. gcvvlscSegment :: Lens' GoogleCloudVideointelligenceV1beta2_LabelSegment (Maybe GoogleCloudVideointelligenceV1beta2_VideoSegment) gcvvlscSegment = lens _gcvvlscSegment (\ s a -> s{_gcvvlscSegment = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_LabelSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2LabelSegment" (\ o -> GoogleCloudVideointelligenceV1beta2_LabelSegment' <$> (o .:? "confidence") <*> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1beta2_LabelSegment where toJSON GoogleCloudVideointelligenceV1beta2_LabelSegment'{..} = object (catMaybes [("confidence" .=) <$> _gcvvlscConfidence, ("segment" .=) <$> _gcvvlscSegment]) -- | A generic detected landmark represented by name in string format and a -- 2D location. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_DetectedLandmark' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_DetectedLandmark = GoogleCloudVideointelligenceV1p2beta1_DetectedLandmark' { _gcvvdl1Confidence :: !(Maybe (Textual Double)) , _gcvvdl1Point :: !(Maybe GoogleCloudVideointelligenceV1p2beta1_NormalizedVertex) , _gcvvdl1Name :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_DetectedLandmark' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvdl1Confidence' -- -- * 'gcvvdl1Point' -- -- * 'gcvvdl1Name' googleCloudVideointelligenceV1p2beta1_DetectedLandmark :: GoogleCloudVideointelligenceV1p2beta1_DetectedLandmark googleCloudVideointelligenceV1p2beta1_DetectedLandmark = GoogleCloudVideointelligenceV1p2beta1_DetectedLandmark' { _gcvvdl1Confidence = Nothing , _gcvvdl1Point = Nothing , _gcvvdl1Name = Nothing } -- | The confidence score of the detected landmark. Range [0, 1]. gcvvdl1Confidence :: Lens' GoogleCloudVideointelligenceV1p2beta1_DetectedLandmark (Maybe Double) gcvvdl1Confidence = lens _gcvvdl1Confidence (\ s a -> s{_gcvvdl1Confidence = a}) . mapping _Coerce -- | The 2D point of the detected landmark using the normalized image -- coordindate system. The normalized coordinates have the range from 0 to -- 1. gcvvdl1Point :: Lens' GoogleCloudVideointelligenceV1p2beta1_DetectedLandmark (Maybe GoogleCloudVideointelligenceV1p2beta1_NormalizedVertex) gcvvdl1Point = lens _gcvvdl1Point (\ s a -> s{_gcvvdl1Point = a}) -- | The name of this landmark, for example, left_hand, right_shoulder. gcvvdl1Name :: Lens' GoogleCloudVideointelligenceV1p2beta1_DetectedLandmark (Maybe Text) gcvvdl1Name = lens _gcvvdl1Name (\ s a -> s{_gcvvdl1Name = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_DetectedLandmark where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1DetectedLandmark" (\ o -> GoogleCloudVideointelligenceV1p2beta1_DetectedLandmark' <$> (o .:? "confidence") <*> (o .:? "point") <*> (o .:? "name")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_DetectedLandmark where toJSON GoogleCloudVideointelligenceV1p2beta1_DetectedLandmark'{..} = object (catMaybes [("confidence" .=) <$> _gcvvdl1Confidence, ("point" .=) <$> _gcvvdl1Point, ("name" .=) <$> _gcvvdl1Name]) -- | Person detection annotation per video. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_PersonDetectionAnnotation' smart constructor. data GoogleCloudVideointelligenceV1beta2_PersonDetectionAnnotation = GoogleCloudVideointelligenceV1beta2_PersonDetectionAnnotation' { _ggTracks :: !(Maybe [GoogleCloudVideointelligenceV1beta2_Track]) , _ggVersion :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_PersonDetectionAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ggTracks' -- -- * 'ggVersion' googleCloudVideointelligenceV1beta2_PersonDetectionAnnotation :: GoogleCloudVideointelligenceV1beta2_PersonDetectionAnnotation googleCloudVideointelligenceV1beta2_PersonDetectionAnnotation = GoogleCloudVideointelligenceV1beta2_PersonDetectionAnnotation' {_ggTracks = Nothing, _ggVersion = Nothing} -- | The detected tracks of a person. ggTracks :: Lens' GoogleCloudVideointelligenceV1beta2_PersonDetectionAnnotation [GoogleCloudVideointelligenceV1beta2_Track] ggTracks = lens _ggTracks (\ s a -> s{_ggTracks = a}) . _Default . _Coerce -- | Feature version. ggVersion :: Lens' GoogleCloudVideointelligenceV1beta2_PersonDetectionAnnotation (Maybe Text) ggVersion = lens _ggVersion (\ s a -> s{_ggVersion = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_PersonDetectionAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2PersonDetectionAnnotation" (\ o -> GoogleCloudVideointelligenceV1beta2_PersonDetectionAnnotation' <$> (o .:? "tracks" .!= mempty) <*> (o .:? "version")) instance ToJSON GoogleCloudVideointelligenceV1beta2_PersonDetectionAnnotation where toJSON GoogleCloudVideointelligenceV1beta2_PersonDetectionAnnotation'{..} = object (catMaybes [("tracks" .=) <$> _ggTracks, ("version" .=) <$> _ggVersion]) -- | Video frame level annotations for object detection and tracking. This -- field stores per frame location, time offset, and confidence. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_ObjectTrackingFrame' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingFrame = GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingFrame' { _gcvvotf1TimeOffSet :: !(Maybe GDuration) , _gcvvotf1NormalizedBoundingBox :: !(Maybe GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvotf1TimeOffSet' -- -- * 'gcvvotf1NormalizedBoundingBox' googleCloudVideointelligenceV1p1beta1_ObjectTrackingFrame :: GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingFrame googleCloudVideointelligenceV1p1beta1_ObjectTrackingFrame = GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingFrame' {_gcvvotf1TimeOffSet = Nothing, _gcvvotf1NormalizedBoundingBox = Nothing} -- | The timestamp of the frame in microseconds. gcvvotf1TimeOffSet :: Lens' GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingFrame (Maybe Scientific) gcvvotf1TimeOffSet = lens _gcvvotf1TimeOffSet (\ s a -> s{_gcvvotf1TimeOffSet = a}) . mapping _GDuration -- | The normalized bounding box location of this object track for the frame. gcvvotf1NormalizedBoundingBox :: Lens' GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingFrame (Maybe GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox) gcvvotf1NormalizedBoundingBox = lens _gcvvotf1NormalizedBoundingBox (\ s a -> s{_gcvvotf1NormalizedBoundingBox = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1ObjectTrackingFrame" (\ o -> GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingFrame' <$> (o .:? "timeOffset") <*> (o .:? "normalizedBoundingBox")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingFrame where toJSON GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvotf1TimeOffSet, ("normalizedBoundingBox" .=) <$> _gcvvotf1NormalizedBoundingBox]) -- | Annotations corresponding to one tracked object. -- -- /See:/ 'googleCloudVideointelligenceV1_ObjectTrackingAnnotation' smart constructor. data GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation = GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation' { _gcvvota1Frames :: !(Maybe [GoogleCloudVideointelligenceV1_ObjectTrackingFrame]) , _gcvvota1Confidence :: !(Maybe (Textual Double)) , _gcvvota1Version :: !(Maybe Text) , _gcvvota1TrackId :: !(Maybe (Textual Int64)) , _gcvvota1Segment :: !(Maybe GoogleCloudVideointelligenceV1_VideoSegment) , _gcvvota1Entity :: !(Maybe GoogleCloudVideointelligenceV1_Entity) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvota1Frames' -- -- * 'gcvvota1Confidence' -- -- * 'gcvvota1Version' -- -- * 'gcvvota1TrackId' -- -- * 'gcvvota1Segment' -- -- * 'gcvvota1Entity' googleCloudVideointelligenceV1_ObjectTrackingAnnotation :: GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation googleCloudVideointelligenceV1_ObjectTrackingAnnotation = GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation' { _gcvvota1Frames = Nothing , _gcvvota1Confidence = Nothing , _gcvvota1Version = Nothing , _gcvvota1TrackId = Nothing , _gcvvota1Segment = Nothing , _gcvvota1Entity = Nothing } -- | Information corresponding to all frames where this object track appears. -- Non-streaming batch mode: it may be one or multiple ObjectTrackingFrame -- messages in frames. Streaming mode: it can only be one -- ObjectTrackingFrame message in frames. gcvvota1Frames :: Lens' GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation [GoogleCloudVideointelligenceV1_ObjectTrackingFrame] gcvvota1Frames = lens _gcvvota1Frames (\ s a -> s{_gcvvota1Frames = a}) . _Default . _Coerce -- | Object category\'s labeling confidence of this track. gcvvota1Confidence :: Lens' GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation (Maybe Double) gcvvota1Confidence = lens _gcvvota1Confidence (\ s a -> s{_gcvvota1Confidence = a}) . mapping _Coerce -- | Feature version. gcvvota1Version :: Lens' GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation (Maybe Text) gcvvota1Version = lens _gcvvota1Version (\ s a -> s{_gcvvota1Version = a}) -- | Streaming mode ONLY. In streaming mode, we do not know the end time of a -- tracked object before it is completed. Hence, there is no VideoSegment -- info returned. Instead, we provide a unique identifiable integer -- track_id so that the customers can correlate the results of the ongoing -- ObjectTrackAnnotation of the same track_id over time. gcvvota1TrackId :: Lens' GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation (Maybe Int64) gcvvota1TrackId = lens _gcvvota1TrackId (\ s a -> s{_gcvvota1TrackId = a}) . mapping _Coerce -- | Non-streaming batch mode ONLY. Each object track corresponds to one -- video segment where it appears. gcvvota1Segment :: Lens' GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation (Maybe GoogleCloudVideointelligenceV1_VideoSegment) gcvvota1Segment = lens _gcvvota1Segment (\ s a -> s{_gcvvota1Segment = a}) -- | Entity to specify the object category that this track is labeled as. gcvvota1Entity :: Lens' GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation (Maybe GoogleCloudVideointelligenceV1_Entity) gcvvota1Entity = lens _gcvvota1Entity (\ s a -> s{_gcvvota1Entity = a}) instance FromJSON GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1ObjectTrackingAnnotation" (\ o -> GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation' <$> (o .:? "frames" .!= mempty) <*> (o .:? "confidence") <*> (o .:? "version") <*> (o .:? "trackId") <*> (o .:? "segment") <*> (o .:? "entity")) instance ToJSON GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation where toJSON GoogleCloudVideointelligenceV1_ObjectTrackingAnnotation'{..} = object (catMaybes [("frames" .=) <$> _gcvvota1Frames, ("confidence" .=) <$> _gcvvota1Confidence, ("version" .=) <$> _gcvvota1Version, ("trackId" .=) <$> _gcvvota1TrackId, ("segment" .=) <$> _gcvvota1Segment, ("entity" .=) <$> _gcvvota1Entity]) -- | Normalized bounding polygon for text (that might not be aligned with -- axis). Contains list of the corner points in clockwise order starting -- from top-left corner. For example, for a rectangular bounding box: When -- the text is horizontal it might look like: 0----1 | | 3----2 When it\'s -- clockwise rotated 180 degrees around the top-left corner it becomes: -- 2----3 | | 1----0 and the vertex order will still be (0, 1, 2, 3). Note -- that values can be less than 0, or greater than 1 due to trignometric -- calculations for location of the box. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_NormalizedBoundingPoly' smart constructor. newtype GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingPoly = GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingPoly' { _gooVertices :: Maybe [GoogleCloudVideointelligenceV1p2beta1_NormalizedVertex] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingPoly' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gooVertices' googleCloudVideointelligenceV1p2beta1_NormalizedBoundingPoly :: GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingPoly googleCloudVideointelligenceV1p2beta1_NormalizedBoundingPoly = GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingPoly' {_gooVertices = Nothing} -- | Normalized vertices of the bounding polygon. gooVertices :: Lens' GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingPoly [GoogleCloudVideointelligenceV1p2beta1_NormalizedVertex] gooVertices = lens _gooVertices (\ s a -> s{_gooVertices = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingPoly where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1NormalizedBoundingPoly" (\ o -> GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingPoly' <$> (o .:? "vertices" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingPoly where toJSON GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingPoly'{..} = object (catMaybes [("vertices" .=) <$> _gooVertices]) -- | Word-specific information for recognized words. Word information is only -- included in the response when certain request parameters are set, such -- as \`enable_word_time_offsets\`. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_WordInfo' smart constructor. data GoogleCloudVideointelligenceV1beta2_WordInfo = GoogleCloudVideointelligenceV1beta2_WordInfo' { _gcvvwi1StartTime :: !(Maybe GDuration) , _gcvvwi1Confidence :: !(Maybe (Textual Double)) , _gcvvwi1EndTime :: !(Maybe GDuration) , _gcvvwi1Word :: !(Maybe Text) , _gcvvwi1SpeakerTag :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_WordInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvwi1StartTime' -- -- * 'gcvvwi1Confidence' -- -- * 'gcvvwi1EndTime' -- -- * 'gcvvwi1Word' -- -- * 'gcvvwi1SpeakerTag' googleCloudVideointelligenceV1beta2_WordInfo :: GoogleCloudVideointelligenceV1beta2_WordInfo googleCloudVideointelligenceV1beta2_WordInfo = GoogleCloudVideointelligenceV1beta2_WordInfo' { _gcvvwi1StartTime = Nothing , _gcvvwi1Confidence = Nothing , _gcvvwi1EndTime = Nothing , _gcvvwi1Word = Nothing , _gcvvwi1SpeakerTag = Nothing } -- | Time offset relative to the beginning of the audio, and corresponding to -- the start of the spoken word. This field is only set if -- \`enable_word_time_offsets=true\` and only in the top hypothesis. This -- is an experimental feature and the accuracy of the time offset can vary. gcvvwi1StartTime :: Lens' GoogleCloudVideointelligenceV1beta2_WordInfo (Maybe Scientific) gcvvwi1StartTime = lens _gcvvwi1StartTime (\ s a -> s{_gcvvwi1StartTime = a}) . mapping _GDuration -- | Output only. The confidence estimate between 0.0 and 1.0. A higher -- number indicates an estimated greater likelihood that the recognized -- words are correct. This field is set only for the top alternative. This -- field is not guaranteed to be accurate and users should not rely on it -- to be always provided. The default of 0.0 is a sentinel value indicating -- \`confidence\` was not set. gcvvwi1Confidence :: Lens' GoogleCloudVideointelligenceV1beta2_WordInfo (Maybe Double) gcvvwi1Confidence = lens _gcvvwi1Confidence (\ s a -> s{_gcvvwi1Confidence = a}) . mapping _Coerce -- | Time offset relative to the beginning of the audio, and corresponding to -- the end of the spoken word. This field is only set if -- \`enable_word_time_offsets=true\` and only in the top hypothesis. This -- is an experimental feature and the accuracy of the time offset can vary. gcvvwi1EndTime :: Lens' GoogleCloudVideointelligenceV1beta2_WordInfo (Maybe Scientific) gcvvwi1EndTime = lens _gcvvwi1EndTime (\ s a -> s{_gcvvwi1EndTime = a}) . mapping _GDuration -- | The word corresponding to this set of information. gcvvwi1Word :: Lens' GoogleCloudVideointelligenceV1beta2_WordInfo (Maybe Text) gcvvwi1Word = lens _gcvvwi1Word (\ s a -> s{_gcvvwi1Word = a}) -- | Output only. A distinct integer value is assigned for every speaker -- within the audio. This field specifies which one of those speakers was -- detected to have spoken this word. Value ranges from 1 up to -- diarization_speaker_count, and is only set if speaker diarization is -- enabled. gcvvwi1SpeakerTag :: Lens' GoogleCloudVideointelligenceV1beta2_WordInfo (Maybe Int32) gcvvwi1SpeakerTag = lens _gcvvwi1SpeakerTag (\ s a -> s{_gcvvwi1SpeakerTag = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1beta2_WordInfo where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2WordInfo" (\ o -> GoogleCloudVideointelligenceV1beta2_WordInfo' <$> (o .:? "startTime") <*> (o .:? "confidence") <*> (o .:? "endTime") <*> (o .:? "word") <*> (o .:? "speakerTag")) instance ToJSON GoogleCloudVideointelligenceV1beta2_WordInfo where toJSON GoogleCloudVideointelligenceV1beta2_WordInfo'{..} = object (catMaybes [("startTime" .=) <$> _gcvvwi1StartTime, ("confidence" .=) <$> _gcvvwi1Confidence, ("endTime" .=) <$> _gcvvwi1EndTime, ("word" .=) <$> _gcvvwi1Word, ("speakerTag" .=) <$> _gcvvwi1SpeakerTag]) -- | Video annotation response. Included in the \`response\` field of the -- \`Operation\` returned by the \`GetOperation\` call of the -- \`google::longrunning::Operations\` service. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_AnnotateVideoResponse' smart constructor. newtype GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoResponse = GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoResponse' { _gooAnnotationResults :: Maybe [GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gooAnnotationResults' googleCloudVideointelligenceV1p3beta1_AnnotateVideoResponse :: GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoResponse googleCloudVideointelligenceV1p3beta1_AnnotateVideoResponse = GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoResponse' {_gooAnnotationResults = Nothing} -- | Annotation results for all videos specified in \`AnnotateVideoRequest\`. gooAnnotationResults :: Lens' GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoResponse [GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationResults] gooAnnotationResults = lens _gooAnnotationResults (\ s a -> s{_gooAnnotationResults = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoResponse where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1AnnotateVideoResponse" (\ o -> GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoResponse' <$> (o .:? "annotationResults" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoResponse where toJSON GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoResponse'{..} = object (catMaybes [("annotationResults" .=) <$> _gooAnnotationResults]) -- | Annotations related to one detected OCR text snippet. This will contain -- the corresponding text, confidence value, and frame level information -- for each detection. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_TextAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_TextAnnotation = GoogleCloudVideointelligenceV1p1beta1_TextAnnotation' { _goooText :: !(Maybe Text) , _goooVersion :: !(Maybe Text) , _goooSegments :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_TextSegment]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_TextAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'goooText' -- -- * 'goooVersion' -- -- * 'goooSegments' googleCloudVideointelligenceV1p1beta1_TextAnnotation :: GoogleCloudVideointelligenceV1p1beta1_TextAnnotation googleCloudVideointelligenceV1p1beta1_TextAnnotation = GoogleCloudVideointelligenceV1p1beta1_TextAnnotation' {_goooText = Nothing, _goooVersion = Nothing, _goooSegments = Nothing} -- | The detected text. goooText :: Lens' GoogleCloudVideointelligenceV1p1beta1_TextAnnotation (Maybe Text) goooText = lens _goooText (\ s a -> s{_goooText = a}) -- | Feature version. goooVersion :: Lens' GoogleCloudVideointelligenceV1p1beta1_TextAnnotation (Maybe Text) goooVersion = lens _goooVersion (\ s a -> s{_goooVersion = a}) -- | All video segments where OCR detected text appears. goooSegments :: Lens' GoogleCloudVideointelligenceV1p1beta1_TextAnnotation [GoogleCloudVideointelligenceV1p1beta1_TextSegment] goooSegments = lens _goooSegments (\ s a -> s{_goooSegments = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p1beta1_TextAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1TextAnnotation" (\ o -> GoogleCloudVideointelligenceV1p1beta1_TextAnnotation' <$> (o .:? "text") <*> (o .:? "version") <*> (o .:? "segments" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_TextAnnotation where toJSON GoogleCloudVideointelligenceV1p1beta1_TextAnnotation'{..} = object (catMaybes [("text" .=) <$> _goooText, ("version" .=) <$> _goooVersion, ("segments" .=) <$> _goooSegments]) -- | Explicit content annotation (based on per-frame visual signals only). If -- no explicit content has been detected in a frame, no annotations are -- present for that frame. -- -- /See:/ 'googleCloudVideointelligenceV1_ExplicitContentAnnotation' smart constructor. data GoogleCloudVideointelligenceV1_ExplicitContentAnnotation = GoogleCloudVideointelligenceV1_ExplicitContentAnnotation' { _gcvvecacFrames :: !(Maybe [GoogleCloudVideointelligenceV1_ExplicitContentFrame]) , _gcvvecacVersion :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_ExplicitContentAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvecacFrames' -- -- * 'gcvvecacVersion' googleCloudVideointelligenceV1_ExplicitContentAnnotation :: GoogleCloudVideointelligenceV1_ExplicitContentAnnotation googleCloudVideointelligenceV1_ExplicitContentAnnotation = GoogleCloudVideointelligenceV1_ExplicitContentAnnotation' {_gcvvecacFrames = Nothing, _gcvvecacVersion = Nothing} -- | All video frames where explicit content was detected. gcvvecacFrames :: Lens' GoogleCloudVideointelligenceV1_ExplicitContentAnnotation [GoogleCloudVideointelligenceV1_ExplicitContentFrame] gcvvecacFrames = lens _gcvvecacFrames (\ s a -> s{_gcvvecacFrames = a}) . _Default . _Coerce -- | Feature version. gcvvecacVersion :: Lens' GoogleCloudVideointelligenceV1_ExplicitContentAnnotation (Maybe Text) gcvvecacVersion = lens _gcvvecacVersion (\ s a -> s{_gcvvecacVersion = a}) instance FromJSON GoogleCloudVideointelligenceV1_ExplicitContentAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1ExplicitContentAnnotation" (\ o -> GoogleCloudVideointelligenceV1_ExplicitContentAnnotation' <$> (o .:? "frames" .!= mempty) <*> (o .:? "version")) instance ToJSON GoogleCloudVideointelligenceV1_ExplicitContentAnnotation where toJSON GoogleCloudVideointelligenceV1_ExplicitContentAnnotation'{..} = object (catMaybes [("frames" .=) <$> _gcvvecacFrames, ("version" .=) <$> _gcvvecacVersion]) -- | Video frame level annotation results for text annotation (OCR). Contains -- information regarding timestamp and bounding box locations for the -- frames containing detected OCR text snippets. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_TextFrame' smart constructor. data GoogleCloudVideointelligenceV1beta2_TextFrame = GoogleCloudVideointelligenceV1beta2_TextFrame' { _gcvvtf1RotatedBoundingBox :: !(Maybe GoogleCloudVideointelligenceV1beta2_NormalizedBoundingPoly) , _gcvvtf1TimeOffSet :: !(Maybe GDuration) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_TextFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvtf1RotatedBoundingBox' -- -- * 'gcvvtf1TimeOffSet' googleCloudVideointelligenceV1beta2_TextFrame :: GoogleCloudVideointelligenceV1beta2_TextFrame googleCloudVideointelligenceV1beta2_TextFrame = GoogleCloudVideointelligenceV1beta2_TextFrame' {_gcvvtf1RotatedBoundingBox = Nothing, _gcvvtf1TimeOffSet = Nothing} -- | Bounding polygon of the detected text for this frame. gcvvtf1RotatedBoundingBox :: Lens' GoogleCloudVideointelligenceV1beta2_TextFrame (Maybe GoogleCloudVideointelligenceV1beta2_NormalizedBoundingPoly) gcvvtf1RotatedBoundingBox = lens _gcvvtf1RotatedBoundingBox (\ s a -> s{_gcvvtf1RotatedBoundingBox = a}) -- | Timestamp of this frame. gcvvtf1TimeOffSet :: Lens' GoogleCloudVideointelligenceV1beta2_TextFrame (Maybe Scientific) gcvvtf1TimeOffSet = lens _gcvvtf1TimeOffSet (\ s a -> s{_gcvvtf1TimeOffSet = a}) . mapping _GDuration instance FromJSON GoogleCloudVideointelligenceV1beta2_TextFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2TextFrame" (\ o -> GoogleCloudVideointelligenceV1beta2_TextFrame' <$> (o .:? "rotatedBoundingBox") <*> (o .:? "timeOffset")) instance ToJSON GoogleCloudVideointelligenceV1beta2_TextFrame where toJSON GoogleCloudVideointelligenceV1beta2_TextFrame'{..} = object (catMaybes [("rotatedBoundingBox" .=) <$> _gcvvtf1RotatedBoundingBox, ("timeOffset" .=) <$> _gcvvtf1TimeOffSet]) -- | Video annotation response. Included in the \`response\` field of the -- \`Operation\` returned by the \`GetOperation\` call of the -- \`google::longrunning::Operations\` service. -- -- /See:/ 'googleCloudVideointelligenceV1_AnnotateVideoResponse' smart constructor. newtype GoogleCloudVideointelligenceV1_AnnotateVideoResponse = GoogleCloudVideointelligenceV1_AnnotateVideoResponse' { _gcvvavrcAnnotationResults :: Maybe [GoogleCloudVideointelligenceV1_VideoAnnotationResults] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_AnnotateVideoResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvavrcAnnotationResults' googleCloudVideointelligenceV1_AnnotateVideoResponse :: GoogleCloudVideointelligenceV1_AnnotateVideoResponse googleCloudVideointelligenceV1_AnnotateVideoResponse = GoogleCloudVideointelligenceV1_AnnotateVideoResponse' {_gcvvavrcAnnotationResults = Nothing} -- | Annotation results for all videos specified in \`AnnotateVideoRequest\`. gcvvavrcAnnotationResults :: Lens' GoogleCloudVideointelligenceV1_AnnotateVideoResponse [GoogleCloudVideointelligenceV1_VideoAnnotationResults] gcvvavrcAnnotationResults = lens _gcvvavrcAnnotationResults (\ s a -> s{_gcvvavrcAnnotationResults = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1_AnnotateVideoResponse where parseJSON = withObject "GoogleCloudVideointelligenceV1AnnotateVideoResponse" (\ o -> GoogleCloudVideointelligenceV1_AnnotateVideoResponse' <$> (o .:? "annotationResults" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1_AnnotateVideoResponse where toJSON GoogleCloudVideointelligenceV1_AnnotateVideoResponse'{..} = object (catMaybes [("annotationResults" .=) <$> _gcvvavrcAnnotationResults]) -- | Explicit content annotation (based on per-frame visual signals only). If -- no explicit content has been detected in a frame, no annotations are -- present for that frame. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation = GoogleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation' { _gcvveca1Frames :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_ExplicitContentFrame]) , _gcvveca1Version :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvveca1Frames' -- -- * 'gcvveca1Version' googleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation :: GoogleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation googleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation = GoogleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation' {_gcvveca1Frames = Nothing, _gcvveca1Version = Nothing} -- | All video frames where explicit content was detected. gcvveca1Frames :: Lens' GoogleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation [GoogleCloudVideointelligenceV1p3beta1_ExplicitContentFrame] gcvveca1Frames = lens _gcvveca1Frames (\ s a -> s{_gcvveca1Frames = a}) . _Default . _Coerce -- | Feature version. gcvveca1Version :: Lens' GoogleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation (Maybe Text) gcvveca1Version = lens _gcvveca1Version (\ s a -> s{_gcvveca1Version = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1ExplicitContentAnnotation" (\ o -> GoogleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation' <$> (o .:? "frames" .!= mempty) <*> (o .:? "version")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation where toJSON GoogleCloudVideointelligenceV1p3beta1_ExplicitContentAnnotation'{..} = object (catMaybes [("frames" .=) <$> _gcvveca1Frames, ("version" .=) <$> _gcvveca1Version]) -- | A vertex represents a 2D point in the image. NOTE: the normalized vertex -- coordinates are relative to the original image and range from 0 to 1. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_NormalizedVertex' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_NormalizedVertex = GoogleCloudVideointelligenceV1p2beta1_NormalizedVertex' { _gooX :: !(Maybe (Textual Double)) , _gooY :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_NormalizedVertex' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gooX' -- -- * 'gooY' googleCloudVideointelligenceV1p2beta1_NormalizedVertex :: GoogleCloudVideointelligenceV1p2beta1_NormalizedVertex googleCloudVideointelligenceV1p2beta1_NormalizedVertex = GoogleCloudVideointelligenceV1p2beta1_NormalizedVertex' {_gooX = Nothing, _gooY = Nothing} -- | X coordinate. gooX :: Lens' GoogleCloudVideointelligenceV1p2beta1_NormalizedVertex (Maybe Double) gooX = lens _gooX (\ s a -> s{_gooX = a}) . mapping _Coerce -- | Y coordinate. gooY :: Lens' GoogleCloudVideointelligenceV1p2beta1_NormalizedVertex (Maybe Double) gooY = lens _gooY (\ s a -> s{_gooY = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1p2beta1_NormalizedVertex where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1NormalizedVertex" (\ o -> GoogleCloudVideointelligenceV1p2beta1_NormalizedVertex' <$> (o .:? "x") <*> (o .:? "y")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_NormalizedVertex where toJSON GoogleCloudVideointelligenceV1p2beta1_NormalizedVertex'{..} = object (catMaybes [("x" .=) <$> _gooX, ("y" .=) <$> _gooY]) -- | Label annotation. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_LabelAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation = GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation' { _gcvvlacCategoryEntities :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_Entity]) , _gcvvlacFrames :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_LabelFrame]) , _gcvvlacVersion :: !(Maybe Text) , _gcvvlacSegments :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_LabelSegment]) , _gcvvlacEntity :: !(Maybe GoogleCloudVideointelligenceV1p2beta1_Entity) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvlacCategoryEntities' -- -- * 'gcvvlacFrames' -- -- * 'gcvvlacVersion' -- -- * 'gcvvlacSegments' -- -- * 'gcvvlacEntity' googleCloudVideointelligenceV1p2beta1_LabelAnnotation :: GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation googleCloudVideointelligenceV1p2beta1_LabelAnnotation = GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation' { _gcvvlacCategoryEntities = Nothing , _gcvvlacFrames = Nothing , _gcvvlacVersion = Nothing , _gcvvlacSegments = Nothing , _gcvvlacEntity = Nothing } -- | Common categories for the detected entity. For example, when the label -- is \`Terrier\`, the category is likely \`dog\`. And in some cases there -- might be more than one categories e.g., \`Terrier\` could also be a -- \`pet\`. gcvvlacCategoryEntities :: Lens' GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation [GoogleCloudVideointelligenceV1p2beta1_Entity] gcvvlacCategoryEntities = lens _gcvvlacCategoryEntities (\ s a -> s{_gcvvlacCategoryEntities = a}) . _Default . _Coerce -- | All video frames where a label was detected. gcvvlacFrames :: Lens' GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation [GoogleCloudVideointelligenceV1p2beta1_LabelFrame] gcvvlacFrames = lens _gcvvlacFrames (\ s a -> s{_gcvvlacFrames = a}) . _Default . _Coerce -- | Feature version. gcvvlacVersion :: Lens' GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation (Maybe Text) gcvvlacVersion = lens _gcvvlacVersion (\ s a -> s{_gcvvlacVersion = a}) -- | All video segments where a label was detected. gcvvlacSegments :: Lens' GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation [GoogleCloudVideointelligenceV1p2beta1_LabelSegment] gcvvlacSegments = lens _gcvvlacSegments (\ s a -> s{_gcvvlacSegments = a}) . _Default . _Coerce -- | Detected entity. gcvvlacEntity :: Lens' GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation (Maybe GoogleCloudVideointelligenceV1p2beta1_Entity) gcvvlacEntity = lens _gcvvlacEntity (\ s a -> s{_gcvvlacEntity = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1LabelAnnotation" (\ o -> GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation' <$> (o .:? "categoryEntities" .!= mempty) <*> (o .:? "frames" .!= mempty) <*> (o .:? "version") <*> (o .:? "segments" .!= mempty) <*> (o .:? "entity")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation where toJSON GoogleCloudVideointelligenceV1p2beta1_LabelAnnotation'{..} = object (catMaybes [("categoryEntities" .=) <$> _gcvvlacCategoryEntities, ("frames" .=) <$> _gcvvlacFrames, ("version" .=) <$> _gcvvlacVersion, ("segments" .=) <$> _gcvvlacSegments, ("entity" .=) <$> _gcvvlacEntity]) -- | Alternative hypotheses (a.k.a. n-best list). -- -- /See:/ 'googleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative' smart constructor. data GoogleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative = GoogleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative' { _g1Confidence :: !(Maybe (Textual Double)) , _g1Words :: !(Maybe [GoogleCloudVideointelligenceV1beta2_WordInfo]) , _g1Transcript :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'g1Confidence' -- -- * 'g1Words' -- -- * 'g1Transcript' googleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative :: GoogleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative googleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative = GoogleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative' {_g1Confidence = Nothing, _g1Words = Nothing, _g1Transcript = Nothing} -- | Output only. The confidence estimate between 0.0 and 1.0. A higher -- number indicates an estimated greater likelihood that the recognized -- words are correct. This field is set only for the top alternative. This -- field is not guaranteed to be accurate and users should not rely on it -- to be always provided. The default of 0.0 is a sentinel value indicating -- \`confidence\` was not set. g1Confidence :: Lens' GoogleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative (Maybe Double) g1Confidence = lens _g1Confidence (\ s a -> s{_g1Confidence = a}) . mapping _Coerce -- | Output only. A list of word-specific information for each recognized -- word. Note: When \`enable_speaker_diarization\` is set to true, you will -- see all the words from the beginning of the audio. g1Words :: Lens' GoogleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative [GoogleCloudVideointelligenceV1beta2_WordInfo] g1Words = lens _g1Words (\ s a -> s{_g1Words = a}) . _Default . _Coerce -- | Transcript text representing the words that the user spoke. g1Transcript :: Lens' GoogleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative (Maybe Text) g1Transcript = lens _g1Transcript (\ s a -> s{_g1Transcript = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2SpeechRecognitionAlternative" (\ o -> GoogleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative' <$> (o .:? "confidence") <*> (o .:? "words" .!= mempty) <*> (o .:? "transcript")) instance ToJSON GoogleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative where toJSON GoogleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative'{..} = object (catMaybes [("confidence" .=) <$> _g1Confidence, ("words" .=) <$> _g1Words, ("transcript" .=) <$> _g1Transcript]) -- | Config for TEXT_DETECTION. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_TextDetectionConfig' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_TextDetectionConfig = GoogleCloudVideointelligenceV1p3beta1_TextDetectionConfig' { _gcvvtdcModel :: !(Maybe Text) , _gcvvtdcLanguageHints :: !(Maybe [Text]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_TextDetectionConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvtdcModel' -- -- * 'gcvvtdcLanguageHints' googleCloudVideointelligenceV1p3beta1_TextDetectionConfig :: GoogleCloudVideointelligenceV1p3beta1_TextDetectionConfig googleCloudVideointelligenceV1p3beta1_TextDetectionConfig = GoogleCloudVideointelligenceV1p3beta1_TextDetectionConfig' {_gcvvtdcModel = Nothing, _gcvvtdcLanguageHints = Nothing} -- | Model to use for text detection. Supported values: \"builtin\/stable\" -- (the default if unset) and \"builtin\/latest\". gcvvtdcModel :: Lens' GoogleCloudVideointelligenceV1p3beta1_TextDetectionConfig (Maybe Text) gcvvtdcModel = lens _gcvvtdcModel (\ s a -> s{_gcvvtdcModel = a}) -- | Language hint can be specified if the language to be detected is known a -- priori. It can increase the accuracy of the detection. Language hint -- must be language code in BCP-47 format. Automatic language detection is -- performed if no hint is provided. gcvvtdcLanguageHints :: Lens' GoogleCloudVideointelligenceV1p3beta1_TextDetectionConfig [Text] gcvvtdcLanguageHints = lens _gcvvtdcLanguageHints (\ s a -> s{_gcvvtdcLanguageHints = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p3beta1_TextDetectionConfig where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1TextDetectionConfig" (\ o -> GoogleCloudVideointelligenceV1p3beta1_TextDetectionConfig' <$> (o .:? "model") <*> (o .:? "languageHints" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_TextDetectionConfig where toJSON GoogleCloudVideointelligenceV1p3beta1_TextDetectionConfig'{..} = object (catMaybes [("model" .=) <$> _gcvvtdcModel, ("languageHints" .=) <$> _gcvvtdcLanguageHints]) -- | For tracking related features. An object at time_offset with attributes, -- and located with normalized_bounding_box. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_TimestampedObject' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_TimestampedObject = GoogleCloudVideointelligenceV1p1beta1_TimestampedObject' { _gcvvtocTimeOffSet :: !(Maybe GDuration) , _gcvvtocAttributes :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_DetectedAttribute]) , _gcvvtocNormalizedBoundingBox :: !(Maybe GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox) , _gcvvtocLandmarks :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_DetectedLandmark]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_TimestampedObject' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvtocTimeOffSet' -- -- * 'gcvvtocAttributes' -- -- * 'gcvvtocNormalizedBoundingBox' -- -- * 'gcvvtocLandmarks' googleCloudVideointelligenceV1p1beta1_TimestampedObject :: GoogleCloudVideointelligenceV1p1beta1_TimestampedObject googleCloudVideointelligenceV1p1beta1_TimestampedObject = GoogleCloudVideointelligenceV1p1beta1_TimestampedObject' { _gcvvtocTimeOffSet = Nothing , _gcvvtocAttributes = Nothing , _gcvvtocNormalizedBoundingBox = Nothing , _gcvvtocLandmarks = Nothing } -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this object. gcvvtocTimeOffSet :: Lens' GoogleCloudVideointelligenceV1p1beta1_TimestampedObject (Maybe Scientific) gcvvtocTimeOffSet = lens _gcvvtocTimeOffSet (\ s a -> s{_gcvvtocTimeOffSet = a}) . mapping _GDuration -- | Optional. The attributes of the object in the bounding box. gcvvtocAttributes :: Lens' GoogleCloudVideointelligenceV1p1beta1_TimestampedObject [GoogleCloudVideointelligenceV1p1beta1_DetectedAttribute] gcvvtocAttributes = lens _gcvvtocAttributes (\ s a -> s{_gcvvtocAttributes = a}) . _Default . _Coerce -- | Normalized Bounding box in a frame, where the object is located. gcvvtocNormalizedBoundingBox :: Lens' GoogleCloudVideointelligenceV1p1beta1_TimestampedObject (Maybe GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox) gcvvtocNormalizedBoundingBox = lens _gcvvtocNormalizedBoundingBox (\ s a -> s{_gcvvtocNormalizedBoundingBox = a}) -- | Optional. The detected landmarks. gcvvtocLandmarks :: Lens' GoogleCloudVideointelligenceV1p1beta1_TimestampedObject [GoogleCloudVideointelligenceV1p1beta1_DetectedLandmark] gcvvtocLandmarks = lens _gcvvtocLandmarks (\ s a -> s{_gcvvtocLandmarks = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p1beta1_TimestampedObject where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1TimestampedObject" (\ o -> GoogleCloudVideointelligenceV1p1beta1_TimestampedObject' <$> (o .:? "timeOffset") <*> (o .:? "attributes" .!= mempty) <*> (o .:? "normalizedBoundingBox") <*> (o .:? "landmarks" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_TimestampedObject where toJSON GoogleCloudVideointelligenceV1p1beta1_TimestampedObject'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvtocTimeOffSet, ("attributes" .=) <$> _gcvvtocAttributes, ("normalizedBoundingBox" .=) <$> _gcvvtocNormalizedBoundingBox, ("landmarks" .=) <$> _gcvvtocLandmarks]) -- | Config for PERSON_DETECTION. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_PersonDetectionConfig' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_PersonDetectionConfig = GoogleCloudVideointelligenceV1p3beta1_PersonDetectionConfig' { _gcvvpdcIncludePoseLandmarks :: !(Maybe Bool) , _gcvvpdcIncludeBoundingBoxes :: !(Maybe Bool) , _gcvvpdcIncludeAttributes :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_PersonDetectionConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvpdcIncludePoseLandmarks' -- -- * 'gcvvpdcIncludeBoundingBoxes' -- -- * 'gcvvpdcIncludeAttributes' googleCloudVideointelligenceV1p3beta1_PersonDetectionConfig :: GoogleCloudVideointelligenceV1p3beta1_PersonDetectionConfig googleCloudVideointelligenceV1p3beta1_PersonDetectionConfig = GoogleCloudVideointelligenceV1p3beta1_PersonDetectionConfig' { _gcvvpdcIncludePoseLandmarks = Nothing , _gcvvpdcIncludeBoundingBoxes = Nothing , _gcvvpdcIncludeAttributes = Nothing } -- | Whether to enable pose landmarks detection. Ignored if -- \'include_bounding_boxes\' is set to false. gcvvpdcIncludePoseLandmarks :: Lens' GoogleCloudVideointelligenceV1p3beta1_PersonDetectionConfig (Maybe Bool) gcvvpdcIncludePoseLandmarks = lens _gcvvpdcIncludePoseLandmarks (\ s a -> s{_gcvvpdcIncludePoseLandmarks = a}) -- | Whether bounding boxes are included in the person detection annotation -- output. gcvvpdcIncludeBoundingBoxes :: Lens' GoogleCloudVideointelligenceV1p3beta1_PersonDetectionConfig (Maybe Bool) gcvvpdcIncludeBoundingBoxes = lens _gcvvpdcIncludeBoundingBoxes (\ s a -> s{_gcvvpdcIncludeBoundingBoxes = a}) -- | Whether to enable person attributes detection, such as cloth color -- (black, blue, etc), type (coat, dress, etc), pattern (plain, floral, -- etc), hair, etc. Ignored if \'include_bounding_boxes\' is set to false. gcvvpdcIncludeAttributes :: Lens' GoogleCloudVideointelligenceV1p3beta1_PersonDetectionConfig (Maybe Bool) gcvvpdcIncludeAttributes = lens _gcvvpdcIncludeAttributes (\ s a -> s{_gcvvpdcIncludeAttributes = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_PersonDetectionConfig where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1PersonDetectionConfig" (\ o -> GoogleCloudVideointelligenceV1p3beta1_PersonDetectionConfig' <$> (o .:? "includePoseLandmarks") <*> (o .:? "includeBoundingBoxes") <*> (o .:? "includeAttributes")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_PersonDetectionConfig where toJSON GoogleCloudVideointelligenceV1p3beta1_PersonDetectionConfig'{..} = object (catMaybes [("includePoseLandmarks" .=) <$> _gcvvpdcIncludePoseLandmarks, ("includeBoundingBoxes" .=) <$> _gcvvpdcIncludeBoundingBoxes, ("includeAttributes" .=) <$> _gcvvpdcIncludeAttributes]) -- | A generic detected attribute represented by name in string format. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_DetectedAttribute' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_DetectedAttribute = GoogleCloudVideointelligenceV1p1beta1_DetectedAttribute' { _gcvvdacValue :: !(Maybe Text) , _gcvvdacConfidence :: !(Maybe (Textual Double)) , _gcvvdacName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_DetectedAttribute' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvdacValue' -- -- * 'gcvvdacConfidence' -- -- * 'gcvvdacName' googleCloudVideointelligenceV1p1beta1_DetectedAttribute :: GoogleCloudVideointelligenceV1p1beta1_DetectedAttribute googleCloudVideointelligenceV1p1beta1_DetectedAttribute = GoogleCloudVideointelligenceV1p1beta1_DetectedAttribute' { _gcvvdacValue = Nothing , _gcvvdacConfidence = Nothing , _gcvvdacName = Nothing } -- | Text value of the detection result. For example, the value for -- \"HairColor\" can be \"black\", \"blonde\", etc. gcvvdacValue :: Lens' GoogleCloudVideointelligenceV1p1beta1_DetectedAttribute (Maybe Text) gcvvdacValue = lens _gcvvdacValue (\ s a -> s{_gcvvdacValue = a}) -- | Detected attribute confidence. Range [0, 1]. gcvvdacConfidence :: Lens' GoogleCloudVideointelligenceV1p1beta1_DetectedAttribute (Maybe Double) gcvvdacConfidence = lens _gcvvdacConfidence (\ s a -> s{_gcvvdacConfidence = a}) . mapping _Coerce -- | The name of the attribute, for example, glasses, dark_glasses, -- mouth_open. A full list of supported type names will be provided in the -- document. gcvvdacName :: Lens' GoogleCloudVideointelligenceV1p1beta1_DetectedAttribute (Maybe Text) gcvvdacName = lens _gcvvdacName (\ s a -> s{_gcvvdacName = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_DetectedAttribute where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1DetectedAttribute" (\ o -> GoogleCloudVideointelligenceV1p1beta1_DetectedAttribute' <$> (o .:? "value") <*> (o .:? "confidence") <*> (o .:? "name")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_DetectedAttribute where toJSON GoogleCloudVideointelligenceV1p1beta1_DetectedAttribute'{..} = object (catMaybes [("value" .=) <$> _gcvvdacValue, ("confidence" .=) <$> _gcvvdacConfidence, ("name" .=) <$> _gcvvdacName]) -- | Video segment. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_VideoSegment' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_VideoSegment = GoogleCloudVideointelligenceV1p1beta1_VideoSegment' { _gooStartTimeOffSet :: !(Maybe GDuration) , _gooEndTimeOffSet :: !(Maybe GDuration) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_VideoSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gooStartTimeOffSet' -- -- * 'gooEndTimeOffSet' googleCloudVideointelligenceV1p1beta1_VideoSegment :: GoogleCloudVideointelligenceV1p1beta1_VideoSegment googleCloudVideointelligenceV1p1beta1_VideoSegment = GoogleCloudVideointelligenceV1p1beta1_VideoSegment' {_gooStartTimeOffSet = Nothing, _gooEndTimeOffSet = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the start of the segment (inclusive). gooStartTimeOffSet :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoSegment (Maybe Scientific) gooStartTimeOffSet = lens _gooStartTimeOffSet (\ s a -> s{_gooStartTimeOffSet = a}) . mapping _GDuration -- | Time-offset, relative to the beginning of the video, corresponding to -- the end of the segment (inclusive). gooEndTimeOffSet :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoSegment (Maybe Scientific) gooEndTimeOffSet = lens _gooEndTimeOffSet (\ s a -> s{_gooEndTimeOffSet = a}) . mapping _GDuration instance FromJSON GoogleCloudVideointelligenceV1p1beta1_VideoSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1VideoSegment" (\ o -> GoogleCloudVideointelligenceV1p1beta1_VideoSegment' <$> (o .:? "startTimeOffset") <*> (o .:? "endTimeOffset")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_VideoSegment where toJSON GoogleCloudVideointelligenceV1p1beta1_VideoSegment'{..} = object (catMaybes [("startTimeOffset" .=) <$> _gooStartTimeOffSet, ("endTimeOffset" .=) <$> _gooEndTimeOffSet]) -- | Face detection annotation. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation = GoogleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation' { _gcvvfda1Thumbnail :: !(Maybe Bytes) , _gcvvfda1Tracks :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_Track]) , _gcvvfda1Version :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvfda1Thumbnail' -- -- * 'gcvvfda1Tracks' -- -- * 'gcvvfda1Version' googleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation :: GoogleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation googleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation = GoogleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation' { _gcvvfda1Thumbnail = Nothing , _gcvvfda1Tracks = Nothing , _gcvvfda1Version = Nothing } -- | The thumbnail of a person\'s face. gcvvfda1Thumbnail :: Lens' GoogleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation (Maybe ByteString) gcvvfda1Thumbnail = lens _gcvvfda1Thumbnail (\ s a -> s{_gcvvfda1Thumbnail = a}) . mapping _Bytes -- | The face tracks with attributes. gcvvfda1Tracks :: Lens' GoogleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation [GoogleCloudVideointelligenceV1p2beta1_Track] gcvvfda1Tracks = lens _gcvvfda1Tracks (\ s a -> s{_gcvvfda1Tracks = a}) . _Default . _Coerce -- | Feature version. gcvvfda1Version :: Lens' GoogleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation (Maybe Text) gcvvfda1Version = lens _gcvvfda1Version (\ s a -> s{_gcvvfda1Version = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1FaceDetectionAnnotation" (\ o -> GoogleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation' <$> (o .:? "thumbnail") <*> (o .:? "tracks" .!= mempty) <*> (o .:? "version")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation where toJSON GoogleCloudVideointelligenceV1p2beta1_FaceDetectionAnnotation'{..} = object (catMaybes [("thumbnail" .=) <$> _gcvvfda1Thumbnail, ("tracks" .=) <$> _gcvvfda1Tracks, ("version" .=) <$> _gcvvfda1Version]) -- | A generic detected attribute represented by name in string format. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_DetectedAttribute' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_DetectedAttribute = GoogleCloudVideointelligenceV1p2beta1_DetectedAttribute' { _gcvvda1Value :: !(Maybe Text) , _gcvvda1Confidence :: !(Maybe (Textual Double)) , _gcvvda1Name :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_DetectedAttribute' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvda1Value' -- -- * 'gcvvda1Confidence' -- -- * 'gcvvda1Name' googleCloudVideointelligenceV1p2beta1_DetectedAttribute :: GoogleCloudVideointelligenceV1p2beta1_DetectedAttribute googleCloudVideointelligenceV1p2beta1_DetectedAttribute = GoogleCloudVideointelligenceV1p2beta1_DetectedAttribute' { _gcvvda1Value = Nothing , _gcvvda1Confidence = Nothing , _gcvvda1Name = Nothing } -- | Text value of the detection result. For example, the value for -- \"HairColor\" can be \"black\", \"blonde\", etc. gcvvda1Value :: Lens' GoogleCloudVideointelligenceV1p2beta1_DetectedAttribute (Maybe Text) gcvvda1Value = lens _gcvvda1Value (\ s a -> s{_gcvvda1Value = a}) -- | Detected attribute confidence. Range [0, 1]. gcvvda1Confidence :: Lens' GoogleCloudVideointelligenceV1p2beta1_DetectedAttribute (Maybe Double) gcvvda1Confidence = lens _gcvvda1Confidence (\ s a -> s{_gcvvda1Confidence = a}) . mapping _Coerce -- | The name of the attribute, for example, glasses, dark_glasses, -- mouth_open. A full list of supported type names will be provided in the -- document. gcvvda1Name :: Lens' GoogleCloudVideointelligenceV1p2beta1_DetectedAttribute (Maybe Text) gcvvda1Name = lens _gcvvda1Name (\ s a -> s{_gcvvda1Name = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_DetectedAttribute where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1DetectedAttribute" (\ o -> GoogleCloudVideointelligenceV1p2beta1_DetectedAttribute' <$> (o .:? "value") <*> (o .:? "confidence") <*> (o .:? "name")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_DetectedAttribute where toJSON GoogleCloudVideointelligenceV1p2beta1_DetectedAttribute'{..} = object (catMaybes [("value" .=) <$> _gcvvda1Value, ("confidence" .=) <$> _gcvvda1Confidence, ("name" .=) <$> _gcvvda1Name]) -- | Annotation corresponding to one detected, tracked and recognized logo -- class. -- -- /See:/ 'googleCloudVideointelligenceV1_LogoRecognitionAnnotation' smart constructor. data GoogleCloudVideointelligenceV1_LogoRecognitionAnnotation = GoogleCloudVideointelligenceV1_LogoRecognitionAnnotation' { _gcvvlracTracks :: !(Maybe [GoogleCloudVideointelligenceV1_Track]) , _gcvvlracSegments :: !(Maybe [GoogleCloudVideointelligenceV1_VideoSegment]) , _gcvvlracEntity :: !(Maybe GoogleCloudVideointelligenceV1_Entity) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_LogoRecognitionAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvlracTracks' -- -- * 'gcvvlracSegments' -- -- * 'gcvvlracEntity' googleCloudVideointelligenceV1_LogoRecognitionAnnotation :: GoogleCloudVideointelligenceV1_LogoRecognitionAnnotation googleCloudVideointelligenceV1_LogoRecognitionAnnotation = GoogleCloudVideointelligenceV1_LogoRecognitionAnnotation' { _gcvvlracTracks = Nothing , _gcvvlracSegments = Nothing , _gcvvlracEntity = Nothing } -- | All logo tracks where the recognized logo appears. Each track -- corresponds to one logo instance appearing in consecutive frames. gcvvlracTracks :: Lens' GoogleCloudVideointelligenceV1_LogoRecognitionAnnotation [GoogleCloudVideointelligenceV1_Track] gcvvlracTracks = lens _gcvvlracTracks (\ s a -> s{_gcvvlracTracks = a}) . _Default . _Coerce -- | All video segments where the recognized logo appears. There might be -- multiple instances of the same logo class appearing in one VideoSegment. gcvvlracSegments :: Lens' GoogleCloudVideointelligenceV1_LogoRecognitionAnnotation [GoogleCloudVideointelligenceV1_VideoSegment] gcvvlracSegments = lens _gcvvlracSegments (\ s a -> s{_gcvvlracSegments = a}) . _Default . _Coerce -- | Entity category information to specify the logo class that all the logo -- tracks within this LogoRecognitionAnnotation are recognized as. gcvvlracEntity :: Lens' GoogleCloudVideointelligenceV1_LogoRecognitionAnnotation (Maybe GoogleCloudVideointelligenceV1_Entity) gcvvlracEntity = lens _gcvvlracEntity (\ s a -> s{_gcvvlracEntity = a}) instance FromJSON GoogleCloudVideointelligenceV1_LogoRecognitionAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1LogoRecognitionAnnotation" (\ o -> GoogleCloudVideointelligenceV1_LogoRecognitionAnnotation' <$> (o .:? "tracks" .!= mempty) <*> (o .:? "segments" .!= mempty) <*> (o .:? "entity")) instance ToJSON GoogleCloudVideointelligenceV1_LogoRecognitionAnnotation where toJSON GoogleCloudVideointelligenceV1_LogoRecognitionAnnotation'{..} = object (catMaybes [("tracks" .=) <$> _gcvvlracTracks, ("segments" .=) <$> _gcvvlracSegments, ("entity" .=) <$> _gcvvlracEntity]) -- | For tracking related features. An object at time_offset with attributes, -- and located with normalized_bounding_box. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_TimestampedObject' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_TimestampedObject = GoogleCloudVideointelligenceV1p2beta1_TimestampedObject' { _gcvvto1TimeOffSet :: !(Maybe GDuration) , _gcvvto1Attributes :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_DetectedAttribute]) , _gcvvto1NormalizedBoundingBox :: !(Maybe GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox) , _gcvvto1Landmarks :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_DetectedLandmark]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_TimestampedObject' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvto1TimeOffSet' -- -- * 'gcvvto1Attributes' -- -- * 'gcvvto1NormalizedBoundingBox' -- -- * 'gcvvto1Landmarks' googleCloudVideointelligenceV1p2beta1_TimestampedObject :: GoogleCloudVideointelligenceV1p2beta1_TimestampedObject googleCloudVideointelligenceV1p2beta1_TimestampedObject = GoogleCloudVideointelligenceV1p2beta1_TimestampedObject' { _gcvvto1TimeOffSet = Nothing , _gcvvto1Attributes = Nothing , _gcvvto1NormalizedBoundingBox = Nothing , _gcvvto1Landmarks = Nothing } -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this object. gcvvto1TimeOffSet :: Lens' GoogleCloudVideointelligenceV1p2beta1_TimestampedObject (Maybe Scientific) gcvvto1TimeOffSet = lens _gcvvto1TimeOffSet (\ s a -> s{_gcvvto1TimeOffSet = a}) . mapping _GDuration -- | Optional. The attributes of the object in the bounding box. gcvvto1Attributes :: Lens' GoogleCloudVideointelligenceV1p2beta1_TimestampedObject [GoogleCloudVideointelligenceV1p2beta1_DetectedAttribute] gcvvto1Attributes = lens _gcvvto1Attributes (\ s a -> s{_gcvvto1Attributes = a}) . _Default . _Coerce -- | Normalized Bounding box in a frame, where the object is located. gcvvto1NormalizedBoundingBox :: Lens' GoogleCloudVideointelligenceV1p2beta1_TimestampedObject (Maybe GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox) gcvvto1NormalizedBoundingBox = lens _gcvvto1NormalizedBoundingBox (\ s a -> s{_gcvvto1NormalizedBoundingBox = a}) -- | Optional. The detected landmarks. gcvvto1Landmarks :: Lens' GoogleCloudVideointelligenceV1p2beta1_TimestampedObject [GoogleCloudVideointelligenceV1p2beta1_DetectedLandmark] gcvvto1Landmarks = lens _gcvvto1Landmarks (\ s a -> s{_gcvvto1Landmarks = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p2beta1_TimestampedObject where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1TimestampedObject" (\ o -> GoogleCloudVideointelligenceV1p2beta1_TimestampedObject' <$> (o .:? "timeOffset") <*> (o .:? "attributes" .!= mempty) <*> (o .:? "normalizedBoundingBox") <*> (o .:? "landmarks" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_TimestampedObject where toJSON GoogleCloudVideointelligenceV1p2beta1_TimestampedObject'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvto1TimeOffSet, ("attributes" .=) <$> _gcvvto1Attributes, ("normalizedBoundingBox" .=) <$> _gcvvto1NormalizedBoundingBox, ("landmarks" .=) <$> _gcvvto1Landmarks]) -- | Detected entity from video analysis. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_Entity' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_Entity = GoogleCloudVideointelligenceV1p3beta1_Entity' { _ggLanguageCode :: !(Maybe Text) , _ggEntityId :: !(Maybe Text) , _ggDescription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_Entity' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ggLanguageCode' -- -- * 'ggEntityId' -- -- * 'ggDescription' googleCloudVideointelligenceV1p3beta1_Entity :: GoogleCloudVideointelligenceV1p3beta1_Entity googleCloudVideointelligenceV1p3beta1_Entity = GoogleCloudVideointelligenceV1p3beta1_Entity' {_ggLanguageCode = Nothing, _ggEntityId = Nothing, _ggDescription = Nothing} -- | Language code for \`description\` in BCP-47 format. ggLanguageCode :: Lens' GoogleCloudVideointelligenceV1p3beta1_Entity (Maybe Text) ggLanguageCode = lens _ggLanguageCode (\ s a -> s{_ggLanguageCode = a}) -- | Opaque entity ID. Some IDs may be available in [Google Knowledge Graph -- Search API](https:\/\/developers.google.com\/knowledge-graph\/). ggEntityId :: Lens' GoogleCloudVideointelligenceV1p3beta1_Entity (Maybe Text) ggEntityId = lens _ggEntityId (\ s a -> s{_ggEntityId = a}) -- | Textual description, e.g., \`Fixed-gear bicycle\`. ggDescription :: Lens' GoogleCloudVideointelligenceV1p3beta1_Entity (Maybe Text) ggDescription = lens _ggDescription (\ s a -> s{_ggDescription = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_Entity where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1Entity" (\ o -> GoogleCloudVideointelligenceV1p3beta1_Entity' <$> (o .:? "languageCode") <*> (o .:? "entityId") <*> (o .:? "description")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_Entity where toJSON GoogleCloudVideointelligenceV1p3beta1_Entity'{..} = object (catMaybes [("languageCode" .=) <$> _ggLanguageCode, ("entityId" .=) <$> _ggEntityId, ("description" .=) <$> _ggDescription]) -- | Config for SHOT_CHANGE_DETECTION. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_ShotChangeDetectionConfig' smart constructor. newtype GoogleCloudVideointelligenceV1p3beta1_ShotChangeDetectionConfig = GoogleCloudVideointelligenceV1p3beta1_ShotChangeDetectionConfig' { _gcvvscdcModel :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_ShotChangeDetectionConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvscdcModel' googleCloudVideointelligenceV1p3beta1_ShotChangeDetectionConfig :: GoogleCloudVideointelligenceV1p3beta1_ShotChangeDetectionConfig googleCloudVideointelligenceV1p3beta1_ShotChangeDetectionConfig = GoogleCloudVideointelligenceV1p3beta1_ShotChangeDetectionConfig' {_gcvvscdcModel = Nothing} -- | Model to use for shot change detection. Supported values: -- \"builtin\/stable\" (the default if unset) and \"builtin\/latest\". gcvvscdcModel :: Lens' GoogleCloudVideointelligenceV1p3beta1_ShotChangeDetectionConfig (Maybe Text) gcvvscdcModel = lens _gcvvscdcModel (\ s a -> s{_gcvvscdcModel = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_ShotChangeDetectionConfig where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1ShotChangeDetectionConfig" (\ o -> GoogleCloudVideointelligenceV1p3beta1_ShotChangeDetectionConfig' <$> (o .:? "model")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_ShotChangeDetectionConfig where toJSON GoogleCloudVideointelligenceV1p3beta1_ShotChangeDetectionConfig'{..} = object (catMaybes [("model" .=) <$> _gcvvscdcModel]) -- | Label annotation. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_LabelAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation = GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation' { _gcvvla1CategoryEntities :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_Entity]) , _gcvvla1Frames :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_LabelFrame]) , _gcvvla1Version :: !(Maybe Text) , _gcvvla1Segments :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_LabelSegment]) , _gcvvla1Entity :: !(Maybe GoogleCloudVideointelligenceV1p1beta1_Entity) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvla1CategoryEntities' -- -- * 'gcvvla1Frames' -- -- * 'gcvvla1Version' -- -- * 'gcvvla1Segments' -- -- * 'gcvvla1Entity' googleCloudVideointelligenceV1p1beta1_LabelAnnotation :: GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation googleCloudVideointelligenceV1p1beta1_LabelAnnotation = GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation' { _gcvvla1CategoryEntities = Nothing , _gcvvla1Frames = Nothing , _gcvvla1Version = Nothing , _gcvvla1Segments = Nothing , _gcvvla1Entity = Nothing } -- | Common categories for the detected entity. For example, when the label -- is \`Terrier\`, the category is likely \`dog\`. And in some cases there -- might be more than one categories e.g., \`Terrier\` could also be a -- \`pet\`. gcvvla1CategoryEntities :: Lens' GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation [GoogleCloudVideointelligenceV1p1beta1_Entity] gcvvla1CategoryEntities = lens _gcvvla1CategoryEntities (\ s a -> s{_gcvvla1CategoryEntities = a}) . _Default . _Coerce -- | All video frames where a label was detected. gcvvla1Frames :: Lens' GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation [GoogleCloudVideointelligenceV1p1beta1_LabelFrame] gcvvla1Frames = lens _gcvvla1Frames (\ s a -> s{_gcvvla1Frames = a}) . _Default . _Coerce -- | Feature version. gcvvla1Version :: Lens' GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation (Maybe Text) gcvvla1Version = lens _gcvvla1Version (\ s a -> s{_gcvvla1Version = a}) -- | All video segments where a label was detected. gcvvla1Segments :: Lens' GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation [GoogleCloudVideointelligenceV1p1beta1_LabelSegment] gcvvla1Segments = lens _gcvvla1Segments (\ s a -> s{_gcvvla1Segments = a}) . _Default . _Coerce -- | Detected entity. gcvvla1Entity :: Lens' GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation (Maybe GoogleCloudVideointelligenceV1p1beta1_Entity) gcvvla1Entity = lens _gcvvla1Entity (\ s a -> s{_gcvvla1Entity = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1LabelAnnotation" (\ o -> GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation' <$> (o .:? "categoryEntities" .!= mempty) <*> (o .:? "frames" .!= mempty) <*> (o .:? "version") <*> (o .:? "segments" .!= mempty) <*> (o .:? "entity")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation where toJSON GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation'{..} = object (catMaybes [("categoryEntities" .=) <$> _gcvvla1CategoryEntities, ("frames" .=) <$> _gcvvla1Frames, ("version" .=) <$> _gcvvla1Version, ("segments" .=) <$> _gcvvla1Segments, ("entity" .=) <$> _gcvvla1Entity]) -- | Video frame level annotation results for label detection. -- -- /See:/ 'googleCloudVideointelligenceV1_LabelFrame' smart constructor. data GoogleCloudVideointelligenceV1_LabelFrame = GoogleCloudVideointelligenceV1_LabelFrame' { _gcvvlf1TimeOffSet :: !(Maybe GDuration) , _gcvvlf1Confidence :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_LabelFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvlf1TimeOffSet' -- -- * 'gcvvlf1Confidence' googleCloudVideointelligenceV1_LabelFrame :: GoogleCloudVideointelligenceV1_LabelFrame googleCloudVideointelligenceV1_LabelFrame = GoogleCloudVideointelligenceV1_LabelFrame' {_gcvvlf1TimeOffSet = Nothing, _gcvvlf1Confidence = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this location. gcvvlf1TimeOffSet :: Lens' GoogleCloudVideointelligenceV1_LabelFrame (Maybe Scientific) gcvvlf1TimeOffSet = lens _gcvvlf1TimeOffSet (\ s a -> s{_gcvvlf1TimeOffSet = a}) . mapping _GDuration -- | Confidence that the label is accurate. Range: [0, 1]. gcvvlf1Confidence :: Lens' GoogleCloudVideointelligenceV1_LabelFrame (Maybe Double) gcvvlf1Confidence = lens _gcvvlf1Confidence (\ s a -> s{_gcvvlf1Confidence = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1_LabelFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1LabelFrame" (\ o -> GoogleCloudVideointelligenceV1_LabelFrame' <$> (o .:? "timeOffset") <*> (o .:? "confidence")) instance ToJSON GoogleCloudVideointelligenceV1_LabelFrame where toJSON GoogleCloudVideointelligenceV1_LabelFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvlf1TimeOffSet, ("confidence" .=) <$> _gcvvlf1Confidence]) -- | Face detection annotation. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation = GoogleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation' { _g1Thumbnail :: !(Maybe Bytes) , _g1Tracks :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_Track]) , _g1Version :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'g1Thumbnail' -- -- * 'g1Tracks' -- -- * 'g1Version' googleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation :: GoogleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation googleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation = GoogleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation' {_g1Thumbnail = Nothing, _g1Tracks = Nothing, _g1Version = Nothing} -- | The thumbnail of a person\'s face. g1Thumbnail :: Lens' GoogleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation (Maybe ByteString) g1Thumbnail = lens _g1Thumbnail (\ s a -> s{_g1Thumbnail = a}) . mapping _Bytes -- | The face tracks with attributes. g1Tracks :: Lens' GoogleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation [GoogleCloudVideointelligenceV1p1beta1_Track] g1Tracks = lens _g1Tracks (\ s a -> s{_g1Tracks = a}) . _Default . _Coerce -- | Feature version. g1Version :: Lens' GoogleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation (Maybe Text) g1Version = lens _g1Version (\ s a -> s{_g1Version = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1FaceDetectionAnnotation" (\ o -> GoogleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation' <$> (o .:? "thumbnail") <*> (o .:? "tracks" .!= mempty) <*> (o .:? "version")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation where toJSON GoogleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation'{..} = object (catMaybes [("thumbnail" .=) <$> _g1Thumbnail, ("tracks" .=) <$> _g1Tracks, ("version" .=) <$> _g1Version]) -- | Annotation corresponding to one detected, tracked and recognized logo -- class. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation = GoogleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation' { _gcvvlra1Tracks :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_Track]) , _gcvvlra1Segments :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_VideoSegment]) , _gcvvlra1Entity :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_Entity) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvlra1Tracks' -- -- * 'gcvvlra1Segments' -- -- * 'gcvvlra1Entity' googleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation :: GoogleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation googleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation = GoogleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation' { _gcvvlra1Tracks = Nothing , _gcvvlra1Segments = Nothing , _gcvvlra1Entity = Nothing } -- | All logo tracks where the recognized logo appears. Each track -- corresponds to one logo instance appearing in consecutive frames. gcvvlra1Tracks :: Lens' GoogleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation [GoogleCloudVideointelligenceV1p3beta1_Track] gcvvlra1Tracks = lens _gcvvlra1Tracks (\ s a -> s{_gcvvlra1Tracks = a}) . _Default . _Coerce -- | All video segments where the recognized logo appears. There might be -- multiple instances of the same logo class appearing in one VideoSegment. gcvvlra1Segments :: Lens' GoogleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation [GoogleCloudVideointelligenceV1p3beta1_VideoSegment] gcvvlra1Segments = lens _gcvvlra1Segments (\ s a -> s{_gcvvlra1Segments = a}) . _Default . _Coerce -- | Entity category information to specify the logo class that all the logo -- tracks within this LogoRecognitionAnnotation are recognized as. gcvvlra1Entity :: Lens' GoogleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation (Maybe GoogleCloudVideointelligenceV1p3beta1_Entity) gcvvlra1Entity = lens _gcvvlra1Entity (\ s a -> s{_gcvvlra1Entity = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1LogoRecognitionAnnotation" (\ o -> GoogleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation' <$> (o .:? "tracks" .!= mempty) <*> (o .:? "segments" .!= mempty) <*> (o .:? "entity")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation where toJSON GoogleCloudVideointelligenceV1p3beta1_LogoRecognitionAnnotation'{..} = object (catMaybes [("tracks" .=) <$> _gcvvlra1Tracks, ("segments" .=) <$> _gcvvlra1Segments, ("entity" .=) <$> _gcvvlra1Entity]) -- | Video frame level annotation results for explicit content. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_ExplicitContentFrame' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFrame = GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFrame' { _gcvvecf1TimeOffSet :: !(Maybe GDuration) , _gcvvecf1PornographyLikelihood :: !(Maybe GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFramePornographyLikelihood) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvecf1TimeOffSet' -- -- * 'gcvvecf1PornographyLikelihood' googleCloudVideointelligenceV1p2beta1_ExplicitContentFrame :: GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFrame googleCloudVideointelligenceV1p2beta1_ExplicitContentFrame = GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFrame' {_gcvvecf1TimeOffSet = Nothing, _gcvvecf1PornographyLikelihood = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this location. gcvvecf1TimeOffSet :: Lens' GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFrame (Maybe Scientific) gcvvecf1TimeOffSet = lens _gcvvecf1TimeOffSet (\ s a -> s{_gcvvecf1TimeOffSet = a}) . mapping _GDuration -- | Likelihood of the pornography content.. gcvvecf1PornographyLikelihood :: Lens' GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFrame (Maybe GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFramePornographyLikelihood) gcvvecf1PornographyLikelihood = lens _gcvvecf1PornographyLikelihood (\ s a -> s{_gcvvecf1PornographyLikelihood = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1ExplicitContentFrame" (\ o -> GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFrame' <$> (o .:? "timeOffset") <*> (o .:? "pornographyLikelihood")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFrame where toJSON GoogleCloudVideointelligenceV1p2beta1_ExplicitContentFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvecf1TimeOffSet, ("pornographyLikelihood" .=) <$> _gcvvecf1PornographyLikelihood]) -- | Detected entity from video analysis. -- -- /See:/ 'googleCloudVideointelligenceV1_Entity' smart constructor. data GoogleCloudVideointelligenceV1_Entity = GoogleCloudVideointelligenceV1_Entity' { _goooLanguageCode :: !(Maybe Text) , _goooEntityId :: !(Maybe Text) , _goooDescription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_Entity' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'goooLanguageCode' -- -- * 'goooEntityId' -- -- * 'goooDescription' googleCloudVideointelligenceV1_Entity :: GoogleCloudVideointelligenceV1_Entity googleCloudVideointelligenceV1_Entity = GoogleCloudVideointelligenceV1_Entity' { _goooLanguageCode = Nothing , _goooEntityId = Nothing , _goooDescription = Nothing } -- | Language code for \`description\` in BCP-47 format. goooLanguageCode :: Lens' GoogleCloudVideointelligenceV1_Entity (Maybe Text) goooLanguageCode = lens _goooLanguageCode (\ s a -> s{_goooLanguageCode = a}) -- | Opaque entity ID. Some IDs may be available in [Google Knowledge Graph -- Search API](https:\/\/developers.google.com\/knowledge-graph\/). goooEntityId :: Lens' GoogleCloudVideointelligenceV1_Entity (Maybe Text) goooEntityId = lens _goooEntityId (\ s a -> s{_goooEntityId = a}) -- | Textual description, e.g., \`Fixed-gear bicycle\`. goooDescription :: Lens' GoogleCloudVideointelligenceV1_Entity (Maybe Text) goooDescription = lens _goooDescription (\ s a -> s{_goooDescription = a}) instance FromJSON GoogleCloudVideointelligenceV1_Entity where parseJSON = withObject "GoogleCloudVideointelligenceV1Entity" (\ o -> GoogleCloudVideointelligenceV1_Entity' <$> (o .:? "languageCode") <*> (o .:? "entityId") <*> (o .:? "description")) instance ToJSON GoogleCloudVideointelligenceV1_Entity where toJSON GoogleCloudVideointelligenceV1_Entity'{..} = object (catMaybes [("languageCode" .=) <$> _goooLanguageCode, ("entityId" .=) <$> _goooEntityId, ("description" .=) <$> _goooDescription]) -- | Video frame level annotation results for label detection. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_LabelFrame' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_LabelFrame = GoogleCloudVideointelligenceV1p3beta1_LabelFrame' { _goo1TimeOffSet :: !(Maybe GDuration) , _goo1Confidence :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_LabelFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'goo1TimeOffSet' -- -- * 'goo1Confidence' googleCloudVideointelligenceV1p3beta1_LabelFrame :: GoogleCloudVideointelligenceV1p3beta1_LabelFrame googleCloudVideointelligenceV1p3beta1_LabelFrame = GoogleCloudVideointelligenceV1p3beta1_LabelFrame' {_goo1TimeOffSet = Nothing, _goo1Confidence = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this location. goo1TimeOffSet :: Lens' GoogleCloudVideointelligenceV1p3beta1_LabelFrame (Maybe Scientific) goo1TimeOffSet = lens _goo1TimeOffSet (\ s a -> s{_goo1TimeOffSet = a}) . mapping _GDuration -- | Confidence that the label is accurate. Range: [0, 1]. goo1Confidence :: Lens' GoogleCloudVideointelligenceV1p3beta1_LabelFrame (Maybe Double) goo1Confidence = lens _goo1Confidence (\ s a -> s{_goo1Confidence = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1p3beta1_LabelFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1LabelFrame" (\ o -> GoogleCloudVideointelligenceV1p3beta1_LabelFrame' <$> (o .:? "timeOffset") <*> (o .:? "confidence")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_LabelFrame where toJSON GoogleCloudVideointelligenceV1p3beta1_LabelFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _goo1TimeOffSet, ("confidence" .=) <$> _goo1Confidence]) -- | Annotation progress for a single video. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_VideoAnnotationProgress' smart constructor. data GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress = GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress' { _ggFeature :: !(Maybe GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgressFeature) , _ggStartTime :: !(Maybe DateTime') , _ggInputURI :: !(Maybe Text) , _ggProgressPercent :: !(Maybe (Textual Int32)) , _ggUpdateTime :: !(Maybe DateTime') , _ggSegment :: !(Maybe GoogleCloudVideointelligenceV1beta2_VideoSegment) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ggFeature' -- -- * 'ggStartTime' -- -- * 'ggInputURI' -- -- * 'ggProgressPercent' -- -- * 'ggUpdateTime' -- -- * 'ggSegment' googleCloudVideointelligenceV1beta2_VideoAnnotationProgress :: GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress googleCloudVideointelligenceV1beta2_VideoAnnotationProgress = GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress' { _ggFeature = Nothing , _ggStartTime = Nothing , _ggInputURI = Nothing , _ggProgressPercent = Nothing , _ggUpdateTime = Nothing , _ggSegment = Nothing } -- | Specifies which feature is being tracked if the request contains more -- than one feature. ggFeature :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress (Maybe GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgressFeature) ggFeature = lens _ggFeature (\ s a -> s{_ggFeature = a}) -- | Time when the request was received. ggStartTime :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress (Maybe UTCTime) ggStartTime = lens _ggStartTime (\ s a -> s{_ggStartTime = a}) . mapping _DateTime -- | Video file location in [Cloud -- Storage](https:\/\/cloud.google.com\/storage\/). ggInputURI :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress (Maybe Text) ggInputURI = lens _ggInputURI (\ s a -> s{_ggInputURI = a}) -- | Approximate percentage processed thus far. Guaranteed to be 100 when -- fully processed. ggProgressPercent :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress (Maybe Int32) ggProgressPercent = lens _ggProgressPercent (\ s a -> s{_ggProgressPercent = a}) . mapping _Coerce -- | Time of the most recent update. ggUpdateTime :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress (Maybe UTCTime) ggUpdateTime = lens _ggUpdateTime (\ s a -> s{_ggUpdateTime = a}) . mapping _DateTime -- | Specifies which segment is being tracked if the request contains more -- than one segment. ggSegment :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress (Maybe GoogleCloudVideointelligenceV1beta2_VideoSegment) ggSegment = lens _ggSegment (\ s a -> s{_ggSegment = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2VideoAnnotationProgress" (\ o -> GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress' <$> (o .:? "feature") <*> (o .:? "startTime") <*> (o .:? "inputUri") <*> (o .:? "progressPercent") <*> (o .:? "updateTime") <*> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress where toJSON GoogleCloudVideointelligenceV1beta2_VideoAnnotationProgress'{..} = object (catMaybes [("feature" .=) <$> _ggFeature, ("startTime" .=) <$> _ggStartTime, ("inputUri" .=) <$> _ggInputURI, ("progressPercent" .=) <$> _ggProgressPercent, ("updateTime" .=) <$> _ggUpdateTime, ("segment" .=) <$> _ggSegment]) -- | A speech recognition result corresponding to a portion of the audio. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_SpeechTranscription' smart constructor. data GoogleCloudVideointelligenceV1beta2_SpeechTranscription = GoogleCloudVideointelligenceV1beta2_SpeechTranscription' { _gcvvst1Alternatives :: !(Maybe [GoogleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative]) , _gcvvst1LanguageCode :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_SpeechTranscription' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvst1Alternatives' -- -- * 'gcvvst1LanguageCode' googleCloudVideointelligenceV1beta2_SpeechTranscription :: GoogleCloudVideointelligenceV1beta2_SpeechTranscription googleCloudVideointelligenceV1beta2_SpeechTranscription = GoogleCloudVideointelligenceV1beta2_SpeechTranscription' {_gcvvst1Alternatives = Nothing, _gcvvst1LanguageCode = Nothing} -- | May contain one or more recognition hypotheses (up to the maximum -- specified in \`max_alternatives\`). These alternatives are ordered in -- terms of accuracy, with the top (first) alternative being the most -- probable, as ranked by the recognizer. gcvvst1Alternatives :: Lens' GoogleCloudVideointelligenceV1beta2_SpeechTranscription [GoogleCloudVideointelligenceV1beta2_SpeechRecognitionAlternative] gcvvst1Alternatives = lens _gcvvst1Alternatives (\ s a -> s{_gcvvst1Alternatives = a}) . _Default . _Coerce -- | Output only. The -- [BCP-47](https:\/\/www.rfc-editor.org\/rfc\/bcp\/bcp47.txt) language tag -- of the language in this result. This language code was detected to have -- the most likelihood of being spoken in the audio. gcvvst1LanguageCode :: Lens' GoogleCloudVideointelligenceV1beta2_SpeechTranscription (Maybe Text) gcvvst1LanguageCode = lens _gcvvst1LanguageCode (\ s a -> s{_gcvvst1LanguageCode = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_SpeechTranscription where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2SpeechTranscription" (\ o -> GoogleCloudVideointelligenceV1beta2_SpeechTranscription' <$> (o .:? "alternatives" .!= mempty) <*> (o .:? "languageCode")) instance ToJSON GoogleCloudVideointelligenceV1beta2_SpeechTranscription where toJSON GoogleCloudVideointelligenceV1beta2_SpeechTranscription'{..} = object (catMaybes [("alternatives" .=) <$> _gcvvst1Alternatives, ("languageCode" .=) <$> _gcvvst1LanguageCode]) -- | Video annotation progress. Included in the \`metadata\` field of the -- \`Operation\` returned by the \`GetOperation\` call of the -- \`google::longrunning::Operations\` service. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_AnnotateVideoProgress' smart constructor. newtype GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoProgress = GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoProgress' { _gooAnnotationProgress :: Maybe [GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoProgress' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gooAnnotationProgress' googleCloudVideointelligenceV1p3beta1_AnnotateVideoProgress :: GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoProgress googleCloudVideointelligenceV1p3beta1_AnnotateVideoProgress = GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoProgress' {_gooAnnotationProgress = Nothing} -- | Progress metadata for all videos specified in \`AnnotateVideoRequest\`. gooAnnotationProgress :: Lens' GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoProgress [GoogleCloudVideointelligenceV1p3beta1_VideoAnnotationProgress] gooAnnotationProgress = lens _gooAnnotationProgress (\ s a -> s{_gooAnnotationProgress = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoProgress where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1AnnotateVideoProgress" (\ o -> GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoProgress' <$> (o .:? "annotationProgress" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoProgress where toJSON GoogleCloudVideointelligenceV1p3beta1_AnnotateVideoProgress'{..} = object (catMaybes [("annotationProgress" .=) <$> _gooAnnotationProgress]) -- | Deprecated. No effect. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_FaceAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_FaceAnnotation = GoogleCloudVideointelligenceV1p3beta1_FaceAnnotation' { _ggThumbnail :: !(Maybe Bytes) , _ggFrames :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_FaceFrame]) , _ggSegments :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_FaceSegment]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_FaceAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ggThumbnail' -- -- * 'ggFrames' -- -- * 'ggSegments' googleCloudVideointelligenceV1p3beta1_FaceAnnotation :: GoogleCloudVideointelligenceV1p3beta1_FaceAnnotation googleCloudVideointelligenceV1p3beta1_FaceAnnotation = GoogleCloudVideointelligenceV1p3beta1_FaceAnnotation' {_ggThumbnail = Nothing, _ggFrames = Nothing, _ggSegments = Nothing} -- | Thumbnail of a representative face view (in JPEG format). ggThumbnail :: Lens' GoogleCloudVideointelligenceV1p3beta1_FaceAnnotation (Maybe ByteString) ggThumbnail = lens _ggThumbnail (\ s a -> s{_ggThumbnail = a}) . mapping _Bytes -- | All video frames where a face was detected. ggFrames :: Lens' GoogleCloudVideointelligenceV1p3beta1_FaceAnnotation [GoogleCloudVideointelligenceV1p3beta1_FaceFrame] ggFrames = lens _ggFrames (\ s a -> s{_ggFrames = a}) . _Default . _Coerce -- | All video segments where a face was detected. ggSegments :: Lens' GoogleCloudVideointelligenceV1p3beta1_FaceAnnotation [GoogleCloudVideointelligenceV1p3beta1_FaceSegment] ggSegments = lens _ggSegments (\ s a -> s{_ggSegments = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p3beta1_FaceAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1FaceAnnotation" (\ o -> GoogleCloudVideointelligenceV1p3beta1_FaceAnnotation' <$> (o .:? "thumbnail") <*> (o .:? "frames" .!= mempty) <*> (o .:? "segments" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_FaceAnnotation where toJSON GoogleCloudVideointelligenceV1p3beta1_FaceAnnotation'{..} = object (catMaybes [("thumbnail" .=) <$> _ggThumbnail, ("frames" .=) <$> _ggFrames, ("segments" .=) <$> _ggSegments]) -- | Annotation results for a single video. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_VideoAnnotationResults' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults = GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults' { _goooShotAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_VideoSegment]) , _goooShotLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation]) , _goooFaceDetectionAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation]) , _goooFaceAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_FaceAnnotation]) , _goooInputURI :: !(Maybe Text) , _goooError :: !(Maybe GoogleRpc_Status) , _goooShotPresenceLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation]) , _goooPersonDetectionAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_PersonDetectionAnnotation]) , _goooObjectAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation]) , _goooFrameLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation]) , _goooSpeechTranscriptions :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_SpeechTranscription]) , _goooSegmentPresenceLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation]) , _goooLogoRecognitionAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation]) , _goooSegment :: !(Maybe GoogleCloudVideointelligenceV1p1beta1_VideoSegment) , _goooTextAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_TextAnnotation]) , _goooSegmentLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation]) , _goooExplicitAnnotation :: !(Maybe GoogleCloudVideointelligenceV1p1beta1_ExplicitContentAnnotation) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'goooShotAnnotations' -- -- * 'goooShotLabelAnnotations' -- -- * 'goooFaceDetectionAnnotations' -- -- * 'goooFaceAnnotations' -- -- * 'goooInputURI' -- -- * 'goooError' -- -- * 'goooShotPresenceLabelAnnotations' -- -- * 'goooPersonDetectionAnnotations' -- -- * 'goooObjectAnnotations' -- -- * 'goooFrameLabelAnnotations' -- -- * 'goooSpeechTranscriptions' -- -- * 'goooSegmentPresenceLabelAnnotations' -- -- * 'goooLogoRecognitionAnnotations' -- -- * 'goooSegment' -- -- * 'goooTextAnnotations' -- -- * 'goooSegmentLabelAnnotations' -- -- * 'goooExplicitAnnotation' googleCloudVideointelligenceV1p1beta1_VideoAnnotationResults :: GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults googleCloudVideointelligenceV1p1beta1_VideoAnnotationResults = GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults' { _goooShotAnnotations = Nothing , _goooShotLabelAnnotations = Nothing , _goooFaceDetectionAnnotations = Nothing , _goooFaceAnnotations = Nothing , _goooInputURI = Nothing , _goooError = Nothing , _goooShotPresenceLabelAnnotations = Nothing , _goooPersonDetectionAnnotations = Nothing , _goooObjectAnnotations = Nothing , _goooFrameLabelAnnotations = Nothing , _goooSpeechTranscriptions = Nothing , _goooSegmentPresenceLabelAnnotations = Nothing , _goooLogoRecognitionAnnotations = Nothing , _goooSegment = Nothing , _goooTextAnnotations = Nothing , _goooSegmentLabelAnnotations = Nothing , _goooExplicitAnnotation = Nothing } -- | Shot annotations. Each shot is represented as a video segment. goooShotAnnotations :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p1beta1_VideoSegment] goooShotAnnotations = lens _goooShotAnnotations (\ s a -> s{_goooShotAnnotations = a}) . _Default . _Coerce -- | Topical label annotations on shot level. There is exactly one element -- for each unique label. goooShotLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation] goooShotLabelAnnotations = lens _goooShotLabelAnnotations (\ s a -> s{_goooShotLabelAnnotations = a}) . _Default . _Coerce -- | Face detection annotations. goooFaceDetectionAnnotations :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p1beta1_FaceDetectionAnnotation] goooFaceDetectionAnnotations = lens _goooFaceDetectionAnnotations (\ s a -> s{_goooFaceDetectionAnnotations = a}) . _Default . _Coerce -- | Deprecated. Please use \`face_detection_annotations\` instead. goooFaceAnnotations :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p1beta1_FaceAnnotation] goooFaceAnnotations = lens _goooFaceAnnotations (\ s a -> s{_goooFaceAnnotations = a}) . _Default . _Coerce -- | Video file location in [Cloud -- Storage](https:\/\/cloud.google.com\/storage\/). goooInputURI :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults (Maybe Text) goooInputURI = lens _goooInputURI (\ s a -> s{_goooInputURI = a}) -- | If set, indicates an error. Note that for a single -- \`AnnotateVideoRequest\` some videos may succeed and some may fail. goooError :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults (Maybe GoogleRpc_Status) goooError = lens _goooError (\ s a -> s{_goooError = a}) -- | Presence label annotations on shot level. There is exactly one element -- for each unique label. Compared to the existing topical -- \`shot_label_annotations\`, this field presents more fine-grained, -- shot-level labels detected in video content and is made available only -- when the client sets \`LabelDetectionConfig.model\` to -- \"builtin\/latest\" in the request. goooShotPresenceLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation] goooShotPresenceLabelAnnotations = lens _goooShotPresenceLabelAnnotations (\ s a -> s{_goooShotPresenceLabelAnnotations = a}) . _Default . _Coerce -- | Person detection annotations. goooPersonDetectionAnnotations :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p1beta1_PersonDetectionAnnotation] goooPersonDetectionAnnotations = lens _goooPersonDetectionAnnotations (\ s a -> s{_goooPersonDetectionAnnotations = a}) . _Default . _Coerce -- | Annotations for list of objects detected and tracked in video. goooObjectAnnotations :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation] goooObjectAnnotations = lens _goooObjectAnnotations (\ s a -> s{_goooObjectAnnotations = a}) . _Default . _Coerce -- | Label annotations on frame level. There is exactly one element for each -- unique label. goooFrameLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation] goooFrameLabelAnnotations = lens _goooFrameLabelAnnotations (\ s a -> s{_goooFrameLabelAnnotations = a}) . _Default . _Coerce -- | Speech transcription. goooSpeechTranscriptions :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p1beta1_SpeechTranscription] goooSpeechTranscriptions = lens _goooSpeechTranscriptions (\ s a -> s{_goooSpeechTranscriptions = a}) . _Default . _Coerce -- | Presence label annotations on video level or user-specified segment -- level. There is exactly one element for each unique label. Compared to -- the existing topical \`segment_label_annotations\`, this field presents -- more fine-grained, segment-level labels detected in video content and is -- made available only when the client sets \`LabelDetectionConfig.model\` -- to \"builtin\/latest\" in the request. goooSegmentPresenceLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation] goooSegmentPresenceLabelAnnotations = lens _goooSegmentPresenceLabelAnnotations (\ s a -> s{_goooSegmentPresenceLabelAnnotations = a}) . _Default . _Coerce -- | Annotations for list of logos detected, tracked and recognized in video. goooLogoRecognitionAnnotations :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p1beta1_LogoRecognitionAnnotation] goooLogoRecognitionAnnotations = lens _goooLogoRecognitionAnnotations (\ s a -> s{_goooLogoRecognitionAnnotations = a}) . _Default . _Coerce -- | Video segment on which the annotation is run. goooSegment :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults (Maybe GoogleCloudVideointelligenceV1p1beta1_VideoSegment) goooSegment = lens _goooSegment (\ s a -> s{_goooSegment = a}) -- | OCR text detection and tracking. Annotations for list of detected text -- snippets. Each will have list of frame information associated with it. goooTextAnnotations :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p1beta1_TextAnnotation] goooTextAnnotations = lens _goooTextAnnotations (\ s a -> s{_goooTextAnnotations = a}) . _Default . _Coerce -- | Topical label annotations on video level or user-specified segment -- level. There is exactly one element for each unique label. goooSegmentLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults [GoogleCloudVideointelligenceV1p1beta1_LabelAnnotation] goooSegmentLabelAnnotations = lens _goooSegmentLabelAnnotations (\ s a -> s{_goooSegmentLabelAnnotations = a}) . _Default . _Coerce -- | Explicit content annotation. goooExplicitAnnotation :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults (Maybe GoogleCloudVideointelligenceV1p1beta1_ExplicitContentAnnotation) goooExplicitAnnotation = lens _goooExplicitAnnotation (\ s a -> s{_goooExplicitAnnotation = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1VideoAnnotationResults" (\ o -> GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults' <$> (o .:? "shotAnnotations" .!= mempty) <*> (o .:? "shotLabelAnnotations" .!= mempty) <*> (o .:? "faceDetectionAnnotations" .!= mempty) <*> (o .:? "faceAnnotations" .!= mempty) <*> (o .:? "inputUri") <*> (o .:? "error") <*> (o .:? "shotPresenceLabelAnnotations" .!= mempty) <*> (o .:? "personDetectionAnnotations" .!= mempty) <*> (o .:? "objectAnnotations" .!= mempty) <*> (o .:? "frameLabelAnnotations" .!= mempty) <*> (o .:? "speechTranscriptions" .!= mempty) <*> (o .:? "segmentPresenceLabelAnnotations" .!= mempty) <*> (o .:? "logoRecognitionAnnotations" .!= mempty) <*> (o .:? "segment") <*> (o .:? "textAnnotations" .!= mempty) <*> (o .:? "segmentLabelAnnotations" .!= mempty) <*> (o .:? "explicitAnnotation")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults where toJSON GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults'{..} = object (catMaybes [("shotAnnotations" .=) <$> _goooShotAnnotations, ("shotLabelAnnotations" .=) <$> _goooShotLabelAnnotations, ("faceDetectionAnnotations" .=) <$> _goooFaceDetectionAnnotations, ("faceAnnotations" .=) <$> _goooFaceAnnotations, ("inputUri" .=) <$> _goooInputURI, ("error" .=) <$> _goooError, ("shotPresenceLabelAnnotations" .=) <$> _goooShotPresenceLabelAnnotations, ("personDetectionAnnotations" .=) <$> _goooPersonDetectionAnnotations, ("objectAnnotations" .=) <$> _goooObjectAnnotations, ("frameLabelAnnotations" .=) <$> _goooFrameLabelAnnotations, ("speechTranscriptions" .=) <$> _goooSpeechTranscriptions, ("segmentPresenceLabelAnnotations" .=) <$> _goooSegmentPresenceLabelAnnotations, ("logoRecognitionAnnotations" .=) <$> _goooLogoRecognitionAnnotations, ("segment" .=) <$> _goooSegment, ("textAnnotations" .=) <$> _goooTextAnnotations, ("segmentLabelAnnotations" .=) <$> _goooSegmentLabelAnnotations, ("explicitAnnotation" .=) <$> _goooExplicitAnnotation]) -- | Video context and\/or feature-specific parameters. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_VideoContext' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_VideoContext = GoogleCloudVideointelligenceV1p3beta1_VideoContext' { _gcvvvcFaceDetectionConfig :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_FaceDetectionConfig) , _gcvvvcSpeechTranscriptionConfig :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig) , _gcvvvcExplicitContentDetectionConfig :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_ExplicitContentDetectionConfig) , _gcvvvcObjectTrackingConfig :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingConfig) , _gcvvvcLabelDetectionConfig :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfig) , _gcvvvcSegments :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_VideoSegment]) , _gcvvvcTextDetectionConfig :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_TextDetectionConfig) , _gcvvvcPersonDetectionConfig :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_PersonDetectionConfig) , _gcvvvcShotChangeDetectionConfig :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_ShotChangeDetectionConfig) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_VideoContext' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvvcFaceDetectionConfig' -- -- * 'gcvvvcSpeechTranscriptionConfig' -- -- * 'gcvvvcExplicitContentDetectionConfig' -- -- * 'gcvvvcObjectTrackingConfig' -- -- * 'gcvvvcLabelDetectionConfig' -- -- * 'gcvvvcSegments' -- -- * 'gcvvvcTextDetectionConfig' -- -- * 'gcvvvcPersonDetectionConfig' -- -- * 'gcvvvcShotChangeDetectionConfig' googleCloudVideointelligenceV1p3beta1_VideoContext :: GoogleCloudVideointelligenceV1p3beta1_VideoContext googleCloudVideointelligenceV1p3beta1_VideoContext = GoogleCloudVideointelligenceV1p3beta1_VideoContext' { _gcvvvcFaceDetectionConfig = Nothing , _gcvvvcSpeechTranscriptionConfig = Nothing , _gcvvvcExplicitContentDetectionConfig = Nothing , _gcvvvcObjectTrackingConfig = Nothing , _gcvvvcLabelDetectionConfig = Nothing , _gcvvvcSegments = Nothing , _gcvvvcTextDetectionConfig = Nothing , _gcvvvcPersonDetectionConfig = Nothing , _gcvvvcShotChangeDetectionConfig = Nothing } -- | Config for FACE_DETECTION. gcvvvcFaceDetectionConfig :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoContext (Maybe GoogleCloudVideointelligenceV1p3beta1_FaceDetectionConfig) gcvvvcFaceDetectionConfig = lens _gcvvvcFaceDetectionConfig (\ s a -> s{_gcvvvcFaceDetectionConfig = a}) -- | Config for SPEECH_TRANSCRIPTION. gcvvvcSpeechTranscriptionConfig :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoContext (Maybe GoogleCloudVideointelligenceV1p3beta1_SpeechTranscriptionConfig) gcvvvcSpeechTranscriptionConfig = lens _gcvvvcSpeechTranscriptionConfig (\ s a -> s{_gcvvvcSpeechTranscriptionConfig = a}) -- | Config for EXPLICIT_CONTENT_DETECTION. gcvvvcExplicitContentDetectionConfig :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoContext (Maybe GoogleCloudVideointelligenceV1p3beta1_ExplicitContentDetectionConfig) gcvvvcExplicitContentDetectionConfig = lens _gcvvvcExplicitContentDetectionConfig (\ s a -> s{_gcvvvcExplicitContentDetectionConfig = a}) -- | Config for OBJECT_TRACKING. gcvvvcObjectTrackingConfig :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoContext (Maybe GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingConfig) gcvvvcObjectTrackingConfig = lens _gcvvvcObjectTrackingConfig (\ s a -> s{_gcvvvcObjectTrackingConfig = a}) -- | Config for LABEL_DETECTION. gcvvvcLabelDetectionConfig :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoContext (Maybe GoogleCloudVideointelligenceV1p3beta1_LabelDetectionConfig) gcvvvcLabelDetectionConfig = lens _gcvvvcLabelDetectionConfig (\ s a -> s{_gcvvvcLabelDetectionConfig = a}) -- | Video segments to annotate. The segments may overlap and are not -- required to be contiguous or span the whole video. If unspecified, each -- video is treated as a single segment. gcvvvcSegments :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoContext [GoogleCloudVideointelligenceV1p3beta1_VideoSegment] gcvvvcSegments = lens _gcvvvcSegments (\ s a -> s{_gcvvvcSegments = a}) . _Default . _Coerce -- | Config for TEXT_DETECTION. gcvvvcTextDetectionConfig :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoContext (Maybe GoogleCloudVideointelligenceV1p3beta1_TextDetectionConfig) gcvvvcTextDetectionConfig = lens _gcvvvcTextDetectionConfig (\ s a -> s{_gcvvvcTextDetectionConfig = a}) -- | Config for PERSON_DETECTION. gcvvvcPersonDetectionConfig :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoContext (Maybe GoogleCloudVideointelligenceV1p3beta1_PersonDetectionConfig) gcvvvcPersonDetectionConfig = lens _gcvvvcPersonDetectionConfig (\ s a -> s{_gcvvvcPersonDetectionConfig = a}) -- | Config for SHOT_CHANGE_DETECTION. gcvvvcShotChangeDetectionConfig :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoContext (Maybe GoogleCloudVideointelligenceV1p3beta1_ShotChangeDetectionConfig) gcvvvcShotChangeDetectionConfig = lens _gcvvvcShotChangeDetectionConfig (\ s a -> s{_gcvvvcShotChangeDetectionConfig = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_VideoContext where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1VideoContext" (\ o -> GoogleCloudVideointelligenceV1p3beta1_VideoContext' <$> (o .:? "faceDetectionConfig") <*> (o .:? "speechTranscriptionConfig") <*> (o .:? "explicitContentDetectionConfig") <*> (o .:? "objectTrackingConfig") <*> (o .:? "labelDetectionConfig") <*> (o .:? "segments" .!= mempty) <*> (o .:? "textDetectionConfig") <*> (o .:? "personDetectionConfig") <*> (o .:? "shotChangeDetectionConfig")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_VideoContext where toJSON GoogleCloudVideointelligenceV1p3beta1_VideoContext'{..} = object (catMaybes [("faceDetectionConfig" .=) <$> _gcvvvcFaceDetectionConfig, ("speechTranscriptionConfig" .=) <$> _gcvvvcSpeechTranscriptionConfig, ("explicitContentDetectionConfig" .=) <$> _gcvvvcExplicitContentDetectionConfig, ("objectTrackingConfig" .=) <$> _gcvvvcObjectTrackingConfig, ("labelDetectionConfig" .=) <$> _gcvvvcLabelDetectionConfig, ("segments" .=) <$> _gcvvvcSegments, ("textDetectionConfig" .=) <$> _gcvvvcTextDetectionConfig, ("personDetectionConfig" .=) <$> _gcvvvcPersonDetectionConfig, ("shotChangeDetectionConfig" .=) <$> _gcvvvcShotChangeDetectionConfig]) -- | Video segment level annotation results for text detection. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_TextSegment' smart constructor. data GoogleCloudVideointelligenceV1beta2_TextSegment = GoogleCloudVideointelligenceV1beta2_TextSegment' { _gcvvts1Frames :: !(Maybe [GoogleCloudVideointelligenceV1beta2_TextFrame]) , _gcvvts1Confidence :: !(Maybe (Textual Double)) , _gcvvts1Segment :: !(Maybe GoogleCloudVideointelligenceV1beta2_VideoSegment) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_TextSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvts1Frames' -- -- * 'gcvvts1Confidence' -- -- * 'gcvvts1Segment' googleCloudVideointelligenceV1beta2_TextSegment :: GoogleCloudVideointelligenceV1beta2_TextSegment googleCloudVideointelligenceV1beta2_TextSegment = GoogleCloudVideointelligenceV1beta2_TextSegment' { _gcvvts1Frames = Nothing , _gcvvts1Confidence = Nothing , _gcvvts1Segment = Nothing } -- | Information related to the frames where OCR detected text appears. gcvvts1Frames :: Lens' GoogleCloudVideointelligenceV1beta2_TextSegment [GoogleCloudVideointelligenceV1beta2_TextFrame] gcvvts1Frames = lens _gcvvts1Frames (\ s a -> s{_gcvvts1Frames = a}) . _Default . _Coerce -- | Confidence for the track of detected text. It is calculated as the -- highest over all frames where OCR detected text appears. gcvvts1Confidence :: Lens' GoogleCloudVideointelligenceV1beta2_TextSegment (Maybe Double) gcvvts1Confidence = lens _gcvvts1Confidence (\ s a -> s{_gcvvts1Confidence = a}) . mapping _Coerce -- | Video segment where a text snippet was detected. gcvvts1Segment :: Lens' GoogleCloudVideointelligenceV1beta2_TextSegment (Maybe GoogleCloudVideointelligenceV1beta2_VideoSegment) gcvvts1Segment = lens _gcvvts1Segment (\ s a -> s{_gcvvts1Segment = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_TextSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2TextSegment" (\ o -> GoogleCloudVideointelligenceV1beta2_TextSegment' <$> (o .:? "frames" .!= mempty) <*> (o .:? "confidence") <*> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1beta2_TextSegment where toJSON GoogleCloudVideointelligenceV1beta2_TextSegment'{..} = object (catMaybes [("frames" .=) <$> _gcvvts1Frames, ("confidence" .=) <$> _gcvvts1Confidence, ("segment" .=) <$> _gcvvts1Segment]) -- | Normalized bounding box. The normalized vertex coordinates are relative -- to the original image. Range: [0, 1]. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_NormalizedBoundingBox' smart constructor. data GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox = GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox' { _gooBottom :: !(Maybe (Textual Double)) , _gooLeft :: !(Maybe (Textual Double)) , _gooRight :: !(Maybe (Textual Double)) , _gooTop :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gooBottom' -- -- * 'gooLeft' -- -- * 'gooRight' -- -- * 'gooTop' googleCloudVideointelligenceV1beta2_NormalizedBoundingBox :: GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox googleCloudVideointelligenceV1beta2_NormalizedBoundingBox = GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox' { _gooBottom = Nothing , _gooLeft = Nothing , _gooRight = Nothing , _gooTop = Nothing } -- | Bottom Y coordinate. gooBottom :: Lens' GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox (Maybe Double) gooBottom = lens _gooBottom (\ s a -> s{_gooBottom = a}) . mapping _Coerce -- | Left X coordinate. gooLeft :: Lens' GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox (Maybe Double) gooLeft = lens _gooLeft (\ s a -> s{_gooLeft = a}) . mapping _Coerce -- | Right X coordinate. gooRight :: Lens' GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox (Maybe Double) gooRight = lens _gooRight (\ s a -> s{_gooRight = a}) . mapping _Coerce -- | Top Y coordinate. gooTop :: Lens' GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox (Maybe Double) gooTop = lens _gooTop (\ s a -> s{_gooTop = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2NormalizedBoundingBox" (\ o -> GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox' <$> (o .:? "bottom") <*> (o .:? "left") <*> (o .:? "right") <*> (o .:? "top")) instance ToJSON GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox where toJSON GoogleCloudVideointelligenceV1beta2_NormalizedBoundingBox'{..} = object (catMaybes [("bottom" .=) <$> _gooBottom, ("left" .=) <$> _gooLeft, ("right" .=) <$> _gooRight, ("top" .=) <$> _gooTop]) -- | A generic detected landmark represented by name in string format and a -- 2D location. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_DetectedLandmark' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_DetectedLandmark = GoogleCloudVideointelligenceV1p1beta1_DetectedLandmark' { _gcvvdl2Confidence :: !(Maybe (Textual Double)) , _gcvvdl2Point :: !(Maybe GoogleCloudVideointelligenceV1p1beta1_NormalizedVertex) , _gcvvdl2Name :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_DetectedLandmark' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvdl2Confidence' -- -- * 'gcvvdl2Point' -- -- * 'gcvvdl2Name' googleCloudVideointelligenceV1p1beta1_DetectedLandmark :: GoogleCloudVideointelligenceV1p1beta1_DetectedLandmark googleCloudVideointelligenceV1p1beta1_DetectedLandmark = GoogleCloudVideointelligenceV1p1beta1_DetectedLandmark' { _gcvvdl2Confidence = Nothing , _gcvvdl2Point = Nothing , _gcvvdl2Name = Nothing } -- | The confidence score of the detected landmark. Range [0, 1]. gcvvdl2Confidence :: Lens' GoogleCloudVideointelligenceV1p1beta1_DetectedLandmark (Maybe Double) gcvvdl2Confidence = lens _gcvvdl2Confidence (\ s a -> s{_gcvvdl2Confidence = a}) . mapping _Coerce -- | The 2D point of the detected landmark using the normalized image -- coordindate system. The normalized coordinates have the range from 0 to -- 1. gcvvdl2Point :: Lens' GoogleCloudVideointelligenceV1p1beta1_DetectedLandmark (Maybe GoogleCloudVideointelligenceV1p1beta1_NormalizedVertex) gcvvdl2Point = lens _gcvvdl2Point (\ s a -> s{_gcvvdl2Point = a}) -- | The name of this landmark, for example, left_hand, right_shoulder. gcvvdl2Name :: Lens' GoogleCloudVideointelligenceV1p1beta1_DetectedLandmark (Maybe Text) gcvvdl2Name = lens _gcvvdl2Name (\ s a -> s{_gcvvdl2Name = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_DetectedLandmark where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1DetectedLandmark" (\ o -> GoogleCloudVideointelligenceV1p1beta1_DetectedLandmark' <$> (o .:? "confidence") <*> (o .:? "point") <*> (o .:? "name")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_DetectedLandmark where toJSON GoogleCloudVideointelligenceV1p1beta1_DetectedLandmark'{..} = object (catMaybes [("confidence" .=) <$> _gcvvdl2Confidence, ("point" .=) <$> _gcvvdl2Point, ("name" .=) <$> _gcvvdl2Name]) -- | Video annotation progress. Included in the \`metadata\` field of the -- \`Operation\` returned by the \`GetOperation\` call of the -- \`google::longrunning::Operations\` service. -- -- /See:/ 'googleCloudVideointelligenceV1_AnnotateVideoProgress' smart constructor. newtype GoogleCloudVideointelligenceV1_AnnotateVideoProgress = GoogleCloudVideointelligenceV1_AnnotateVideoProgress' { _gcvvavpcAnnotationProgress :: Maybe [GoogleCloudVideointelligenceV1_VideoAnnotationProgress] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_AnnotateVideoProgress' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvavpcAnnotationProgress' googleCloudVideointelligenceV1_AnnotateVideoProgress :: GoogleCloudVideointelligenceV1_AnnotateVideoProgress googleCloudVideointelligenceV1_AnnotateVideoProgress = GoogleCloudVideointelligenceV1_AnnotateVideoProgress' {_gcvvavpcAnnotationProgress = Nothing} -- | Progress metadata for all videos specified in \`AnnotateVideoRequest\`. gcvvavpcAnnotationProgress :: Lens' GoogleCloudVideointelligenceV1_AnnotateVideoProgress [GoogleCloudVideointelligenceV1_VideoAnnotationProgress] gcvvavpcAnnotationProgress = lens _gcvvavpcAnnotationProgress (\ s a -> s{_gcvvavpcAnnotationProgress = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1_AnnotateVideoProgress where parseJSON = withObject "GoogleCloudVideointelligenceV1AnnotateVideoProgress" (\ o -> GoogleCloudVideointelligenceV1_AnnotateVideoProgress' <$> (o .:? "annotationProgress" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1_AnnotateVideoProgress where toJSON GoogleCloudVideointelligenceV1_AnnotateVideoProgress'{..} = object (catMaybes [("annotationProgress" .=) <$> _gcvvavpcAnnotationProgress]) -- | Deprecated. No effect. -- -- /See:/ 'googleCloudVideointelligenceV1_FaceAnnotation' smart constructor. data GoogleCloudVideointelligenceV1_FaceAnnotation = GoogleCloudVideointelligenceV1_FaceAnnotation' { _gcvvfa1Thumbnail :: !(Maybe Bytes) , _gcvvfa1Frames :: !(Maybe [GoogleCloudVideointelligenceV1_FaceFrame]) , _gcvvfa1Segments :: !(Maybe [GoogleCloudVideointelligenceV1_FaceSegment]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_FaceAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvfa1Thumbnail' -- -- * 'gcvvfa1Frames' -- -- * 'gcvvfa1Segments' googleCloudVideointelligenceV1_FaceAnnotation :: GoogleCloudVideointelligenceV1_FaceAnnotation googleCloudVideointelligenceV1_FaceAnnotation = GoogleCloudVideointelligenceV1_FaceAnnotation' { _gcvvfa1Thumbnail = Nothing , _gcvvfa1Frames = Nothing , _gcvvfa1Segments = Nothing } -- | Thumbnail of a representative face view (in JPEG format). gcvvfa1Thumbnail :: Lens' GoogleCloudVideointelligenceV1_FaceAnnotation (Maybe ByteString) gcvvfa1Thumbnail = lens _gcvvfa1Thumbnail (\ s a -> s{_gcvvfa1Thumbnail = a}) . mapping _Bytes -- | All video frames where a face was detected. gcvvfa1Frames :: Lens' GoogleCloudVideointelligenceV1_FaceAnnotation [GoogleCloudVideointelligenceV1_FaceFrame] gcvvfa1Frames = lens _gcvvfa1Frames (\ s a -> s{_gcvvfa1Frames = a}) . _Default . _Coerce -- | All video segments where a face was detected. gcvvfa1Segments :: Lens' GoogleCloudVideointelligenceV1_FaceAnnotation [GoogleCloudVideointelligenceV1_FaceSegment] gcvvfa1Segments = lens _gcvvfa1Segments (\ s a -> s{_gcvvfa1Segments = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1_FaceAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1FaceAnnotation" (\ o -> GoogleCloudVideointelligenceV1_FaceAnnotation' <$> (o .:? "thumbnail") <*> (o .:? "frames" .!= mempty) <*> (o .:? "segments" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1_FaceAnnotation where toJSON GoogleCloudVideointelligenceV1_FaceAnnotation'{..} = object (catMaybes [("thumbnail" .=) <$> _gcvvfa1Thumbnail, ("frames" .=) <$> _gcvvfa1Frames, ("segments" .=) <$> _gcvvfa1Segments]) -- | A track of an object instance. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_Track' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_Track = GoogleCloudVideointelligenceV1p2beta1_Track' { _gcvvt1Confidence :: !(Maybe (Textual Double)) , _gcvvt1Attributes :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_DetectedAttribute]) , _gcvvt1Segment :: !(Maybe GoogleCloudVideointelligenceV1p2beta1_VideoSegment) , _gcvvt1TimestampedObjects :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_TimestampedObject]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_Track' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvt1Confidence' -- -- * 'gcvvt1Attributes' -- -- * 'gcvvt1Segment' -- -- * 'gcvvt1TimestampedObjects' googleCloudVideointelligenceV1p2beta1_Track :: GoogleCloudVideointelligenceV1p2beta1_Track googleCloudVideointelligenceV1p2beta1_Track = GoogleCloudVideointelligenceV1p2beta1_Track' { _gcvvt1Confidence = Nothing , _gcvvt1Attributes = Nothing , _gcvvt1Segment = Nothing , _gcvvt1TimestampedObjects = Nothing } -- | Optional. The confidence score of the tracked object. gcvvt1Confidence :: Lens' GoogleCloudVideointelligenceV1p2beta1_Track (Maybe Double) gcvvt1Confidence = lens _gcvvt1Confidence (\ s a -> s{_gcvvt1Confidence = a}) . mapping _Coerce -- | Optional. Attributes in the track level. gcvvt1Attributes :: Lens' GoogleCloudVideointelligenceV1p2beta1_Track [GoogleCloudVideointelligenceV1p2beta1_DetectedAttribute] gcvvt1Attributes = lens _gcvvt1Attributes (\ s a -> s{_gcvvt1Attributes = a}) . _Default . _Coerce -- | Video segment of a track. gcvvt1Segment :: Lens' GoogleCloudVideointelligenceV1p2beta1_Track (Maybe GoogleCloudVideointelligenceV1p2beta1_VideoSegment) gcvvt1Segment = lens _gcvvt1Segment (\ s a -> s{_gcvvt1Segment = a}) -- | The object with timestamp and attributes per frame in the track. gcvvt1TimestampedObjects :: Lens' GoogleCloudVideointelligenceV1p2beta1_Track [GoogleCloudVideointelligenceV1p2beta1_TimestampedObject] gcvvt1TimestampedObjects = lens _gcvvt1TimestampedObjects (\ s a -> s{_gcvvt1TimestampedObjects = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p2beta1_Track where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1Track" (\ o -> GoogleCloudVideointelligenceV1p2beta1_Track' <$> (o .:? "confidence") <*> (o .:? "attributes" .!= mempty) <*> (o .:? "segment") <*> (o .:? "timestampedObjects" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_Track where toJSON GoogleCloudVideointelligenceV1p2beta1_Track'{..} = object (catMaybes [("confidence" .=) <$> _gcvvt1Confidence, ("attributes" .=) <$> _gcvvt1Attributes, ("segment" .=) <$> _gcvvt1Segment, ("timestampedObjects" .=) <$> _gcvvt1TimestampedObjects]) -- | The normal response of the operation in case of success. If the original -- method returns no data on success, such as \`Delete\`, the response is -- \`google.protobuf.Empty\`. If the original method is standard -- \`Get\`\/\`Create\`\/\`Update\`, the response should be the resource. -- For other methods, the response should have the type \`XxxResponse\`, -- where \`Xxx\` is the original method name. For example, if the original -- method name is \`TakeSnapshot()\`, the inferred response type is -- \`TakeSnapshotResponse\`. -- -- /See:/ 'googleLongrunning_OperationResponse' smart constructor. newtype GoogleLongrunning_OperationResponse = GoogleLongrunning_OperationResponse' { _glorAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleLongrunning_OperationResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'glorAddtional' googleLongrunning_OperationResponse :: HashMap Text JSONValue -- ^ 'glorAddtional' -> GoogleLongrunning_OperationResponse googleLongrunning_OperationResponse pGlorAddtional_ = GoogleLongrunning_OperationResponse' {_glorAddtional = _Coerce # pGlorAddtional_} -- | Properties of the object. Contains field \'type with type URL. glorAddtional :: Lens' GoogleLongrunning_OperationResponse (HashMap Text JSONValue) glorAddtional = lens _glorAddtional (\ s a -> s{_glorAddtional = a}) . _Coerce instance FromJSON GoogleLongrunning_OperationResponse where parseJSON = withObject "GoogleLongrunningOperationResponse" (\ o -> GoogleLongrunning_OperationResponse' <$> (parseJSONObject o)) instance ToJSON GoogleLongrunning_OperationResponse where toJSON = toJSON . _glorAddtional -- | Normalized bounding polygon for text (that might not be aligned with -- axis). Contains list of the corner points in clockwise order starting -- from top-left corner. For example, for a rectangular bounding box: When -- the text is horizontal it might look like: 0----1 | | 3----2 When it\'s -- clockwise rotated 180 degrees around the top-left corner it becomes: -- 2----3 | | 1----0 and the vertex order will still be (0, 1, 2, 3). Note -- that values can be less than 0, or greater than 1 due to trignometric -- calculations for location of the box. -- -- /See:/ 'googleCloudVideointelligenceV1_NormalizedBoundingPoly' smart constructor. newtype GoogleCloudVideointelligenceV1_NormalizedBoundingPoly = GoogleCloudVideointelligenceV1_NormalizedBoundingPoly' { _gcvvnbpcVertices :: Maybe [GoogleCloudVideointelligenceV1_NormalizedVertex] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_NormalizedBoundingPoly' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvnbpcVertices' googleCloudVideointelligenceV1_NormalizedBoundingPoly :: GoogleCloudVideointelligenceV1_NormalizedBoundingPoly googleCloudVideointelligenceV1_NormalizedBoundingPoly = GoogleCloudVideointelligenceV1_NormalizedBoundingPoly' {_gcvvnbpcVertices = Nothing} -- | Normalized vertices of the bounding polygon. gcvvnbpcVertices :: Lens' GoogleCloudVideointelligenceV1_NormalizedBoundingPoly [GoogleCloudVideointelligenceV1_NormalizedVertex] gcvvnbpcVertices = lens _gcvvnbpcVertices (\ s a -> s{_gcvvnbpcVertices = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1_NormalizedBoundingPoly where parseJSON = withObject "GoogleCloudVideointelligenceV1NormalizedBoundingPoly" (\ o -> GoogleCloudVideointelligenceV1_NormalizedBoundingPoly' <$> (o .:? "vertices" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1_NormalizedBoundingPoly where toJSON GoogleCloudVideointelligenceV1_NormalizedBoundingPoly'{..} = object (catMaybes [("vertices" .=) <$> _gcvvnbpcVertices]) -- | A vertex represents a 2D point in the image. NOTE: the normalized vertex -- coordinates are relative to the original image and range from 0 to 1. -- -- /See:/ 'googleCloudVideointelligenceV1_NormalizedVertex' smart constructor. data GoogleCloudVideointelligenceV1_NormalizedVertex = GoogleCloudVideointelligenceV1_NormalizedVertex' { _gcvvnvcX :: !(Maybe (Textual Double)) , _gcvvnvcY :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_NormalizedVertex' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvnvcX' -- -- * 'gcvvnvcY' googleCloudVideointelligenceV1_NormalizedVertex :: GoogleCloudVideointelligenceV1_NormalizedVertex googleCloudVideointelligenceV1_NormalizedVertex = GoogleCloudVideointelligenceV1_NormalizedVertex' {_gcvvnvcX = Nothing, _gcvvnvcY = Nothing} -- | X coordinate. gcvvnvcX :: Lens' GoogleCloudVideointelligenceV1_NormalizedVertex (Maybe Double) gcvvnvcX = lens _gcvvnvcX (\ s a -> s{_gcvvnvcX = a}) . mapping _Coerce -- | Y coordinate. gcvvnvcY :: Lens' GoogleCloudVideointelligenceV1_NormalizedVertex (Maybe Double) gcvvnvcY = lens _gcvvnvcY (\ s a -> s{_gcvvnvcY = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1_NormalizedVertex where parseJSON = withObject "GoogleCloudVideointelligenceV1NormalizedVertex" (\ o -> GoogleCloudVideointelligenceV1_NormalizedVertex' <$> (o .:? "x") <*> (o .:? "y")) instance ToJSON GoogleCloudVideointelligenceV1_NormalizedVertex where toJSON GoogleCloudVideointelligenceV1_NormalizedVertex'{..} = object (catMaybes [("x" .=) <$> _gcvvnvcX, ("y" .=) <$> _gcvvnvcY]) -- | Annotation progress for a single video. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress = GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress' { _gcvvvap1Feature :: !(Maybe GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgressFeature) , _gcvvvap1StartTime :: !(Maybe DateTime') , _gcvvvap1InputURI :: !(Maybe Text) , _gcvvvap1ProgressPercent :: !(Maybe (Textual Int32)) , _gcvvvap1UpdateTime :: !(Maybe DateTime') , _gcvvvap1Segment :: !(Maybe GoogleCloudVideointelligenceV1p1beta1_VideoSegment) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvvap1Feature' -- -- * 'gcvvvap1StartTime' -- -- * 'gcvvvap1InputURI' -- -- * 'gcvvvap1ProgressPercent' -- -- * 'gcvvvap1UpdateTime' -- -- * 'gcvvvap1Segment' googleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress :: GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress googleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress = GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress' { _gcvvvap1Feature = Nothing , _gcvvvap1StartTime = Nothing , _gcvvvap1InputURI = Nothing , _gcvvvap1ProgressPercent = Nothing , _gcvvvap1UpdateTime = Nothing , _gcvvvap1Segment = Nothing } -- | Specifies which feature is being tracked if the request contains more -- than one feature. gcvvvap1Feature :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress (Maybe GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgressFeature) gcvvvap1Feature = lens _gcvvvap1Feature (\ s a -> s{_gcvvvap1Feature = a}) -- | Time when the request was received. gcvvvap1StartTime :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress (Maybe UTCTime) gcvvvap1StartTime = lens _gcvvvap1StartTime (\ s a -> s{_gcvvvap1StartTime = a}) . mapping _DateTime -- | Video file location in [Cloud -- Storage](https:\/\/cloud.google.com\/storage\/). gcvvvap1InputURI :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress (Maybe Text) gcvvvap1InputURI = lens _gcvvvap1InputURI (\ s a -> s{_gcvvvap1InputURI = a}) -- | Approximate percentage processed thus far. Guaranteed to be 100 when -- fully processed. gcvvvap1ProgressPercent :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress (Maybe Int32) gcvvvap1ProgressPercent = lens _gcvvvap1ProgressPercent (\ s a -> s{_gcvvvap1ProgressPercent = a}) . mapping _Coerce -- | Time of the most recent update. gcvvvap1UpdateTime :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress (Maybe UTCTime) gcvvvap1UpdateTime = lens _gcvvvap1UpdateTime (\ s a -> s{_gcvvvap1UpdateTime = a}) . mapping _DateTime -- | Specifies which segment is being tracked if the request contains more -- than one segment. gcvvvap1Segment :: Lens' GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress (Maybe GoogleCloudVideointelligenceV1p1beta1_VideoSegment) gcvvvap1Segment = lens _gcvvvap1Segment (\ s a -> s{_gcvvvap1Segment = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1VideoAnnotationProgress" (\ o -> GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress' <$> (o .:? "feature") <*> (o .:? "startTime") <*> (o .:? "inputUri") <*> (o .:? "progressPercent") <*> (o .:? "updateTime") <*> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress where toJSON GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationProgress'{..} = object (catMaybes [("feature" .=) <$> _gcvvvap1Feature, ("startTime" .=) <$> _gcvvvap1StartTime, ("inputUri" .=) <$> _gcvvvap1InputURI, ("progressPercent" .=) <$> _gcvvvap1ProgressPercent, ("updateTime" .=) <$> _gcvvvap1UpdateTime, ("segment" .=) <$> _gcvvvap1Segment]) -- | Face detection annotation. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_FaceDetectionAnnotation' smart constructor. data GoogleCloudVideointelligenceV1beta2_FaceDetectionAnnotation = GoogleCloudVideointelligenceV1beta2_FaceDetectionAnnotation' { _goo1Thumbnail :: !(Maybe Bytes) , _goo1Tracks :: !(Maybe [GoogleCloudVideointelligenceV1beta2_Track]) , _goo1Version :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_FaceDetectionAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'goo1Thumbnail' -- -- * 'goo1Tracks' -- -- * 'goo1Version' googleCloudVideointelligenceV1beta2_FaceDetectionAnnotation :: GoogleCloudVideointelligenceV1beta2_FaceDetectionAnnotation googleCloudVideointelligenceV1beta2_FaceDetectionAnnotation = GoogleCloudVideointelligenceV1beta2_FaceDetectionAnnotation' {_goo1Thumbnail = Nothing, _goo1Tracks = Nothing, _goo1Version = Nothing} -- | The thumbnail of a person\'s face. goo1Thumbnail :: Lens' GoogleCloudVideointelligenceV1beta2_FaceDetectionAnnotation (Maybe ByteString) goo1Thumbnail = lens _goo1Thumbnail (\ s a -> s{_goo1Thumbnail = a}) . mapping _Bytes -- | The face tracks with attributes. goo1Tracks :: Lens' GoogleCloudVideointelligenceV1beta2_FaceDetectionAnnotation [GoogleCloudVideointelligenceV1beta2_Track] goo1Tracks = lens _goo1Tracks (\ s a -> s{_goo1Tracks = a}) . _Default . _Coerce -- | Feature version. goo1Version :: Lens' GoogleCloudVideointelligenceV1beta2_FaceDetectionAnnotation (Maybe Text) goo1Version = lens _goo1Version (\ s a -> s{_goo1Version = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_FaceDetectionAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2FaceDetectionAnnotation" (\ o -> GoogleCloudVideointelligenceV1beta2_FaceDetectionAnnotation' <$> (o .:? "thumbnail") <*> (o .:? "tracks" .!= mempty) <*> (o .:? "version")) instance ToJSON GoogleCloudVideointelligenceV1beta2_FaceDetectionAnnotation where toJSON GoogleCloudVideointelligenceV1beta2_FaceDetectionAnnotation'{..} = object (catMaybes [("thumbnail" .=) <$> _goo1Thumbnail, ("tracks" .=) <$> _goo1Tracks, ("version" .=) <$> _goo1Version]) -- | A vertex represents a 2D point in the image. NOTE: the normalized vertex -- coordinates are relative to the original image and range from 0 to 1. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_NormalizedVertex' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_NormalizedVertex = GoogleCloudVideointelligenceV1p3beta1_NormalizedVertex' { _ggX :: !(Maybe (Textual Double)) , _ggY :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_NormalizedVertex' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ggX' -- -- * 'ggY' googleCloudVideointelligenceV1p3beta1_NormalizedVertex :: GoogleCloudVideointelligenceV1p3beta1_NormalizedVertex googleCloudVideointelligenceV1p3beta1_NormalizedVertex = GoogleCloudVideointelligenceV1p3beta1_NormalizedVertex' {_ggX = Nothing, _ggY = Nothing} -- | X coordinate. ggX :: Lens' GoogleCloudVideointelligenceV1p3beta1_NormalizedVertex (Maybe Double) ggX = lens _ggX (\ s a -> s{_ggX = a}) . mapping _Coerce -- | Y coordinate. ggY :: Lens' GoogleCloudVideointelligenceV1p3beta1_NormalizedVertex (Maybe Double) ggY = lens _ggY (\ s a -> s{_ggY = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1p3beta1_NormalizedVertex where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1NormalizedVertex" (\ o -> GoogleCloudVideointelligenceV1p3beta1_NormalizedVertex' <$> (o .:? "x") <*> (o .:? "y")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_NormalizedVertex where toJSON GoogleCloudVideointelligenceV1p3beta1_NormalizedVertex'{..} = object (catMaybes [("x" .=) <$> _ggX, ("y" .=) <$> _ggY]) -- | Video frame level annotation results for text annotation (OCR). Contains -- information regarding timestamp and bounding box locations for the -- frames containing detected OCR text snippets. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_TextFrame' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_TextFrame = GoogleCloudVideointelligenceV1p2beta1_TextFrame' { _g1RotatedBoundingBox :: !(Maybe GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingPoly) , _g1TimeOffSet :: !(Maybe GDuration) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_TextFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'g1RotatedBoundingBox' -- -- * 'g1TimeOffSet' googleCloudVideointelligenceV1p2beta1_TextFrame :: GoogleCloudVideointelligenceV1p2beta1_TextFrame googleCloudVideointelligenceV1p2beta1_TextFrame = GoogleCloudVideointelligenceV1p2beta1_TextFrame' {_g1RotatedBoundingBox = Nothing, _g1TimeOffSet = Nothing} -- | Bounding polygon of the detected text for this frame. g1RotatedBoundingBox :: Lens' GoogleCloudVideointelligenceV1p2beta1_TextFrame (Maybe GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingPoly) g1RotatedBoundingBox = lens _g1RotatedBoundingBox (\ s a -> s{_g1RotatedBoundingBox = a}) -- | Timestamp of this frame. g1TimeOffSet :: Lens' GoogleCloudVideointelligenceV1p2beta1_TextFrame (Maybe Scientific) g1TimeOffSet = lens _g1TimeOffSet (\ s a -> s{_g1TimeOffSet = a}) . mapping _GDuration instance FromJSON GoogleCloudVideointelligenceV1p2beta1_TextFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1TextFrame" (\ o -> GoogleCloudVideointelligenceV1p2beta1_TextFrame' <$> (o .:? "rotatedBoundingBox") <*> (o .:? "timeOffset")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_TextFrame where toJSON GoogleCloudVideointelligenceV1p2beta1_TextFrame'{..} = object (catMaybes [("rotatedBoundingBox" .=) <$> _g1RotatedBoundingBox, ("timeOffset" .=) <$> _g1TimeOffSet]) -- | Normalized bounding polygon for text (that might not be aligned with -- axis). Contains list of the corner points in clockwise order starting -- from top-left corner. For example, for a rectangular bounding box: When -- the text is horizontal it might look like: 0----1 | | 3----2 When it\'s -- clockwise rotated 180 degrees around the top-left corner it becomes: -- 2----3 | | 1----0 and the vertex order will still be (0, 1, 2, 3). Note -- that values can be less than 0, or greater than 1 due to trignometric -- calculations for location of the box. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly' smart constructor. newtype GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly = GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly' { _ggVertices :: Maybe [GoogleCloudVideointelligenceV1p3beta1_NormalizedVertex] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ggVertices' googleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly :: GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly googleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly = GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly' {_ggVertices = Nothing} -- | Normalized vertices of the bounding polygon. ggVertices :: Lens' GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly [GoogleCloudVideointelligenceV1p3beta1_NormalizedVertex] ggVertices = lens _ggVertices (\ s a -> s{_ggVertices = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1NormalizedBoundingPoly" (\ o -> GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly' <$> (o .:? "vertices" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly where toJSON GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingPoly'{..} = object (catMaybes [("vertices" .=) <$> _ggVertices]) -- | Label annotation. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_LabelAnnotation' smart constructor. data GoogleCloudVideointelligenceV1beta2_LabelAnnotation = GoogleCloudVideointelligenceV1beta2_LabelAnnotation' { _gcvvla2CategoryEntities :: !(Maybe [GoogleCloudVideointelligenceV1beta2_Entity]) , _gcvvla2Frames :: !(Maybe [GoogleCloudVideointelligenceV1beta2_LabelFrame]) , _gcvvla2Version :: !(Maybe Text) , _gcvvla2Segments :: !(Maybe [GoogleCloudVideointelligenceV1beta2_LabelSegment]) , _gcvvla2Entity :: !(Maybe GoogleCloudVideointelligenceV1beta2_Entity) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_LabelAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvla2CategoryEntities' -- -- * 'gcvvla2Frames' -- -- * 'gcvvla2Version' -- -- * 'gcvvla2Segments' -- -- * 'gcvvla2Entity' googleCloudVideointelligenceV1beta2_LabelAnnotation :: GoogleCloudVideointelligenceV1beta2_LabelAnnotation googleCloudVideointelligenceV1beta2_LabelAnnotation = GoogleCloudVideointelligenceV1beta2_LabelAnnotation' { _gcvvla2CategoryEntities = Nothing , _gcvvla2Frames = Nothing , _gcvvla2Version = Nothing , _gcvvla2Segments = Nothing , _gcvvla2Entity = Nothing } -- | Common categories for the detected entity. For example, when the label -- is \`Terrier\`, the category is likely \`dog\`. And in some cases there -- might be more than one categories e.g., \`Terrier\` could also be a -- \`pet\`. gcvvla2CategoryEntities :: Lens' GoogleCloudVideointelligenceV1beta2_LabelAnnotation [GoogleCloudVideointelligenceV1beta2_Entity] gcvvla2CategoryEntities = lens _gcvvla2CategoryEntities (\ s a -> s{_gcvvla2CategoryEntities = a}) . _Default . _Coerce -- | All video frames where a label was detected. gcvvla2Frames :: Lens' GoogleCloudVideointelligenceV1beta2_LabelAnnotation [GoogleCloudVideointelligenceV1beta2_LabelFrame] gcvvla2Frames = lens _gcvvla2Frames (\ s a -> s{_gcvvla2Frames = a}) . _Default . _Coerce -- | Feature version. gcvvla2Version :: Lens' GoogleCloudVideointelligenceV1beta2_LabelAnnotation (Maybe Text) gcvvla2Version = lens _gcvvla2Version (\ s a -> s{_gcvvla2Version = a}) -- | All video segments where a label was detected. gcvvla2Segments :: Lens' GoogleCloudVideointelligenceV1beta2_LabelAnnotation [GoogleCloudVideointelligenceV1beta2_LabelSegment] gcvvla2Segments = lens _gcvvla2Segments (\ s a -> s{_gcvvla2Segments = a}) . _Default . _Coerce -- | Detected entity. gcvvla2Entity :: Lens' GoogleCloudVideointelligenceV1beta2_LabelAnnotation (Maybe GoogleCloudVideointelligenceV1beta2_Entity) gcvvla2Entity = lens _gcvvla2Entity (\ s a -> s{_gcvvla2Entity = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_LabelAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2LabelAnnotation" (\ o -> GoogleCloudVideointelligenceV1beta2_LabelAnnotation' <$> (o .:? "categoryEntities" .!= mempty) <*> (o .:? "frames" .!= mempty) <*> (o .:? "version") <*> (o .:? "segments" .!= mempty) <*> (o .:? "entity")) instance ToJSON GoogleCloudVideointelligenceV1beta2_LabelAnnotation where toJSON GoogleCloudVideointelligenceV1beta2_LabelAnnotation'{..} = object (catMaybes [("categoryEntities" .=) <$> _gcvvla2CategoryEntities, ("frames" .=) <$> _gcvvla2Frames, ("version" .=) <$> _gcvvla2Version, ("segments" .=) <$> _gcvvla2Segments, ("entity" .=) <$> _gcvvla2Entity]) -- | \`StreamingAnnotateVideoResponse\` is the only message returned to the -- client by \`StreamingAnnotateVideo\`. A series of zero or more -- \`StreamingAnnotateVideoResponse\` messages are streamed back to the -- client. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_StreamingAnnotateVideoResponse' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_StreamingAnnotateVideoResponse = GoogleCloudVideointelligenceV1p3beta1_StreamingAnnotateVideoResponse' { _gcvvsavrError :: !(Maybe GoogleRpc_Status) , _gcvvsavrAnnotationResults :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults) , _gcvvsavrAnnotationResultsURI :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_StreamingAnnotateVideoResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvsavrError' -- -- * 'gcvvsavrAnnotationResults' -- -- * 'gcvvsavrAnnotationResultsURI' googleCloudVideointelligenceV1p3beta1_StreamingAnnotateVideoResponse :: GoogleCloudVideointelligenceV1p3beta1_StreamingAnnotateVideoResponse googleCloudVideointelligenceV1p3beta1_StreamingAnnotateVideoResponse = GoogleCloudVideointelligenceV1p3beta1_StreamingAnnotateVideoResponse' { _gcvvsavrError = Nothing , _gcvvsavrAnnotationResults = Nothing , _gcvvsavrAnnotationResultsURI = Nothing } -- | If set, returns a google.rpc.Status message that specifies the error for -- the operation. gcvvsavrError :: Lens' GoogleCloudVideointelligenceV1p3beta1_StreamingAnnotateVideoResponse (Maybe GoogleRpc_Status) gcvvsavrError = lens _gcvvsavrError (\ s a -> s{_gcvvsavrError = a}) -- | Streaming annotation results. gcvvsavrAnnotationResults :: Lens' GoogleCloudVideointelligenceV1p3beta1_StreamingAnnotateVideoResponse (Maybe GoogleCloudVideointelligenceV1p3beta1_StreamingVideoAnnotationResults) gcvvsavrAnnotationResults = lens _gcvvsavrAnnotationResults (\ s a -> s{_gcvvsavrAnnotationResults = a}) -- | Google Cloud Storage URI that stores annotation results of one streaming -- session in JSON format. It is the annotation_result_storage_directory -- from the request followed by \'\/cloud_project_number-session_id\'. gcvvsavrAnnotationResultsURI :: Lens' GoogleCloudVideointelligenceV1p3beta1_StreamingAnnotateVideoResponse (Maybe Text) gcvvsavrAnnotationResultsURI = lens _gcvvsavrAnnotationResultsURI (\ s a -> s{_gcvvsavrAnnotationResultsURI = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_StreamingAnnotateVideoResponse where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1StreamingAnnotateVideoResponse" (\ o -> GoogleCloudVideointelligenceV1p3beta1_StreamingAnnotateVideoResponse' <$> (o .:? "error") <*> (o .:? "annotationResults") <*> (o .:? "annotationResultsUri")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_StreamingAnnotateVideoResponse where toJSON GoogleCloudVideointelligenceV1p3beta1_StreamingAnnotateVideoResponse'{..} = object (catMaybes [("error" .=) <$> _gcvvsavrError, ("annotationResults" .=) <$> _gcvvsavrAnnotationResults, ("annotationResultsUri" .=) <$> _gcvvsavrAnnotationResultsURI]) -- | A speech recognition result corresponding to a portion of the audio. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_SpeechTranscription' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_SpeechTranscription = GoogleCloudVideointelligenceV1p1beta1_SpeechTranscription' { _g1Alternatives :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative]) , _g1LanguageCode :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_SpeechTranscription' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'g1Alternatives' -- -- * 'g1LanguageCode' googleCloudVideointelligenceV1p1beta1_SpeechTranscription :: GoogleCloudVideointelligenceV1p1beta1_SpeechTranscription googleCloudVideointelligenceV1p1beta1_SpeechTranscription = GoogleCloudVideointelligenceV1p1beta1_SpeechTranscription' {_g1Alternatives = Nothing, _g1LanguageCode = Nothing} -- | May contain one or more recognition hypotheses (up to the maximum -- specified in \`max_alternatives\`). These alternatives are ordered in -- terms of accuracy, with the top (first) alternative being the most -- probable, as ranked by the recognizer. g1Alternatives :: Lens' GoogleCloudVideointelligenceV1p1beta1_SpeechTranscription [GoogleCloudVideointelligenceV1p1beta1_SpeechRecognitionAlternative] g1Alternatives = lens _g1Alternatives (\ s a -> s{_g1Alternatives = a}) . _Default . _Coerce -- | Output only. The -- [BCP-47](https:\/\/www.rfc-editor.org\/rfc\/bcp\/bcp47.txt) language tag -- of the language in this result. This language code was detected to have -- the most likelihood of being spoken in the audio. g1LanguageCode :: Lens' GoogleCloudVideointelligenceV1p1beta1_SpeechTranscription (Maybe Text) g1LanguageCode = lens _g1LanguageCode (\ s a -> s{_g1LanguageCode = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_SpeechTranscription where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1SpeechTranscription" (\ o -> GoogleCloudVideointelligenceV1p1beta1_SpeechTranscription' <$> (o .:? "alternatives" .!= mempty) <*> (o .:? "languageCode")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_SpeechTranscription where toJSON GoogleCloudVideointelligenceV1p1beta1_SpeechTranscription'{..} = object (catMaybes [("alternatives" .=) <$> _g1Alternatives, ("languageCode" .=) <$> _g1LanguageCode]) -- | Annotation results for a single video. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_VideoAnnotationResults' smart constructor. data GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults = GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults' { _gcvvvar1ShotAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1beta2_VideoSegment]) , _gcvvvar1ShotLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1beta2_LabelAnnotation]) , _gcvvvar1FaceDetectionAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1beta2_FaceDetectionAnnotation]) , _gcvvvar1FaceAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1beta2_FaceAnnotation]) , _gcvvvar1InputURI :: !(Maybe Text) , _gcvvvar1Error :: !(Maybe GoogleRpc_Status) , _gcvvvar1ShotPresenceLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1beta2_LabelAnnotation]) , _gcvvvar1PersonDetectionAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1beta2_PersonDetectionAnnotation]) , _gcvvvar1ObjectAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation]) , _gcvvvar1FrameLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1beta2_LabelAnnotation]) , _gcvvvar1SpeechTranscriptions :: !(Maybe [GoogleCloudVideointelligenceV1beta2_SpeechTranscription]) , _gcvvvar1SegmentPresenceLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1beta2_LabelAnnotation]) , _gcvvvar1LogoRecognitionAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation]) , _gcvvvar1Segment :: !(Maybe GoogleCloudVideointelligenceV1beta2_VideoSegment) , _gcvvvar1TextAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1beta2_TextAnnotation]) , _gcvvvar1SegmentLabelAnnotations :: !(Maybe [GoogleCloudVideointelligenceV1beta2_LabelAnnotation]) , _gcvvvar1ExplicitAnnotation :: !(Maybe GoogleCloudVideointelligenceV1beta2_ExplicitContentAnnotation) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvvar1ShotAnnotations' -- -- * 'gcvvvar1ShotLabelAnnotations' -- -- * 'gcvvvar1FaceDetectionAnnotations' -- -- * 'gcvvvar1FaceAnnotations' -- -- * 'gcvvvar1InputURI' -- -- * 'gcvvvar1Error' -- -- * 'gcvvvar1ShotPresenceLabelAnnotations' -- -- * 'gcvvvar1PersonDetectionAnnotations' -- -- * 'gcvvvar1ObjectAnnotations' -- -- * 'gcvvvar1FrameLabelAnnotations' -- -- * 'gcvvvar1SpeechTranscriptions' -- -- * 'gcvvvar1SegmentPresenceLabelAnnotations' -- -- * 'gcvvvar1LogoRecognitionAnnotations' -- -- * 'gcvvvar1Segment' -- -- * 'gcvvvar1TextAnnotations' -- -- * 'gcvvvar1SegmentLabelAnnotations' -- -- * 'gcvvvar1ExplicitAnnotation' googleCloudVideointelligenceV1beta2_VideoAnnotationResults :: GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults googleCloudVideointelligenceV1beta2_VideoAnnotationResults = GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults' { _gcvvvar1ShotAnnotations = Nothing , _gcvvvar1ShotLabelAnnotations = Nothing , _gcvvvar1FaceDetectionAnnotations = Nothing , _gcvvvar1FaceAnnotations = Nothing , _gcvvvar1InputURI = Nothing , _gcvvvar1Error = Nothing , _gcvvvar1ShotPresenceLabelAnnotations = Nothing , _gcvvvar1PersonDetectionAnnotations = Nothing , _gcvvvar1ObjectAnnotations = Nothing , _gcvvvar1FrameLabelAnnotations = Nothing , _gcvvvar1SpeechTranscriptions = Nothing , _gcvvvar1SegmentPresenceLabelAnnotations = Nothing , _gcvvvar1LogoRecognitionAnnotations = Nothing , _gcvvvar1Segment = Nothing , _gcvvvar1TextAnnotations = Nothing , _gcvvvar1SegmentLabelAnnotations = Nothing , _gcvvvar1ExplicitAnnotation = Nothing } -- | Shot annotations. Each shot is represented as a video segment. gcvvvar1ShotAnnotations :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults [GoogleCloudVideointelligenceV1beta2_VideoSegment] gcvvvar1ShotAnnotations = lens _gcvvvar1ShotAnnotations (\ s a -> s{_gcvvvar1ShotAnnotations = a}) . _Default . _Coerce -- | Topical label annotations on shot level. There is exactly one element -- for each unique label. gcvvvar1ShotLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults [GoogleCloudVideointelligenceV1beta2_LabelAnnotation] gcvvvar1ShotLabelAnnotations = lens _gcvvvar1ShotLabelAnnotations (\ s a -> s{_gcvvvar1ShotLabelAnnotations = a}) . _Default . _Coerce -- | Face detection annotations. gcvvvar1FaceDetectionAnnotations :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults [GoogleCloudVideointelligenceV1beta2_FaceDetectionAnnotation] gcvvvar1FaceDetectionAnnotations = lens _gcvvvar1FaceDetectionAnnotations (\ s a -> s{_gcvvvar1FaceDetectionAnnotations = a}) . _Default . _Coerce -- | Deprecated. Please use \`face_detection_annotations\` instead. gcvvvar1FaceAnnotations :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults [GoogleCloudVideointelligenceV1beta2_FaceAnnotation] gcvvvar1FaceAnnotations = lens _gcvvvar1FaceAnnotations (\ s a -> s{_gcvvvar1FaceAnnotations = a}) . _Default . _Coerce -- | Video file location in [Cloud -- Storage](https:\/\/cloud.google.com\/storage\/). gcvvvar1InputURI :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults (Maybe Text) gcvvvar1InputURI = lens _gcvvvar1InputURI (\ s a -> s{_gcvvvar1InputURI = a}) -- | If set, indicates an error. Note that for a single -- \`AnnotateVideoRequest\` some videos may succeed and some may fail. gcvvvar1Error :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults (Maybe GoogleRpc_Status) gcvvvar1Error = lens _gcvvvar1Error (\ s a -> s{_gcvvvar1Error = a}) -- | Presence label annotations on shot level. There is exactly one element -- for each unique label. Compared to the existing topical -- \`shot_label_annotations\`, this field presents more fine-grained, -- shot-level labels detected in video content and is made available only -- when the client sets \`LabelDetectionConfig.model\` to -- \"builtin\/latest\" in the request. gcvvvar1ShotPresenceLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults [GoogleCloudVideointelligenceV1beta2_LabelAnnotation] gcvvvar1ShotPresenceLabelAnnotations = lens _gcvvvar1ShotPresenceLabelAnnotations (\ s a -> s{_gcvvvar1ShotPresenceLabelAnnotations = a}) . _Default . _Coerce -- | Person detection annotations. gcvvvar1PersonDetectionAnnotations :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults [GoogleCloudVideointelligenceV1beta2_PersonDetectionAnnotation] gcvvvar1PersonDetectionAnnotations = lens _gcvvvar1PersonDetectionAnnotations (\ s a -> s{_gcvvvar1PersonDetectionAnnotations = a}) . _Default . _Coerce -- | Annotations for list of objects detected and tracked in video. gcvvvar1ObjectAnnotations :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults [GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation] gcvvvar1ObjectAnnotations = lens _gcvvvar1ObjectAnnotations (\ s a -> s{_gcvvvar1ObjectAnnotations = a}) . _Default . _Coerce -- | Label annotations on frame level. There is exactly one element for each -- unique label. gcvvvar1FrameLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults [GoogleCloudVideointelligenceV1beta2_LabelAnnotation] gcvvvar1FrameLabelAnnotations = lens _gcvvvar1FrameLabelAnnotations (\ s a -> s{_gcvvvar1FrameLabelAnnotations = a}) . _Default . _Coerce -- | Speech transcription. gcvvvar1SpeechTranscriptions :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults [GoogleCloudVideointelligenceV1beta2_SpeechTranscription] gcvvvar1SpeechTranscriptions = lens _gcvvvar1SpeechTranscriptions (\ s a -> s{_gcvvvar1SpeechTranscriptions = a}) . _Default . _Coerce -- | Presence label annotations on video level or user-specified segment -- level. There is exactly one element for each unique label. Compared to -- the existing topical \`segment_label_annotations\`, this field presents -- more fine-grained, segment-level labels detected in video content and is -- made available only when the client sets \`LabelDetectionConfig.model\` -- to \"builtin\/latest\" in the request. gcvvvar1SegmentPresenceLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults [GoogleCloudVideointelligenceV1beta2_LabelAnnotation] gcvvvar1SegmentPresenceLabelAnnotations = lens _gcvvvar1SegmentPresenceLabelAnnotations (\ s a -> s{_gcvvvar1SegmentPresenceLabelAnnotations = a}) . _Default . _Coerce -- | Annotations for list of logos detected, tracked and recognized in video. gcvvvar1LogoRecognitionAnnotations :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults [GoogleCloudVideointelligenceV1beta2_LogoRecognitionAnnotation] gcvvvar1LogoRecognitionAnnotations = lens _gcvvvar1LogoRecognitionAnnotations (\ s a -> s{_gcvvvar1LogoRecognitionAnnotations = a}) . _Default . _Coerce -- | Video segment on which the annotation is run. gcvvvar1Segment :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults (Maybe GoogleCloudVideointelligenceV1beta2_VideoSegment) gcvvvar1Segment = lens _gcvvvar1Segment (\ s a -> s{_gcvvvar1Segment = a}) -- | OCR text detection and tracking. Annotations for list of detected text -- snippets. Each will have list of frame information associated with it. gcvvvar1TextAnnotations :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults [GoogleCloudVideointelligenceV1beta2_TextAnnotation] gcvvvar1TextAnnotations = lens _gcvvvar1TextAnnotations (\ s a -> s{_gcvvvar1TextAnnotations = a}) . _Default . _Coerce -- | Topical label annotations on video level or user-specified segment -- level. There is exactly one element for each unique label. gcvvvar1SegmentLabelAnnotations :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults [GoogleCloudVideointelligenceV1beta2_LabelAnnotation] gcvvvar1SegmentLabelAnnotations = lens _gcvvvar1SegmentLabelAnnotations (\ s a -> s{_gcvvvar1SegmentLabelAnnotations = a}) . _Default . _Coerce -- | Explicit content annotation. gcvvvar1ExplicitAnnotation :: Lens' GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults (Maybe GoogleCloudVideointelligenceV1beta2_ExplicitContentAnnotation) gcvvvar1ExplicitAnnotation = lens _gcvvvar1ExplicitAnnotation (\ s a -> s{_gcvvvar1ExplicitAnnotation = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2VideoAnnotationResults" (\ o -> GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults' <$> (o .:? "shotAnnotations" .!= mempty) <*> (o .:? "shotLabelAnnotations" .!= mempty) <*> (o .:? "faceDetectionAnnotations" .!= mempty) <*> (o .:? "faceAnnotations" .!= mempty) <*> (o .:? "inputUri") <*> (o .:? "error") <*> (o .:? "shotPresenceLabelAnnotations" .!= mempty) <*> (o .:? "personDetectionAnnotations" .!= mempty) <*> (o .:? "objectAnnotations" .!= mempty) <*> (o .:? "frameLabelAnnotations" .!= mempty) <*> (o .:? "speechTranscriptions" .!= mempty) <*> (o .:? "segmentPresenceLabelAnnotations" .!= mempty) <*> (o .:? "logoRecognitionAnnotations" .!= mempty) <*> (o .:? "segment") <*> (o .:? "textAnnotations" .!= mempty) <*> (o .:? "segmentLabelAnnotations" .!= mempty) <*> (o .:? "explicitAnnotation")) instance ToJSON GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults where toJSON GoogleCloudVideointelligenceV1beta2_VideoAnnotationResults'{..} = object (catMaybes [("shotAnnotations" .=) <$> _gcvvvar1ShotAnnotations, ("shotLabelAnnotations" .=) <$> _gcvvvar1ShotLabelAnnotations, ("faceDetectionAnnotations" .=) <$> _gcvvvar1FaceDetectionAnnotations, ("faceAnnotations" .=) <$> _gcvvvar1FaceAnnotations, ("inputUri" .=) <$> _gcvvvar1InputURI, ("error" .=) <$> _gcvvvar1Error, ("shotPresenceLabelAnnotations" .=) <$> _gcvvvar1ShotPresenceLabelAnnotations, ("personDetectionAnnotations" .=) <$> _gcvvvar1PersonDetectionAnnotations, ("objectAnnotations" .=) <$> _gcvvvar1ObjectAnnotations, ("frameLabelAnnotations" .=) <$> _gcvvvar1FrameLabelAnnotations, ("speechTranscriptions" .=) <$> _gcvvvar1SpeechTranscriptions, ("segmentPresenceLabelAnnotations" .=) <$> _gcvvvar1SegmentPresenceLabelAnnotations, ("logoRecognitionAnnotations" .=) <$> _gcvvvar1LogoRecognitionAnnotations, ("segment" .=) <$> _gcvvvar1Segment, ("textAnnotations" .=) <$> _gcvvvar1TextAnnotations, ("segmentLabelAnnotations" .=) <$> _gcvvvar1SegmentLabelAnnotations, ("explicitAnnotation" .=) <$> _gcvvvar1ExplicitAnnotation]) -- | Deprecated. No effect. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_FaceFrame' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_FaceFrame = GoogleCloudVideointelligenceV1p3beta1_FaceFrame' { _gcvvff1TimeOffSet :: !(Maybe GDuration) , _gcvvff1NormalizedBoundingBoxes :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_FaceFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvff1TimeOffSet' -- -- * 'gcvvff1NormalizedBoundingBoxes' googleCloudVideointelligenceV1p3beta1_FaceFrame :: GoogleCloudVideointelligenceV1p3beta1_FaceFrame googleCloudVideointelligenceV1p3beta1_FaceFrame = GoogleCloudVideointelligenceV1p3beta1_FaceFrame' {_gcvvff1TimeOffSet = Nothing, _gcvvff1NormalizedBoundingBoxes = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this location. gcvvff1TimeOffSet :: Lens' GoogleCloudVideointelligenceV1p3beta1_FaceFrame (Maybe Scientific) gcvvff1TimeOffSet = lens _gcvvff1TimeOffSet (\ s a -> s{_gcvvff1TimeOffSet = a}) . mapping _GDuration -- | Normalized Bounding boxes in a frame. There can be more than one boxes -- if the same face is detected in multiple locations within the current -- frame. gcvvff1NormalizedBoundingBoxes :: Lens' GoogleCloudVideointelligenceV1p3beta1_FaceFrame [GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox] gcvvff1NormalizedBoundingBoxes = lens _gcvvff1NormalizedBoundingBoxes (\ s a -> s{_gcvvff1NormalizedBoundingBoxes = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p3beta1_FaceFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1FaceFrame" (\ o -> GoogleCloudVideointelligenceV1p3beta1_FaceFrame' <$> (o .:? "timeOffset") <*> (o .:? "normalizedBoundingBoxes" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_FaceFrame where toJSON GoogleCloudVideointelligenceV1p3beta1_FaceFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvff1TimeOffSet, ("normalizedBoundingBoxes" .=) <$> _gcvvff1NormalizedBoundingBoxes]) -- | Video segment level annotation results for label detection. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_LabelSegment' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_LabelSegment = GoogleCloudVideointelligenceV1p2beta1_LabelSegment' { _gcvvls1Confidence :: !(Maybe (Textual Double)) , _gcvvls1Segment :: !(Maybe GoogleCloudVideointelligenceV1p2beta1_VideoSegment) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_LabelSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvls1Confidence' -- -- * 'gcvvls1Segment' googleCloudVideointelligenceV1p2beta1_LabelSegment :: GoogleCloudVideointelligenceV1p2beta1_LabelSegment googleCloudVideointelligenceV1p2beta1_LabelSegment = GoogleCloudVideointelligenceV1p2beta1_LabelSegment' {_gcvvls1Confidence = Nothing, _gcvvls1Segment = Nothing} -- | Confidence that the label is accurate. Range: [0, 1]. gcvvls1Confidence :: Lens' GoogleCloudVideointelligenceV1p2beta1_LabelSegment (Maybe Double) gcvvls1Confidence = lens _gcvvls1Confidence (\ s a -> s{_gcvvls1Confidence = a}) . mapping _Coerce -- | Video segment where a label was detected. gcvvls1Segment :: Lens' GoogleCloudVideointelligenceV1p2beta1_LabelSegment (Maybe GoogleCloudVideointelligenceV1p2beta1_VideoSegment) gcvvls1Segment = lens _gcvvls1Segment (\ s a -> s{_gcvvls1Segment = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_LabelSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1LabelSegment" (\ o -> GoogleCloudVideointelligenceV1p2beta1_LabelSegment' <$> (o .:? "confidence") <*> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_LabelSegment where toJSON GoogleCloudVideointelligenceV1p2beta1_LabelSegment'{..} = object (catMaybes [("confidence" .=) <$> _gcvvls1Confidence, ("segment" .=) <$> _gcvvls1Segment]) -- | A generic detected landmark represented by name in string format and a -- 2D location. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_DetectedLandmark' smart constructor. data GoogleCloudVideointelligenceV1beta2_DetectedLandmark = GoogleCloudVideointelligenceV1beta2_DetectedLandmark' { _g2Confidence :: !(Maybe (Textual Double)) , _g2Point :: !(Maybe GoogleCloudVideointelligenceV1beta2_NormalizedVertex) , _g2Name :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_DetectedLandmark' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'g2Confidence' -- -- * 'g2Point' -- -- * 'g2Name' googleCloudVideointelligenceV1beta2_DetectedLandmark :: GoogleCloudVideointelligenceV1beta2_DetectedLandmark googleCloudVideointelligenceV1beta2_DetectedLandmark = GoogleCloudVideointelligenceV1beta2_DetectedLandmark' {_g2Confidence = Nothing, _g2Point = Nothing, _g2Name = Nothing} -- | The confidence score of the detected landmark. Range [0, 1]. g2Confidence :: Lens' GoogleCloudVideointelligenceV1beta2_DetectedLandmark (Maybe Double) g2Confidence = lens _g2Confidence (\ s a -> s{_g2Confidence = a}) . mapping _Coerce -- | The 2D point of the detected landmark using the normalized image -- coordindate system. The normalized coordinates have the range from 0 to -- 1. g2Point :: Lens' GoogleCloudVideointelligenceV1beta2_DetectedLandmark (Maybe GoogleCloudVideointelligenceV1beta2_NormalizedVertex) g2Point = lens _g2Point (\ s a -> s{_g2Point = a}) -- | The name of this landmark, for example, left_hand, right_shoulder. g2Name :: Lens' GoogleCloudVideointelligenceV1beta2_DetectedLandmark (Maybe Text) g2Name = lens _g2Name (\ s a -> s{_g2Name = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_DetectedLandmark where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2DetectedLandmark" (\ o -> GoogleCloudVideointelligenceV1beta2_DetectedLandmark' <$> (o .:? "confidence") <*> (o .:? "point") <*> (o .:? "name")) instance ToJSON GoogleCloudVideointelligenceV1beta2_DetectedLandmark where toJSON GoogleCloudVideointelligenceV1beta2_DetectedLandmark'{..} = object (catMaybes [("confidence" .=) <$> _g2Confidence, ("point" .=) <$> _g2Point, ("name" .=) <$> _g2Name]) -- | Deprecated. No effect. -- -- /See:/ 'googleCloudVideointelligenceV1_FaceFrame' smart constructor. data GoogleCloudVideointelligenceV1_FaceFrame = GoogleCloudVideointelligenceV1_FaceFrame' { _gcvvff2TimeOffSet :: !(Maybe GDuration) , _gcvvff2NormalizedBoundingBoxes :: !(Maybe [GoogleCloudVideointelligenceV1_NormalizedBoundingBox]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_FaceFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvff2TimeOffSet' -- -- * 'gcvvff2NormalizedBoundingBoxes' googleCloudVideointelligenceV1_FaceFrame :: GoogleCloudVideointelligenceV1_FaceFrame googleCloudVideointelligenceV1_FaceFrame = GoogleCloudVideointelligenceV1_FaceFrame' {_gcvvff2TimeOffSet = Nothing, _gcvvff2NormalizedBoundingBoxes = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this location. gcvvff2TimeOffSet :: Lens' GoogleCloudVideointelligenceV1_FaceFrame (Maybe Scientific) gcvvff2TimeOffSet = lens _gcvvff2TimeOffSet (\ s a -> s{_gcvvff2TimeOffSet = a}) . mapping _GDuration -- | Normalized Bounding boxes in a frame. There can be more than one boxes -- if the same face is detected in multiple locations within the current -- frame. gcvvff2NormalizedBoundingBoxes :: Lens' GoogleCloudVideointelligenceV1_FaceFrame [GoogleCloudVideointelligenceV1_NormalizedBoundingBox] gcvvff2NormalizedBoundingBoxes = lens _gcvvff2NormalizedBoundingBoxes (\ s a -> s{_gcvvff2NormalizedBoundingBoxes = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1_FaceFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1FaceFrame" (\ o -> GoogleCloudVideointelligenceV1_FaceFrame' <$> (o .:? "timeOffset") <*> (o .:? "normalizedBoundingBoxes" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1_FaceFrame where toJSON GoogleCloudVideointelligenceV1_FaceFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvff2TimeOffSet, ("normalizedBoundingBoxes" .=) <$> _gcvvff2NormalizedBoundingBoxes]) -- | Normalized bounding box. The normalized vertex coordinates are relative -- to the original image. Range: [0, 1]. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox = GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox' { _gcvvnbbcBottom :: !(Maybe (Textual Double)) , _gcvvnbbcLeft :: !(Maybe (Textual Double)) , _gcvvnbbcRight :: !(Maybe (Textual Double)) , _gcvvnbbcTop :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvnbbcBottom' -- -- * 'gcvvnbbcLeft' -- -- * 'gcvvnbbcRight' -- -- * 'gcvvnbbcTop' googleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox :: GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox googleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox = GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox' { _gcvvnbbcBottom = Nothing , _gcvvnbbcLeft = Nothing , _gcvvnbbcRight = Nothing , _gcvvnbbcTop = Nothing } -- | Bottom Y coordinate. gcvvnbbcBottom :: Lens' GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox (Maybe Double) gcvvnbbcBottom = lens _gcvvnbbcBottom (\ s a -> s{_gcvvnbbcBottom = a}) . mapping _Coerce -- | Left X coordinate. gcvvnbbcLeft :: Lens' GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox (Maybe Double) gcvvnbbcLeft = lens _gcvvnbbcLeft (\ s a -> s{_gcvvnbbcLeft = a}) . mapping _Coerce -- | Right X coordinate. gcvvnbbcRight :: Lens' GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox (Maybe Double) gcvvnbbcRight = lens _gcvvnbbcRight (\ s a -> s{_gcvvnbbcRight = a}) . mapping _Coerce -- | Top Y coordinate. gcvvnbbcTop :: Lens' GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox (Maybe Double) gcvvnbbcTop = lens _gcvvnbbcTop (\ s a -> s{_gcvvnbbcTop = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1NormalizedBoundingBox" (\ o -> GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox' <$> (o .:? "bottom") <*> (o .:? "left") <*> (o .:? "right") <*> (o .:? "top")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox where toJSON GoogleCloudVideointelligenceV1p1beta1_NormalizedBoundingBox'{..} = object (catMaybes [("bottom" .=) <$> _gcvvnbbcBottom, ("left" .=) <$> _gcvvnbbcLeft, ("right" .=) <$> _gcvvnbbcRight, ("top" .=) <$> _gcvvnbbcTop]) -- | Video segment level annotation results for text detection. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_TextSegment' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_TextSegment = GoogleCloudVideointelligenceV1p1beta1_TextSegment' { _gcvvts2Frames :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_TextFrame]) , _gcvvts2Confidence :: !(Maybe (Textual Double)) , _gcvvts2Segment :: !(Maybe GoogleCloudVideointelligenceV1p1beta1_VideoSegment) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_TextSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvts2Frames' -- -- * 'gcvvts2Confidence' -- -- * 'gcvvts2Segment' googleCloudVideointelligenceV1p1beta1_TextSegment :: GoogleCloudVideointelligenceV1p1beta1_TextSegment googleCloudVideointelligenceV1p1beta1_TextSegment = GoogleCloudVideointelligenceV1p1beta1_TextSegment' { _gcvvts2Frames = Nothing , _gcvvts2Confidence = Nothing , _gcvvts2Segment = Nothing } -- | Information related to the frames where OCR detected text appears. gcvvts2Frames :: Lens' GoogleCloudVideointelligenceV1p1beta1_TextSegment [GoogleCloudVideointelligenceV1p1beta1_TextFrame] gcvvts2Frames = lens _gcvvts2Frames (\ s a -> s{_gcvvts2Frames = a}) . _Default . _Coerce -- | Confidence for the track of detected text. It is calculated as the -- highest over all frames where OCR detected text appears. gcvvts2Confidence :: Lens' GoogleCloudVideointelligenceV1p1beta1_TextSegment (Maybe Double) gcvvts2Confidence = lens _gcvvts2Confidence (\ s a -> s{_gcvvts2Confidence = a}) . mapping _Coerce -- | Video segment where a text snippet was detected. gcvvts2Segment :: Lens' GoogleCloudVideointelligenceV1p1beta1_TextSegment (Maybe GoogleCloudVideointelligenceV1p1beta1_VideoSegment) gcvvts2Segment = lens _gcvvts2Segment (\ s a -> s{_gcvvts2Segment = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_TextSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1TextSegment" (\ o -> GoogleCloudVideointelligenceV1p1beta1_TextSegment' <$> (o .:? "frames" .!= mempty) <*> (o .:? "confidence") <*> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_TextSegment where toJSON GoogleCloudVideointelligenceV1p1beta1_TextSegment'{..} = object (catMaybes [("frames" .=) <$> _gcvvts2Frames, ("confidence" .=) <$> _gcvvts2Confidence, ("segment" .=) <$> _gcvvts2Segment]) -- | The annotation result of a celebrity face track. RecognizedCelebrity -- field could be empty if the face track does not have any matched -- celebrities. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_CelebrityTrack' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_CelebrityTrack = GoogleCloudVideointelligenceV1p3beta1_CelebrityTrack' { _gcvvctCelebrities :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_RecognizedCelebrity]) , _gcvvctFaceTrack :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_Track) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_CelebrityTrack' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvctCelebrities' -- -- * 'gcvvctFaceTrack' googleCloudVideointelligenceV1p3beta1_CelebrityTrack :: GoogleCloudVideointelligenceV1p3beta1_CelebrityTrack googleCloudVideointelligenceV1p3beta1_CelebrityTrack = GoogleCloudVideointelligenceV1p3beta1_CelebrityTrack' {_gcvvctCelebrities = Nothing, _gcvvctFaceTrack = Nothing} -- | Top N match of the celebrities for the face in this track. gcvvctCelebrities :: Lens' GoogleCloudVideointelligenceV1p3beta1_CelebrityTrack [GoogleCloudVideointelligenceV1p3beta1_RecognizedCelebrity] gcvvctCelebrities = lens _gcvvctCelebrities (\ s a -> s{_gcvvctCelebrities = a}) . _Default . _Coerce -- | A track of a person\'s face. gcvvctFaceTrack :: Lens' GoogleCloudVideointelligenceV1p3beta1_CelebrityTrack (Maybe GoogleCloudVideointelligenceV1p3beta1_Track) gcvvctFaceTrack = lens _gcvvctFaceTrack (\ s a -> s{_gcvvctFaceTrack = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_CelebrityTrack where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1CelebrityTrack" (\ o -> GoogleCloudVideointelligenceV1p3beta1_CelebrityTrack' <$> (o .:? "celebrities" .!= mempty) <*> (o .:? "faceTrack")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_CelebrityTrack where toJSON GoogleCloudVideointelligenceV1p3beta1_CelebrityTrack'{..} = object (catMaybes [("celebrities" .=) <$> _gcvvctCelebrities, ("faceTrack" .=) <$> _gcvvctFaceTrack]) -- | A track of an object instance. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_Track' smart constructor. data GoogleCloudVideointelligenceV1beta2_Track = GoogleCloudVideointelligenceV1beta2_Track' { _gcvvt2Confidence :: !(Maybe (Textual Double)) , _gcvvt2Attributes :: !(Maybe [GoogleCloudVideointelligenceV1beta2_DetectedAttribute]) , _gcvvt2Segment :: !(Maybe GoogleCloudVideointelligenceV1beta2_VideoSegment) , _gcvvt2TimestampedObjects :: !(Maybe [GoogleCloudVideointelligenceV1beta2_TimestampedObject]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_Track' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvt2Confidence' -- -- * 'gcvvt2Attributes' -- -- * 'gcvvt2Segment' -- -- * 'gcvvt2TimestampedObjects' googleCloudVideointelligenceV1beta2_Track :: GoogleCloudVideointelligenceV1beta2_Track googleCloudVideointelligenceV1beta2_Track = GoogleCloudVideointelligenceV1beta2_Track' { _gcvvt2Confidence = Nothing , _gcvvt2Attributes = Nothing , _gcvvt2Segment = Nothing , _gcvvt2TimestampedObjects = Nothing } -- | Optional. The confidence score of the tracked object. gcvvt2Confidence :: Lens' GoogleCloudVideointelligenceV1beta2_Track (Maybe Double) gcvvt2Confidence = lens _gcvvt2Confidence (\ s a -> s{_gcvvt2Confidence = a}) . mapping _Coerce -- | Optional. Attributes in the track level. gcvvt2Attributes :: Lens' GoogleCloudVideointelligenceV1beta2_Track [GoogleCloudVideointelligenceV1beta2_DetectedAttribute] gcvvt2Attributes = lens _gcvvt2Attributes (\ s a -> s{_gcvvt2Attributes = a}) . _Default . _Coerce -- | Video segment of a track. gcvvt2Segment :: Lens' GoogleCloudVideointelligenceV1beta2_Track (Maybe GoogleCloudVideointelligenceV1beta2_VideoSegment) gcvvt2Segment = lens _gcvvt2Segment (\ s a -> s{_gcvvt2Segment = a}) -- | The object with timestamp and attributes per frame in the track. gcvvt2TimestampedObjects :: Lens' GoogleCloudVideointelligenceV1beta2_Track [GoogleCloudVideointelligenceV1beta2_TimestampedObject] gcvvt2TimestampedObjects = lens _gcvvt2TimestampedObjects (\ s a -> s{_gcvvt2TimestampedObjects = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1beta2_Track where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2Track" (\ o -> GoogleCloudVideointelligenceV1beta2_Track' <$> (o .:? "confidence") <*> (o .:? "attributes" .!= mempty) <*> (o .:? "segment") <*> (o .:? "timestampedObjects" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1beta2_Track where toJSON GoogleCloudVideointelligenceV1beta2_Track'{..} = object (catMaybes [("confidence" .=) <$> _gcvvt2Confidence, ("attributes" .=) <$> _gcvvt2Attributes, ("segment" .=) <$> _gcvvt2Segment, ("timestampedObjects" .=) <$> _gcvvt2TimestampedObjects]) -- | Video frame level annotations for object detection and tracking. This -- field stores per frame location, time offset, and confidence. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_ObjectTrackingFrame' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingFrame = GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingFrame' { _gcvvotf2TimeOffSet :: !(Maybe GDuration) , _gcvvotf2NormalizedBoundingBox :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvotf2TimeOffSet' -- -- * 'gcvvotf2NormalizedBoundingBox' googleCloudVideointelligenceV1p3beta1_ObjectTrackingFrame :: GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingFrame googleCloudVideointelligenceV1p3beta1_ObjectTrackingFrame = GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingFrame' {_gcvvotf2TimeOffSet = Nothing, _gcvvotf2NormalizedBoundingBox = Nothing} -- | The timestamp of the frame in microseconds. gcvvotf2TimeOffSet :: Lens' GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingFrame (Maybe Scientific) gcvvotf2TimeOffSet = lens _gcvvotf2TimeOffSet (\ s a -> s{_gcvvotf2TimeOffSet = a}) . mapping _GDuration -- | The normalized bounding box location of this object track for the frame. gcvvotf2NormalizedBoundingBox :: Lens' GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingFrame (Maybe GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox) gcvvotf2NormalizedBoundingBox = lens _gcvvotf2NormalizedBoundingBox (\ s a -> s{_gcvvotf2NormalizedBoundingBox = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1ObjectTrackingFrame" (\ o -> GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingFrame' <$> (o .:? "timeOffset") <*> (o .:? "normalizedBoundingBox")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingFrame where toJSON GoogleCloudVideointelligenceV1p3beta1_ObjectTrackingFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvotf2TimeOffSet, ("normalizedBoundingBox" .=) <$> _gcvvotf2NormalizedBoundingBox]) -- | Annotations corresponding to one tracked object. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation = GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation' { _gcvvota2Frames :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingFrame]) , _gcvvota2Confidence :: !(Maybe (Textual Double)) , _gcvvota2Version :: !(Maybe Text) , _gcvvota2TrackId :: !(Maybe (Textual Int64)) , _gcvvota2Segment :: !(Maybe GoogleCloudVideointelligenceV1p1beta1_VideoSegment) , _gcvvota2Entity :: !(Maybe GoogleCloudVideointelligenceV1p1beta1_Entity) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvota2Frames' -- -- * 'gcvvota2Confidence' -- -- * 'gcvvota2Version' -- -- * 'gcvvota2TrackId' -- -- * 'gcvvota2Segment' -- -- * 'gcvvota2Entity' googleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation :: GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation googleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation = GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation' { _gcvvota2Frames = Nothing , _gcvvota2Confidence = Nothing , _gcvvota2Version = Nothing , _gcvvota2TrackId = Nothing , _gcvvota2Segment = Nothing , _gcvvota2Entity = Nothing } -- | Information corresponding to all frames where this object track appears. -- Non-streaming batch mode: it may be one or multiple ObjectTrackingFrame -- messages in frames. Streaming mode: it can only be one -- ObjectTrackingFrame message in frames. gcvvota2Frames :: Lens' GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation [GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingFrame] gcvvota2Frames = lens _gcvvota2Frames (\ s a -> s{_gcvvota2Frames = a}) . _Default . _Coerce -- | Object category\'s labeling confidence of this track. gcvvota2Confidence :: Lens' GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation (Maybe Double) gcvvota2Confidence = lens _gcvvota2Confidence (\ s a -> s{_gcvvota2Confidence = a}) . mapping _Coerce -- | Feature version. gcvvota2Version :: Lens' GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation (Maybe Text) gcvvota2Version = lens _gcvvota2Version (\ s a -> s{_gcvvota2Version = a}) -- | Streaming mode ONLY. In streaming mode, we do not know the end time of a -- tracked object before it is completed. Hence, there is no VideoSegment -- info returned. Instead, we provide a unique identifiable integer -- track_id so that the customers can correlate the results of the ongoing -- ObjectTrackAnnotation of the same track_id over time. gcvvota2TrackId :: Lens' GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation (Maybe Int64) gcvvota2TrackId = lens _gcvvota2TrackId (\ s a -> s{_gcvvota2TrackId = a}) . mapping _Coerce -- | Non-streaming batch mode ONLY. Each object track corresponds to one -- video segment where it appears. gcvvota2Segment :: Lens' GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation (Maybe GoogleCloudVideointelligenceV1p1beta1_VideoSegment) gcvvota2Segment = lens _gcvvota2Segment (\ s a -> s{_gcvvota2Segment = a}) -- | Entity to specify the object category that this track is labeled as. gcvvota2Entity :: Lens' GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation (Maybe GoogleCloudVideointelligenceV1p1beta1_Entity) gcvvota2Entity = lens _gcvvota2Entity (\ s a -> s{_gcvvota2Entity = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1ObjectTrackingAnnotation" (\ o -> GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation' <$> (o .:? "frames" .!= mempty) <*> (o .:? "confidence") <*> (o .:? "version") <*> (o .:? "trackId") <*> (o .:? "segment") <*> (o .:? "entity")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation where toJSON GoogleCloudVideointelligenceV1p1beta1_ObjectTrackingAnnotation'{..} = object (catMaybes [("frames" .=) <$> _gcvvota2Frames, ("confidence" .=) <$> _gcvvota2Confidence, ("version" .=) <$> _gcvvota2Version, ("trackId" .=) <$> _gcvvota2TrackId, ("segment" .=) <$> _gcvvota2Segment, ("entity" .=) <$> _gcvvota2Entity]) -- | Normalized bounding box. The normalized vertex coordinates are relative -- to the original image. Range: [0, 1]. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox = GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox' { _ggBottom :: !(Maybe (Textual Double)) , _ggLeft :: !(Maybe (Textual Double)) , _ggRight :: !(Maybe (Textual Double)) , _ggTop :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ggBottom' -- -- * 'ggLeft' -- -- * 'ggRight' -- -- * 'ggTop' googleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox :: GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox googleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox = GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox' { _ggBottom = Nothing , _ggLeft = Nothing , _ggRight = Nothing , _ggTop = Nothing } -- | Bottom Y coordinate. ggBottom :: Lens' GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox (Maybe Double) ggBottom = lens _ggBottom (\ s a -> s{_ggBottom = a}) . mapping _Coerce -- | Left X coordinate. ggLeft :: Lens' GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox (Maybe Double) ggLeft = lens _ggLeft (\ s a -> s{_ggLeft = a}) . mapping _Coerce -- | Right X coordinate. ggRight :: Lens' GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox (Maybe Double) ggRight = lens _ggRight (\ s a -> s{_ggRight = a}) . mapping _Coerce -- | Top Y coordinate. ggTop :: Lens' GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox (Maybe Double) ggTop = lens _ggTop (\ s a -> s{_ggTop = a}) . mapping _Coerce instance FromJSON GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1NormalizedBoundingBox" (\ o -> GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox' <$> (o .:? "bottom") <*> (o .:? "left") <*> (o .:? "right") <*> (o .:? "top")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox where toJSON GoogleCloudVideointelligenceV1p2beta1_NormalizedBoundingBox'{..} = object (catMaybes [("bottom" .=) <$> _ggBottom, ("left" .=) <$> _ggLeft, ("right" .=) <$> _ggRight, ("top" .=) <$> _ggTop]) -- | Video segment level annotation results for text detection. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_TextSegment' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_TextSegment = GoogleCloudVideointelligenceV1p2beta1_TextSegment' { _goo2Frames :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_TextFrame]) , _goo2Confidence :: !(Maybe (Textual Double)) , _goo2Segment :: !(Maybe GoogleCloudVideointelligenceV1p2beta1_VideoSegment) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_TextSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'goo2Frames' -- -- * 'goo2Confidence' -- -- * 'goo2Segment' googleCloudVideointelligenceV1p2beta1_TextSegment :: GoogleCloudVideointelligenceV1p2beta1_TextSegment googleCloudVideointelligenceV1p2beta1_TextSegment = GoogleCloudVideointelligenceV1p2beta1_TextSegment' {_goo2Frames = Nothing, _goo2Confidence = Nothing, _goo2Segment = Nothing} -- | Information related to the frames where OCR detected text appears. goo2Frames :: Lens' GoogleCloudVideointelligenceV1p2beta1_TextSegment [GoogleCloudVideointelligenceV1p2beta1_TextFrame] goo2Frames = lens _goo2Frames (\ s a -> s{_goo2Frames = a}) . _Default . _Coerce -- | Confidence for the track of detected text. It is calculated as the -- highest over all frames where OCR detected text appears. goo2Confidence :: Lens' GoogleCloudVideointelligenceV1p2beta1_TextSegment (Maybe Double) goo2Confidence = lens _goo2Confidence (\ s a -> s{_goo2Confidence = a}) . mapping _Coerce -- | Video segment where a text snippet was detected. goo2Segment :: Lens' GoogleCloudVideointelligenceV1p2beta1_TextSegment (Maybe GoogleCloudVideointelligenceV1p2beta1_VideoSegment) goo2Segment = lens _goo2Segment (\ s a -> s{_goo2Segment = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_TextSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1TextSegment" (\ o -> GoogleCloudVideointelligenceV1p2beta1_TextSegment' <$> (o .:? "frames" .!= mempty) <*> (o .:? "confidence") <*> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_TextSegment where toJSON GoogleCloudVideointelligenceV1p2beta1_TextSegment'{..} = object (catMaybes [("frames" .=) <$> _goo2Frames, ("confidence" .=) <$> _goo2Confidence, ("segment" .=) <$> _goo2Segment]) -- | A speech recognition result corresponding to a portion of the audio. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_SpeechTranscription' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_SpeechTranscription = GoogleCloudVideointelligenceV1p2beta1_SpeechTranscription' { _goo1Alternatives :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative]) , _goo1LanguageCode :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_SpeechTranscription' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'goo1Alternatives' -- -- * 'goo1LanguageCode' googleCloudVideointelligenceV1p2beta1_SpeechTranscription :: GoogleCloudVideointelligenceV1p2beta1_SpeechTranscription googleCloudVideointelligenceV1p2beta1_SpeechTranscription = GoogleCloudVideointelligenceV1p2beta1_SpeechTranscription' {_goo1Alternatives = Nothing, _goo1LanguageCode = Nothing} -- | May contain one or more recognition hypotheses (up to the maximum -- specified in \`max_alternatives\`). These alternatives are ordered in -- terms of accuracy, with the top (first) alternative being the most -- probable, as ranked by the recognizer. goo1Alternatives :: Lens' GoogleCloudVideointelligenceV1p2beta1_SpeechTranscription [GoogleCloudVideointelligenceV1p2beta1_SpeechRecognitionAlternative] goo1Alternatives = lens _goo1Alternatives (\ s a -> s{_goo1Alternatives = a}) . _Default . _Coerce -- | Output only. The -- [BCP-47](https:\/\/www.rfc-editor.org\/rfc\/bcp\/bcp47.txt) language tag -- of the language in this result. This language code was detected to have -- the most likelihood of being spoken in the audio. goo1LanguageCode :: Lens' GoogleCloudVideointelligenceV1p2beta1_SpeechTranscription (Maybe Text) goo1LanguageCode = lens _goo1LanguageCode (\ s a -> s{_goo1LanguageCode = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_SpeechTranscription where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1SpeechTranscription" (\ o -> GoogleCloudVideointelligenceV1p2beta1_SpeechTranscription' <$> (o .:? "alternatives" .!= mempty) <*> (o .:? "languageCode")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_SpeechTranscription where toJSON GoogleCloudVideointelligenceV1p2beta1_SpeechTranscription'{..} = object (catMaybes [("alternatives" .=) <$> _goo1Alternatives, ("languageCode" .=) <$> _goo1LanguageCode]) -- | The \`Status\` type defines a logical error model that is suitable for -- different programming environments, including REST APIs and RPC APIs. It -- is used by [gRPC](https:\/\/github.com\/grpc). Each \`Status\` message -- contains three pieces of data: error code, error message, and error -- details. You can find out more about this error model and how to work -- with it in the [API Design -- Guide](https:\/\/cloud.google.com\/apis\/design\/errors). -- -- /See:/ 'googleRpc_Status' smart constructor. data GoogleRpc_Status = GoogleRpc_Status' { _grsDetails :: !(Maybe [GoogleRpc_StatusDetailsItem]) , _grsCode :: !(Maybe (Textual Int32)) , _grsMessage :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleRpc_Status' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'grsDetails' -- -- * 'grsCode' -- -- * 'grsMessage' googleRpc_Status :: GoogleRpc_Status googleRpc_Status = GoogleRpc_Status' {_grsDetails = Nothing, _grsCode = Nothing, _grsMessage = Nothing} -- | A list of messages that carry the error details. There is a common set -- of message types for APIs to use. grsDetails :: Lens' GoogleRpc_Status [GoogleRpc_StatusDetailsItem] grsDetails = lens _grsDetails (\ s a -> s{_grsDetails = a}) . _Default . _Coerce -- | The status code, which should be an enum value of google.rpc.Code. grsCode :: Lens' GoogleRpc_Status (Maybe Int32) grsCode = lens _grsCode (\ s a -> s{_grsCode = a}) . mapping _Coerce -- | A developer-facing error message, which should be in English. Any -- user-facing error message should be localized and sent in the -- google.rpc.Status.details field, or localized by the client. grsMessage :: Lens' GoogleRpc_Status (Maybe Text) grsMessage = lens _grsMessage (\ s a -> s{_grsMessage = a}) instance FromJSON GoogleRpc_Status where parseJSON = withObject "GoogleRpcStatus" (\ o -> GoogleRpc_Status' <$> (o .:? "details" .!= mempty) <*> (o .:? "code") <*> (o .:? "message")) instance ToJSON GoogleRpc_Status where toJSON GoogleRpc_Status'{..} = object (catMaybes [("details" .=) <$> _grsDetails, ("code" .=) <$> _grsCode, ("message" .=) <$> _grsMessage]) -- | Video frame level annotations for object detection and tracking. This -- field stores per frame location, time offset, and confidence. -- -- /See:/ 'googleCloudVideointelligenceV1_ObjectTrackingFrame' smart constructor. data GoogleCloudVideointelligenceV1_ObjectTrackingFrame = GoogleCloudVideointelligenceV1_ObjectTrackingFrame' { _g2TimeOffSet :: !(Maybe GDuration) , _g2NormalizedBoundingBox :: !(Maybe GoogleCloudVideointelligenceV1_NormalizedBoundingBox) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_ObjectTrackingFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'g2TimeOffSet' -- -- * 'g2NormalizedBoundingBox' googleCloudVideointelligenceV1_ObjectTrackingFrame :: GoogleCloudVideointelligenceV1_ObjectTrackingFrame googleCloudVideointelligenceV1_ObjectTrackingFrame = GoogleCloudVideointelligenceV1_ObjectTrackingFrame' {_g2TimeOffSet = Nothing, _g2NormalizedBoundingBox = Nothing} -- | The timestamp of the frame in microseconds. g2TimeOffSet :: Lens' GoogleCloudVideointelligenceV1_ObjectTrackingFrame (Maybe Scientific) g2TimeOffSet = lens _g2TimeOffSet (\ s a -> s{_g2TimeOffSet = a}) . mapping _GDuration -- | The normalized bounding box location of this object track for the frame. g2NormalizedBoundingBox :: Lens' GoogleCloudVideointelligenceV1_ObjectTrackingFrame (Maybe GoogleCloudVideointelligenceV1_NormalizedBoundingBox) g2NormalizedBoundingBox = lens _g2NormalizedBoundingBox (\ s a -> s{_g2NormalizedBoundingBox = a}) instance FromJSON GoogleCloudVideointelligenceV1_ObjectTrackingFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1ObjectTrackingFrame" (\ o -> GoogleCloudVideointelligenceV1_ObjectTrackingFrame' <$> (o .:? "timeOffset") <*> (o .:? "normalizedBoundingBox")) instance ToJSON GoogleCloudVideointelligenceV1_ObjectTrackingFrame where toJSON GoogleCloudVideointelligenceV1_ObjectTrackingFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _g2TimeOffSet, ("normalizedBoundingBox" .=) <$> _g2NormalizedBoundingBox]) -- | Deprecated. No effect. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_FaceAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_FaceAnnotation = GoogleCloudVideointelligenceV1p2beta1_FaceAnnotation' { _gcvvfa2Thumbnail :: !(Maybe Bytes) , _gcvvfa2Frames :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_FaceFrame]) , _gcvvfa2Segments :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_FaceSegment]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_FaceAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvfa2Thumbnail' -- -- * 'gcvvfa2Frames' -- -- * 'gcvvfa2Segments' googleCloudVideointelligenceV1p2beta1_FaceAnnotation :: GoogleCloudVideointelligenceV1p2beta1_FaceAnnotation googleCloudVideointelligenceV1p2beta1_FaceAnnotation = GoogleCloudVideointelligenceV1p2beta1_FaceAnnotation' { _gcvvfa2Thumbnail = Nothing , _gcvvfa2Frames = Nothing , _gcvvfa2Segments = Nothing } -- | Thumbnail of a representative face view (in JPEG format). gcvvfa2Thumbnail :: Lens' GoogleCloudVideointelligenceV1p2beta1_FaceAnnotation (Maybe ByteString) gcvvfa2Thumbnail = lens _gcvvfa2Thumbnail (\ s a -> s{_gcvvfa2Thumbnail = a}) . mapping _Bytes -- | All video frames where a face was detected. gcvvfa2Frames :: Lens' GoogleCloudVideointelligenceV1p2beta1_FaceAnnotation [GoogleCloudVideointelligenceV1p2beta1_FaceFrame] gcvvfa2Frames = lens _gcvvfa2Frames (\ s a -> s{_gcvvfa2Frames = a}) . _Default . _Coerce -- | All video segments where a face was detected. gcvvfa2Segments :: Lens' GoogleCloudVideointelligenceV1p2beta1_FaceAnnotation [GoogleCloudVideointelligenceV1p2beta1_FaceSegment] gcvvfa2Segments = lens _gcvvfa2Segments (\ s a -> s{_gcvvfa2Segments = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p2beta1_FaceAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1FaceAnnotation" (\ o -> GoogleCloudVideointelligenceV1p2beta1_FaceAnnotation' <$> (o .:? "thumbnail") <*> (o .:? "frames" .!= mempty) <*> (o .:? "segments" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_FaceAnnotation where toJSON GoogleCloudVideointelligenceV1p2beta1_FaceAnnotation'{..} = object (catMaybes [("thumbnail" .=) <$> _gcvvfa2Thumbnail, ("frames" .=) <$> _gcvvfa2Frames, ("segments" .=) <$> _gcvvfa2Segments]) -- | Video segment level annotation results for face detection. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_FaceSegment' smart constructor. newtype GoogleCloudVideointelligenceV1beta2_FaceSegment = GoogleCloudVideointelligenceV1beta2_FaceSegment' { _gcvvfs1Segment :: Maybe GoogleCloudVideointelligenceV1beta2_VideoSegment } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_FaceSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvfs1Segment' googleCloudVideointelligenceV1beta2_FaceSegment :: GoogleCloudVideointelligenceV1beta2_FaceSegment googleCloudVideointelligenceV1beta2_FaceSegment = GoogleCloudVideointelligenceV1beta2_FaceSegment' {_gcvvfs1Segment = Nothing} -- | Video segment where a face was detected. gcvvfs1Segment :: Lens' GoogleCloudVideointelligenceV1beta2_FaceSegment (Maybe GoogleCloudVideointelligenceV1beta2_VideoSegment) gcvvfs1Segment = lens _gcvvfs1Segment (\ s a -> s{_gcvvfs1Segment = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_FaceSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2FaceSegment" (\ o -> GoogleCloudVideointelligenceV1beta2_FaceSegment' <$> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1beta2_FaceSegment where toJSON GoogleCloudVideointelligenceV1beta2_FaceSegment'{..} = object (catMaybes [("segment" .=) <$> _gcvvfs1Segment]) -- | Video segment. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_VideoSegment' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_VideoSegment = GoogleCloudVideointelligenceV1p3beta1_VideoSegment' { _gcvvvscStartTimeOffSet :: !(Maybe GDuration) , _gcvvvscEndTimeOffSet :: !(Maybe GDuration) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_VideoSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvvscStartTimeOffSet' -- -- * 'gcvvvscEndTimeOffSet' googleCloudVideointelligenceV1p3beta1_VideoSegment :: GoogleCloudVideointelligenceV1p3beta1_VideoSegment googleCloudVideointelligenceV1p3beta1_VideoSegment = GoogleCloudVideointelligenceV1p3beta1_VideoSegment' {_gcvvvscStartTimeOffSet = Nothing, _gcvvvscEndTimeOffSet = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the start of the segment (inclusive). gcvvvscStartTimeOffSet :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoSegment (Maybe Scientific) gcvvvscStartTimeOffSet = lens _gcvvvscStartTimeOffSet (\ s a -> s{_gcvvvscStartTimeOffSet = a}) . mapping _GDuration -- | Time-offset, relative to the beginning of the video, corresponding to -- the end of the segment (inclusive). gcvvvscEndTimeOffSet :: Lens' GoogleCloudVideointelligenceV1p3beta1_VideoSegment (Maybe Scientific) gcvvvscEndTimeOffSet = lens _gcvvvscEndTimeOffSet (\ s a -> s{_gcvvvscEndTimeOffSet = a}) . mapping _GDuration instance FromJSON GoogleCloudVideointelligenceV1p3beta1_VideoSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1VideoSegment" (\ o -> GoogleCloudVideointelligenceV1p3beta1_VideoSegment' <$> (o .:? "startTimeOffset") <*> (o .:? "endTimeOffset")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_VideoSegment where toJSON GoogleCloudVideointelligenceV1p3beta1_VideoSegment'{..} = object (catMaybes [("startTimeOffset" .=) <$> _gcvvvscStartTimeOffSet, ("endTimeOffset" .=) <$> _gcvvvscEndTimeOffSet]) -- | For tracking related features. An object at time_offset with attributes, -- and located with normalized_bounding_box. -- -- /See:/ 'googleCloudVideointelligenceV1_TimestampedObject' smart constructor. data GoogleCloudVideointelligenceV1_TimestampedObject = GoogleCloudVideointelligenceV1_TimestampedObject' { _gcvvto2TimeOffSet :: !(Maybe GDuration) , _gcvvto2Attributes :: !(Maybe [GoogleCloudVideointelligenceV1_DetectedAttribute]) , _gcvvto2NormalizedBoundingBox :: !(Maybe GoogleCloudVideointelligenceV1_NormalizedBoundingBox) , _gcvvto2Landmarks :: !(Maybe [GoogleCloudVideointelligenceV1_DetectedLandmark]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_TimestampedObject' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvto2TimeOffSet' -- -- * 'gcvvto2Attributes' -- -- * 'gcvvto2NormalizedBoundingBox' -- -- * 'gcvvto2Landmarks' googleCloudVideointelligenceV1_TimestampedObject :: GoogleCloudVideointelligenceV1_TimestampedObject googleCloudVideointelligenceV1_TimestampedObject = GoogleCloudVideointelligenceV1_TimestampedObject' { _gcvvto2TimeOffSet = Nothing , _gcvvto2Attributes = Nothing , _gcvvto2NormalizedBoundingBox = Nothing , _gcvvto2Landmarks = Nothing } -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this object. gcvvto2TimeOffSet :: Lens' GoogleCloudVideointelligenceV1_TimestampedObject (Maybe Scientific) gcvvto2TimeOffSet = lens _gcvvto2TimeOffSet (\ s a -> s{_gcvvto2TimeOffSet = a}) . mapping _GDuration -- | Optional. The attributes of the object in the bounding box. gcvvto2Attributes :: Lens' GoogleCloudVideointelligenceV1_TimestampedObject [GoogleCloudVideointelligenceV1_DetectedAttribute] gcvvto2Attributes = lens _gcvvto2Attributes (\ s a -> s{_gcvvto2Attributes = a}) . _Default . _Coerce -- | Normalized Bounding box in a frame, where the object is located. gcvvto2NormalizedBoundingBox :: Lens' GoogleCloudVideointelligenceV1_TimestampedObject (Maybe GoogleCloudVideointelligenceV1_NormalizedBoundingBox) gcvvto2NormalizedBoundingBox = lens _gcvvto2NormalizedBoundingBox (\ s a -> s{_gcvvto2NormalizedBoundingBox = a}) -- | Optional. The detected landmarks. gcvvto2Landmarks :: Lens' GoogleCloudVideointelligenceV1_TimestampedObject [GoogleCloudVideointelligenceV1_DetectedLandmark] gcvvto2Landmarks = lens _gcvvto2Landmarks (\ s a -> s{_gcvvto2Landmarks = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1_TimestampedObject where parseJSON = withObject "GoogleCloudVideointelligenceV1TimestampedObject" (\ o -> GoogleCloudVideointelligenceV1_TimestampedObject' <$> (o .:? "timeOffset") <*> (o .:? "attributes" .!= mempty) <*> (o .:? "normalizedBoundingBox") <*> (o .:? "landmarks" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1_TimestampedObject where toJSON GoogleCloudVideointelligenceV1_TimestampedObject'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvto2TimeOffSet, ("attributes" .=) <$> _gcvvto2Attributes, ("normalizedBoundingBox" .=) <$> _gcvvto2NormalizedBoundingBox, ("landmarks" .=) <$> _gcvvto2Landmarks]) -- | A generic detected attribute represented by name in string format. -- -- /See:/ 'googleCloudVideointelligenceV1_DetectedAttribute' smart constructor. data GoogleCloudVideointelligenceV1_DetectedAttribute = GoogleCloudVideointelligenceV1_DetectedAttribute' { _gcvvda2Value :: !(Maybe Text) , _gcvvda2Confidence :: !(Maybe (Textual Double)) , _gcvvda2Name :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_DetectedAttribute' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvda2Value' -- -- * 'gcvvda2Confidence' -- -- * 'gcvvda2Name' googleCloudVideointelligenceV1_DetectedAttribute :: GoogleCloudVideointelligenceV1_DetectedAttribute googleCloudVideointelligenceV1_DetectedAttribute = GoogleCloudVideointelligenceV1_DetectedAttribute' { _gcvvda2Value = Nothing , _gcvvda2Confidence = Nothing , _gcvvda2Name = Nothing } -- | Text value of the detection result. For example, the value for -- \"HairColor\" can be \"black\", \"blonde\", etc. gcvvda2Value :: Lens' GoogleCloudVideointelligenceV1_DetectedAttribute (Maybe Text) gcvvda2Value = lens _gcvvda2Value (\ s a -> s{_gcvvda2Value = a}) -- | Detected attribute confidence. Range [0, 1]. gcvvda2Confidence :: Lens' GoogleCloudVideointelligenceV1_DetectedAttribute (Maybe Double) gcvvda2Confidence = lens _gcvvda2Confidence (\ s a -> s{_gcvvda2Confidence = a}) . mapping _Coerce -- | The name of the attribute, for example, glasses, dark_glasses, -- mouth_open. A full list of supported type names will be provided in the -- document. gcvvda2Name :: Lens' GoogleCloudVideointelligenceV1_DetectedAttribute (Maybe Text) gcvvda2Name = lens _gcvvda2Name (\ s a -> s{_gcvvda2Name = a}) instance FromJSON GoogleCloudVideointelligenceV1_DetectedAttribute where parseJSON = withObject "GoogleCloudVideointelligenceV1DetectedAttribute" (\ o -> GoogleCloudVideointelligenceV1_DetectedAttribute' <$> (o .:? "value") <*> (o .:? "confidence") <*> (o .:? "name")) instance ToJSON GoogleCloudVideointelligenceV1_DetectedAttribute where toJSON GoogleCloudVideointelligenceV1_DetectedAttribute'{..} = object (catMaybes [("value" .=) <$> _gcvvda2Value, ("confidence" .=) <$> _gcvvda2Confidence, ("name" .=) <$> _gcvvda2Name]) -- | Annotation corresponding to one detected, tracked and recognized logo -- class. -- -- /See:/ 'googleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation = GoogleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation' { _gcvvlra2Tracks :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_Track]) , _gcvvlra2Segments :: !(Maybe [GoogleCloudVideointelligenceV1p2beta1_VideoSegment]) , _gcvvlra2Entity :: !(Maybe GoogleCloudVideointelligenceV1p2beta1_Entity) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvlra2Tracks' -- -- * 'gcvvlra2Segments' -- -- * 'gcvvlra2Entity' googleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation :: GoogleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation googleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation = GoogleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation' { _gcvvlra2Tracks = Nothing , _gcvvlra2Segments = Nothing , _gcvvlra2Entity = Nothing } -- | All logo tracks where the recognized logo appears. Each track -- corresponds to one logo instance appearing in consecutive frames. gcvvlra2Tracks :: Lens' GoogleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation [GoogleCloudVideointelligenceV1p2beta1_Track] gcvvlra2Tracks = lens _gcvvlra2Tracks (\ s a -> s{_gcvvlra2Tracks = a}) . _Default . _Coerce -- | All video segments where the recognized logo appears. There might be -- multiple instances of the same logo class appearing in one VideoSegment. gcvvlra2Segments :: Lens' GoogleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation [GoogleCloudVideointelligenceV1p2beta1_VideoSegment] gcvvlra2Segments = lens _gcvvlra2Segments (\ s a -> s{_gcvvlra2Segments = a}) . _Default . _Coerce -- | Entity category information to specify the logo class that all the logo -- tracks within this LogoRecognitionAnnotation are recognized as. gcvvlra2Entity :: Lens' GoogleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation (Maybe GoogleCloudVideointelligenceV1p2beta1_Entity) gcvvlra2Entity = lens _gcvvlra2Entity (\ s a -> s{_gcvvlra2Entity = a}) instance FromJSON GoogleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p2beta1LogoRecognitionAnnotation" (\ o -> GoogleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation' <$> (o .:? "tracks" .!= mempty) <*> (o .:? "segments" .!= mempty) <*> (o .:? "entity")) instance ToJSON GoogleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation where toJSON GoogleCloudVideointelligenceV1p2beta1_LogoRecognitionAnnotation'{..} = object (catMaybes [("tracks" .=) <$> _gcvvlra2Tracks, ("segments" .=) <$> _gcvvlra2Segments, ("entity" .=) <$> _gcvvlra2Entity]) -- | Annotations related to one detected OCR text snippet. This will contain -- the corresponding text, confidence value, and frame level information -- for each detection. -- -- /See:/ 'googleCloudVideointelligenceV1_TextAnnotation' smart constructor. data GoogleCloudVideointelligenceV1_TextAnnotation = GoogleCloudVideointelligenceV1_TextAnnotation' { _gcvvta1Text :: !(Maybe Text) , _gcvvta1Version :: !(Maybe Text) , _gcvvta1Segments :: !(Maybe [GoogleCloudVideointelligenceV1_TextSegment]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_TextAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvta1Text' -- -- * 'gcvvta1Version' -- -- * 'gcvvta1Segments' googleCloudVideointelligenceV1_TextAnnotation :: GoogleCloudVideointelligenceV1_TextAnnotation googleCloudVideointelligenceV1_TextAnnotation = GoogleCloudVideointelligenceV1_TextAnnotation' { _gcvvta1Text = Nothing , _gcvvta1Version = Nothing , _gcvvta1Segments = Nothing } -- | The detected text. gcvvta1Text :: Lens' GoogleCloudVideointelligenceV1_TextAnnotation (Maybe Text) gcvvta1Text = lens _gcvvta1Text (\ s a -> s{_gcvvta1Text = a}) -- | Feature version. gcvvta1Version :: Lens' GoogleCloudVideointelligenceV1_TextAnnotation (Maybe Text) gcvvta1Version = lens _gcvvta1Version (\ s a -> s{_gcvvta1Version = a}) -- | All video segments where OCR detected text appears. gcvvta1Segments :: Lens' GoogleCloudVideointelligenceV1_TextAnnotation [GoogleCloudVideointelligenceV1_TextSegment] gcvvta1Segments = lens _gcvvta1Segments (\ s a -> s{_gcvvta1Segments = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1_TextAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1TextAnnotation" (\ o -> GoogleCloudVideointelligenceV1_TextAnnotation' <$> (o .:? "text") <*> (o .:? "version") <*> (o .:? "segments" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1_TextAnnotation where toJSON GoogleCloudVideointelligenceV1_TextAnnotation'{..} = object (catMaybes [("text" .=) <$> _gcvvta1Text, ("version" .=) <$> _gcvvta1Version, ("segments" .=) <$> _gcvvta1Segments]) -- | Video segment. -- -- /See:/ 'googleCloudVideointelligenceV1_VideoSegment' smart constructor. data GoogleCloudVideointelligenceV1_VideoSegment = GoogleCloudVideointelligenceV1_VideoSegment' { _ggStartTimeOffSet :: !(Maybe GDuration) , _ggEndTimeOffSet :: !(Maybe GDuration) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_VideoSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ggStartTimeOffSet' -- -- * 'ggEndTimeOffSet' googleCloudVideointelligenceV1_VideoSegment :: GoogleCloudVideointelligenceV1_VideoSegment googleCloudVideointelligenceV1_VideoSegment = GoogleCloudVideointelligenceV1_VideoSegment' {_ggStartTimeOffSet = Nothing, _ggEndTimeOffSet = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the start of the segment (inclusive). ggStartTimeOffSet :: Lens' GoogleCloudVideointelligenceV1_VideoSegment (Maybe Scientific) ggStartTimeOffSet = lens _ggStartTimeOffSet (\ s a -> s{_ggStartTimeOffSet = a}) . mapping _GDuration -- | Time-offset, relative to the beginning of the video, corresponding to -- the end of the segment (inclusive). ggEndTimeOffSet :: Lens' GoogleCloudVideointelligenceV1_VideoSegment (Maybe Scientific) ggEndTimeOffSet = lens _ggEndTimeOffSet (\ s a -> s{_ggEndTimeOffSet = a}) . mapping _GDuration instance FromJSON GoogleCloudVideointelligenceV1_VideoSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1VideoSegment" (\ o -> GoogleCloudVideointelligenceV1_VideoSegment' <$> (o .:? "startTimeOffset") <*> (o .:? "endTimeOffset")) instance ToJSON GoogleCloudVideointelligenceV1_VideoSegment where toJSON GoogleCloudVideointelligenceV1_VideoSegment'{..} = object (catMaybes [("startTimeOffset" .=) <$> _ggStartTimeOffSet, ("endTimeOffset" .=) <$> _ggEndTimeOffSet]) -- | For tracking related features. An object at time_offset with attributes, -- and located with normalized_bounding_box. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_TimestampedObject' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_TimestampedObject = GoogleCloudVideointelligenceV1p3beta1_TimestampedObject' { _goo2TimeOffSet :: !(Maybe GDuration) , _goo2Attributes :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_DetectedAttribute]) , _goo2NormalizedBoundingBox :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox) , _goo2Landmarks :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_DetectedLandmark]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_TimestampedObject' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'goo2TimeOffSet' -- -- * 'goo2Attributes' -- -- * 'goo2NormalizedBoundingBox' -- -- * 'goo2Landmarks' googleCloudVideointelligenceV1p3beta1_TimestampedObject :: GoogleCloudVideointelligenceV1p3beta1_TimestampedObject googleCloudVideointelligenceV1p3beta1_TimestampedObject = GoogleCloudVideointelligenceV1p3beta1_TimestampedObject' { _goo2TimeOffSet = Nothing , _goo2Attributes = Nothing , _goo2NormalizedBoundingBox = Nothing , _goo2Landmarks = Nothing } -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this object. goo2TimeOffSet :: Lens' GoogleCloudVideointelligenceV1p3beta1_TimestampedObject (Maybe Scientific) goo2TimeOffSet = lens _goo2TimeOffSet (\ s a -> s{_goo2TimeOffSet = a}) . mapping _GDuration -- | Optional. The attributes of the object in the bounding box. goo2Attributes :: Lens' GoogleCloudVideointelligenceV1p3beta1_TimestampedObject [GoogleCloudVideointelligenceV1p3beta1_DetectedAttribute] goo2Attributes = lens _goo2Attributes (\ s a -> s{_goo2Attributes = a}) . _Default . _Coerce -- | Normalized Bounding box in a frame, where the object is located. goo2NormalizedBoundingBox :: Lens' GoogleCloudVideointelligenceV1p3beta1_TimestampedObject (Maybe GoogleCloudVideointelligenceV1p3beta1_NormalizedBoundingBox) goo2NormalizedBoundingBox = lens _goo2NormalizedBoundingBox (\ s a -> s{_goo2NormalizedBoundingBox = a}) -- | Optional. The detected landmarks. goo2Landmarks :: Lens' GoogleCloudVideointelligenceV1p3beta1_TimestampedObject [GoogleCloudVideointelligenceV1p3beta1_DetectedLandmark] goo2Landmarks = lens _goo2Landmarks (\ s a -> s{_goo2Landmarks = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p3beta1_TimestampedObject where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1TimestampedObject" (\ o -> GoogleCloudVideointelligenceV1p3beta1_TimestampedObject' <$> (o .:? "timeOffset") <*> (o .:? "attributes" .!= mempty) <*> (o .:? "normalizedBoundingBox") <*> (o .:? "landmarks" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_TimestampedObject where toJSON GoogleCloudVideointelligenceV1p3beta1_TimestampedObject'{..} = object (catMaybes [("timeOffset" .=) <$> _goo2TimeOffSet, ("attributes" .=) <$> _goo2Attributes, ("normalizedBoundingBox" .=) <$> _goo2NormalizedBoundingBox, ("landmarks" .=) <$> _goo2Landmarks]) -- | Explicit content annotation (based on per-frame visual signals only). If -- no explicit content has been detected in a frame, no annotations are -- present for that frame. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_ExplicitContentAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_ExplicitContentAnnotation = GoogleCloudVideointelligenceV1p1beta1_ExplicitContentAnnotation' { _gcvveca2Frames :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_ExplicitContentFrame]) , _gcvveca2Version :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_ExplicitContentAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvveca2Frames' -- -- * 'gcvveca2Version' googleCloudVideointelligenceV1p1beta1_ExplicitContentAnnotation :: GoogleCloudVideointelligenceV1p1beta1_ExplicitContentAnnotation googleCloudVideointelligenceV1p1beta1_ExplicitContentAnnotation = GoogleCloudVideointelligenceV1p1beta1_ExplicitContentAnnotation' {_gcvveca2Frames = Nothing, _gcvveca2Version = Nothing} -- | All video frames where explicit content was detected. gcvveca2Frames :: Lens' GoogleCloudVideointelligenceV1p1beta1_ExplicitContentAnnotation [GoogleCloudVideointelligenceV1p1beta1_ExplicitContentFrame] gcvveca2Frames = lens _gcvveca2Frames (\ s a -> s{_gcvveca2Frames = a}) . _Default . _Coerce -- | Feature version. gcvveca2Version :: Lens' GoogleCloudVideointelligenceV1p1beta1_ExplicitContentAnnotation (Maybe Text) gcvveca2Version = lens _gcvveca2Version (\ s a -> s{_gcvveca2Version = a}) instance FromJSON GoogleCloudVideointelligenceV1p1beta1_ExplicitContentAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1ExplicitContentAnnotation" (\ o -> GoogleCloudVideointelligenceV1p1beta1_ExplicitContentAnnotation' <$> (o .:? "frames" .!= mempty) <*> (o .:? "version")) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_ExplicitContentAnnotation where toJSON GoogleCloudVideointelligenceV1p1beta1_ExplicitContentAnnotation'{..} = object (catMaybes [("frames" .=) <$> _gcvveca2Frames, ("version" .=) <$> _gcvveca2Version]) -- | A generic detected attribute represented by name in string format. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_DetectedAttribute' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_DetectedAttribute = GoogleCloudVideointelligenceV1p3beta1_DetectedAttribute' { _gcvvda3Value :: !(Maybe Text) , _gcvvda3Confidence :: !(Maybe (Textual Double)) , _gcvvda3Name :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_DetectedAttribute' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvda3Value' -- -- * 'gcvvda3Confidence' -- -- * 'gcvvda3Name' googleCloudVideointelligenceV1p3beta1_DetectedAttribute :: GoogleCloudVideointelligenceV1p3beta1_DetectedAttribute googleCloudVideointelligenceV1p3beta1_DetectedAttribute = GoogleCloudVideointelligenceV1p3beta1_DetectedAttribute' { _gcvvda3Value = Nothing , _gcvvda3Confidence = Nothing , _gcvvda3Name = Nothing } -- | Text value of the detection result. For example, the value for -- \"HairColor\" can be \"black\", \"blonde\", etc. gcvvda3Value :: Lens' GoogleCloudVideointelligenceV1p3beta1_DetectedAttribute (Maybe Text) gcvvda3Value = lens _gcvvda3Value (\ s a -> s{_gcvvda3Value = a}) -- | Detected attribute confidence. Range [0, 1]. gcvvda3Confidence :: Lens' GoogleCloudVideointelligenceV1p3beta1_DetectedAttribute (Maybe Double) gcvvda3Confidence = lens _gcvvda3Confidence (\ s a -> s{_gcvvda3Confidence = a}) . mapping _Coerce -- | The name of the attribute, for example, glasses, dark_glasses, -- mouth_open. A full list of supported type names will be provided in the -- document. gcvvda3Name :: Lens' GoogleCloudVideointelligenceV1p3beta1_DetectedAttribute (Maybe Text) gcvvda3Name = lens _gcvvda3Name (\ s a -> s{_gcvvda3Name = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_DetectedAttribute where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1DetectedAttribute" (\ o -> GoogleCloudVideointelligenceV1p3beta1_DetectedAttribute' <$> (o .:? "value") <*> (o .:? "confidence") <*> (o .:? "name")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_DetectedAttribute where toJSON GoogleCloudVideointelligenceV1p3beta1_DetectedAttribute'{..} = object (catMaybes [("value" .=) <$> _gcvvda3Value, ("confidence" .=) <$> _gcvvda3Confidence, ("name" .=) <$> _gcvvda3Name]) -- | Annotations related to one detected OCR text snippet. This will contain -- the corresponding text, confidence value, and frame level information -- for each detection. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_TextAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_TextAnnotation = GoogleCloudVideointelligenceV1p3beta1_TextAnnotation' { _gcvvta2Text :: !(Maybe Text) , _gcvvta2Version :: !(Maybe Text) , _gcvvta2Segments :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_TextSegment]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_TextAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvta2Text' -- -- * 'gcvvta2Version' -- -- * 'gcvvta2Segments' googleCloudVideointelligenceV1p3beta1_TextAnnotation :: GoogleCloudVideointelligenceV1p3beta1_TextAnnotation googleCloudVideointelligenceV1p3beta1_TextAnnotation = GoogleCloudVideointelligenceV1p3beta1_TextAnnotation' { _gcvvta2Text = Nothing , _gcvvta2Version = Nothing , _gcvvta2Segments = Nothing } -- | The detected text. gcvvta2Text :: Lens' GoogleCloudVideointelligenceV1p3beta1_TextAnnotation (Maybe Text) gcvvta2Text = lens _gcvvta2Text (\ s a -> s{_gcvvta2Text = a}) -- | Feature version. gcvvta2Version :: Lens' GoogleCloudVideointelligenceV1p3beta1_TextAnnotation (Maybe Text) gcvvta2Version = lens _gcvvta2Version (\ s a -> s{_gcvvta2Version = a}) -- | All video segments where OCR detected text appears. gcvvta2Segments :: Lens' GoogleCloudVideointelligenceV1p3beta1_TextAnnotation [GoogleCloudVideointelligenceV1p3beta1_TextSegment] gcvvta2Segments = lens _gcvvta2Segments (\ s a -> s{_gcvvta2Segments = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p3beta1_TextAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1TextAnnotation" (\ o -> GoogleCloudVideointelligenceV1p3beta1_TextAnnotation' <$> (o .:? "text") <*> (o .:? "version") <*> (o .:? "segments" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_TextAnnotation where toJSON GoogleCloudVideointelligenceV1p3beta1_TextAnnotation'{..} = object (catMaybes [("text" .=) <$> _gcvvta2Text, ("version" .=) <$> _gcvvta2Version, ("segments" .=) <$> _gcvvta2Segments]) -- | Video annotation response. Included in the \`response\` field of the -- \`Operation\` returned by the \`GetOperation\` call of the -- \`google::longrunning::Operations\` service. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_AnnotateVideoResponse' smart constructor. newtype GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoResponse = GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoResponse' { _ggAnnotationResults :: Maybe [GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ggAnnotationResults' googleCloudVideointelligenceV1p1beta1_AnnotateVideoResponse :: GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoResponse googleCloudVideointelligenceV1p1beta1_AnnotateVideoResponse = GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoResponse' {_ggAnnotationResults = Nothing} -- | Annotation results for all videos specified in \`AnnotateVideoRequest\`. ggAnnotationResults :: Lens' GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoResponse [GoogleCloudVideointelligenceV1p1beta1_VideoAnnotationResults] ggAnnotationResults = lens _ggAnnotationResults (\ s a -> s{_ggAnnotationResults = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoResponse where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1AnnotateVideoResponse" (\ o -> GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoResponse' <$> (o .:? "annotationResults" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoResponse where toJSON GoogleCloudVideointelligenceV1p1beta1_AnnotateVideoResponse'{..} = object (catMaybes [("annotationResults" .=) <$> _ggAnnotationResults]) -- | Video frame level annotation results for explicit content. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_ExplicitContentFrame' smart constructor. data GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame = GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame' { _gcvvecf2TimeOffSet :: !(Maybe GDuration) , _gcvvecf2PornographyLikelihood :: !(Maybe GoogleCloudVideointelligenceV1beta2_ExplicitContentFramePornographyLikelihood) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvecf2TimeOffSet' -- -- * 'gcvvecf2PornographyLikelihood' googleCloudVideointelligenceV1beta2_ExplicitContentFrame :: GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame googleCloudVideointelligenceV1beta2_ExplicitContentFrame = GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame' {_gcvvecf2TimeOffSet = Nothing, _gcvvecf2PornographyLikelihood = Nothing} -- | Time-offset, relative to the beginning of the video, corresponding to -- the video frame for this location. gcvvecf2TimeOffSet :: Lens' GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame (Maybe Scientific) gcvvecf2TimeOffSet = lens _gcvvecf2TimeOffSet (\ s a -> s{_gcvvecf2TimeOffSet = a}) . mapping _GDuration -- | Likelihood of the pornography content.. gcvvecf2PornographyLikelihood :: Lens' GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame (Maybe GoogleCloudVideointelligenceV1beta2_ExplicitContentFramePornographyLikelihood) gcvvecf2PornographyLikelihood = lens _gcvvecf2PornographyLikelihood (\ s a -> s{_gcvvecf2PornographyLikelihood = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2ExplicitContentFrame" (\ o -> GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame' <$> (o .:? "timeOffset") <*> (o .:? "pornographyLikelihood")) instance ToJSON GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame where toJSON GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame'{..} = object (catMaybes [("timeOffset" .=) <$> _gcvvecf2TimeOffSet, ("pornographyLikelihood" .=) <$> _gcvvecf2PornographyLikelihood]) -- | Config for EXPLICIT_CONTENT_DETECTION. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_ExplicitContentDetectionConfig' smart constructor. newtype GoogleCloudVideointelligenceV1p3beta1_ExplicitContentDetectionConfig = GoogleCloudVideointelligenceV1p3beta1_ExplicitContentDetectionConfig' { _gcvvecdcModel :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_ExplicitContentDetectionConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvecdcModel' googleCloudVideointelligenceV1p3beta1_ExplicitContentDetectionConfig :: GoogleCloudVideointelligenceV1p3beta1_ExplicitContentDetectionConfig googleCloudVideointelligenceV1p3beta1_ExplicitContentDetectionConfig = GoogleCloudVideointelligenceV1p3beta1_ExplicitContentDetectionConfig' {_gcvvecdcModel = Nothing} -- | Model to use for explicit content detection. Supported values: -- \"builtin\/stable\" (the default if unset) and \"builtin\/latest\". gcvvecdcModel :: Lens' GoogleCloudVideointelligenceV1p3beta1_ExplicitContentDetectionConfig (Maybe Text) gcvvecdcModel = lens _gcvvecdcModel (\ s a -> s{_gcvvecdcModel = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_ExplicitContentDetectionConfig where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1ExplicitContentDetectionConfig" (\ o -> GoogleCloudVideointelligenceV1p3beta1_ExplicitContentDetectionConfig' <$> (o .:? "model")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_ExplicitContentDetectionConfig where toJSON GoogleCloudVideointelligenceV1p3beta1_ExplicitContentDetectionConfig'{..} = object (catMaybes [("model" .=) <$> _gcvvecdcModel]) -- | A track of an object instance. -- -- /See:/ 'googleCloudVideointelligenceV1p1beta1_Track' smart constructor. data GoogleCloudVideointelligenceV1p1beta1_Track = GoogleCloudVideointelligenceV1p1beta1_Track' { _gcvvt3Confidence :: !(Maybe (Textual Double)) , _gcvvt3Attributes :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_DetectedAttribute]) , _gcvvt3Segment :: !(Maybe GoogleCloudVideointelligenceV1p1beta1_VideoSegment) , _gcvvt3TimestampedObjects :: !(Maybe [GoogleCloudVideointelligenceV1p1beta1_TimestampedObject]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p1beta1_Track' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvt3Confidence' -- -- * 'gcvvt3Attributes' -- -- * 'gcvvt3Segment' -- -- * 'gcvvt3TimestampedObjects' googleCloudVideointelligenceV1p1beta1_Track :: GoogleCloudVideointelligenceV1p1beta1_Track googleCloudVideointelligenceV1p1beta1_Track = GoogleCloudVideointelligenceV1p1beta1_Track' { _gcvvt3Confidence = Nothing , _gcvvt3Attributes = Nothing , _gcvvt3Segment = Nothing , _gcvvt3TimestampedObjects = Nothing } -- | Optional. The confidence score of the tracked object. gcvvt3Confidence :: Lens' GoogleCloudVideointelligenceV1p1beta1_Track (Maybe Double) gcvvt3Confidence = lens _gcvvt3Confidence (\ s a -> s{_gcvvt3Confidence = a}) . mapping _Coerce -- | Optional. Attributes in the track level. gcvvt3Attributes :: Lens' GoogleCloudVideointelligenceV1p1beta1_Track [GoogleCloudVideointelligenceV1p1beta1_DetectedAttribute] gcvvt3Attributes = lens _gcvvt3Attributes (\ s a -> s{_gcvvt3Attributes = a}) . _Default . _Coerce -- | Video segment of a track. gcvvt3Segment :: Lens' GoogleCloudVideointelligenceV1p1beta1_Track (Maybe GoogleCloudVideointelligenceV1p1beta1_VideoSegment) gcvvt3Segment = lens _gcvvt3Segment (\ s a -> s{_gcvvt3Segment = a}) -- | The object with timestamp and attributes per frame in the track. gcvvt3TimestampedObjects :: Lens' GoogleCloudVideointelligenceV1p1beta1_Track [GoogleCloudVideointelligenceV1p1beta1_TimestampedObject] gcvvt3TimestampedObjects = lens _gcvvt3TimestampedObjects (\ s a -> s{_gcvvt3TimestampedObjects = a}) . _Default . _Coerce instance FromJSON GoogleCloudVideointelligenceV1p1beta1_Track where parseJSON = withObject "GoogleCloudVideointelligenceV1p1beta1Track" (\ o -> GoogleCloudVideointelligenceV1p1beta1_Track' <$> (o .:? "confidence") <*> (o .:? "attributes" .!= mempty) <*> (o .:? "segment") <*> (o .:? "timestampedObjects" .!= mempty)) instance ToJSON GoogleCloudVideointelligenceV1p1beta1_Track where toJSON GoogleCloudVideointelligenceV1p1beta1_Track'{..} = object (catMaybes [("confidence" .=) <$> _gcvvt3Confidence, ("attributes" .=) <$> _gcvvt3Attributes, ("segment" .=) <$> _gcvvt3Segment, ("timestampedObjects" .=) <$> _gcvvt3TimestampedObjects]) -- | Video segment level annotation results for label detection. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_LabelSegment' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_LabelSegment = GoogleCloudVideointelligenceV1p3beta1_LabelSegment' { _gcvvls2Confidence :: !(Maybe (Textual Double)) , _gcvvls2Segment :: !(Maybe GoogleCloudVideointelligenceV1p3beta1_VideoSegment) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_LabelSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvls2Confidence' -- -- * 'gcvvls2Segment' googleCloudVideointelligenceV1p3beta1_LabelSegment :: GoogleCloudVideointelligenceV1p3beta1_LabelSegment googleCloudVideointelligenceV1p3beta1_LabelSegment = GoogleCloudVideointelligenceV1p3beta1_LabelSegment' {_gcvvls2Confidence = Nothing, _gcvvls2Segment = Nothing} -- | Confidence that the label is accurate. Range: [0, 1]. gcvvls2Confidence :: Lens' GoogleCloudVideointelligenceV1p3beta1_LabelSegment (Maybe Double) gcvvls2Confidence = lens _gcvvls2Confidence (\ s a -> s{_gcvvls2Confidence = a}) . mapping _Coerce -- | Video segment where a label was detected. gcvvls2Segment :: Lens' GoogleCloudVideointelligenceV1p3beta1_LabelSegment (Maybe GoogleCloudVideointelligenceV1p3beta1_VideoSegment) gcvvls2Segment = lens _gcvvls2Segment (\ s a -> s{_gcvvls2Segment = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_LabelSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1LabelSegment" (\ o -> GoogleCloudVideointelligenceV1p3beta1_LabelSegment' <$> (o .:? "confidence") <*> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_LabelSegment where toJSON GoogleCloudVideointelligenceV1p3beta1_LabelSegment'{..} = object (catMaybes [("confidence" .=) <$> _gcvvls2Confidence, ("segment" .=) <$> _gcvvls2Segment]) -- | Person detection annotation per video. -- -- /See:/ 'googleCloudVideointelligenceV1p3beta1_PersonDetectionAnnotation' smart constructor. data GoogleCloudVideointelligenceV1p3beta1_PersonDetectionAnnotation = GoogleCloudVideointelligenceV1p3beta1_PersonDetectionAnnotation' { _gcvvpda1Tracks :: !(Maybe [GoogleCloudVideointelligenceV1p3beta1_Track]) , _gcvvpda1Version :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1p3beta1_PersonDetectionAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvpda1Tracks' -- -- * 'gcvvpda1Version' googleCloudVideointelligenceV1p3beta1_PersonDetectionAnnotation :: GoogleCloudVideointelligenceV1p3beta1_PersonDetectionAnnotation googleCloudVideointelligenceV1p3beta1_PersonDetectionAnnotation = GoogleCloudVideointelligenceV1p3beta1_PersonDetectionAnnotation' {_gcvvpda1Tracks = Nothing, _gcvvpda1Version = Nothing} -- | The detected tracks of a person. gcvvpda1Tracks :: Lens' GoogleCloudVideointelligenceV1p3beta1_PersonDetectionAnnotation [GoogleCloudVideointelligenceV1p3beta1_Track] gcvvpda1Tracks = lens _gcvvpda1Tracks (\ s a -> s{_gcvvpda1Tracks = a}) . _Default . _Coerce -- | Feature version. gcvvpda1Version :: Lens' GoogleCloudVideointelligenceV1p3beta1_PersonDetectionAnnotation (Maybe Text) gcvvpda1Version = lens _gcvvpda1Version (\ s a -> s{_gcvvpda1Version = a}) instance FromJSON GoogleCloudVideointelligenceV1p3beta1_PersonDetectionAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1p3beta1PersonDetectionAnnotation" (\ o -> GoogleCloudVideointelligenceV1p3beta1_PersonDetectionAnnotation' <$> (o .:? "tracks" .!= mempty) <*> (o .:? "version")) instance ToJSON GoogleCloudVideointelligenceV1p3beta1_PersonDetectionAnnotation where toJSON GoogleCloudVideointelligenceV1p3beta1_PersonDetectionAnnotation'{..} = object (catMaybes [("tracks" .=) <$> _gcvvpda1Tracks, ("version" .=) <$> _gcvvpda1Version]) -- | Video segment level annotation results for label detection. -- -- /See:/ 'googleCloudVideointelligenceV1_LabelSegment' smart constructor. data GoogleCloudVideointelligenceV1_LabelSegment = GoogleCloudVideointelligenceV1_LabelSegment' { _gcvvls3Confidence :: !(Maybe (Textual Double)) , _gcvvls3Segment :: !(Maybe GoogleCloudVideointelligenceV1_VideoSegment) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_LabelSegment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvls3Confidence' -- -- * 'gcvvls3Segment' googleCloudVideointelligenceV1_LabelSegment :: GoogleCloudVideointelligenceV1_LabelSegment googleCloudVideointelligenceV1_LabelSegment = GoogleCloudVideointelligenceV1_LabelSegment' {_gcvvls3Confidence = Nothing, _gcvvls3Segment = Nothing} -- | Confidence that the label is accurate. Range: [0, 1]. gcvvls3Confidence :: Lens' GoogleCloudVideointelligenceV1_LabelSegment (Maybe Double) gcvvls3Confidence = lens _gcvvls3Confidence (\ s a -> s{_gcvvls3Confidence = a}) . mapping _Coerce -- | Video segment where a label was detected. gcvvls3Segment :: Lens' GoogleCloudVideointelligenceV1_LabelSegment (Maybe GoogleCloudVideointelligenceV1_VideoSegment) gcvvls3Segment = lens _gcvvls3Segment (\ s a -> s{_gcvvls3Segment = a}) instance FromJSON GoogleCloudVideointelligenceV1_LabelSegment where parseJSON = withObject "GoogleCloudVideointelligenceV1LabelSegment" (\ o -> GoogleCloudVideointelligenceV1_LabelSegment' <$> (o .:? "confidence") <*> (o .:? "segment")) instance ToJSON GoogleCloudVideointelligenceV1_LabelSegment where toJSON GoogleCloudVideointelligenceV1_LabelSegment'{..} = object (catMaybes [("confidence" .=) <$> _gcvvls3Confidence, ("segment" .=) <$> _gcvvls3Segment]) -- | Annotations corresponding to one tracked object. -- -- /See:/ 'googleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation' smart constructor. data GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation = GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation' { _gcvvota3Frames :: !(Maybe [GoogleCloudVideointelligenceV1beta2_ObjectTrackingFrame]) , _gcvvota3Confidence :: !(Maybe (Textual Double)) , _gcvvota3Version :: !(Maybe Text) , _gcvvota3TrackId :: !(Maybe (Textual Int64)) , _gcvvota3Segment :: !(Maybe GoogleCloudVideointelligenceV1beta2_VideoSegment) , _gcvvota3Entity :: !(Maybe GoogleCloudVideointelligenceV1beta2_Entity) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvota3Frames' -- -- * 'gcvvota3Confidence' -- -- * 'gcvvota3Version' -- -- * 'gcvvota3TrackId' -- -- * 'gcvvota3Segment' -- -- * 'gcvvota3Entity' googleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation :: GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation googleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation = GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation' { _gcvvota3Frames = Nothing , _gcvvota3Confidence = Nothing , _gcvvota3Version = Nothing , _gcvvota3TrackId = Nothing , _gcvvota3Segment = Nothing , _gcvvota3Entity = Nothing } -- | Information corresponding to all frames where this object track appears. -- Non-streaming batch mode: it may be one or multiple ObjectTrackingFrame -- messages in frames. Streaming mode: it can only be one -- ObjectTrackingFrame message in frames. gcvvota3Frames :: Lens' GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation [GoogleCloudVideointelligenceV1beta2_ObjectTrackingFrame] gcvvota3Frames = lens _gcvvota3Frames (\ s a -> s{_gcvvota3Frames = a}) . _Default . _Coerce -- | Object category\'s labeling confidence of this track. gcvvota3Confidence :: Lens' GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation (Maybe Double) gcvvota3Confidence = lens _gcvvota3Confidence (\ s a -> s{_gcvvota3Confidence = a}) . mapping _Coerce -- | Feature version. gcvvota3Version :: Lens' GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation (Maybe Text) gcvvota3Version = lens _gcvvota3Version (\ s a -> s{_gcvvota3Version = a}) -- | Streaming mode ONLY. In streaming mode, we do not know the end time of a -- tracked object before it is completed. Hence, there is no VideoSegment -- info returned. Instead, we provide a unique identifiable integer -- track_id so that the customers can correlate the results of the ongoing -- ObjectTrackAnnotation of the same track_id over time. gcvvota3TrackId :: Lens' GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation (Maybe Int64) gcvvota3TrackId = lens _gcvvota3TrackId (\ s a -> s{_gcvvota3TrackId = a}) . mapping _Coerce -- | Non-streaming batch mode ONLY. Each object track corresponds to one -- video segment where it appears. gcvvota3Segment :: Lens' GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation (Maybe GoogleCloudVideointelligenceV1beta2_VideoSegment) gcvvota3Segment = lens _gcvvota3Segment (\ s a -> s{_gcvvota3Segment = a}) -- | Entity to specify the object category that this track is labeled as. gcvvota3Entity :: Lens' GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation (Maybe GoogleCloudVideointelligenceV1beta2_Entity) gcvvota3Entity = lens _gcvvota3Entity (\ s a -> s{_gcvvota3Entity = a}) instance FromJSON GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1beta2ObjectTrackingAnnotation" (\ o -> GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation' <$> (o .:? "frames" .!= mempty) <*> (o .:? "confidence") <*> (o .:? "version") <*> (o .:? "trackId") <*> (o .:? "segment") <*> (o .:? "entity")) instance ToJSON GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation where toJSON GoogleCloudVideointelligenceV1beta2_ObjectTrackingAnnotation'{..} = object (catMaybes [("frames" .=) <$> _gcvvota3Frames, ("confidence" .=) <$> _gcvvota3Confidence, ("version" .=) <$> _gcvvota3Version, ("trackId" .=) <$> _gcvvota3TrackId, ("segment" .=) <$> _gcvvota3Segment, ("entity" .=) <$> _gcvvota3Entity]) -- | Person detection annotation per video. -- -- /See:/ 'googleCloudVideointelligenceV1_PersonDetectionAnnotation' smart constructor. data GoogleCloudVideointelligenceV1_PersonDetectionAnnotation = GoogleCloudVideointelligenceV1_PersonDetectionAnnotation' { _gcvvpda2Tracks :: !(Maybe [GoogleCloudVideointelligenceV1_Track]) , _gcvvpda2Version :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudVideointelligenceV1_PersonDetectionAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcvvpda2Tracks' -- -- * 'gcvvpda2Version' googleCloudVideointelligenceV1_PersonDetectionAnnotation :: GoogleCloudVideointelligenceV1_PersonDetectionAnnotation googleCloudVideointelligenceV1_PersonDetectionAnnotation = GoogleCloudVideointelligenceV1_PersonDetectionAnnotation' {_gcvvpda2Tracks = Nothing, _gcvvpda2Version = Nothing} -- | The detected tracks of a person. gcvvpda2Tracks :: Lens' GoogleCloudVideointelligenceV1_PersonDetectionAnnotation [GoogleCloudVideointelligenceV1_Track] gcvvpda2Tracks = lens _gcvvpda2Tracks (\ s a -> s{_gcvvpda2Tracks = a}) . _Default . _Coerce -- | Feature version. gcvvpda2Version :: Lens' GoogleCloudVideointelligenceV1_PersonDetectionAnnotation (Maybe Text) gcvvpda2Version = lens _gcvvpda2Version (\ s a -> s{_gcvvpda2Version = a}) instance FromJSON GoogleCloudVideointelligenceV1_PersonDetectionAnnotation where parseJSON = withObject "GoogleCloudVideointelligenceV1PersonDetectionAnnotation" (\ o -> GoogleCloudVideointelligenceV1_PersonDetectionAnnotation' <$> (o .:? "tracks" .!= mempty) <*> (o .:? "version")) instance ToJSON GoogleCloudVideointelligenceV1_PersonDetectionAnnotation where toJSON GoogleCloudVideointelligenceV1_PersonDetectionAnnotation'{..} = object (catMaybes [("tracks" .=) <$> _gcvvpda2Tracks, ("version" .=) <$> _gcvvpda2Version])
brendanhay/gogol
gogol-videointelligence/gen/Network/Google/VideoIntelligence/Types/Product.hs
mpl-2.0
581,931
0
29
117,161
75,971
43,582
32,389
9,876
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Reseller.Resellernotify.Register -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Registers a Reseller for receiving notifications. -- -- /See:/ <https://developers.google.com/google-apps/reseller/ Google Workspace Reseller API Reference> for @reseller.resellernotify.register@. module Network.Google.Resource.Reseller.Resellernotify.Register ( -- * REST Resource ResellernotifyRegisterResource -- * Creating a Request , resellernotifyRegister , ResellernotifyRegister -- * Request Lenses , rrXgafv , rrUploadProtocol , rrAccessToken , rrUploadType , rrServiceAccountEmailAddress , rrCallback ) where import Network.Google.AppsReseller.Types import Network.Google.Prelude -- | A resource alias for @reseller.resellernotify.register@ method which the -- 'ResellernotifyRegister' request conforms to. type ResellernotifyRegisterResource = "apps" :> "reseller" :> "v1" :> "resellernotify" :> "register" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "serviceAccountEmailAddress" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Post '[JSON] ResellernotifyResource -- | Registers a Reseller for receiving notifications. -- -- /See:/ 'resellernotifyRegister' smart constructor. data ResellernotifyRegister = ResellernotifyRegister' { _rrXgafv :: !(Maybe Xgafv) , _rrUploadProtocol :: !(Maybe Text) , _rrAccessToken :: !(Maybe Text) , _rrUploadType :: !(Maybe Text) , _rrServiceAccountEmailAddress :: !(Maybe Text) , _rrCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ResellernotifyRegister' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rrXgafv' -- -- * 'rrUploadProtocol' -- -- * 'rrAccessToken' -- -- * 'rrUploadType' -- -- * 'rrServiceAccountEmailAddress' -- -- * 'rrCallback' resellernotifyRegister :: ResellernotifyRegister resellernotifyRegister = ResellernotifyRegister' { _rrXgafv = Nothing , _rrUploadProtocol = Nothing , _rrAccessToken = Nothing , _rrUploadType = Nothing , _rrServiceAccountEmailAddress = Nothing , _rrCallback = Nothing } -- | V1 error format. rrXgafv :: Lens' ResellernotifyRegister (Maybe Xgafv) rrXgafv = lens _rrXgafv (\ s a -> s{_rrXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). rrUploadProtocol :: Lens' ResellernotifyRegister (Maybe Text) rrUploadProtocol = lens _rrUploadProtocol (\ s a -> s{_rrUploadProtocol = a}) -- | OAuth access token. rrAccessToken :: Lens' ResellernotifyRegister (Maybe Text) rrAccessToken = lens _rrAccessToken (\ s a -> s{_rrAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). rrUploadType :: Lens' ResellernotifyRegister (Maybe Text) rrUploadType = lens _rrUploadType (\ s a -> s{_rrUploadType = a}) -- | The service account which will own the created Cloud-PubSub topic. rrServiceAccountEmailAddress :: Lens' ResellernotifyRegister (Maybe Text) rrServiceAccountEmailAddress = lens _rrServiceAccountEmailAddress (\ s a -> s{_rrServiceAccountEmailAddress = a}) -- | JSONP rrCallback :: Lens' ResellernotifyRegister (Maybe Text) rrCallback = lens _rrCallback (\ s a -> s{_rrCallback = a}) instance GoogleRequest ResellernotifyRegister where type Rs ResellernotifyRegister = ResellernotifyResource type Scopes ResellernotifyRegister = '["https://www.googleapis.com/auth/apps.order"] requestClient ResellernotifyRegister'{..} = go _rrXgafv _rrUploadProtocol _rrAccessToken _rrUploadType _rrServiceAccountEmailAddress _rrCallback (Just AltJSON) appsResellerService where go = buildClient (Proxy :: Proxy ResellernotifyRegisterResource) mempty
brendanhay/gogol
gogol-apps-reseller/gen/Network/Google/Resource/Reseller/Resellernotify/Register.hs
mpl-2.0
5,004
0
19
1,169
714
415
299
106
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Spanner.Projects.Instances.Databases.Sessions.ExecuteStreamingSQL -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Like ExecuteSql, except returns the result set as a stream. Unlike -- ExecuteSql, there is no limit on the size of the returned result set. -- However, no individual row in the result set can exceed 100 MiB, and no -- column value can exceed 10 MiB. -- -- /See:/ <https://cloud.google.com/spanner/ Cloud Spanner API Reference> for @spanner.projects.instances.databases.sessions.executeStreamingSql@. module Network.Google.Resource.Spanner.Projects.Instances.Databases.Sessions.ExecuteStreamingSQL ( -- * REST Resource ProjectsInstancesDatabasesSessionsExecuteStreamingSQLResource -- * Creating a Request , projectsInstancesDatabasesSessionsExecuteStreamingSQL , ProjectsInstancesDatabasesSessionsExecuteStreamingSQL -- * Request Lenses , pidsessqlXgafv , pidsessqlUploadProtocol , pidsessqlAccessToken , pidsessqlUploadType , pidsessqlPayload , pidsessqlSession , pidsessqlCallback ) where import Network.Google.Prelude import Network.Google.Spanner.Types -- | A resource alias for @spanner.projects.instances.databases.sessions.executeStreamingSql@ method which the -- 'ProjectsInstancesDatabasesSessionsExecuteStreamingSQL' request conforms to. type ProjectsInstancesDatabasesSessionsExecuteStreamingSQLResource = "v1" :> CaptureMode "session" "executeStreamingSql" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] ExecuteSQLRequest :> Post '[JSON] PartialResultSet -- | Like ExecuteSql, except returns the result set as a stream. Unlike -- ExecuteSql, there is no limit on the size of the returned result set. -- However, no individual row in the result set can exceed 100 MiB, and no -- column value can exceed 10 MiB. -- -- /See:/ 'projectsInstancesDatabasesSessionsExecuteStreamingSQL' smart constructor. data ProjectsInstancesDatabasesSessionsExecuteStreamingSQL = ProjectsInstancesDatabasesSessionsExecuteStreamingSQL' { _pidsessqlXgafv :: !(Maybe Xgafv) , _pidsessqlUploadProtocol :: !(Maybe Text) , _pidsessqlAccessToken :: !(Maybe Text) , _pidsessqlUploadType :: !(Maybe Text) , _pidsessqlPayload :: !ExecuteSQLRequest , _pidsessqlSession :: !Text , _pidsessqlCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsInstancesDatabasesSessionsExecuteStreamingSQL' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pidsessqlXgafv' -- -- * 'pidsessqlUploadProtocol' -- -- * 'pidsessqlAccessToken' -- -- * 'pidsessqlUploadType' -- -- * 'pidsessqlPayload' -- -- * 'pidsessqlSession' -- -- * 'pidsessqlCallback' projectsInstancesDatabasesSessionsExecuteStreamingSQL :: ExecuteSQLRequest -- ^ 'pidsessqlPayload' -> Text -- ^ 'pidsessqlSession' -> ProjectsInstancesDatabasesSessionsExecuteStreamingSQL projectsInstancesDatabasesSessionsExecuteStreamingSQL pPidsessqlPayload_ pPidsessqlSession_ = ProjectsInstancesDatabasesSessionsExecuteStreamingSQL' { _pidsessqlXgafv = Nothing , _pidsessqlUploadProtocol = Nothing , _pidsessqlAccessToken = Nothing , _pidsessqlUploadType = Nothing , _pidsessqlPayload = pPidsessqlPayload_ , _pidsessqlSession = pPidsessqlSession_ , _pidsessqlCallback = Nothing } -- | V1 error format. pidsessqlXgafv :: Lens' ProjectsInstancesDatabasesSessionsExecuteStreamingSQL (Maybe Xgafv) pidsessqlXgafv = lens _pidsessqlXgafv (\ s a -> s{_pidsessqlXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pidsessqlUploadProtocol :: Lens' ProjectsInstancesDatabasesSessionsExecuteStreamingSQL (Maybe Text) pidsessqlUploadProtocol = lens _pidsessqlUploadProtocol (\ s a -> s{_pidsessqlUploadProtocol = a}) -- | OAuth access token. pidsessqlAccessToken :: Lens' ProjectsInstancesDatabasesSessionsExecuteStreamingSQL (Maybe Text) pidsessqlAccessToken = lens _pidsessqlAccessToken (\ s a -> s{_pidsessqlAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pidsessqlUploadType :: Lens' ProjectsInstancesDatabasesSessionsExecuteStreamingSQL (Maybe Text) pidsessqlUploadType = lens _pidsessqlUploadType (\ s a -> s{_pidsessqlUploadType = a}) -- | Multipart request metadata. pidsessqlPayload :: Lens' ProjectsInstancesDatabasesSessionsExecuteStreamingSQL ExecuteSQLRequest pidsessqlPayload = lens _pidsessqlPayload (\ s a -> s{_pidsessqlPayload = a}) -- | Required. The session in which the SQL query should be performed. pidsessqlSession :: Lens' ProjectsInstancesDatabasesSessionsExecuteStreamingSQL Text pidsessqlSession = lens _pidsessqlSession (\ s a -> s{_pidsessqlSession = a}) -- | JSONP pidsessqlCallback :: Lens' ProjectsInstancesDatabasesSessionsExecuteStreamingSQL (Maybe Text) pidsessqlCallback = lens _pidsessqlCallback (\ s a -> s{_pidsessqlCallback = a}) instance GoogleRequest ProjectsInstancesDatabasesSessionsExecuteStreamingSQL where type Rs ProjectsInstancesDatabasesSessionsExecuteStreamingSQL = PartialResultSet type Scopes ProjectsInstancesDatabasesSessionsExecuteStreamingSQL = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/spanner.data"] requestClient ProjectsInstancesDatabasesSessionsExecuteStreamingSQL'{..} = go _pidsessqlSession _pidsessqlXgafv _pidsessqlUploadProtocol _pidsessqlAccessToken _pidsessqlUploadType _pidsessqlCallback (Just AltJSON) _pidsessqlPayload spannerService where go = buildClient (Proxy :: Proxy ProjectsInstancesDatabasesSessionsExecuteStreamingSQLResource) mempty
brendanhay/gogol
gogol-spanner/gen/Network/Google/Resource/Spanner/Projects/Instances/Databases/Sessions/ExecuteStreamingSQL.hs
mpl-2.0
7,076
0
16
1,436
788
463
325
127
1
{- Habit of Fate, a game to incentivize habit formation. Copyright (C) 2019 Gregory Crosswhite This program is free software: you can redistribute it and/or modify it under version 3 of the terms of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. -} {-# LANGUAGE AutoDeriveTypeable #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE UnicodeSyntax #-} module HabitOfFate.Testing.Data where import HabitOfFate.Prelude import Data.UUID import HabitOfFate.Data.Group import HabitOfFate.Data.Habit import HabitOfFate.Data.Repeated import HabitOfFate.Data.Scale import HabitOfFate.Data.Tagged import HabitOfFate.Testing.DayHour test_account_id ∷ Text test_account_id = "test" test_account_id_1 ∷ Text test_account_id_1 = "test-1" test_account_id_2 ∷ Text test_account_id_2 = "test-2" test_group_id ∷ UUID test_group_id = read "f5ccdfde-1776-483c-9140-385e9e75e31d" test_group, test_group_2 ∷ Group test_group = "group" test_group_2 = "grouper" test_habit = Habit "name" (Tagged (Success Low) (Failure Medium)) Indefinite [] Nothing test_habit_1 = Habit "name1" (Tagged (Success VeryLow) (Failure Medium)) Indefinite [] Nothing test_habit_2 = Habit "name2" (Tagged (Success Medium) (Failure VeryHigh)) Indefinite [] Nothing test_habit_3 = Habit "name3" (Tagged (Success Low) (Failure VeryLow)) Indefinite [] Nothing test_habit_once = Habit "once" (Tagged (Success Medium) (Failure Medium)) (Once $ Just $ day 0) [] Nothing test_habit_daily = def & name_ .~ "daily" & frequency_ .~ (Repeated (KeepNumberOfDays 2) (dayHour 2 3) (Daily 2)) test_habit_weekly = def & name_ .~ "daily" & frequency_ .~ (Repeated (KeepDaysInPast 4) (dayHour 3 2) (Weekly 1 (def & tuesday_ .~ True & thursday_ .~ True))) test_habit_with_last_marked = def & name_ .~ "test" & maybe_last_marked_ .~ (Just $ dayHour 1 2) test_habit_group = Habit "group" (Tagged (Success High) (Failure Low)) Indefinite [test_group_id] Nothing test_habit_id = read "95bef3cf-9031-4f64-8458-884aa6781563" ∷ UUID test_habit_id_1 = read "9f679733-9d10-4d8b-bc9c-ec5e6ff46445" ∷ UUID test_habit_id_2 = read "9e801a68-4288-4a23-8779-aa68f94991f9" ∷ UUID test_habit_id_3 = read "db2ce73f-594b-4ef2-bf45-ae2f841f6ca2" ∷ UUID test_habit_id_once = read "7dbafaf9-560a-4ac4-b6bb-b64c647e387d" ∷ UUID test_habit_id_with_last_marked = read "7ada06ff-ccf5-4c68-83df-e54999cc42b3" ∷ UUID test_habit_id_group = read "74d6b013-df62-4989-8ce8-b0e0af3e29d3" ∷ UUID
gcross/habit-of-fate
sources/library/HabitOfFate/Testing/Data.hs
agpl-3.0
2,920
0
14
412
595
321
274
41
1
module Main where import Data.IORef import Control.Concurrent import Control.Monad import FRP.Yampa.Simulation import FRP.Yampa(DTime) import Brick.BChan import Brick.Main import qualified Graphics.Vty as V import Wrapper.ToBrick import Wrapper.FromBrick import Game.Games import Game.GameState import Input dtime :: DTime dtime = 100000 main :: IO () main = do yampaStateRef <- newIORef neutralShowGame chan <- newBChan 10 _ <- forkIO $ forever $ do writeBChan chan dtime threadDelay $ round dtime --YampaInit h <- yampaInit yampaStateRef -- void $ customMain (V.mkVty V.defaultConfig) (Just chan) app (h, yampaStateRef, neutralShowGame) where neutralShowGame =( gameStateToBrickInput neutralGameState) yampaInit :: IORef ShowGameState -> IO (ReactHandle Input GameState) yampaInit ref = do reactInit (return NoInput) (outputSFResult ref) wholeGame
no-moree-ria10/utsuEater
app/Main.hs
apache-2.0
917
0
12
175
273
143
130
31
1
{-# LANGUAGE ViewPatterns #-} module Specialize.Frame (Frame,frameAlloc,lookupAddr,emptyFrame,frameTop,withAddr) where import qualified Data.Map as M import PCode import ID data Frame = Frame { frameTop :: Int, frameAddrs :: M.Map ID Int } deriving Show emptyFrame = Frame 0 M.empty align n a = case n`mod`a of 0 -> n ; m -> n+a-m frameAlloc sz bv f = Frame (top+(bSize bv`align`sz)) newAddrs where bSize (bindSize -> (n,nr)) = n+nr*sz newAddrs = foldr (uncurry M.insert) (frameAddrs f) [(s,n+top) | (s,n,_) <- flattenBind sz bv] top = frameTop f lookupAddr s = M.lookup s . frameAddrs withAddr sz s f = case lookupAddr s f of Just a -> (a,f) Nothing -> (frameTop f,frameAlloc sz (symBind s) f)
lih/Alpha
src/Specialize/Frame.hs
bsd-2-clause
741
0
11
161
342
187
155
19
2
module Problem346 where import qualified Data.HashSet as S main :: IO () -- 1*b^0+..1*b^n = (b^(n+1)-1)(b-1) -- 1 = 1 in all bases -- n = 11 in base (n-1) -- so atleast 3 digit in other bases: 1+b+b^2<=n => b<=sqrt n main = print $ sum $ S.fromList $ (1 :) $ concat $ [ drop 2 $ takeWhile (<= lim) $ scanl1 (+) $ iterate (* b) 1 | b <- [2 .. lim'] ] where lim :: Int lim = 10 ^ 12 lim' :: Int lim' = ceiling $ sqrt $ fromIntegral lim
adityagupta1089/Project-Euler-Haskell
src/problems/Problem346.hs
bsd-3-clause
518
0
11
181
147
84
63
15
1
{-# LANGUAGE Trustworthy, Rank2Types, FlexibleInstances, FlexibleContexts, MultiParamTypeClasses, UndecidableInstances #-} module Control.Monad.Reader.CPS (ReaderT(..) , runReaderT , mapReaderT , Reader , runReader , module Control.Monad.Reader.Class) where import Control.Monad.Reader.Class import Control.Monad.State.Class import Control.Applicative import Control.Monad.Identity import Control.Monad.Trans import Control.Monad.IO.Class import Control.Monad.Error.Class import Control.Monad.Writer.Class newtype ReaderT r m a = ReaderT { unReaderT :: forall b. r -> (a -> m b) -> m b } runReaderT :: Monad m => ReaderT r m a -> r -> m a runReaderT m r = unReaderT m r return {-# INLINABLE runReaderT #-} mapReaderT :: (Monad m, Monad n) => (m a -> n b) -> ReaderT r m a -> ReaderT r n b mapReaderT t m = ReaderT $ \r c -> t (unReaderT m r return) >>= c instance Functor (ReaderT r m) where fmap f m = ReaderT $ \r c -> unReaderT m r (c . f) {-# INLINABLE fmap #-} instance Applicative (ReaderT r m) where pure x = ReaderT $ \_ c -> c x {-# INLINABLE pure #-} mf <*> ma = ReaderT $ \r c -> unReaderT mf r $ \f -> unReaderT ma r (c . f) {-# INLINABLE (<*>) #-} m *> n = ReaderT $ \r c -> unReaderT m r (\_ -> unReaderT n r c) {-# INLINABLE (*>) #-} instance Monad (ReaderT r m) where return x = ReaderT $ \_ c -> c x {-# INLINABLE return #-} m >>= k = ReaderT $ \r c -> unReaderT m r (\a -> unReaderT (k a) r c) {-# INLINABLE (>>=) #-} (>>) = (*>) {-# INLINE (>>) #-} instance MonadReader r (ReaderT r m) where ask = ReaderT $ \r c -> c r {-# INLINABLE ask #-} local f m = ReaderT $ \r c -> unReaderT m (f r) c {-# INLINABLE local #-} reader f = ReaderT $ \r c -> c (f r) {-# INLINABLE reader #-} instance MonadIO m => MonadIO (ReaderT r m) where liftIO = lift . liftIO {-# INLINABLE liftIO #-} instance MonadState s m => MonadState s (ReaderT r m) where get = lift get {-# INLINABLE get #-} put = lift . put {-# INLINABLE put #-} instance MonadTrans (ReaderT r) where lift m = ReaderT $ const (m >>=) {-# INLINABLE lift #-} instance MonadError e m => MonadError e (ReaderT r m) where throwError = lift . throwError {-# INLINABLE throwError #-} catchError m h = ReaderT $ \r c -> catchError (unReaderT m r return) (\e -> runReaderT (h e) r) >>= c {-# INLINABLE catchError #-} instance MonadWriter w m => MonadWriter w (ReaderT r m) where tell = lift . tell listen m = ReaderT $ \r c -> listen (runReaderT m r) >>= c pass m = ReaderT $ \r c -> pass (runReaderT m r) >>= c type Reader r = ReaderT r Identity runReader :: Reader r a -> r -> a runReader m r = runIdentity (runReaderT m r) {-# INLINE runReader #-}
fumieval/mtl-c
Control/Monad/Reader/CPS.hs
bsd-3-clause
2,785
0
14
677
1,028
548
480
53
1
module Problem39 where import Data.Ord import Data.List main :: IO () main = print . fst . maximumBy (comparing snd) $ [ (n, pythagoreasSolutions n) | n <- [1 .. 1000] ] pythagoreasSolutions :: Int -> Int pythagoreasSolutions s = length [ True | a <- [1 .. s - 1] , b <- [1 .. a] , a + b < s , a * a + b * b == (s - a - b) * (s - a - b) ]
adityagupta1089/Project-Euler-Haskell
src/problems/Problem39.hs
bsd-3-clause
394
0
12
139
189
102
87
16
1
module Control.Monatron.Monad ( State, Writer, Reader, Exception, Cont, state,writer,reader,exception,cont, runState, runWriter, runReader, runException, runCont, Id(..), Lift(..) ) where import Control.Monatron.Transformer import Control.Monad import Control.Monad.Fix newtype Id a = Id {runId :: a} data Lift a = L {runLift :: a} type State s = StateT s Id type Writer w = WriterT w Id type Reader r = ReaderT r Id type Exception x = ExcT x Id type Cont r = ContT r Id state :: (s -> (a, s)) -> State s a state st = stateT $ \s -> Id $ st s runState :: s -> State s a -> (a,s) runState s = runId. runStateT s writer :: Monoid w => (a,w) -> Writer w a writer = writerT . Id runWriter :: Monoid w => Writer w a -> (a,w) runWriter = runId. runWriterT reader :: (r -> a) -> Reader r a reader e = readerT $ \r -> Id (e r) runReader :: r -> Reader r a -> a runReader r = runId . runReaderT r exception :: Either x a -> Exception x a exception = excT . Id runException :: Exception x a -> Either x a runException = runId. runExcT cont :: ((a -> r) -> r) -> Cont r a cont c = contT $ \k -> Id $ c (runId . k) runCont :: (a -> r) -> Cont r a -> r runCont k = runId. runContT (Id. k) instance Monad Id where return = pure fail = error m >>= f = f (runId m) instance Monad Lift where return x = L x fail x = error x L x >>= k = k x instance Functor Id where fmap = liftM instance Functor Lift where fmap = liftM instance Applicative Id where pure = Id ; (<*>) = ap instance Applicative Lift where pure = L ; (<*>) = ap instance MonadFix Id where mfix f = let m = f (runId m) in m instance MonadFix Lift where mfix f = let m = f (runLift m) in m
neothemachine/monadiccp
src/Control/Monatron/Monad.hs
bsd-3-clause
1,725
0
12
437
804
434
370
49
1
-- | Value level 'Ord'er. Sometimes values stored in e.g. 'Data.Set.Set's have -- an 'Ord' instance, which does not represent the desired order. In that case -- use this product type to pass a value along with the value to be for -- comparison by the 'Eq' and 'Ord' instances. module Data.MediaBus.Basics.OrderedBy ( OrderedBy (..), ) where -- | A wrapper around a /payload/ value paired with a value to be used when /comparing/ that payload value. data OrderedBy cmp a = MkOrderedBy { -- | Value to compare orderedByComparableValue :: cmp, -- | actual value orderedByValue :: a } instance Eq cmp => Eq (OrderedBy cmp a) where MkOrderedBy cmpa _ == MkOrderedBy cmpb _ = cmpa == cmpb instance Ord cmp => Ord (OrderedBy cmp a) where MkOrderedBy cmpa _ `compare` MkOrderedBy cmpb _ = cmpa `compare` cmpb
lindenbaum/mediabus
src/Data/MediaBus/Basics/OrderedBy.hs
bsd-3-clause
850
0
8
189
148
83
65
10
0
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE JavaScriptFFI #-} {-# LANGUAGE OverloadedStrings #-} module Reflex.Dom.Xhr.Foreign ( XMLHttpRequest , XMLHttpRequestResponseType(..) , module Reflex.Dom.Xhr.Foreign ) where import Control.Exception (throwIO) import Control.Monad.IO.Class (MonadIO(..)) import Data.Maybe (fromMaybe) import Data.Text (Text) import Data.ByteString (ByteString) import Foreign.JavaScript.Utils (bsFromMutableArrayBuffer, bsToArrayBuffer) import GHCJS.DOM.Enums import GHCJS.DOM.EventM (EventM, on, onSync) import GHCJS.DOM.EventTarget (dispatchEvent) import GHCJS.DOM.Types (MonadJSM, ToJSString, FormData, Document, Blob (..), ArrayBuffer (..), JSVal, JSM, IsEvent, XMLHttpRequestProgressEvent, ProgressEvent, Event, XMLHttpRequestUpload, FromJSString, ArrayBufferView (..), liftJSM, castTo) import GHCJS.DOM.XMLHttpRequest import Language.Javascript.JSaddle.Helper (mutableArrayBufferFromJSVal) import qualified Language.Javascript.JSaddle.Monad as JS (catch) import Prelude hiding (error) import Reflex.Dom.Xhr.Exception import Reflex.Dom.Xhr.ResponseType xmlHttpRequestNew :: MonadJSM m => m XMLHttpRequest xmlHttpRequestNew = newXMLHttpRequest xmlHttpRequestOpen :: (ToJSString method, ToJSString url, ToJSString user, ToJSString password, MonadJSM m) => XMLHttpRequest -> method -> url -> Bool -> user -> password -> m () xmlHttpRequestOpen request method url async user password = open request method url async (Just user) (Just password) convertException :: XHRError -> XhrException convertException e = case e of XHRError -> XhrException_Error XHRAborted -> XhrException_Aborted class IsXhrPayload a where sendXhrPayload :: MonadJSM m => XMLHttpRequest -> a -> m () instance IsXhrPayload () where sendXhrPayload xhr _ = send xhr instance IsXhrPayload String where sendXhrPayload = sendString instance IsXhrPayload Text where sendXhrPayload = sendString instance IsXhrPayload FormData where sendXhrPayload = sendFormData instance IsXhrPayload Document where sendXhrPayload = sendDocument instance IsXhrPayload Blob where sendXhrPayload = sendBlob instance IsXhrPayload ArrayBuffer where sendXhrPayload xhr ab = sendArrayBuffer xhr (ArrayBufferView $ unArrayBuffer ab) instance IsXhrPayload ByteString where sendXhrPayload xhr bs = sendXhrPayload xhr =<< liftJSM (bsToArrayBuffer bs) newtype XhrPayload = XhrPayload { unXhrPayload :: JSVal } -- This used to be a non blocking call, but now it uses an interruptible ffi xmlHttpRequestSend :: IsXhrPayload payload => XMLHttpRequest -> payload -> JSM () xmlHttpRequestSend self p = sendXhrPayload self p `JS.catch` (liftIO . throwIO . convertException) xmlHttpRequestSetRequestHeader :: (ToJSString header, ToJSString value, MonadJSM m) => XMLHttpRequest -> header -> value -> m () xmlHttpRequestSetRequestHeader = setRequestHeader xmlHttpRequestAbort :: MonadJSM m => XMLHttpRequest -> m () xmlHttpRequestAbort = abort xmlHttpRequestGetAllResponseHeaders :: MonadJSM m => XMLHttpRequest -> m Text xmlHttpRequestGetAllResponseHeaders = getAllResponseHeaders xmlHttpRequestGetResponseHeader :: (ToJSString header, MonadJSM m) => XMLHttpRequest -> header -> m Text xmlHttpRequestGetResponseHeader self header = fromMaybe "" <$> getResponseHeader self header xmlHttpRequestOverrideMimeType :: (ToJSString override, MonadJSM m) => XMLHttpRequest -> override -> m () xmlHttpRequestOverrideMimeType = overrideMimeType xmlHttpRequestDispatchEvent :: (IsEvent evt, MonadJSM m) => XMLHttpRequest -> evt -> m Bool xmlHttpRequestDispatchEvent = dispatchEvent xmlHttpRequestOnabort :: XMLHttpRequest -> EventM XMLHttpRequest XMLHttpRequestProgressEvent () -> JSM (JSM ()) xmlHttpRequestOnabort = (`on` abortEvent) xmlHttpRequestOnerror :: XMLHttpRequest -> EventM XMLHttpRequest XMLHttpRequestProgressEvent () -> JSM (JSM ()) xmlHttpRequestOnerror = (`on` error) xmlHttpRequestOnload :: XMLHttpRequest -> EventM XMLHttpRequest XMLHttpRequestProgressEvent () -> JSM (JSM ()) xmlHttpRequestOnload = (`on` load) xmlHttpRequestOnloadend :: XMLHttpRequest -> EventM XMLHttpRequest ProgressEvent () -> JSM (JSM ()) xmlHttpRequestOnloadend = (`on` loadEnd) xmlHttpRequestOnloadstart :: XMLHttpRequest -> EventM XMLHttpRequest ProgressEvent () -> JSM (JSM ()) xmlHttpRequestOnloadstart = (`on` loadStart) xmlHttpRequestOnprogress :: XMLHttpRequest -> EventM XMLHttpRequest XMLHttpRequestProgressEvent () -> JSM (JSM ()) xmlHttpRequestOnprogress = (`on` progress) xmlHttpRequestOntimeout :: XMLHttpRequest -> EventM XMLHttpRequest ProgressEvent () -> JSM (JSM ()) xmlHttpRequestOntimeout = (`on` timeout) xmlHttpRequestOnreadystatechange :: XMLHttpRequest -> EventM XMLHttpRequest Event () -> JSM (JSM ()) xmlHttpRequestOnreadystatechange = (`onSync` readyStateChange) xmlHttpRequestSetTimeout :: MonadJSM m => XMLHttpRequest -> Word -> m () xmlHttpRequestSetTimeout = setTimeout xmlHttpRequestGetTimeout :: MonadJSM m => XMLHttpRequest -> m Word xmlHttpRequestGetTimeout = getTimeout xmlHttpRequestGetReadyState :: MonadJSM m => XMLHttpRequest -> m Word xmlHttpRequestGetReadyState = getReadyState xmlHttpRequestSetWithCredentials :: MonadJSM m => XMLHttpRequest -> Bool -> m () xmlHttpRequestSetWithCredentials = setWithCredentials xmlHttpRequestGetWithCredentials :: MonadJSM m => XMLHttpRequest -> m Bool xmlHttpRequestGetWithCredentials = getWithCredentials xmlHttpRequestGetUpload :: MonadJSM m => XMLHttpRequest -> m (Maybe XMLHttpRequestUpload) xmlHttpRequestGetUpload = fmap Just . getUpload xmlHttpRequestGetResponseText :: (FromJSString result, MonadJSM m) => XMLHttpRequest -> m (Maybe result) xmlHttpRequestGetResponseText = getResponseText xmlHttpRequestGetResponseXML :: MonadJSM m => XMLHttpRequest -> m (Maybe Document) xmlHttpRequestGetResponseXML = getResponseXML xmlHttpRequestSetResponseType :: MonadJSM m => XMLHttpRequest -> XMLHttpRequestResponseType -> m () xmlHttpRequestSetResponseType = setResponseType fromResponseType :: XhrResponseType -> XMLHttpRequestResponseType fromResponseType XhrResponseType_Default = XMLHttpRequestResponseType fromResponseType XhrResponseType_ArrayBuffer = XMLHttpRequestResponseTypeArraybuffer fromResponseType XhrResponseType_Blob = XMLHttpRequestResponseTypeBlob fromResponseType XhrResponseType_Text = XMLHttpRequestResponseTypeText toResponseType :: XMLHttpRequestResponseType -> Maybe XhrResponseType toResponseType XMLHttpRequestResponseType = Just XhrResponseType_Default toResponseType XMLHttpRequestResponseTypeArraybuffer = Just XhrResponseType_ArrayBuffer toResponseType XMLHttpRequestResponseTypeBlob = Just XhrResponseType_Blob toResponseType XMLHttpRequestResponseTypeText = Just XhrResponseType_Text toResponseType _ = Nothing xmlHttpRequestGetResponseType :: MonadJSM m => XMLHttpRequest -> m (Maybe XhrResponseType) xmlHttpRequestGetResponseType = fmap toResponseType . getResponseType xmlHttpRequestGetStatus :: MonadJSM m => XMLHttpRequest -> m Word xmlHttpRequestGetStatus = getStatus xmlHttpRequestGetStatusText :: MonadJSM m => FromJSString result => XMLHttpRequest -> m result xmlHttpRequestGetStatusText = getStatusText xmlHttpRequestGetResponseURL :: (FromJSString result, MonadJSM m) => XMLHttpRequest -> m result xmlHttpRequestGetResponseURL = getResponseURL xmlHttpRequestGetResponse :: MonadJSM m => XMLHttpRequest -> m (Maybe XhrResponseBody) xmlHttpRequestGetResponse xhr = do mr <- getResponse xhr rt <- xmlHttpRequestGetResponseType xhr case rt of Just XhrResponseType_Blob -> fmap XhrResponseBody_Blob <$> castTo Blob mr Just XhrResponseType_Text -> Just . XhrResponseBody_Text <$> xmlHttpRequestGetStatusText xhr Just XhrResponseType_Default -> Just . XhrResponseBody_Text <$> xmlHttpRequestGetStatusText xhr Just XhrResponseType_ArrayBuffer -> do ab <- liftJSM $ mutableArrayBufferFromJSVal mr Just . XhrResponseBody_ArrayBuffer <$> bsFromMutableArrayBuffer ab _ -> return Nothing
reflex-frp/reflex-dom
reflex-dom-core/src/Reflex/Dom/Xhr/Foreign.hs
bsd-3-clause
8,079
0
14
1,073
1,927
1,020
907
-1
-1
module RPF.Lexer where import RPF.Types import Text.Parsec import Text.Parsec.String import Text.ParserCombinators.Parsec.Language import Text.ParserCombinators.Parsec.Token as P ---------------------------------------------------------------- type Lexer st a = GenParser Char st a ---------------------------------------------------------------- rpfStyle :: LanguageDef st rpfStyle = emptyDef { commentStart = "/*" , commentEnd = "*/" , commentLine = "//" , nestedComments = True , identStart = char '$' , identLetter = alphaNum <|> oneOf "_-" , reservedOpNames= ["&&", "==", "!=", "="] , reservedNames = actionWords ++ variableNames ++ resultWords ++ blockNames ++ noyes , caseSensitive = True } lexer :: P.TokenParser a lexer = P.makeTokenParser rpfStyle ---------------------------------------------------------------- whiteSpace :: Lexer st () whiteSpace = P.whiteSpace lexer ---------------------------------------------------------------- semi :: Lexer st String semi = P.semi lexer comma :: Lexer st String comma = P.comma lexer colon :: Lexer st String colon = P.colon lexer identifier :: Lexer st String identifier = P.identifier lexer ---------------------------------------------------------------- symbol :: String -> Lexer st String symbol = P.symbol lexer reserved :: String -> Lexer st () reserved = P.reserved lexer reservedOp :: String -> Lexer st () reservedOp = P.reservedOp lexer ---------------------------------------------------------------- braces :: Lexer st a -> Lexer st a braces = P.braces lexer lexeme :: Lexer st a -> Lexer st a lexeme = P.lexeme lexer commaSep1 :: Lexer st a -> Lexer st [a] commaSep1 = P.commaSep1 lexer
kazu-yamamoto/rpf
RPF/Lexer.hs
bsd-3-clause
1,765
0
10
324
454
248
206
43
1
module Text ( loadCharset , displayString ) where import Control.Applicative import Control.Monad import Data.Array import Data.List import Data.Word import Foreign.Marshal import Foreign.Ptr import Graphics.Rendering.OpenGL import GraphUtils loadCharset file = do dat <- lines <$> readFile file let cs = unfoldr parseChar dat cpos = map (\n -> (n `mod` 8,n `div` 8)) [0..] cdat = array (' ','Z') (zip (map fst cs) cpos) mkpix '#' = [255,255,255,255] mkpix _ = [255,255,255,0] tid <- createTexture 256 256 False $ \tex -> do pokeArray tex $ concat (replicate (256*256) [255,255,255,0]) forM_ (zip cs cpos) $ \((_,cimg),(x,y)) -> do forM_ (zip cimg [0..]) $ \(crow,ry) -> pokeArray (advancePtr tex ((x*32+1)*4+(y*32+1+ry)*256*4)) (concatMap mkpix crow) return (tid,cdat) parseChar dat = if null dat' then Nothing else Just ((c,explodeMatrix 3 img),dat'') where dat' = dropWhile null dat c = head (head dat') (img,dat'') = span (not . null) (tail dat') displayString tid cdat x y m s = do textureBinding Texture2D $= Just tid let displayChar c x = do let (cx,cy) = cdat ! c u = fromIntegral (cx*32+1)/256 v = fromIntegral (cy*32+1)/256 texCoord2 u (v+ch) vertex3 x y 0 texCoord2 (u+cw) (v+ch) vertex3 (x+8*m) y 0 texCoord2 (u+cw) v vertex3 (x+8*m) (y+10*m) 0 texCoord2 u v vertex3 x (y+10*m) 0 cw = 24/256 ch = 30/256 renderPrimitive Quads $ forM_ (zip s [0..]) $ \(c,i) -> displayChar c (x+i*8*m)
cobbpg/dow
src/Text.hs
bsd-3-clause
1,611
0
28
440
844
440
404
46
2
module Chp92 where {-- when The when function is found in Control.Monad (to get access to it, do import Control.Monad). It's interesting because in a do block it looks like a control flow statement, but it's actually a normal function. It takes a boolean value and an I/O action if that boolean value is True, it returns the same I/O action that we supplied to it. However, if it's False, it returns the return (), action, so an I/O action that doesn't do anything. --} import Control.Monad import Data.Char main1 = do c <- getChar when (c /= ' ') $ do putChar c main1 {-- review $ again $ just a way to group the computation, the parenthesis not have any implication of prcedence, but the operators and function application have, and $ also. $ will wrap right part all together, and apply its left hand function to right hand side value when the precedence of $ meet as highest priority: map :: (a->b) -> [a] -> [b] map f [] = [] map f (x:xs) = f x : map f xs Function application has higher precedence than any infix operator, and thus the right-hand side of the second equation: f x : map f xs parses as: (f x) : (map f xs) (* 1) $ 2 + 5 => (\x -> x * 1) $ 2 + 5 -- due to $'s low precedence, (x => x * 1) $ 2 will not apply, -- so 2 + 5 will take higher precedence => (\x -> x * 1) $ 7 => (\x -> x * 1) 7 => 7 * 1 => 7 The whole expression will still be deduct from left right each time and evaludate by each operation precedence. --} res1 = ((-) 1) $ 1 * 5 res2 = 2 + 5 * 1 res3 = (* 1) $ 2 + 5 res4 = (+ 1) $ (* 3) $ (^ 2) $ 5 ^ 2 + 3 - 1 * 2 {-- (+ 1) $ (* 3) $ (^ 2) $ 5 ^ 2 + 3 - 1 * 2 since $ is right-associative, and almost lowest precedence (+ 1) $ (* 3) $ (^ 2) $ 5 ^ 2 + 3 - 1 * 2 => (\x -> x + 1) $ (* 3) $ (^ 2) $ 5 ^ 2 + 3 - 1 * 2 => (\x -> x + 1) $ (\y -> y * 3) $ (^ 2) $ 5 ^ 2 + 3 - 1 * 2 => (\x -> x + 1) $ (\y -> y * 3) $ (\z -> z ^ 2) $ 5 ^ 2 + 3 - 1 * 2 -- $ take lowest pred. => ... $ 25 + 3 - 1 * 2 => ... $ 25 + 3 - 2 => ... $ 28 - 2 => ... $ 26 => ... $ (\z -> z ^ 2) $ 26 => ... $ 676 => ... $ (\y -> y * 3) $ 676 => ... $ 2028 => (\x -> x + 1) $ 2028 => 2029 Since $ operator usually get lowest precedence, so both part will apply first from left to right before applying $ operator. --} main2 = do a <- getLine b <- getLine c <- getLine print [a,b,c] main3 = do rs <- sequence [getLine, getLine, getLine] print rs {-- sequence sequence :: [IO a] -> IO [a] takes a list of I/O actions and returns an I/O actions that will perform those actions one after the other. main2 is the same as main3 So sequence [getLine, getLine, getLine] makes an I/O action that will perform getLine three times. --} {-- example: ghci> sequence (map print [1,2,3,4,5]) 1 2 3 4 5 [(),(),(),(),()] What's with the [(),(),(),(),()] at the end? Well, when we evaluate an I/O action in GHCI, it's performed and then its result is printed out, unless that result is (), in which case it's not printed out. That's why evaluating putStrLn "hehe" in GHCI just prints out hehe (because the contained result in putStrLn "hehe" is ()). But when we do getLine in GHCI, the result of that I/O action is printed out, because getLine has a type of IO String. --} res5 = mapM print [1,2,3] -- :t print -- print :: Show a => a -> IO () -- :t mapM -- mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b) -- res5 => [(), (), ()] res6 = mapM_ print [1,2,3] -- :t mapM_ -- mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m () {-- mapM and mapM_ were introduced. mapM takes a function and a list, maps the function over the list and then sequences it. mapM_ does the same, only it throws away the result later. We usually use mapM_ when we don't care what result our sequenced I/O actions have. --} {-- forever takes an I/O action and returns an I/O action that just repeats the I/O action it got forever. forM (located in Control.Monad) is like mapM, only that it has its parameters switched around. The first parameter is the list and the second one is the function to map over that list --} main4 = forever $ do putStr "Give me some input: " l <- getLine putStrLn $ map toUpper l main5 = do colors <- forM [1,2,3,4] (\a -> do putStrLn $ "Which color do you associate with the number " ++ show a ++ "?" color <- getLine return color) putStrLn "The colors that you associate with 1, 2, 3 and 4 are: " mapM putStrLn colors {-- The (\a -> do ... ) is a function that takes a number and returns an I/O action. We have to surround it with parentheses, otherwise the lambda thinks the last two I/O actions belong to it. (putStrLn and mapM) for "return color" We actually didn't have to do that, because getLine already has that contained within it. Doing color <- getLine and then return color is just unpacking the result from getLine and then repackaging it again, so it's the same as just doing getLine. --}
jamesyang124/haskell-playground
src/Chp92.hs
bsd-3-clause
5,010
0
15
1,253
388
207
181
33
1
-- | Export Module for SSTG.Core.SMT module SSTG.Core.SMT ( module SSTG.Core.SMT.Syntax ) where import SSTG.Core.SMT.Syntax
AntonXue/SSTG
src/SSTG/Core/SMT.hs
bsd-3-clause
134
0
5
25
25
18
7
3
0
{-# OPTIONS_HADDOCK show-extensions #-} {- | Copyright : Copyright (C) 2006-2015 Douglas McClean License : BSD3 Maintainer : douglas.mcclean@gmail.com Stability : Experimental Portability: GHC only = Summary A type checker plugin for GHC that can perform unification in the Abelian group of types of kind 'Numeric.Units.Dimensional.DK.Dimensions.TypeLevel.Dimension' under 'Numeric.Units.Dimensional.DK.Dimensions.TypeLevel.*'. -} module Numeric.Units.Dimensional.DK.Solver ( plugin ) where -- GHC API import Outputable (Outputable (..), (<+>), ($$), text) import Plugins (Plugin (..), defaultPlugin) import TcEvidence (EvTerm) import TcPluginM (TcPluginM, tcPluginIO, tcPluginTrace, zonkCt) import TcRnTypes (Ct, TcPlugin (..), TcPluginResult(..), ctEvidence, ctEvPred, ctPred, ctLoc, isGiven, isWanted, mkNonCanonical) import TcType (mkEqPred, typeKind) import Type (EqRel (NomEq), Kind, PredTree (EqPred), Type, TyVar, classifyPredType, mkTyVarTy) -- | To use the plugin, add -- -- @ -- {\-\# OPTIONS_GHC -fplugin Numeric.Units.Dimensional.DK.Solver \#-\} -- @ -- -- To the header of your file. plugin :: Plugin plugin = defaultPlugin { tcPlugin = const $ Nothing }
bjornbm/dimensional-dk-experimental
src/Numeric/Units/Dimensional/DK/Solver.hs
bsd-3-clause
1,251
0
7
228
199
136
63
15
1
module Haskell99Pointfree.P19 ( ) where import Control.Applicative ((<*>), liftA2) import Data.Tuple (swap) import Control.Monad.Extra (ifM) import Data.Function ((&)) import Control.Monad (join, ap) p19_1 :: [a] -> Int -> [a] p19_1 = ( . ) . ( ( uncurry (++) .swap) . ) . flip splitAt <*> flip mod . length p19_2 :: [a] -> Int -> [a] p19_2 = liftA2 ((<*>) . (ifM ( < 0) . )) ( ((reverse .) . ) . ( ( . abs) . ) . ( . reverse)) id shifter where shifter :: [a] -> Int -> [a] shifter = ap (( . ) . flip ( join (( . take) . liftA2 (++) . drop)) ) (flip mod . length )
SvenWille/Haskell99Pointfree
src/Haskell99Pointfree/P19.hs
bsd-3-clause
597
1
16
150
297
177
120
13
1
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Orphans where -- import Solr.Query.Lucene -- -- import Data.Coerce (coerce) -- import Prelude.Compat -- import Test.QuickCheck.Arbitrary -- import Test.QuickCheck.Gen -- import Test.QuickCheck.Instances () -- -- instance Arbitrary (LocalParam LuceneQuerySYM) where -- arbitrary = oneof -- [ df <$> arbitrary -- , pure opAnd -- , pure opOr -- ] -- -- -- Subtract by 1, but don't go below 0 -- scaleSub1 :: Gen a -> Gen a -- scaleSub1 g = scale (max 0 . subtract 1) g -- -- #if !MIN_VERSION_QuickCheck(2,8,0) -- scale :: (Int -> Int) -> Gen a -> Gen a -- scale f g = sized (\n -> resize (f n) g) -- #endif
Sentenai/solr-query
test/Orphans.hs
bsd-3-clause
707
0
2
155
29
28
1
3
0
module Handler.User where import Import import qualified Data.Text as T getUserR :: Handler Html getUserR = do Entity userId user' <- requireAuth user <- case user' of UserInfo { userInfoIdent = uid, userInfoAuthId = "" } -> do authId <- liftIO $ genAuthId userId uid runDB $ do update userId [ UserInfoAuthId =. authId ] get404 userId _ -> do liftIO $ print user' return user' defaultLayout $ do setTitle "User settings" $(widgetFile "user") postUserR :: Handler Html postUserR = do Entity userId _ <- requireAuth mres <- lookupPostParam "input-name" liftIO $ print mres case mres of Just name | name /= "" && T.length name < 256 -> do runDB $ update userId [ UserInfoName =. name ] setMessage [shamlet|<div.alert.alert-success>Update success|] _ -> setMessage [shamlet|<div.alert.alert-error>Please input valid name|] redirect UserR getRankingR :: Handler Html getRankingR = do ranking <- runDB $ zip [1 :: Int .. ] <$> selectList [ UserInfoNumRequests >. 0 ] [ Desc UserInfoScore ] defaultLayout $ do setTitle "Ranking" $(widgetFile "ranking")
tanakh/icfp2013-clone
Handler/User.hs
bsd-3-clause
1,176
0
18
295
374
178
196
-1
-1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} module Main where import Control.Concurrent (threadDelay) import Control.Exception import Control.Lens import Data.ByteString.Char8 (isInfixOf) import Data.Default import MVC import MVC.Prelude import MVC.Service import System.IO (stdout) import System.Log.Formatter (simpleLogFormatter) import System.Log.Handler (setFormatter) import System.Log.Handler.Simple (streamHandler) import System.Log.Logger import MVC.Socket ----------------------------------------------------------------------------- model :: Model () ServiceOut (Either ServiceIn String) model = asPipe $ do sendEvent $ ServiceCommand ServiceReportStatus sendEvent $ ConnectionCommand $ Connect 0 onCondition (== ServiceStatus ServiceActive) $ sendEvent $ Send "hello1\n" onCondition (streamContains "server: hello1\n") $ sendEvent $ ConnectionCommand Disconnect onCondition (== ServiceStatus ServicePending) $ sendEvent $ ConnectionCommand $ Connect 0 onCondition (== ServiceStatus ServiceActive) $ sendEvent $ Send "hello2\n" for cat logEvent where sendEvent = yield . Left logEvent = yield . Right . show streamContains bs = \case Stream x -> bs `isInfixOf` x _ -> False onCondition cond action = go where go = do e <- await logEvent e if cond e then action else go ----------------------------------------------------------------------------- services :: Managed (View (Either ServiceIn String), Controller ServiceOut) services = do (socketV,socketC) <- toManagedMVC $ toManagedService $ socketService $ def & scSocketParams .~ SocketParams "127.0.0.1" "44444" return ( handles _Left socketV <> handles _Right stdoutLines , socketC ) ----------------------------------------------------------------------------- main :: IO () main = do handler <- streamHandler stdout DEBUG >>= \h -> return $ setFormatter h $ simpleLogFormatter "$time $loggername $prio: $msg" updateGlobalLogger rootLoggerName (setLevel DEBUG . setHandlers [handler]) finally (runMVC () model services) (threadDelay 1000000)
cmahon/mvc-service
executable/SocketTestClient.hs
bsd-3-clause
2,367
0
13
578
571
292
279
55
3
module HVX.DcpTests.OkConcaveNondecConcave where import HVX main :: IO () main = do let x = EVar "x" _ = hlog $ hlog x _ = hlog $ hmin x return ()
chrisnc/hvx
test/DcpTests/OkConcaveNondecConcave.hs
bsd-3-clause
165
0
11
49
71
35
36
8
1
-- All rights reserved {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE LambdaCase #-} module AuthService.Types where import Control.Lens import Data.Aeson import Data.Aeson.TH import Data.ByteString (ByteString) import Data.ByteString.Conversion import Data.Data import Data.String import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import qualified Data.UUID as UUID import Data.Time.Clock (UTCTime) import Web.HttpApiData import Web.PathPieces import Helpers newtype InstanceID = InstanceID { unInstanceID :: UUID.UUID } deriving ( Show, Read, Eq, Ord, Typeable, Data ) makePrisms ''InstanceID instance PathPiece InstanceID where fromPathPiece = fmap InstanceID . UUID.fromText toPathPiece = Text.pack . UUID.toString . unInstanceID instance ToHttpApiData InstanceID where toUrlPiece = toPathPiece instance FromHttpApiData InstanceID where parseUrlPiece txt = case fromPathPiece txt of Nothing -> Left $ "Could not parse user id " <> txt Just uuid -> Right uuid newtype UserID = UserID { unUserID :: UUID.UUID } deriving ( Show, Read, Eq, Ord, Typeable, Data ) makePrisms ''UserID instance ToJSON InstanceID where toJSON (InstanceID uid) = toJSON $ UUID.toText uid instance FromJSON InstanceID where parseJSON v = do txt <- parseJSON v case UUID.fromText txt of Nothing -> fail $ "Can't parse UUID " <> Text.unpack txt Just uuid -> return $ InstanceID uuid instance ToByteString InstanceID where builder = builder . Text.encodeUtf8 . UUID.toText . unInstanceID instance PathPiece UserID where fromPathPiece = fmap UserID . UUID.fromText toPathPiece = Text.pack . UUID.toString . unUserID instance ToHttpApiData UserID where toUrlPiece = toPathPiece instance FromHttpApiData UserID where parseUrlPiece txt = case fromPathPiece txt of Nothing -> Left $ "Could not parse user id " <> txt Just uuid -> Right uuid instance ToJSON UserID where toJSON (UserID uid) = toJSON $ UUID.toText uid instance FromJSON UserID where parseJSON v = do txt <- parseJSON v case UUID.fromText txt of Nothing -> fail $ "Can't parse UUID " <> Text.unpack txt Just uuid -> return $ UserID uuid instance ToByteString UserID where builder = builder . Text.encodeUtf8 . UUID.toText . unUserID newtype Name = Name{ unName :: Text} deriving ( Show, Read, Eq, Ord, Typeable, Data, PathPiece , ToJSON, FromJSON , IsString, ToByteString , ToHttpApiData, FromHttpApiData ) makePrisms ''Name newtype Password = Password{ unPassword :: Text} deriving ( Show, Read, Eq, Ord, Typeable, Data , ToJSON, FromJSON , IsString , ToHttpApiData, FromHttpApiData ) makePrisms ''Password newtype PasswordHash = PasswordHash{ unPasswordHash :: ByteString} deriving ( Show, Eq, Ord, Typeable, Data ) makePrisms ''PasswordHash newtype Email = Email{ unEmail :: Text} deriving ( Show, Eq, Ord, Typeable, Data , ToJSON, FromJSON , IsString , ToHttpApiData, FromHttpApiData ) makePrisms ''Email newtype Phone = Phone { unPhone :: Text} deriving ( Show, Eq, Ord, Typeable, Data , ToJSON, FromJSON , IsString , ToHttpApiData, FromHttpApiData ) makePrisms ''Phone newtype B64Token = B64Token { unB64Token :: Text } deriving ( Show, Read, Eq, Ord, Typeable, Data, PathPiece , ToByteString , ToHttpApiData, FromHttpApiData , ToJSON, FromJSON ) makePrisms ''B64Token type Role = Text data AuthHeader = AuthHeader { authHeaderUserID :: UserID , authHeaderEmail :: Email , authHeaderName :: Name , authHeaderRoles :: [Role] } makeLensesWith camelCaseFields ''AuthHeader deriveJSON defaultOptions{fieldLabelModifier = dropPrefix "authHeader"} ''AuthHeader -------------------------------------------------------------------------------- -- User -------------------------------------------------------------------------------- data AddUser = AddUser { addUserUuid :: Maybe UserID , addUserEmail :: Email , addUserPassword :: Password , addUserName :: Name , addUserPhone :: Maybe Phone , addUserInstances :: [InstanceID] , addUserRoles :: [Text] } deriving (Show) deriveJSON defaultOptions{fieldLabelModifier = dropPrefix "addUser"} ''AddUser makeLensesWith camelCaseFields ''AddUser data ReturnUser = ReturnUser { returnUserUser :: UserID , returnUserRoles :: [Role] } deriving (Show, Eq) deriveJSON defaultOptions{fieldLabelModifier = dropPrefix "returnUser"} ''ReturnUser makeLensesWith camelCaseFields ''ReturnUser data ReturnInstance = ReturnInstance { returnInstanceName :: Text , returnInstanceId :: InstanceID } deriving ( Show, Read, Eq, Ord , Typeable, Data ) makeLensesWith camelCaseFields ''ReturnInstance deriveJSON defaultOptions{fieldLabelModifier = dropPrefix "returnInstance"} ''ReturnInstance data ReturnUserInfo = ReturnUserInfo { returnUserInfoId :: UserID , returnUserInfoEmail :: Email , returnUserInfoName :: Name , returnUserInfoPhone :: Maybe Phone , returnUserInfoInstances :: [ReturnInstance] , returnUserInfoRoles :: [Text] , returnUserInfoDeactivate :: Maybe UTCTime } deriving Show deriveJSON defaultOptions{fieldLabelModifier = dropPrefix "returnUserInfo"} ''ReturnUserInfo makeLensesWith camelCaseFields ''ReturnUserInfo -- | User info if found data FoundUserInfo = FoundUserInfo { foundUserInfoId :: UserID , foundUserInfoInfo :: Maybe ReturnUserInfo } deriving Show deriveJSON defaultOptions{fieldLabelModifier = dropPrefix "foundUserInfo"} ''FoundUserInfo makeLensesWith camelCaseFields ''FoundUserInfo data Login = Login { loginUser :: Email , loginPassword :: Password , loginOtp :: Maybe Password } deriving ( Show, Eq, Ord, Typeable, Data ) deriveJSON defaultOptions{fieldLabelModifier = dropPrefix "login"} ''Login makeLensesWith camelCaseFields ''Login data ReturnLogin = ReturnLogin { returnLoginToken :: B64Token , returnLoginInstances :: [ReturnInstance] } deriving ( Show, Read, Eq, Ord , Typeable, Data ) makeLensesWith camelCaseFields ''ReturnLogin deriveJSON defaultOptions{fieldLabelModifier = dropPrefix "returnLogin"} ''ReturnLogin data ChangePassword = ChangePassword { changePasswordOldPasword :: Password , changePasswordNewPassword :: Password , changePasswordOtp :: Maybe Password } deriving ( Show, Eq, Ord, Typeable, Data ) deriveJSON defaultOptions{fieldLabelModifier = dropPrefix "changePassword"} ''ChangePassword makeLensesWith camelCaseFields ''ChangePassword -------------------------------------------------------------------------------- -- Password Reset -------------------------------------------------------------------------------- newtype PasswordResetRequest = PasswordResetRequest { passwordResetRequestEmail :: Email } deriving (Show) makeLensesWith camelCaseFields ''PasswordResetRequest deriveJSON defaultOptions {fieldLabelModifier = dropPrefix "passwordResetRequest"} ''PasswordResetRequest newtype ResetTokenInfo = ResetTokenInfo { resetTokenInfoEmail :: Email } deriving (Show) makeLensesWith camelCaseFields ''ResetTokenInfo deriveJSON defaultOptions {fieldLabelModifier = dropPrefix "resetTokenInfo"} ''ResetTokenInfo data PasswordReset = PasswordReset { passwordResetToken :: Text , passwordResetOtp :: Maybe Password , passwordResetNewPassword :: Password } deriving (Show) makeLensesWith camelCaseFields ''PasswordReset deriveJSON defaultOptions {fieldLabelModifier = dropPrefix "passwordReset"} ''PasswordReset -------------------------------------------------------------------------------- -- Account Creation -------------------------------------------------------------------------------- data CreateAccount = CreateAccount { createAccountEmail :: Email , createAccountPassword :: Password , createAccountName :: Name , createAccountPhone :: Maybe Phone } deriving (Show) makeLensesWith camelCaseFields ''CreateAccount deriveJSON defaultOptions {fieldLabelModifier = dropPrefix "createAccount"} ''CreateAccount -------------------------------------------------------------------------------- -- Account Disabling ----------------------------------------------------------- -------------------------------------------------------------------------------- data DeactivateAt = DeactivateNow | DeactivateAt UTCTime deriving (Show) instance ToJSON DeactivateAt where toJSON DeactivateNow = String "now" toJSON (DeactivateAt time) = toJSON time instance FromJSON DeactivateAt where parseJSON (String "now") = return DeactivateNow parseJSON v = DeactivateAt <$> parseJSON v makePrisms ''DeactivateAt newtype DeactivateUser = DeactivateUser { deactivateUserDeactivateAt :: DeactivateAt } deriving (Show) makeLensesWith camelCaseFields ''DeactivateUser deriveJSON defaultOptions {fieldLabelModifier = camelTo2 '_' . dropPrefix "deactivateUser"} ''DeactivateUser
nejla/auth-service
auth-service-core/src/AuthService/Types.hs
bsd-3-clause
11,190
0
13
3,419
2,215
1,179
1,036
227
0
{-# LANGUAGE MagicHash #-} {-# LANGUAGE UnliftedFFITypes #-} module MCL.Curves.Fp254BNb.Fp12 ( Fp12 , beta , mkFp12 , fp12_c0 , fp12_c1 , fp12_c2 , fp12_c3 , fp12_c4 , fp12_c5 , fp12_isZero ) where import Control.DeepSeq import Data.Binary import Foreign.C.Types import MCL.Curves.Fp254BNb.Fp2 import qualified MCL.Internal.Field as I import qualified MCL.Internal.Prim as I -- | Sixth degree field extension of 'Fp2' defined as @Fp2(β)@, where @β⁶ = 1 + α@. data Fp12 = Fp12 { unFp12 :: I.CC Fp12 } instance Binary Fp12 where put n = put (fp12_c0 n) *> put (fp12_c1 n) *> put (fp12_c2 n) *> put (fp12_c3 n) *> put (fp12_c4 n) *> put (fp12_c5 n) get = mkFp12 <$> get <*> get <*> get <*> get <*> get <*> get instance NFData Fp12 where rnf = (`seq` ()) instance Num Fp12 where (+) = I.addFp (-) = I.subtractFp (*) = I.multiplyFp negate = I.negateFp abs = I.absFp signum = I.signumFp fromInteger n = mkFp12 (fromInteger n) 0 0 0 0 0 instance Fractional Fp12 where recip = I.recipFp fromRational = I.fromRationalFp instance Eq Fp12 where (==) = I.eqFp instance Show Fp12 where showsPrec p a = showsPrec p (fp12_c0 a, fp12_c1 a, fp12_c2 a, fp12_c3 a, fp12_c4 a, fp12_c5 a) -- | Root of the polynomial @x⁶ - 1 - α@. {-# NOINLINE beta #-} beta :: Fp12 beta = mkFp12 0 0 0 1 0 0 -- Construct an element of Fp12 from six coordinates in Fp2. {-# INLINE mkFp12 #-} mkFp12 :: Fp2 -> Fp2 -> Fp2 -> Fp2 -> Fp2 -> Fp2 -> Fp12 mkFp12 = I.unsafeOp6_ c_mcl_fp254bnb_fp12_from_base -- | Return first Fp2 coordinate of the element in Fp12. {-# INLINE fp12_c0 #-} fp12_c0 :: Fp12 -> Fp2 fp12_c0 = I.unsafeOp1_ c_mcl_fp254bnb_fp12_c0 -- | Return second Fp2 coordinate of the element in Fp12. {-# INLINE fp12_c1 #-} fp12_c1 :: Fp12 -> Fp2 fp12_c1 = I.unsafeOp1_ c_mcl_fp254bnb_fp12_c1 -- | Return third Fp2 coordinate of the element in Fp12. {-# INLINE fp12_c2 #-} fp12_c2 :: Fp12 -> Fp2 fp12_c2 = I.unsafeOp1_ c_mcl_fp254bnb_fp12_c2 -- | Return fourth Fp2 coordinate of the element in Fp12. {-# INLINE fp12_c3 #-} fp12_c3 :: Fp12 -> Fp2 fp12_c3 = I.unsafeOp1_ c_mcl_fp254bnb_fp12_c3 -- | Return fifth Fp2 coordinate of the element in Fp12. {-# INLINE fp12_c4 #-} fp12_c4 :: Fp12 -> Fp2 fp12_c4 = I.unsafeOp1_ c_mcl_fp254bnb_fp12_c4 -- | Return sixth Fp2 coordinate of the element in Fp12. {-# INLINE fp12_c5 #-} fp12_c5 :: Fp12 -> Fp2 fp12_c5 = I.unsafeOp1_ c_mcl_fp254bnb_fp12_c5 -- | Check whether the element of Fp12 is zero. {-# INLINE fp12_isZero #-} fp12_isZero :: Fp12 -> Bool fp12_isZero = I.isZero ---------------------------------------- -- | Internal instance I.Prim Fp12 where prim_size _ = fromIntegral c_mcl_fp254bnb_fp12_size prim_wrap = Fp12 prim_unwrap = unFp12 -- | Internal instance I.HasArith Fp12 where c_add _ = c_mcl_fp254bnb_fp12_add c_subtract _ = c_mcl_fp254bnb_fp12_subtract c_multiply _ = c_mcl_fp254bnb_fp12_multiply c_negate _ = c_mcl_fp254bnb_fp12_negate c_invert _ = c_mcl_fp254bnb_fp12_invert c_eq _ = c_mcl_fp254bnb_fp12_eq c_is_zero _ = c_mcl_fp254bnb_fp12_is_zero foreign import ccall unsafe "hs_mcl_fp254bnb_fp12_size" c_mcl_fp254bnb_fp12_size :: CInt foreign import ccall unsafe "hs_mcl_fp254bnb_fp12_add" c_mcl_fp254bnb_fp12_add :: I.CC Fp12 -> I.CC Fp12 -> I.MC Fp12 -> IO () foreign import ccall unsafe "hs_mcl_fp254bnb_fp12_subtract" c_mcl_fp254bnb_fp12_subtract :: I.CC Fp12 -> I.CC Fp12 -> I.MC Fp12 -> IO () foreign import ccall unsafe "hs_mcl_fp254bnb_fp12_multiply" c_mcl_fp254bnb_fp12_multiply :: I.CC Fp12 -> I.CC Fp12 -> I.MC Fp12 -> IO () foreign import ccall unsafe "hs_mcl_fp254bnb_fp12_negate" c_mcl_fp254bnb_fp12_negate :: I.CC Fp12 -> I.MC Fp12 -> IO () foreign import ccall unsafe "hs_mcl_fp254bnb_fp12_from_base" c_mcl_fp254bnb_fp12_from_base :: I.CC Fp2 -> I.CC Fp2 -> I.CC Fp2 -> I.CC Fp2 -> I.CC Fp2 -> I.CC Fp2 -> I.MC Fp12 -> IO () foreign import ccall unsafe "hs_mcl_fp254bnb_fp12_invert" c_mcl_fp254bnb_fp12_invert :: I.CC Fp12 -> I.MC Fp12 -> IO () foreign import ccall unsafe "hs_mcl_fp254bnb_fp12_eq" c_mcl_fp254bnb_fp12_eq :: I.CC Fp12 -> I.CC Fp12 -> IO CInt foreign import ccall unsafe "hs_mcl_fp254bnb_fp12_c0" c_mcl_fp254bnb_fp12_c0 :: I.CC Fp12 -> I.MC Fp2 -> IO () foreign import ccall unsafe "hs_mcl_fp254bnb_fp12_c1" c_mcl_fp254bnb_fp12_c1 :: I.CC Fp12 -> I.MC Fp2 -> IO () foreign import ccall unsafe "hs_mcl_fp254bnb_fp12_c2" c_mcl_fp254bnb_fp12_c2 :: I.CC Fp12 -> I.MC Fp2 -> IO () foreign import ccall unsafe "hs_mcl_fp254bnb_fp12_c3" c_mcl_fp254bnb_fp12_c3 :: I.CC Fp12 -> I.MC Fp2 -> IO () foreign import ccall unsafe "hs_mcl_fp254bnb_fp12_c4" c_mcl_fp254bnb_fp12_c4 :: I.CC Fp12 -> I.MC Fp2 -> IO () foreign import ccall unsafe "hs_mcl_fp254bnb_fp12_c5" c_mcl_fp254bnb_fp12_c5 :: I.CC Fp12 -> I.MC Fp2 -> IO () foreign import ccall unsafe "hs_mcl_fp254bnb_fp12_is_zero" c_mcl_fp254bnb_fp12_is_zero :: I.CC Fp12 -> IO CInt
arybczak/haskell-mcl
src/MCL/Curves/Fp254BNb/Fp12.hs
bsd-3-clause
5,109
0
14
1,039
1,326
695
631
113
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE LambdaCase #-} module SimpTT.Expr ( Variable (..) , ExprF (..) , Expr , getPosition , free , shift , subst , areEqual -- Constructors , var , lam , forall , app , universe ) where import Control.Arrow (first, second) import Control.Monad.Reader import Data.Foldable import Data.Functor.Foldable (Fix (..), cata) import Data.Monoid (Any (..), (<>)) import Data.Text (Text, pack) import Data.String import GHC.Generics (Generic) import Language.SimplePi.Types (Position, dummyPos) newtype Variable = Variable Text deriving (Show, Eq, Ord, Generic) instance IsString Variable where fromString = Variable . pack data ExprF e = Var Position !Variable !Integer -- x | Lambda Position !Variable e e -- ƛ x:A. e | Pi Position !Variable e e -- (x:A) → B | App Position e e -- f a | Universe Position !Integer -- Type₀, Type₁, ... deriving (Functor, Generic, Foldable, Traversable) var :: Variable -> Integer -> Expr var x n = Fix $ Var dummyPos x n lam :: Variable -> Expr -> Expr -> Expr lam x t b = Fix $ Lambda dummyPos x t b forall :: Variable -> Expr -> Expr -> Expr forall x k t = Fix $ Pi dummyPos x k t app :: Expr -> Expr -> Expr app f a = Fix $ App dummyPos f a universe :: Integer -> Expr universe n = Fix $ Universe dummyPos n getPosition :: Expr -> Position getPosition (Fix (Var pos _ _)) = pos getPosition (Fix (Universe pos _)) = pos getPosition (Fix (Pi pos _ _ _)) = pos getPosition (Fix (Lambda pos _ _ _)) = pos getPosition (Fix (App pos _ _)) = pos type Expr = Fix ExprF free :: Variable -> Integer -> Expr -> Bool free x n0 expr = getAny $ runReader (cata alg expr) n0 where alg :: ExprF (Reader Integer Any) -> Reader Integer Any alg (Var _ x' n') = do n <- ask return $ Any (x == x' && n == n') alg (Lambda _ x' t b) = do t' <- t b' <- if x == x' then local succ b else b return $ t' <> b' alg (Pi _ x' k t) = do k' <- k t' <- if x == x' then local succ t else t return $ k' <> t' alg e = fold <$> sequence e shift :: Integer -> Variable -> Expr -> Expr shift d x e = runReader (cata alg e) 0 where alg :: ExprF (Reader Integer Expr) -> Reader Integer Expr alg = \case Var pos x' n -> do c <- ask return $ Fix $ Var pos x' $ if x == x' && n >= c then n + d else n Lambda pos x' a b -> do a' <- a b' <- if x == x' then local succ b else b return $ Fix $ Lambda pos x' a' b' Pi pos x' a b -> do a' <- a b' <- if x == x' then local succ b else b return $ Fix $ Pi pos x' a' b' other -> Fix <$> sequence other subst :: Variable -> Integer -> Expr -> Expr -> Expr subst x n0 sub0 expr = runReader (cata alg expr) (n0, sub0) where succIndex :: Reader (Integer, Expr) a -> Reader (Integer, Expr) a succIndex = local (first succ) shifted :: Integer -> Variable -> Reader (Integer, Expr) a -> Reader (Integer, Expr) a shifted d x = local (second (shift d x)) alg :: ExprF (Reader (Integer, Expr) Expr) -> Reader (Integer, Expr) Expr alg = \case Var pos x' n' -> do (n, sub) <- ask if x' == x && n' == n then return sub else return (Fix (Var pos x' n')) Lambda pos x' a b -> do a' <- a b' <- shifted 1 x' $ if x == x' then succIndex b else b return (Fix (Lambda pos x' a' b')) Pi pos x' a b -> do a' <- a b' <- shifted 1 x' $ if x == x' then succIndex b else b return (Fix (Pi pos x' a' b')) other -> Fix <$> sequence other areEqual :: Expr -> Expr -> Bool areEqual a b = runReader (go a b) [] where go :: Expr -> Expr -> Reader [(Variable, Variable)] Bool go (Fix a) (Fix b) = case (a, b) of (Var _ x n, Var _ x' n') -> match (x, n) (x', n') (Lambda _ x t b, Lambda _ x' t' b') -> (&&) <$> go t t' <*> push x x' (go b b') (Pi _ x k t, Pi _ x' k' t') -> (&&) <$> go k k' <*> push x x' (go t t') (App _ f a, App _ f' a') -> (&&) <$> go f f' <*> go a a' (Universe _ u, Universe _ u') -> return (u == u') (_, _) -> return False push :: Variable -> Variable -> Reader [(Variable, Variable)] a -> Reader [(Variable, Variable)] a push x x' = local ((x, x') :) match :: (Variable, Integer) -> (Variable, Integer) -> Reader [(Variable, Variable)] Bool match (x, n) (y, m) = go 0 0 <$> ask where go :: Integer -> Integer -> [(Variable, Variable)] -> Bool go !n' !m' = \case ((x', y') : rest) -> x == x' && y == y' && n == n' && m == m' || go (if x == x' then succ n' else n') (if y == y' then succ m' else m') rest [] -> x == y && n' == m'
esmolanka/simple-pi
src/SimpTT/Expr.hs
bsd-3-clause
5,210
0
19
1,761
2,253
1,168
1,085
157
9
module TriangleKata.Day7Spec (spec) where import Test.Hspec import TriangleKata.Day7 (triangle, TriangleType(..)) spec :: Spec spec = do it "equilateral triangle has all sides equal" $ do triangle (10, 10, 10) `shouldBe` Equilateral it "isosceles triangle has first two sides equal" $ do triangle (6, 6, 8) `shouldBe` Isosceles it "isosceles triangle has last two sides equal" $ do triangle (8, 6, 6) `shouldBe` Isosceles it "isosceles triangle has the first and the last sides equal" $ do triangle (6, 8, 6) `shouldBe` Isosceles it "scalene triangle has no equal sides" $ do triangle (6, 7, 8) `shouldBe` Scalene it "illegal triangle has sum of first two sides less or equal to the third one" $ do triangle (4, 5, 10) `shouldBe` Illegal triangle (4, 5, 9) `shouldBe` Illegal it "illegal triangle has sum of last two sides less or equal to the first one" $ do triangle (10, 5, 4) `shouldBe` Illegal triangle (9, 5, 4) `shouldBe` Illegal it "illegal triangle has sum of the first and the last sides less or equal to the second one" $ do triangle (5, 10, 4) `shouldBe` Illegal triangle (5, 9, 4) `shouldBe` Illegal it "illegal triangle has all sides equal to zero" $ do triangle (0, 0, 0) `shouldBe` Illegal
Alex-Diez/haskell-tdd-kata
old-katas/test/TriangleKata/Day7Spec.hs
bsd-3-clause
1,448
0
12
449
385
207
178
26
1
module Math.Budget.Demo where import Math.Budget import Control.Applicative import Data.List import Data.List.NonEmpty hiding (iterate, zipWith, tail) import Data.Maybe import Data.Time import Data.Time.Calendar.OrdinalDate paydaydiffs :: ZonedTime -> FixedPeriods paydaydiffs = (zipWith (\v w -> let UTCTime vd _ = zonedTimeToUTC v UTCTime wd _ = zonedTimeToUTC w in everySeconds (diffDays wd vd * 24 * 60 * 60)) <*> tail) . paydays -- Fred is paid on the first prior business day on (and including) the 15th and last day of every calendar month. paydays :: ZonedTime -> [ZonedTime] paydays (ZonedTime (LocalTime d t) z) = let validPayday q = let (_, x) = mondayStartWeek q (_, m', r) = toGregorian q in not $ or [ x == 6 -- is Saturday , x == 7 -- is Sunday , m' == 4 && r == 15 -- 15 April, Bedrock Day ] (yy, mm, dd) = toGregorian d (n, f) = if dd <= 15 then (1, const . const $ 15) else (16, gregorianMonthLength) next = fromGregorian yy mm (f yy mm) rewind = ZonedTime (LocalTime (fromMaybe (fromGregorian yy mm n) . find validPayday . iterate (addDays (-1)) $ next) t) z rest = paydays (ZonedTime (LocalTime (addDays 1 next) t) z) in rewind : rest bedrockTime :: Integer -> Int -> Int -> TimeOfDay -> ZonedTime bedrockTime y m d t = ZonedTime (LocalTime (fromGregorian y m d) t) (hoursToTimeZone 10) mybudget :: Budget mybudget = budget [ expensePayment "Rent" (bedrockTime 1966 11 20 (TimeOfDay 9 0 0)) (bankDeposit "Mr Landlord" "123456" "00118421") (fixedInterval everyWeek) 200 , expensePayment "Electricity" (bedrockTime 1966 8 17 (TimeOfDay 12 0 0)) -- todo function of priors (internetMethod $ URI { uriScheme = "http" , uriAuthority = Just $ URIAuth { uriUserInfo = "" , uriRegName = "acmepower.com" , uriPort = "" } , uriPath = "/paybill" , uriQuery = "account=123" , uriFragment = "" }) (fixedInterval $ everyMonths 3) 300 -- todo function of priors , let start = bedrockTime 1966 6 15 (TimeOfDay 12 0 0) in incomePayment "Fred's pay" (bedrockTime 1966 11 20 (TimeOfDay 9 0 0)) (bankDeposit "Fred Flintstone" "678345" "019930") (arbitraryInterval (paydaydiffs start)) 1000 ]
tonymorris/hbudget
demo/src/Math/Budget/Demo.hs
bsd-3-clause
2,657
0
19
922
790
419
371
79
2
{-# LANGUAGE BangPatterns #-} module Development.Cake.Options ( Options(..), defaultOptions, parseOptions ) where import Development.Cake.Core.Types import Control.Applicative import Data.Maybe ( fromMaybe, listToMaybe ) import GHC.Conc ( numCapabilities ) -- | Command line options for Cake. data Options = Options { optionVerbosity :: Verbosity -- ^ Verbosity level of logging. , optionThreads :: Int -- ^ Maximum allowed number of simultaneous build tasks. } deriving (Eq, Ord, Show) -- | Default options to use. defaultOptions :: Options defaultOptions = Options { optionVerbosity = silent , optionThreads = numCapabilities } type Message = String -- | Parse options from list of command line flags. -- -- Returns the parsed options, the list of unprocessed flags, and a -- list of warning messages for flags that failed to parse. Currently -- supported command line flags are: -- -- > -v[0-4] .. set verbosity level (no argument = -v3) -- > -j<N> .. allow up to <N> concurrent workers, <N> >= 1 -- parseOptions :: [String] -> Options -> (Options, [String], [Message]) parseOptions args opts0 = filterArgs opts0 args [] [] where filterArgs opts [] unparsed warns = (opts, reverse unparsed, reverse warns) filterArgs opts (arg:args) unparsed warns = case arg of '-':'v':n -> let !opts' = opts{ optionVerbosity = fromMaybe verbose (verbosityFromInt <$> parseInt n) } in filterArgs opts' args unparsed warns '-':'j':n -> let (opts', warns') = case parseInt n of Nothing -> let warn = "Could not parse argument to -j: " ++ n in (opts, warn:warns) Just nworkers | nworkers < 1 -> (opts{ optionThreads = 1 }, "Argument to -j too small, using 1" : warns) | otherwise -> (opts{ optionThreads = nworkers }, warns) in filterArgs opts' args unparsed warns' _ -> filterArgs opts args (arg:unparsed) warns addWarningIf True warn warns = warn:warns addWarningIf _ _ warns = warns parseInt :: String -> Maybe Int parseInt str = fst <$> listToMaybe (filter (null . snd) (reads str))
nominolo/cake
src/Development/Cake/Options.hs
bsd-3-clause
2,324
0
21
671
545
299
246
46
6
-- This demo shows how to use Yesod with the XING API. -- -- The OAuth handshake is implemented without using yesod-auth. -- Have a look at the yesod-auth-xing package for a simpler -- solution to authenticate users using the XING API. -- -- Make sure to set the environment variables XING_CONSUMER_KEY and -- XING_CONSUMER_SECRET before trying this demo. {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} module Main where -- TODO: Web.XING.Types.User.FullUser also exports languages. Find a better name. import Yesod.Core hiding (languages) import Network.Wai.Handler.Warp (run) import Text.Hamlet (hamlet) import Web.XING import Network.HTTP.Conduit (newManager, def) import Data.Maybe (fromJust, isJust, fromMaybe) import qualified Data.Map as M import Helper.YesodHelper ( bootstrapLayout, bootstrapCDN , writeTokenToSession, getTokenFromSession , deleteTokenFromSession ) import qualified Data.ByteString.Char8 as BS import Data.Monoid (mappend) import qualified Data.Text.Encoding as E import Data.Time import qualified Data.Text as T import System.Environment (getEnv) data HelloXING = HelloXING { httpManager :: Manager , oAuthConsumer :: OAuth } instance Yesod HelloXING where defaultLayout = bootstrapLayout mkYesod "HelloXING" [parseRoutes| / HomeR GET /handshake HandshakeR POST /callback CallbackR GET /logout LogoutR POST |] postHandshakeR :: Handler RepHtml postHandshakeR = do yesod <- getYesod let oa = oAuthConsumer yesod let manager = httpManager yesod (requestToken, url) <- getRequestToken oa manager writeTokenToSession "request" requestToken redirect $ E.decodeUtf8 url getCallbackR :: Handler RepHtml getCallbackR = do yesod <- getYesod let oa = oAuthConsumer yesod let manager = httpManager yesod maybeRequestToken <- getTokenFromSession "request" maybeVerifier <- lookupGetParam "oauth_verifier" let verifier = E.encodeUtf8 (fromMaybe "" maybeVerifier) if isJust maybeRequestToken then do (accessToken, _) <- getAccessToken (fromJust maybeRequestToken) verifier oa manager writeTokenToSession "access" accessToken else return () redirect HomeR postLogoutR :: Handler RepHtml postLogoutR = do deleteTokenFromSession "access" deleteTokenFromSession "request" redirect HomeR daysUntilBirthday :: Maybe BirthDate -> Day -> Integer daysUntilBirthday (Just (DayOnly birthMonth birthDay)) today = calcDays birthMonth birthDay today daysUntilBirthday (Just (FullDate _ birthMonth birthDay)) today = calcDays birthMonth birthDay today daysUntilBirthday Nothing _ = 0 calcDays :: Int -> Int -> Day -> Integer calcDays birthMonth birthDay today = if (birthDayThisYear >= 0) then birthDayThisYear else birthDayNextYear where (year, _, _) = toGregorian today birthDayThisYear = diffDays (fromGregorian (year ) birthMonth birthDay) today birthDayNextYear = diffDays (fromGregorian (year + 1) birthMonth birthDay) today getHomeR :: Handler RepHtml getHomeR = do maybeAccessToken <- getTokenFromSession "access" widget <- case maybeAccessToken of Just accessToken -> do yesod <- getYesod users <- getUsers (oAuthConsumer yesod) (httpManager yesod) accessToken ["me"] today <- liftIO $ getCurrentTime let firstUser = head $ unUserList users let birthDayInDays = daysUntilBirthday (birthDate firstUser) (utctDay today) return $ whoAmI firstUser birthDayInDays Nothing -> return pleaseLogIn defaultLayout $ do addStylesheetRemote $ bootstrapCDN `mappend` "/css/bootstrap-combined.min.css" [whamlet| <h1>Welcome to the XING API demo ^{widget} |] pleaseLogIn :: Widget pleaseLogIn = toWidget [hamlet| <img src="https://www.xing.com/img/n/nobody_m.png"> <p>Hello unknown user. Please log-in. <form method=POST action=@{HandshakeR}> <input type=submit value="Login with XING"> |] whoAmI :: FullUser -> Integer -> Widget whoAmI user birthDayInDays = do toWidget [hamlet| <img src=#{fromMaybe "" $ M.lookup "large" (photoUrls user)}> <p> <a href=#{permalink user}>#{displayName user} <p> Hey #{firstName user}! Welcome to this demo.<br> <p> Your next birthday is in #{show birthDayInDays} days. <p> Did you know? In Germany you would be greeted with "Guten Tag $if (gender user) == Male Herr $else Frau \ #{lastName user}". $if (length (M.keys (languages user)) > 1) <p> Impressive! You are speaking #{length (M.keys (languages user))} languages: \ #{T.intercalate ", " (M.keys (languages user))}. $maybe mail <- activeEmail user <p>Your active email address is <a href=mailto:#{mail}>#{mail}</a>. <p>Here is a list of your premium services <ul> $forall service <- premiumServices user <li>#{service} $if null $ badges user You have no badges. $else <p>Your badges: <ul> $forall badge <- badges user <li>#{badge} <form method=POST action=@{LogoutR}> <input type=submit value="Logout"> |] main :: IO () main = do manager <- newManager def let port = 3000 consumer_key <- getEnv "XING_CONSUMER_KEY" consumer_secret <- getEnv "XING_CONSUMER_SECRET" let xingConsumer = consumer (BS.pack consumer_key) (BS.pack consumer_secret) let xingConsumer' = xingConsumer{ oauthCallback = Just $ "http://localhost:" `mappend` (BS.pack.show) port `mappend` "/callback" } putStrLn $ "Starting on port " ++ show port run port =<< toWaiApp (HelloXING manager xingConsumer')
JanAhrens/xing-api-haskell
demos/yesod-demo.hs
bsd-3-clause
5,981
0
18
1,392
1,071
555
516
109
2
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} -- | -- Module: $HEADER$ -- Description: TODO -- Copyright: (c) 2014 Peter Trsko -- License: BSD3 -- -- Maintainer: peter.trsko@gmail.com -- Stability: experimental -- Portability: NoImplicitPrelude, OverloadedStrings -- -- TODO module Skeletos.ShowOpt ( showDefine , showTemplateType , showTemplateType' , showQueryAtom , showQueryAtom' , showQuery ) where import Data.Data (Data(toConstr), showConstr) import Data.Function ((.), ($)) import qualified Data.List as List (map) import Data.Maybe (Maybe(Just, Nothing)) import Data.Monoid (Monoid(mempty), (<>)) import Text.Show (Show(show)) import Data.CaseInsensitive (CI) import qualified Data.CaseInsensitive as CI (foldedCase, map, mk) import Data.Text (Text) import Data.Text as Text (concatMap, pack, singleton, unwords) import Control.Lens ((^?), (^.), view) import Data.Maybe.Strict (_Just) import Skeletos.Internal.Utils (dropSuffix) import Skeletos.Type.Define import Skeletos.Type.Query (Query, QueryAtom(..), queryAtoms) import Skeletos.Type.TemplateType (TemplateType) showDefine :: Define -> Text showDefine d = "-D" <> (d ^. name) <> case d ^? value . _Just of Nothing -> mempty Just v -> Text.singleton '=' <> case v of TextValue t -> "\"text:" <> escape t <> "\"" BoolValue b -> "bool:" <> if b then "true" else "false" IntValue i -> "int:" <> Text.pack (show i) WordValue w -> "word:" <> Text.pack (show w) showTemplateType :: TemplateType -> Text showTemplateType = CI.foldedCase . showTemplateType' showTemplateType' :: TemplateType -> CI Text showTemplateType' = CI.mk . Text.pack . showConstr . toConstr showQueryAtom :: QueryAtom -> Text showQueryAtom = CI.foldedCase . showQueryAtom' showQueryAtom' :: QueryAtom -> CI Text showQueryAtom' q = atomName <> eq <> case q of TypeAtom x -> showTemplateType' x LanguageAtom x -> ciTextContent x TagAtom x -> ciTextContent x where ciTextContent = CI.map escape atomName = CI.mk . Text.pack . dropSuffix "Atom" . showConstr $ toConstr q eq = CI.mk (Text.singleton '=') showQuery :: Query -> Text showQuery = Text.unwords . List.map showQueryAtom . view queryAtoms escape :: Text -> Text escape = concatMap $ \ch -> case ch of '"' -> "\\\"" '$' -> "\\$" ' ' -> "\\ " '\'' -> "\\'" _ -> Text.singleton ch --showQueryAtom :: QueryAtom
trskop/skeletos
src/Skeletos/ShowOpt.hs
bsd-3-clause
2,504
0
16
518
733
414
319
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeOperators #-} -- | -- Module : Crypto.Classical.Cipher.Enigma -- Copyright : (c) Colin Woodbury, 2015 - 2020 -- License : BSD3 -- Maintainer: Colin Woodbury <colin@fosskers.ca> module Crypto.Classical.Cipher.Enigma where import Control.Monad.Trans.State.Strict import Crypto.Classical.Types import Crypto.Classical.Util import qualified Data.ByteString.Lazy.Char8 as B import Data.Char import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Maybe (fromJust) import Data.Modular --- newtype Enigma a = Enigma { _enigma :: a } deriving (Eq, Show, Functor) instance Applicative Enigma where pure = Enigma Enigma f <*> Enigma a = Enigma $ f a instance Monad Enigma where return = pure Enigma a >>= f = f a -- | When a machine operator presses a key, the Rotors rotate. A circuit is then -- completed as they hold the key down, and a bulb is lit. Here, we make sure to -- rotate the Rotors before encrypting the character. -- -- NOTE: Decryption is the same as encryption. instance Cipher EnigmaKey Enigma where decrypt = encrypt encrypt k m = pure . B.pack $ evalState (traverse f $ B.unpack m) k' where k' :: EnigmaKey k' = withInitPositions k f :: Char -> State EnigmaKey Char f c | not $ isLetter c = return c | isLower c = f $ toUpper c | otherwise = do modify (\x -> x { _rotors = turn $ _rotors x }) EnigmaKey rots _ rl pl <- get let rs = map _circuit rots rs' = reverse $ map mapInverse rs pl' = mapInverse pl cmp = foldl1 compose e = pl |.| cmp rs |.| rl |.| cmp rs' |.| pl' pure . letter . fromJust . flip M.lookup e $ int c -- | Applies the initial Rotor settings as defined in the Key to the Rotors -- themselves. These initial rotations do not trigger the turnover of -- neighbouring Rotors as usual. withInitPositions :: EnigmaKey -> EnigmaKey withInitPositions k = k { _rotors = zipWith f (_rotors k) (_settings k) } where f :: Rotor -> Char -> Rotor f r s = r { _circuit = rotate (int s) $ _circuit r , _turnover = (\n -> n - int s) $ _turnover r } -- | Turn the (machine's) right-most (left-most in List) Rotor by one position. -- If its turnover value wraps back to 25, then turn the next Rotor as well. turn :: [Rotor] -> [Rotor] turn [] = [] turn (r:rs) = if _turnover r' == 25 then r' : turn rs else r' : rs where r' :: Rotor r' = r { _circuit = rotate 1 $ _circuit r , _turnover = pred $ _turnover r } -- | Rotate a Rotor by `n` positions. By subtracting 1 from every key and value, -- we perfectly simulate rotation. Example: -- -- >>> rotate $ M.fromList [(0,2),(1,0),(2,3),(3,4),(4,1)] -- M.fromList [(4,1),(0,4),(1,2),(2,3),(3,0)] rotate :: ℤ/26 -> Map (ℤ/26) (ℤ/26) -> Map (ℤ/26) (ℤ/26) rotate n r = M.fromList . map (both (\n' -> n' - n)) $ M.toList r
fosskers/crypto-classical
lib/Crypto/Classical/Cipher/Enigma.hs
bsd-3-clause
3,178
0
18
868
813
435
378
51
2
{- | Module : $Header$ Description : export logic graph information as XML Copyright : (c) Christian Maeder DFKI GmbH 2013 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : non-portable (via imports) export logic graph information as XML -} module Logic.LGToXml where import Logic.Comorphism import Logic.Grothendieck import Logic.Logic import Logic.Prover import Control.Monad import qualified Data.Map as Map import Data.Char import Data.Maybe import Common.Consistency import Common.ToXml import Text.XML.Light usableProvers :: LogicGraph -> IO Element usableProvers lg = do ps <- mapM proversOfLogic . Map.elems $ logics lg return $ unode "provers" $ concat ps proversOfLogic :: AnyLogic -> IO [Element] proversOfLogic (Logic lid) = do bps <- filterM (fmap isNothing . proverUsable) $ provers lid return $ map (\ p -> add_attrs [ mkNameAttr $ proverName p , mkAttr "logic" $ language_name lid] $ unode "prover" ()) bps lGToXml :: LogicGraph -> IO Element lGToXml lg = do let cs = Map.elems $ comorphisms lg groupC = Map.toList . Map.fromListWith (++) ssubs = groupC $ map (\ (Comorphism cid) -> (G_sublogics (sourceLogic cid) $ sourceSublogic cid, [language_name cid])) cs tsubs = groupC $ map (\ (Comorphism cid) -> (G_sublogics (targetLogic cid) $ targetSublogic cid, [language_name cid])) cs nameC = map (\ n -> add_attr (mkNameAttr n) $ unode "comorphism" ()) ls <- mapM logicToXml . Map.elems $ logics lg return $ unode "LogicGraph" $ ls ++ map (\ (a, ns) -> add_attr (mkNameAttr $ show a) $ unode "sourceSublogic" $ nameC ns) ssubs ++ map (\ (a, ns) -> add_attr (mkNameAttr $ show a) $ unode "targetSublogic" $ nameC ns) tsubs ++ map comorphismToXml cs logicToXml :: AnyLogic -> IO Element logicToXml (Logic lid) = do let ps = provers lid cs1 = cons_checkers lid cs2 = conservativityCheck lid ua b = mkAttr "usable" . map toLower $ show $ isNothing b bps <- mapM proverUsable ps bcs1 <- mapM ccUsable cs1 bcs2 <- mapM checkerUsable cs2 return $ add_attrs [ mkNameAttr $ language_name lid , mkAttr "Stability" . show $ stability lid , mkAttr "has_basic_parser" . show . not . Map.null $ parsersAndPrinters lid , mkAttr "has_basic_analysis" . show . isJust $ basic_analysis lid , mkAttr "has_symbol_list_parser" . show . isJust $ parse_symb_items lid , mkAttr "has_symbol_map_parser" . show . isJust $ parse_symb_map_items lid , mkAttr "is_a_process_logic" . show . isJust $ data_logic lid ] . unode "logic" $ unode "Description" (mkText $ description lid) : map (\ a -> add_attr (mkNameAttr a) $ unode "Serialization" ()) (filter (not . null) . Map.keys $ parsersAndPrinters lid) ++ zipWith (\ a b -> add_attrs [mkNameAttr $ proverName a, ua b] $ unode "Prover" ()) ps bps ++ zipWith (\ a b -> add_attrs [mkNameAttr $ ccName a, ua b] $ unode "ConsistencyChecker" ()) cs1 bcs1 ++ zipWith (\ a b -> add_attrs [mkNameAttr $ checkerId a, ua b] $ unode "ConservativityChecker" ()) cs2 bcs2 ++ [unode "Sublogics" . unlines . map sublogicName $ all_sublogics lid] comorphismToXml :: AnyComorphism -> Element comorphismToXml (Comorphism cid) = add_attrs [ mkNameAttr $ language_name cid , mkAttr "source" $ language_name (sourceLogic cid) , mkAttr "target" $ language_name (targetLogic cid) , mkAttr "sourceSublogic" . sublogicName $ sourceSublogic cid , mkAttr "targetSublogic" . sublogicName $ targetSublogic cid , mkAttr "is_inclusion" . show $ isInclusionComorphism cid , mkAttr "has_model_expansion" . show $ has_model_expansion cid , mkAttr "is_weakly_amalgamable" . show $ is_weakly_amalgamable cid ] $ unode "comorphism" ()
keithodulaigh/Hets
Logic/LGToXml.hs
gpl-2.0
3,888
0
21
851
1,296
633
663
81
1
module EnumFromTo3 where main :: [Int] main = list where list :: [Int] list = [50..60]
roberth/uu-helium
test/correct/EnumFromTo3.hs
gpl-3.0
98
0
7
27
37
23
14
5
1
{-# LANGUAGE FlexibleContexts, TypeFamilies #-} {- | Helpers for debug output and pretty-printing (using pretty-simple, with which there may be some overlap). This module also exports Debug.Trace. @dbg0@-@dbg9@ will pretty-print values to stderr if the program was run with a sufficiently high @--debug=N@ argument. (@--debug@ with no argument means @--debug=1@; @dbg0@ always prints). The @debugLevel@ global is set once at startup using unsafePerformIO. In GHCI, this happens only on the first run of :main, so if you want to change the debug level without restarting GHCI, save a dummy change in Debug.hs and do a :reload. (Sometimes it's more convenient to temporarily add dbg0's and :reload.) In hledger, debug levels are used as follows: Debug level: What to show: ------------ --------------------------------------------------------- 0 normal command output only (no warnings, eg) 1 (--debug) useful warnings, most common troubleshooting info, eg valuation 2 common troubleshooting info, more detail 3 report options selection 4 report generation 5 report generation, more detail 6 input file reading 7 input file reading, more detail 8 command line parsing 9 any other rarely needed / more in-depth info -} -- more: -- http://hackage.haskell.org/packages/archive/TraceUtils/0.1.0.2/doc/html/Debug-TraceUtils.html -- http://hackage.haskell.org/packages/archive/trace-call/0.1/doc/html/Debug-TraceCall.html -- http://hackage.haskell.org/packages/archive/htrace/0.1/doc/html/Debug-HTrace.html -- http://hackage.haskell.org/packages/archive/traced/2009.7.20/doc/html/Debug-Traced.html module Hledger.Utils.Debug ( -- * Pretty printing pprint ,pshow -- * Tracing ,traceWith -- * Pretty tracing ,ptrace -- ** Debug-level-aware tracing ,debugLevel ,traceAt ,traceAtWith ,ptraceAt ,ptraceAtWith -- ** Easiest form (recommended) ,dbg0 ,dbg1 ,dbg2 ,dbg3 ,dbg4 ,dbg5 ,dbg6 ,dbg7 ,dbg8 ,dbg9 ,dbgExit -- ** More control ,dbg0With ,dbg1With ,dbg2With ,dbg3With ,dbg4With ,dbg5With ,dbg6With ,dbg7With ,dbg8With ,dbg9With -- ** For standalone lines in IO blocks ,ptraceAtIO ,dbg0IO ,dbg1IO ,dbg2IO ,dbg3IO ,dbg4IO ,dbg5IO ,dbg6IO ,dbg7IO ,dbg8IO ,dbg9IO -- ** Trace the state of hledger parsers ,traceParse ,dbgparse ,module Debug.Trace ,useColorOnStdout ,useColorOnStderr ,dlog) where import Control.Monad (when) import Control.Monad.IO.Class import Data.List hiding (uncons) import qualified Data.Text as T import qualified Data.Text.Lazy as TL import Debug.Trace import Hledger.Utils.Parse import Safe (readDef) import System.Environment (getArgs, lookupEnv) import System.Exit import System.IO.Unsafe (unsafePerformIO) import Text.Megaparsec import Text.Printf import Text.Pretty.Simple -- (defaultOutputOptionsDarkBg, OutputOptions(..), pShowOpt, pPrintOpt) import Data.Maybe (isJust) import System.Console.ANSI (hSupportsANSIColor) import System.IO (stdout, Handle, stderr) prettyopts = baseopts { outputOptionsIndentAmount=2 , outputOptionsCompact=True } where baseopts | useColorOnStderr = defaultOutputOptionsDarkBg -- defaultOutputOptionsLightBg | otherwise = defaultOutputOptionsNoColor -- | Pretty print. Generic alias for pretty-simple's pPrint. pprint :: Show a => a -> IO () pprint = pPrintOpt CheckColorTty prettyopts -- | Pretty show. Generic alias for pretty-simple's pShow. pshow :: Show a => a -> String pshow = TL.unpack . pShowOpt prettyopts -- XXX some of the below can be improved with pretty-simple, https://github.com/cdepillabout/pretty-simple#readme -- | Pretty trace. Easier alias for traceShowId + pShow. ptrace :: Show a => a -> a ptrace = traceWith pshow -- | Like traceShowId, but uses a custom show function to render the value. -- traceShowIdWith was too much of a mouthful. traceWith :: Show a => (a -> String) -> a -> a traceWith f a = trace (f a) a -- | Global debug level, which controls the verbosity of debug errput -- on the console. The default is 0 meaning no debug errput. The -- @--debug@ command line flag sets it to 1, or @--debug=N@ sets it to -- a higher value (note: not @--debug N@ for some reason). This uses -- unsafePerformIO and can be accessed from anywhere and before normal -- command-line processing. When running with :main in GHCI, you must -- touch and reload this module to see the effect of a new --debug option. -- {-# OPTIONS_GHC -fno-cse #-} {-# NOINLINE debugLevel #-} -- Avoid using dbg* in this function (infinite loop). debugLevel :: Int debugLevel = case dropWhile (/="--debug") args of ["--debug"] -> 1 "--debug":n:_ -> readDef 1 n _ -> case take 1 $ filter ("--debug" `isPrefixOf`) args of ['-':'-':'d':'e':'b':'u':'g':'=':v] -> readDef 1 v _ -> 0 where args = unsafePerformIO getArgs -- Avoid using dbg*, pshow etc. in this function (infinite loop). -- | Check the IO environment to see if ANSI colour codes should be used on stdout. -- This is done using unsafePerformIO so it can be used anywhere, eg in -- low-level debug utilities, which should be ok since we are just reading. -- The logic is: use color if -- the program was started with --color=yes|always -- or ( -- the program was not started with --color=no|never -- and a NO_COLOR environment variable is not defined -- and stdout supports ANSI color and -o/--output-file was not used or is "-" -- ). -- Caveats: -- When running code in GHCI, this module must be reloaded to see a change. -- {-# OPTIONS_GHC -fno-cse #-} -- {-# NOINLINE useColorOnStdout #-} useColorOnStdout :: Bool useColorOnStdout = not hasOutputFile && useColorOnHandle stdout -- Avoid using dbg*, pshow etc. in this function (infinite loop). -- | Like useColorOnStdout, but checks for ANSI color support on stderr, -- and is not affected by -o/--output-file. -- {-# OPTIONS_GHC -fno-cse #-} -- {-# NOINLINE useColorOnStdout #-} useColorOnStderr :: Bool useColorOnStderr = useColorOnHandle stderr -- Avoid using dbg*, pshow etc. in this function (infinite loop). -- XXX sorry, I'm just cargo-culting these pragmas: -- {-# OPTIONS_GHC -fno-cse #-} -- {-# NOINLINE useColorOnHandle #-} useColorOnHandle :: Handle -> Bool useColorOnHandle h = unsafePerformIO $ do no_color <- isJust <$> lookupEnv "NO_COLOR" supports_color <- hSupportsANSIColor h let coloroption = colorOption return $ coloroption `elem` ["always","yes"] || (coloroption `notElem` ["never","no"] && not no_color && supports_color) -- Keep synced with color/colour flag definition in hledger:CliOptions. -- Avoid using dbg*, pshow etc. in this function (infinite loop). -- | Read the value of the --color or --colour command line option provided at program startup -- using unsafePerformIO. If this option was not provided, returns the empty string. -- (When running code in GHCI, this module must be reloaded to see a change.) -- {-# OPTIONS_GHC -fno-cse #-} -- {-# NOINLINE colorOption #-} colorOption :: String colorOption = -- similar to debugLevel let args = unsafePerformIO getArgs in case dropWhile (/="--color") args of -- --color ARG "--color":v:_ -> v _ -> case take 1 $ filter ("--color=" `isPrefixOf`) args of -- --color=ARG ['-':'-':'c':'o':'l':'o':'r':'=':v] -> v _ -> case dropWhile (/="--colour") args of -- --colour ARG "--colour":v:_ -> v _ -> case take 1 $ filter ("--colour=" `isPrefixOf`) args of -- --colour=ARG ['-':'-':'c':'o':'l':'o':'u':'r':'=':v] -> v _ -> "" -- Avoid using dbg*, pshow etc. in this function (infinite loop). -- | Check whether the -o/--output-file option has been used at program startup -- with an argument other than "-", using unsafePerformIO. -- {-# OPTIONS_GHC -fno-cse #-} -- {-# NOINLINE hasOutputFile #-} hasOutputFile :: Bool hasOutputFile = outputFileOption `notElem` [Nothing, Just "-"] -- Keep synced with output-file flag definition in hledger:CliOptions. -- Avoid using dbg*, pshow etc. in this function (infinite loop). -- | Read the value of the -o/--output-file command line option provided at program startup, -- if any, using unsafePerformIO. -- (When running code in GHCI, this module must be reloaded to see a change.) -- {-# OPTIONS_GHC -fno-cse #-} -- {-# NOINLINE outputFileOption #-} outputFileOption :: Maybe String outputFileOption = let args = unsafePerformIO getArgs in case dropWhile (not . ("-o" `isPrefixOf`)) args of -- -oARG ('-':'o':v@(_:_)):_ -> Just v -- -o ARG "-o":v:_ -> Just v _ -> case dropWhile (/="--output-file") args of -- --output-file ARG "--output-file":v:_ -> Just v _ -> case take 1 $ filter ("--output-file=" `isPrefixOf`) args of -- --output=file=ARG ['-':'-':'o':'u':'t':'p':'u':'t':'-':'f':'i':'l':'e':'=':v] -> Just v _ -> Nothing -- | Trace (print to stderr) a string if the global debug level is at -- or above the specified level. At level 0, always prints. Otherwise, -- uses unsafePerformIO. traceAt :: Int -> String -> a -> a traceAt level | level > 0 && debugLevel < level = const id | otherwise = trace -- | Trace (print to stderr) a showable value using a custom show function, -- if the global debug level is at or above the specified level. -- At level 0, always prints. Otherwise, uses unsafePerformIO. traceAtWith :: Int -> (a -> String) -> a -> a traceAtWith level f a = traceAt level (f a) a -- | Pretty-print a label and a showable value to the console -- if the global debug level is at or above the specified level. -- At level 0, always prints. Otherwise, uses unsafePerformIO. ptraceAt :: Show a => Int -> String -> a -> a ptraceAt level | level > 0 && debugLevel < level = const id | otherwise = \s a -> let p = pshow a ls = lines p nlorspace | length ls > 1 = "\n" | otherwise = replicate (11 - length s) ' ' ls' | length ls > 1 = map (' ':) ls | otherwise = ls in trace (s++":"++nlorspace++intercalate "\n" ls') a -- | Like ptraceAt, but takes a custom show function instead of a label. ptraceAtWith :: Show a => Int -> (a -> String) -> a -> a ptraceAtWith level f | level > 0 && debugLevel < level = id | otherwise = \a -> let p = f a -- ls = lines p -- nlorspace | length ls > 1 = "\n" -- | otherwise = " " ++ take (10 - length s) (repeat ' ') -- ls' | length ls > 1 = map (" "++) ls -- | otherwise = ls -- in trace (s++":"++nlorspace++intercalate "\n" ls') a in trace p a -- | Log a pretty-printed showable value to "./debug.log". Uses unsafePerformIO. dlog :: Show a => a -> a dlog x = unsafePerformIO $ appendFile "debug.log" (pshow x ++ "\n") >> return x -- "dbg" would clash with megaparsec. -- | Pretty-print a label and the showable value to the console, then return it. dbg0 :: Show a => String -> a -> a dbg0 = ptraceAt 0 -- | Pretty-print a label and the showable value to the console when the global debug level is >= 1, then return it. -- Uses unsafePerformIO. dbg1 :: Show a => String -> a -> a dbg1 = ptraceAt 1 dbg2 :: Show a => String -> a -> a dbg2 = ptraceAt 2 dbg3 :: Show a => String -> a -> a dbg3 = ptraceAt 3 dbg4 :: Show a => String -> a -> a dbg4 = ptraceAt 4 dbg5 :: Show a => String -> a -> a dbg5 = ptraceAt 5 dbg6 :: Show a => String -> a -> a dbg6 = ptraceAt 6 dbg7 :: Show a => String -> a -> a dbg7 = ptraceAt 7 dbg8 :: Show a => String -> a -> a dbg8 = ptraceAt 8 dbg9 :: Show a => String -> a -> a dbg9 = ptraceAt 9 -- | Like dbg0, but also exit the program. Uses unsafePerformIO. dbgExit :: Show a => String -> a -> a dbgExit msg = const (unsafePerformIO exitFailure) . dbg0 msg -- | Like dbg0, but takes a custom show function instead of a label. dbg0With :: Show a => (a -> String) -> a -> a dbg0With = ptraceAtWith 0 dbg1With :: Show a => (a -> String) -> a -> a dbg1With = ptraceAtWith 1 dbg2With :: Show a => (a -> String) -> a -> a dbg2With = ptraceAtWith 2 dbg3With :: Show a => (a -> String) -> a -> a dbg3With = ptraceAtWith 3 dbg4With :: Show a => (a -> String) -> a -> a dbg4With = ptraceAtWith 4 dbg5With :: Show a => (a -> String) -> a -> a dbg5With = ptraceAtWith 5 dbg6With :: Show a => (a -> String) -> a -> a dbg6With = ptraceAtWith 6 dbg7With :: Show a => (a -> String) -> a -> a dbg7With = ptraceAtWith 7 dbg8With :: Show a => (a -> String) -> a -> a dbg8With = ptraceAtWith 8 dbg9With :: Show a => (a -> String) -> a -> a dbg9With = ptraceAtWith 9 -- | Like ptraceAt, but convenient to insert in an IO monad and -- enforces monadic sequencing (plus convenience aliases). -- XXX These have a bug; they should use -- traceIO, not trace, otherwise GHC can occasionally over-optimise -- (cf lpaste a few days ago where it killed/blocked a child thread). ptraceAtIO :: (MonadIO m, Show a) => Int -> String -> a -> m () ptraceAtIO lvl lbl x = liftIO $ ptraceAt lvl lbl x `seq` return () -- XXX Could not deduce (a ~ ()) -- ptraceAtM :: (Monad m, Show a) => Int -> String -> a -> m a -- ptraceAtM lvl lbl x = ptraceAt lvl lbl x `seq` return x dbg0IO :: (MonadIO m, Show a) => String -> a -> m () dbg0IO = ptraceAtIO 0 dbg1IO :: (MonadIO m, Show a) => String -> a -> m () dbg1IO = ptraceAtIO 1 dbg2IO :: (MonadIO m, Show a) => String -> a -> m () dbg2IO = ptraceAtIO 2 dbg3IO :: (MonadIO m, Show a) => String -> a -> m () dbg3IO = ptraceAtIO 3 dbg4IO :: (MonadIO m, Show a) => String -> a -> m () dbg4IO = ptraceAtIO 4 dbg5IO :: (MonadIO m, Show a) => String -> a -> m () dbg5IO = ptraceAtIO 5 dbg6IO :: (MonadIO m, Show a) => String -> a -> m () dbg6IO = ptraceAtIO 6 dbg7IO :: (MonadIO m, Show a) => String -> a -> m () dbg7IO = ptraceAtIO 7 dbg8IO :: (MonadIO m, Show a) => String -> a -> m () dbg8IO = ptraceAtIO 8 dbg9IO :: (MonadIO m, Show a) => String -> a -> m () dbg9IO = ptraceAtIO 9 -- | Print the provided label (if non-null) and current parser state -- (position and next input) to the console. See also megaparsec's dbg. traceParse :: String -> TextParser m () traceParse msg = do pos <- getSourcePos next <- (T.take peeklength) `fmap` getInput let (l,c) = (sourceLine pos, sourceColumn pos) s = printf "at line %2d col %2d: %s" (unPos l) (unPos c) (show next) :: String s' = printf ("%-"++show (peeklength+30)++"s") s ++ " " ++ msg trace s' $ return () where peeklength = 30 -- | Print the provided label (if non-null) and current parser state -- (position and next input) to the console if the global debug level -- is at or above the specified level. Uses unsafePerformIO. -- (See also megaparsec's dbg.) traceParseAt :: Int -> String -> TextParser m () traceParseAt level msg = when (level <= debugLevel) $ traceParse msg -- | Convenience alias for traceParseAt dbgparse :: Int -> String -> TextParser m () dbgparse = traceParseAt
adept/hledger
hledger-lib/Hledger/Utils/Debug.hs
gpl-3.0
15,643
0
30
3,789
3,211
1,728
1,483
232
5
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.AutoScaling.PutScheduledUpdateGroupAction -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates or updates a scheduled scaling action for an Auto Scaling group. -- When updating a scheduled scaling action, if you leave a parameter -- unspecified, the corresponding value remains unchanged in the affected -- Auto Scaling group. -- -- For more information, see -- <http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/schedule_time.html Scheduled Scaling> -- in the /Auto Scaling Developer Guide/. -- -- /See:/ <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_PutScheduledUpdateGroupAction.html AWS API Reference> for PutScheduledUpdateGroupAction. module Network.AWS.AutoScaling.PutScheduledUpdateGroupAction ( -- * Creating a Request putScheduledUpdateGroupAction , PutScheduledUpdateGroupAction -- * Request Lenses , psugaStartTime , psugaTime , psugaMaxSize , psugaRecurrence , psugaDesiredCapacity , psugaMinSize , psugaEndTime , psugaAutoScalingGroupName , psugaScheduledActionName -- * Destructuring the Response , putScheduledUpdateGroupActionResponse , PutScheduledUpdateGroupActionResponse ) where import Network.AWS.AutoScaling.Types import Network.AWS.AutoScaling.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'putScheduledUpdateGroupAction' smart constructor. data PutScheduledUpdateGroupAction = PutScheduledUpdateGroupAction' { _psugaStartTime :: !(Maybe ISO8601) , _psugaTime :: !(Maybe ISO8601) , _psugaMaxSize :: !(Maybe Int) , _psugaRecurrence :: !(Maybe Text) , _psugaDesiredCapacity :: !(Maybe Int) , _psugaMinSize :: !(Maybe Int) , _psugaEndTime :: !(Maybe ISO8601) , _psugaAutoScalingGroupName :: !Text , _psugaScheduledActionName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'PutScheduledUpdateGroupAction' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'psugaStartTime' -- -- * 'psugaTime' -- -- * 'psugaMaxSize' -- -- * 'psugaRecurrence' -- -- * 'psugaDesiredCapacity' -- -- * 'psugaMinSize' -- -- * 'psugaEndTime' -- -- * 'psugaAutoScalingGroupName' -- -- * 'psugaScheduledActionName' putScheduledUpdateGroupAction :: Text -- ^ 'psugaAutoScalingGroupName' -> Text -- ^ 'psugaScheduledActionName' -> PutScheduledUpdateGroupAction putScheduledUpdateGroupAction pAutoScalingGroupName_ pScheduledActionName_ = PutScheduledUpdateGroupAction' { _psugaStartTime = Nothing , _psugaTime = Nothing , _psugaMaxSize = Nothing , _psugaRecurrence = Nothing , _psugaDesiredCapacity = Nothing , _psugaMinSize = Nothing , _psugaEndTime = Nothing , _psugaAutoScalingGroupName = pAutoScalingGroupName_ , _psugaScheduledActionName = pScheduledActionName_ } -- | The time for this action to start, in \"YYYY-MM-DDThh:mm:ssZ\" format in -- UTC\/GMT only (for example, '2014-06-01T00:00:00Z'). -- -- If you try to schedule your action in the past, Auto Scaling returns an -- error message. -- -- When 'StartTime' and 'EndTime' are specified with 'Recurrence', they -- form the boundaries of when the recurring action starts and stops. psugaStartTime :: Lens' PutScheduledUpdateGroupAction (Maybe UTCTime) psugaStartTime = lens _psugaStartTime (\ s a -> s{_psugaStartTime = a}) . mapping _Time; -- | This parameter is deprecated; use 'StartTime' instead. -- -- The time for this action to start. If both 'Time' and 'StartTime' are -- specified, their values must be identical. psugaTime :: Lens' PutScheduledUpdateGroupAction (Maybe UTCTime) psugaTime = lens _psugaTime (\ s a -> s{_psugaTime = a}) . mapping _Time; -- | The maximum size for the Auto Scaling group. psugaMaxSize :: Lens' PutScheduledUpdateGroupAction (Maybe Int) psugaMaxSize = lens _psugaMaxSize (\ s a -> s{_psugaMaxSize = a}); -- | The time when recurring future actions will start. Start time is -- specified by the user following the Unix cron syntax format. For more -- information, see <http://en.wikipedia.org/wiki/Cron Cron> in Wikipedia. -- -- When 'StartTime' and 'EndTime' are specified with 'Recurrence', they -- form the boundaries of when the recurring action will start and stop. psugaRecurrence :: Lens' PutScheduledUpdateGroupAction (Maybe Text) psugaRecurrence = lens _psugaRecurrence (\ s a -> s{_psugaRecurrence = a}); -- | The number of EC2 instances that should be running in the group. psugaDesiredCapacity :: Lens' PutScheduledUpdateGroupAction (Maybe Int) psugaDesiredCapacity = lens _psugaDesiredCapacity (\ s a -> s{_psugaDesiredCapacity = a}); -- | The minimum size for the Auto Scaling group. psugaMinSize :: Lens' PutScheduledUpdateGroupAction (Maybe Int) psugaMinSize = lens _psugaMinSize (\ s a -> s{_psugaMinSize = a}); -- | The time for this action to end. psugaEndTime :: Lens' PutScheduledUpdateGroupAction (Maybe UTCTime) psugaEndTime = lens _psugaEndTime (\ s a -> s{_psugaEndTime = a}) . mapping _Time; -- | The name or Amazon Resource Name (ARN) of the Auto Scaling group. psugaAutoScalingGroupName :: Lens' PutScheduledUpdateGroupAction Text psugaAutoScalingGroupName = lens _psugaAutoScalingGroupName (\ s a -> s{_psugaAutoScalingGroupName = a}); -- | The name of this scaling action. psugaScheduledActionName :: Lens' PutScheduledUpdateGroupAction Text psugaScheduledActionName = lens _psugaScheduledActionName (\ s a -> s{_psugaScheduledActionName = a}); instance AWSRequest PutScheduledUpdateGroupAction where type Rs PutScheduledUpdateGroupAction = PutScheduledUpdateGroupActionResponse request = postQuery autoScaling response = receiveNull PutScheduledUpdateGroupActionResponse' instance ToHeaders PutScheduledUpdateGroupAction where toHeaders = const mempty instance ToPath PutScheduledUpdateGroupAction where toPath = const "/" instance ToQuery PutScheduledUpdateGroupAction where toQuery PutScheduledUpdateGroupAction'{..} = mconcat ["Action" =: ("PutScheduledUpdateGroupAction" :: ByteString), "Version" =: ("2011-01-01" :: ByteString), "StartTime" =: _psugaStartTime, "Time" =: _psugaTime, "MaxSize" =: _psugaMaxSize, "Recurrence" =: _psugaRecurrence, "DesiredCapacity" =: _psugaDesiredCapacity, "MinSize" =: _psugaMinSize, "EndTime" =: _psugaEndTime, "AutoScalingGroupName" =: _psugaAutoScalingGroupName, "ScheduledActionName" =: _psugaScheduledActionName] -- | /See:/ 'putScheduledUpdateGroupActionResponse' smart constructor. data PutScheduledUpdateGroupActionResponse = PutScheduledUpdateGroupActionResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'PutScheduledUpdateGroupActionResponse' with the minimum fields required to make a request. -- putScheduledUpdateGroupActionResponse :: PutScheduledUpdateGroupActionResponse putScheduledUpdateGroupActionResponse = PutScheduledUpdateGroupActionResponse'
fmapfmapfmap/amazonka
amazonka-autoscaling/gen/Network/AWS/AutoScaling/PutScheduledUpdateGroupAction.hs
mpl-2.0
7,971
0
11
1,495
1,020
611
409
120
1
{-# LANGUAGE OverloadedStrings #-} module DB.Admin(resetDatabase) where import Config (dbName) import Control.Monad (when) import qualified Lib.DB as DB import System.Directory (doesFileExist, removeFile) resetDatabase :: IO String resetDatabase = do fileExists <- doesFileExist dbName when fileExists $ removeFile dbName conn <- DB.open dbName mapM_ (DB.execute_ conn) [ "CREATE TABLE IF NOT EXISTS tenant (\ \id INTEGER PRIMARY KEY, \ \name TEXT NOT NULL UNIQUE)" , "CREATE TABLE IF NOT EXISTS project (\ \id INTEGER PRIMARY KEY, \ \tenantId INTEGER , \ \description TEXT, \ \content TEXT)" , "CREATE TABLE IF NOT EXISTS user (\ \id INTEGER PRIMARY KEY, \ \name TEXT NOT NULL, \ \passSalt TEXT, \ \passHash TEXT, \ \identityId INTEGER)" ,"CREATE TABLE IF NOT EXISTS identity (\ \id INTEGER PRIMARY KEY, \ \name TEXT UNIQUE)" ,"CREATE TABLE IF NOT EXISTS claim (\ \id INTEGER PRIMARY KEY, \ \identityId INTEGER, \ \name TEXT, \ \value TEXT)" ] DB.close conn return $ "database " ++ dbName ++ " created."
arealities/simplestore
src/DB/Admin.hs
unlicense
1,283
0
10
436
153
81
72
19
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Program : imageviewer.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:48 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Main where import Qtc.Enums.Classes.Core import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.Classes.Gui import Qtc.Classes.Object import Qtc.Enums.Base import Qtc.ClassTypes.Core import Qtc.Core.Base import Qtc.Enums.Core.Qt import Qtc.Core.QCoreApplication import Qtc.Core.QIODevice import Qtc.Enums.Core.QIODevice import Qtc.Core.QFile import Qtc.ClassTypes.Gui import Qtc.Gui.Base import Qtc.Gui.QApplication import Qtc.Gui.QWidget import Qtc.Gui.QMainWindow import Qtc.Gui.QLabel import Qtc.Gui.QPushButton import Qtc.Gui.QAbstractButton import Qtc.Gui.QRadioButton import Qtc.Gui.QScrollArea import Qtc.Enums.Gui.QSizePolicy import Qtc.Enums.Gui.QPalette import Qtc.Gui.QAction import Qtc.Gui.QKeySequence import Qtc.Gui.QMenu import Qtc.Gui.QMenuBar import Qtc.Gui.QFileDialog import Qtc.Gui.QMessageBox import Qtc.Enums.Gui.QMessageBox import Qtc.Gui.QImage import Qtc.Enums.Gui.QImage import Qtc.Gui.QPixmap import Qtc.Core.QDir import Qtc.Core.QFileInfo import Qtc.Gui.QDialog import Qtc.Gui.QTabWidget import Qtc.Gui.QBoxLayout import Qtc.Gui.QVBoxLayout import Qtc.Gui.QHBoxLayout import Qtc.Gui.QGridLayout import Qtc.Gui.QGroupBox import Qtc.Gui.QButtonGroup import Qtc.Gui.QLayout import Qtc.Gui.QDialogButtonBox import Qtc.Enums.Gui.QDialogButtonBox import Qtc.Gui.QLineEdit import Qtc.Gui.QProgressDialog import Qtc.Gui.QAbstractScrollArea import Qtc.Gui.QScrollBar import Qtc.Gui.QAbstractSlider import Numeric import Data.IORef import Data.Word import Data.Char import Qt.Glome hiding (dir) maybeRead :: Read a => String -> Maybe a maybeRead s = case reads s of [(x, str)] | all isSpace str -> Just x _ -> Nothing type MyQMainWindow = QMainWindowSc (CMyQMainWindow) data CMyQMainWindow = CMyQMainWindow myQMainWindow :: IO (MyQMainWindow) myQMainWindow = qSubClass (qMainWindow ()) type MyQDialog = QDialogSc (CMyQDialog) data CMyQDialog = CMyQDialog myQDialog :: IO (MyQDialog) myQDialog = qSubClass $ qDialog () type MyQTabWidget = QTabWidgetSc (CMyQTabWidget) data CMyQTabWidget = CMyQTabWidget myQTabWidget :: IO (MyQTabWidget) myQTabWidget = qSubClass $ qTabWidget () type MyQPushButton = QPushButtonSc (CMyQPushButton) data CMyQPushButton = CMyQPushButton myQPushButton :: String -> IO (MyQPushButton) myQPushButton t = qSubClass $ qPushButton t data ImgVec = ImgVec { img :: IORef (QImage ()), pxm :: IORef (QPixmap ()), iwidth, iheight, tblock_size, tdepth, fwidth, fheight, strt, s_end, scnum, skp_s, skp_e :: IORef Int, tim, fps :: IORef Double, drr, prf :: IORef String} getIVpxm iv = readIORef (pxm iv) getIVimg iv = readIORef (img iv) setIVpxm iv pm = do cpm <- readIORef (pxm iv) modifyIORef (pxm iv) (\_ -> pm) setIVimg iv im = do cim <- readIORef (img iv) modifyIORef (img iv) (\_ -> im) newVar i = newIORef i getVar :: IORef a -> IO a getVar ioi = readIORef ioi setVar :: IORef a -> a -> IO () setVar ioi i = modifyIORef ioi (\_ -> i) type CellLineEdit_ a = (IORef a, QLineEdit ()) data CellLineEdit = forall a . QrwCell a => CellLineEdit a type ColumnLineEdits = [CellLineEdit] type GridLineEdits = [ColumnLineEdits] data IGR = IGR {ml :: QHBoxLayout (), gle :: GridLineEdits} type Prefs = [GridLineEdits] data ImgAs = ImgAs {zi, zo, ns, fw :: QAction ()} data NblAs = NblAs {sv, pa :: QAction ()} main :: IO () main = do app <- qApplication () mainWindow <- createMainWindow app i <- qImage () p <- qPixmapFromImage i qshow mainWindow () ok <- qApplicationExec () returnGC createMainWindow :: QApplication () -> IO (MyQMainWindow) createMainWindow qapp = do mw <- myQMainWindow imageLabel <- qLabel () setBackgroundRole imageLabel eBase setSizePolicy imageLabel (eIgnored, eIgnored) setScaledContents imageLabel True scrollArea <- qScrollArea () setBackgroundRole scrollArea eDark setWidget scrollArea imageLabel setCentralWidget mw scrollArea ti <- qImage () tp <- qPixmapFromImage ti npi <- newIORef ti npm <- newIORef tp nw <- newVar 256 nh <- newVar 192 nb <- newVar 32 nd <- newVar 2 nfw <- newVar 0 nfh <- newVar 0 ns <- newVar 0 ne <- newVar 0 nn <- newVar 2 nss <- newVar 0 nse <- newVar 0 ntm <- newVar 0.0 nfp <- newVar 24.0 ndir <- newVar "" nprf <- newVar "dgi" let iv = ImgVec npi npm nw nh nb nd nfw nfh ns ne nn nss nse ntm nfp ndir nprf sf <- newIORef (0.0) d <- myQDialog mainLayout <- qVBoxLayout () tw <- myQTabWidget prefs <- mapM (createTab iv tw) [("Image", addImageGrid), ("Sequence", addSequenceGrid), ("Files", addNamesGrid)] addWidget mainLayout tw addWidget mainLayout =<< createButtonBox prefs d setLayout d mainLayout createMenus imageLabel scrollArea sf mw qapp iv d prefs setWindowTitle mw "Image Viewer" resize mw (500::Int, 400::Int) return mw createTab :: ImgVec -> MyQTabWidget -> (String, (QHBoxLayout () -> ImgVec -> IO GridLineEdits)) -> IO GridLineEdits createTab iv tw (title, gf) = do w <- qWidget () l <- qHBoxLayout () gle <- gf l iv setLayout w l addTab tw (w, title) return gle createButtonBox :: Prefs -> MyQDialog -> IO (QWidget a) createButtonBox prefs dlg = do buttonBox <- qDialogButtonBox ((fOk + fCancel)::QDialogButtonBoxStandardButtons) connectSlot buttonBox "accepted()" dlg "myaccept()" (myAccept prefs) connectSlot buttonBox "rejected()" dlg "reject()" () return $ objectCast buttonBox myAccept :: Prefs -> MyQDialog -> IO () myAccept prefs dlg = do mapM_ readGle prefs accept dlg () readGle :: GridLineEdits -> IO () readGle gle = mapM_ readCle gle writeGle :: GridLineEdits -> IO () writeGle gle = mapM_ writeCle gle readCle :: ColumnLineEdits -> IO () readCle cle = mapM_ readCell cle writeCle :: ColumnLineEdits -> IO () writeCle cle = mapM_ writeCell cle class QrwCell a where readCell :: a -> IO () writeCell :: a -> IO () updateCell :: a -> Maybe String -> IO () instance QrwCell CellLineEdit where readCell (CellLineEdit a) = readCell a writeCell (CellLineEdit a) = writeCell a updateCell (CellLineEdit a) = updateCell a instance QrwCell (CellLineEdit_ Int) where readCell (ri, re) = do tw <- text re () case (maybeRead tw) of Just x -> setVar ri $ (x :: Int) _ -> return () writeCell (ri, re) = do i <- getVar ri :: IO Int clear re () insert re $ show i updateCell (ri, re) ms = udc re ms instance QrwCell (CellLineEdit_ Double) where readCell (ri, re) = do tw <- text re () case (maybeRead tw) of Just x -> setVar ri $ (x :: Double) _ -> return () writeCell (ri, re) = do d <- getVar ri :: IO Double clear re () insert re $ show d updateCell (ri, re) ms = udc re ms instance QrwCell (CellLineEdit_ String) where readCell (ri, re) = setVar ri =<< text re () writeCell (ri, re) = do s <- getVar ri :: IO String clear re () insert re s updateCell (ri, re) ms = udc re ms udc :: QLineEdit () -> Maybe String -> IO () udc le ms = case ms of Just s -> do clear le () insert le s Nothing -> return () addImageGrid :: QHBoxLayout () -> ImgVec -> IO GridLineEdits addImageGrid grid iv = createGGBs grid [("Image Dimensions", [(iwidth iv, "Width", "90000000"), (iheight iv, "Height", "90000000")]), ("Trace Parameters", [(tblock_size iv, "Block Size", "90000000"), (tdepth iv, "Depth", "9000")]), ("Final Dimensions", [(fwidth iv, "Width", "9000000"), (fheight iv, "Height", "9000000")])] addSequenceGrid :: QHBoxLayout () -> ImgVec -> IO GridLineEdits addSequenceGrid grid iv = createGGB grid "Timing" [(tim iv, "Elapsed Time", "Xxxxxxxxx"), (fps iv, "Frames Per Second", "Xxxxxxxxx")] >>= \nglef -> createGGBs grid [("Steps", [(strt iv, "Start", "9000000"), (s_end iv, "End", "9000000")]), ("Skip Frames", [(skp_s iv, "Start", "9000000"), (skp_e iv, "End", "9000000")])] >>= \nglei -> return $ nglef:nglei addNamesGrid :: QHBoxLayout () -> ImgVec -> IO GridLineEdits addNamesGrid grid iv = do ng <- createGGBs grid [("Image Names", [(drr iv, "Directory", ""), (prf iv, "Prefix", "")])] chooseGroupBox <- qGroupBox "Select" cl <- qVBoxLayout () setLayout chooseGroupBox cl cb <- myQPushButton "Choose Names" addWidget cl cb addWidget grid chooseGroupBox cbg <- qButtonGroup () clb <- qHBoxLayout () drb <- qRadioButton "Directory" prb <- qRadioButton "Prefix" brb <- qRadioButton "Both" setChecked brb True addButton cbg drb addButton cbg prb addButton cbg brb addWidget clb drb addWidget clb prb addWidget clb brb addLayout cl clb connectSlot cb "clicked()" cb "chooseNames()" $ chooseNames (drr iv) (prf iv) ng drb prb brb return ng createGGBs _ [] = return [] createGGBs grid ((title, fields):tfs) = do cgle <- createGGB grid title fields ngle <- createGGBs grid tfs return (cgle:ngle) createGGB grid title fields = do gridGroupBox <- qGroupBox title gridLayout <- qGridLayout () gle <- add_lablins gridLayout fields setLayout gridGroupBox gridLayout addWidget grid gridGroupBox return gle add_lablins :: QrwCell (CellLineEdit_ a) => QGridLayout () -> [(IORef a, String, String)] -> IO ColumnLineEdits add_lablins lt tms = add_lablinsi lt tms 0 add_lablinsi :: QrwCell (CellLineEdit_ a) => QGridLayout () -> [(IORef a, String, String)] -> Int -> IO ColumnLineEdits add_lablinsi _ [] _ = return [] add_lablinsi lt ((ioi, t, m):tms) cc = do nlb <- qLabel t nln <- qLineEdit () setInputMask nln m addWidget lt (nlb, cc, 0::Int) addWidget lt (nln, cc, 1::Int) nlns <- add_lablinsi lt tms (cc + 1) return ((CellLineEdit (ioi, nln)):nlns) createMenus :: QLabel () -> QScrollArea () -> IORef Double -> MyQMainWindow -> QApplication () -> ImgVec -> MyQDialog -> Prefs -> IO () createMenus il sa sf mw qapp iv d prefs = do openAct <- cfa "&Open..." "Ctrl+O" True saveAct <- cfa "&Save as..." "Ctrl+S" False printAct <- cfa "&Print..." "Ctrl+P" False exitAct <- cfa "E&xit" "Ctrl+Q" True fileMenu <- qMenu ("&File", mw) aam fileMenu True [openAct, saveAct, printAct, exitAct] zoomInAct <- cva "Zoom &In (25%)" "Ctrl++" False zoomOutAct <- cva "Zoom &Out (25%)" "Ctrl+-" False normalSizeAct <- cva "&Normal Size" "Ctrl+N" False fitToWindowAct <- cva "&Fit to Window" "Ctrl+F" True viewMenu <- qMenu ("&View", mw) aam viewMenu True [zoomInAct, zoomOutAct, normalSizeAct, fitToWindowAct] genAct <- csa "&Generate..." "Ctrl+G" prefAct <- csa "&Preferences..." "Ctrl+R" toolsMenu <- qMenu ("&Tools", mw) scenesMenu <- addMenu toolsMenu "&Scenes" gdnScnAct <- qAction ("Geometric Garden", mw) setCheckable gdnScnAct True sdsScnAct <- qAction ("Colored Shadows", mw) setCheckable sdsScnAct True cscnum <- getVar (scnum iv) aam scenesMenu False [gdnScnAct, sdsScnAct] aam toolsMenu False [genAct, prefAct] aboutAct <- qAction ("&About", mw); aboutQtAct <- qAction ("About &Qt", mw); helpMenu <- qMenu ("&Help", mw) aam helpMenu False [aboutAct, aboutQtAct] mb <- menuBar mw () mapM_ (addMenu mb) [fileMenu, viewMenu, toolsMenu, helpMenu] let imgas = ImgAs zoomInAct zoomOutAct normalSizeAct fitToWindowAct nblas = NblAs saveAct printAct let scnvec = [(1, gdnScnAct), (2, sdsScnAct)] mapM_ (\(s, a) -> if (s == cscnum) then setChecked a True else return ()) scnvec mapM_ (\(a, ss, sf) -> connectSlot a "triggered()" mw ss sf) [(openAct, "open()", (myOpen il sa sf nblas imgas iv)), (saveAct, "saveAs()", (saveAs saveAct iv)), (printAct, "print()", myPrint), (zoomInAct, "zoomIn()", (zoomIn il sa sf zoomInAct zoomOutAct)), (zoomOutAct, "zoomOut()", (zoomOut il sa sf zoomInAct zoomOutAct)), (normalSizeAct, "normalSize()", (normalSize il sf)), (fitToWindowAct, "fitToWindow()", (fitToWindow il sa sf imgas)), (genAct, "genScene()", (genScene il sa sf nblas imgas iv)), (prefAct, "preferences()", (preferences d prefs)), (aboutAct, "about()", myAbout)] mapM_ (\a -> connectSlot a "triggered()" mw "switchScene()" (switchScene scnvec (scnum iv))) [gdnScnAct, sdsScnAct] connectSlot exitAct "triggered()" mw "close()" () connectSlot aboutQtAct "triggered()" qapp "aboutQt()" () where cfa txt key ebl = ca txt key ebl False cva txt key chk = ca txt key False chk csa txt key = ca txt key True False ca txt key ebl chk = do na <- qAction (txt, mw) setShortcut na =<< qKeySequence key if (not ebl) then setEnabled na False else return () if (chk) then setCheckable na True else return () return na aam _ _ [] = return () aam mnu True (a:[]) = do addSeparator mnu () addAction mnu a aam mnu ps (a:as) = do addAction mnu a aam mnu ps as switchScene :: [(Int, QAction ())] -> IORef Int -> MyQMainWindow -> IO () switchScene scnvec ioi mw = do mapM_ (\(s, a) -> setChecked a False) scnvec ca <- qCast_QAction =<< sender mw () setChecked ca True mapM_ (\(s, a) -> do ic <- isChecked a () if (ic) then setVar ioi s else return () ) scnvec genScene :: QLabel () -> QScrollArea () -> IORef Double -> NblAs -> ImgAs -> ImgVec -> MyQMainWindow -> IO () genScene il sa sf nas ias iv mw = do bcp <- qDirCurrentPath () sw <- getVar $ iwidth iv sh <- getVar $ iheight iv bs <- getVar $ tblock_size iv dp <- getVar $ tdepth iv sb <- getVar $ strt iv se <- getVar $ s_end iv sn <- getVar $ scnum iv st <- getVar $ tim iv sp <- getVar $ fps iv csk_s <- getVar $ skp_s iv csk_e <- getVar $ skp_e iv fnw <- getVar $ fwidth iv fnh <- getVar $ fheight iv cdr <- getVar $ drr iv cpf <- getVar $ prf iv let ss = se <= sb fsw = fromIntegral sw fsh = fromIntegral sh sts = se - sb + 1 rto = if (st == 0.0) then 1.0 else (fromIntegral sts) / (st * sp) fms = if (st == 0.0) then (fromIntegral sts) else floor (st * sp) sbf = fromIntegral sb cp = if (cdr /= "") then cdr else bcp mb <- qMessageBox mw ni <- qImage (sw, sh, eQImageFormat_RGB888) progress <- qProgressDialog ("Generating Image...", "Abort", 0::Int, sw, mw) setValue progress (0::Int) qshow progress () mapM_ (\t -> do qCoreApplicationProcessEvents () pc <- wasCanceled progress () if (pc) then return () else do setValue progress (0::Int) qshow progress () qCoreApplicationProcessEvents () let rltm = sbf + ((fromIntegral t) * rto) scene <- scn sn sb se (sbf + ((fromIntegral t) * rto)) gen_blocks_list fsw fsh 32 scene ni progress dp qCoreApplicationProcessEvents () pc <- wasCanceled progress () if (pc) then return () else do ni_s <- if (((fnw /= sw) && (fnh /= sh)) && ((fnw > 0) && (fnh > 0))) then scaled ni (fnw, fnh) else return ni np <- qPixmapFromImage ni_s setPixmap il np setIVpxm iv np setIVimg iv ni_s modifyIORef sf (\_ -> 1.0) setEnabled (pa nas) True setEnabled (fw ias) True setEnabled (zi ias) True setEnabled (zo ias) True setEnabled (ns ias) True setEnabled (sv nas) True let filename = cp ++ "/" ++ cpf ++ "_" ++ (sr t sb se) ++ ".png" save ni filename fwchk <- isChecked (fw ias) () if (not fwchk) then adjustSize il () else return () qCoreApplicationProcessEvents () returnGC) [csk_s..(fms-1-csk_e)] qProgressDialog_delete progress returnGC sr :: Int -> Int -> Int -> String sr t b e = let m = Prelude.max b e ml = Prelude.length $ show m tl = Prelude.length $ show t pl = ml - tl in (take pl "0000000000") ++ (show t) preferences :: MyQDialog -> Prefs -> MyQMainWindow -> IO () preferences d prefs mw = do mapM_ writeGle prefs qshow d () chooseNames :: IORef String -> IORef String -> GridLineEdits -> QRadioButton () -> QRadioButton () -> QRadioButton () -> MyQPushButton -> IO () chooseNames dv pv ng drb prb brb this = do fileName <- qFileDialogGetOpenFileName (this, "Choose Image File Names") if (fileName /= "") then do icd <- isChecked drb () icp <- isChecked prb () icb <- isChecked brb () fi <- qFileInfo fileName mfp <- if (icd || icb) then do fd <- dir fi () fp <- path fd () return $ Just fp else return Nothing mpf <- if (icp || icb) then do bn <- baseName fi () return $ Just $ fst $ break ('_'==) bn else return Nothing updateCle (head ng) [mfp, mpf] else return () updateCle :: ColumnLineEdits -> [Maybe String] -> IO () updateCle _ [] = return () updateCle [] _ = return () updateCle (le:cle) (ms:mss) = do updateCell le ms updateCle cle mss myOpen :: QLabel () -> QScrollArea () -> IORef Double -> NblAs -> ImgAs -> ImgVec -> MyQMainWindow -> IO () myOpen il sa sf nas ias iv mw = do fileName <- qFileDialogGetOpenFileName (mw, "Open File") if (fileName /= "") then do ni <- qImage fileName if (objectIsNull ni) then do rb <- qMessageBoxInformation (mw, "Image Viewer", ("Cannot load " ++ fileName ++ ".")) :: IO QMessageBoxStandardButton return () else do w <- qwidth ni () h <- qheight ni () np <- qPixmapFromImage ni setPixmap il np setIVpxm iv np modifyIORef sf (\_ -> 1.0) setEnabled (pa nas) True setEnabled (fw ias) True setEnabled (sv nas) False updateActions (fw ias) (zi ias) (zo ias) (ns ias) fwchk <- isChecked (fw ias) () if (not fwchk) then adjustSize il () else return () else return () returnGC saveAs :: QAction () -> ImgVec -> MyQMainWindow -> IO () saveAs sv iv mw = do cp <- qDirCurrentPath () fileName <- qFileDialogGetSaveFileName (mw, "Save File As", cp) if (fileName /= "") then do civ <- getIVimg iv save civ fileName setEnabled sv False else return () updateActions :: QAction () -> QAction () -> QAction () -> QAction () -> IO () updateActions fw zi zo ns = do fwchk <- isChecked fw () let nfwchk = not fwchk in do setEnabled zi nfwchk setEnabled zo nfwchk setEnabled ns nfwchk scaleImage :: QLabel () -> QScrollArea () -> IORef Double -> Double -> QAction () -> QAction () -> IO () scaleImage il sa sf f zi zo = do pm <- pixmap il () if (objectIsNull pm) then return () else do csf <- readIORef sf let nsf = csf * f modifyIORef sf (\_ -> nsf) w <- qwidth pm () h <- qheight pm () resize il ((round (nsf * (fromIntegral w)))::Int, (round (nsf * (fromIntegral h)))::Int) adjustScrollBar f =<< horizontalScrollBar sa () adjustScrollBar f =<< verticalScrollBar sa () setEnabled zi $ nsf < 3.0 setEnabled zo $ nsf > 0.333 adjustScrollBar :: Double -> QScrollBar () -> IO () adjustScrollBar f sb = do v <- value sb () ps <- pageStep sb () setValue sb (round ((f * (fromIntegral v)) + ((f - 1.0) * ((fromIntegral ps) / 2.0)))::Int) zoomIn :: QLabel () -> QScrollArea () -> IORef Double -> QAction () -> QAction () -> MyQMainWindow -> IO () zoomIn il sa sf zi zo mw = scaleImage il sa sf 1.25 zi zo zoomOut :: QLabel () -> QScrollArea () -> IORef Double -> QAction () -> QAction () -> MyQMainWindow -> IO () zoomOut il sa sf zi zo mw = scaleImage il sa sf 0.8 zi zo normalSize :: QLabel () -> IORef Double -> MyQMainWindow -> IO () normalSize il sf mw = do adjustSize il () modifyIORef sf (\_ -> 1.0) fitToWindow :: QLabel () -> QScrollArea () -> IORef Double -> ImgAs -> MyQMainWindow -> IO () fitToWindow il sa sf ias mw = do fwchk <- isChecked (fw ias) () setWidgetResizable sa fwchk if (not fwchk) then normalSize il sf mw else return () updateActions (fw ias) (zi ias) (zo ias) (ns ias) myPrint :: MyQMainWindow -> IO () myPrint mw = do return () myAbout :: MyQMainWindow -> IO () myAbout mw = do return ()
uduki/hsQt
demos/Glome/imageviewer.hs
bsd-2-clause
21,788
0
25
6,085
8,253
4,069
4,184
-1
-1
{-# OPTIONS -fno-implicit-prelude #-} ----------------------------------------------------------------------------- -- | -- Module : Foreign.Storable -- Copyright : (c) The FFI task force 2001 -- License : see libraries/base/LICENSE -- -- Maintainer : ffi@haskell.org -- Stability : provisional -- Portability : portable -- -- The module "Foreign.Storable" provides most elementary support for -- marshalling and is part of the language-independent portion of the -- Foreign Function Interface (FFI), and will normally be imported via -- the "Foreign" module. -- ----------------------------------------------------------------------------- module Foreign.Storable ( Storable( sizeOf, -- :: a -> Int alignment, -- :: a -> Int peekElemOff, -- :: Ptr a -> Int -> IO a pokeElemOff, -- :: Ptr a -> Int -> a -> IO () peekByteOff, -- :: Ptr b -> Int -> IO a pokeByteOff, -- :: Ptr b -> Int -> a -> IO () peek, -- :: Ptr a -> IO a poke) -- :: Ptr a -> a -> IO () ) where #ifdef __NHC__ import NHC.FFI (Storable(..),Ptr,FunPtr,StablePtr ,Int8,Int16,Int32,Int64,Word8,Word16,Word32,Word64) #else import Control.Monad ( liftM ) #include "MachDeps.h" #include "config.h" #ifdef __GLASGOW_HASKELL__ import GHC.Storable import GHC.Stable ( StablePtr ) import GHC.Num import GHC.Int import GHC.Word import GHC.Stable import GHC.Ptr import GHC.Float import GHC.Err import GHC.IOBase import GHC.Base #else import Data.Int import Data.Word import Foreign.Ptr import Foreign.StablePtr #endif #ifdef __HUGS__ import Hugs.Prelude import Hugs.Storable #endif {- | The member functions of this class facilitate writing values of primitive types to raw memory (which may have been allocated with the above mentioned routines) and reading values from blocks of raw memory. The class, furthermore, includes support for computing the storage requirements and alignment restrictions of storable types. Memory addresses are represented as values of type @'Ptr' a@, for some @a@ which is an instance of class 'Storable'. The type argument to 'Ptr' helps provide some valuable type safety in FFI code (you can\'t mix pointers of different types without an explicit cast), while helping the Haskell type system figure out which marshalling method is needed for a given pointer. All marshalling between Haskell and a foreign language ultimately boils down to translating Haskell data structures into the binary representation of a corresponding data structure of the foreign language and vice versa. To code this marshalling in Haskell, it is necessary to manipulate primtive data types stored in unstructured memory blocks. The class 'Storable' facilitates this manipulation on all types for which it is instantiated, which are the standard basic types of Haskell, the fixed size @Int@ types ('Int8', 'Int16', 'Int32', 'Int64'), the fixed size @Word@ types ('Word8', 'Word16', 'Word32', 'Word64'), 'StablePtr', all types from "Foreign.C.Types", as well as 'Ptr'. Minimal complete definition: 'sizeOf', 'alignment', one of 'peek', 'peekElemOff' and 'peekByteOff', and one of 'poke', 'pokeElemOff' and 'pokeByteOff'. -} class Storable a where sizeOf :: a -> Int -- ^ Computes the storage requirements (in bytes) of the argument. -- The value of the argument is not used. alignment :: a -> Int -- ^ Computes the alignment constraint of the argument. An -- alignment constraint @x@ is fulfilled by any address divisible -- by @x@. The value of the argument is not used. peekElemOff :: Ptr a -> Int -> IO a -- ^ Read a value from a memory area regarded as an array -- of values of the same kind. The first argument specifies -- the start address of the array and the second the index into -- the array (the first element of the array has index -- @0@). The following equality holds, -- -- > peekElemOff addr idx = IOExts.fixIO $ \result -> -- > peek (addr `plusPtr` (idx * sizeOf result)) -- -- Note that this is only a specification, not -- necessarily the concrete implementation of the -- function. pokeElemOff :: Ptr a -> Int -> a -> IO () -- ^ Write a value to a memory area regarded as an array of -- values of the same kind. The following equality holds: -- -- > pokeElemOff addr idx x = -- > poke (addr `plusPtr` (idx * sizeOf x)) x peekByteOff :: Ptr b -> Int -> IO a -- ^ Read a value from a memory location given by a base -- address and offset. The following equality holds: -- -- > peekByteOff addr off = peek (addr `plusPtr` off) pokeByteOff :: Ptr b -> Int -> a -> IO () -- ^ Write a value to a memory location given by a base -- address and offset. The following equality holds: -- -- > pokeByteOff addr off x = poke (addr `plusPtr` off) x peek :: Ptr a -> IO a -- ^ Read a value from the given memory location. -- -- Note that the peek and poke functions might require properly -- aligned addresses to function correctly. This is architecture -- dependent; thus, portable code should ensure that when peeking or -- poking values of some type @a@, the alignment -- constraint for @a@, as given by the function -- 'alignment' is fulfilled. poke :: Ptr a -> a -> IO () -- ^ Write the given value to the given memory location. Alignment -- restrictions might apply; see 'peek'. -- circular default instances #ifdef __GLASGOW_HASKELL__ peekElemOff = peekElemOff_ undefined where peekElemOff_ :: a -> Ptr a -> Int -> IO a peekElemOff_ undef ptr off = peekByteOff ptr (off * sizeOf undef) #else peekElemOff ptr off = peekByteOff ptr (off * sizeOfPtr ptr undefined) #endif pokeElemOff ptr off val = pokeByteOff ptr (off * sizeOf val) val peekByteOff ptr off = peek (ptr `plusPtr` off) pokeByteOff ptr off = poke (ptr `plusPtr` off) peek ptr = peekElemOff ptr 0 poke ptr = pokeElemOff ptr 0 #ifndef __GLASGOW_HASKELL__ sizeOfPtr :: Storable a => Ptr a -> a -> Int sizeOfPtr px x = sizeOf x #endif -- System-dependent, but rather obvious instances instance Storable Bool where sizeOf _ = sizeOf (undefined::HTYPE_INT) alignment _ = alignment (undefined::HTYPE_INT) peekElemOff p i = liftM (/= (0::HTYPE_INT)) $ peekElemOff (castPtr p) i pokeElemOff p i x = pokeElemOff (castPtr p) i (if x then 1 else 0::HTYPE_INT) #define STORABLE(T,size,align,read,write) \ instance Storable (T) where { \ sizeOf _ = size; \ alignment _ = align; \ peekElemOff = read; \ pokeElemOff = write } #ifdef __GLASGOW_HASKELL__ STORABLE(Char,SIZEOF_INT32,ALIGNMENT_INT32, readWideCharOffPtr,writeWideCharOffPtr) #elif defined(__HUGS__) STORABLE(Char,SIZEOF_HSCHAR,ALIGNMENT_HSCHAR, readCharOffPtr,writeCharOffPtr) #endif STORABLE(Int,SIZEOF_HSINT,ALIGNMENT_HSINT, readIntOffPtr,writeIntOffPtr) #ifdef __GLASGOW_HASKELL__ STORABLE(Word,SIZEOF_HSWORD,ALIGNMENT_HSWORD, readWordOffPtr,writeWordOffPtr) #endif STORABLE((Ptr a),SIZEOF_HSPTR,ALIGNMENT_HSPTR, readPtrOffPtr,writePtrOffPtr) STORABLE((FunPtr a),SIZEOF_HSFUNPTR,ALIGNMENT_HSFUNPTR, readFunPtrOffPtr,writeFunPtrOffPtr) STORABLE((StablePtr a),SIZEOF_HSSTABLEPTR,ALIGNMENT_HSSTABLEPTR, readStablePtrOffPtr,writeStablePtrOffPtr) STORABLE(Float,SIZEOF_HSFLOAT,ALIGNMENT_HSFLOAT, readFloatOffPtr,writeFloatOffPtr) STORABLE(Double,SIZEOF_HSDOUBLE,ALIGNMENT_HSDOUBLE, readDoubleOffPtr,writeDoubleOffPtr) STORABLE(Word8,SIZEOF_WORD8,ALIGNMENT_WORD8, readWord8OffPtr,writeWord8OffPtr) STORABLE(Word16,SIZEOF_WORD16,ALIGNMENT_WORD16, readWord16OffPtr,writeWord16OffPtr) STORABLE(Word32,SIZEOF_WORD32,ALIGNMENT_WORD32, readWord32OffPtr,writeWord32OffPtr) STORABLE(Word64,SIZEOF_WORD64,ALIGNMENT_WORD64, readWord64OffPtr,writeWord64OffPtr) STORABLE(Int8,SIZEOF_INT8,ALIGNMENT_INT8, readInt8OffPtr,writeInt8OffPtr) STORABLE(Int16,SIZEOF_INT16,ALIGNMENT_INT16, readInt16OffPtr,writeInt16OffPtr) STORABLE(Int32,SIZEOF_INT32,ALIGNMENT_INT32, readInt32OffPtr,writeInt32OffPtr) STORABLE(Int64,SIZEOF_INT64,ALIGNMENT_INT64, readInt64OffPtr,writeInt64OffPtr) #endif
alekar/hugs
cpphs/tests/Storable.hs
bsd-3-clause
8,408
51
13
1,737
1,010
604
406
-1
-1
{-# LANGUAGE CPP, ScopedTypeVariables #-} -- -- Copyright (C) 2004 Don Stewart - http://www.cse.unsw.edu.au/~dons -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -- USA -- -- This module has was created from System.Plugins.Utils, but has -- had certain functions (with dependencies) removed. module SystemUtils ( Arg, hWrite, dropSuffix, mkModid, changeFileExt, joinFileExt, splitFileExt, isSublistOf, -- :: Eq a => [a] -> [a] -> Bool dirname, basename, (</>), (<.>), (<+>), (<>), newer, encode, decode, EncodedString, panic ) where import Control.Exception (IOException, catch) import Data.Char import Data.List import Prelude hiding (catch) import System.IO import System.Environment ( getEnv ) import System.Directory ( doesFileExist, getModificationTime, removeFile ) -- --------------------------------------------------------------------- -- some misc types we use type Arg = String -- --------------------------------------------------------------------- -- | useful -- panic s = ioError ( userError s ) -- --------------------------------------------------------------------- -- | writeFile for Handles -- hWrite :: Handle -> String -> IO () hWrite hdl src = hPutStr hdl src >> hClose hdl >> return () -- --------------------------------------------------------------------- -- some filename manipulation stuff -- -- | </>, <.> : join two path components -- infixr 6 </> infixr 6 <.> (</>), (<.>), (<+>), (<>) :: FilePath -> FilePath -> FilePath [] </> b = b a </> b = a ++ "/" ++ b [] <.> b = b a <.> b = a ++ "." ++ b [] <+> b = b a <+> b = a ++ " " ++ b [] <> b = b a <> b = a ++ b -- -- | dirname : return the directory portion of a file path -- if null, return "." -- dirname :: FilePath -> FilePath dirname p = let x = findIndices (== '\\') p y = findIndices (== '/') p in if not $ null x then if not $ null y then if (maximum x) > (maximum y) then dirname' '\\' p else dirname' '/' p else dirname' '\\' p else dirname' '/' p where dirname' chara pa = case reverse $ dropWhile (/= chara) $ reverse pa of [] -> "." pa' -> pa' -- -- | basename : return the filename portion of a path -- basename :: FilePath -> FilePath basename p = let x = findIndices (== '\\') p y = findIndices (== '/') p in if not $ null x then if not $ null y then if (maximum x) > (maximum y) then basename' '\\' p else basename' '/' p else basename' '\\' p else basename' '/' p where basename' chara pa = reverse $ takeWhile (/= chara) $ reverse pa -- -- drop suffix -- dropSuffix :: FilePath -> FilePath dropSuffix f = reverse . tail . dropWhile (/= '.') $ reverse f -- -- | work out the mod name from a filepath mkModid :: String -> String mkModid = (takeWhile (/= '.')) . reverse . (takeWhile (\x -> ('/'/= x) && ('\\' /= x))) . reverse ----------------------------------------------------------- -- Code from Cabal ---------------------------------------- -- | Changes the extension of a file path. changeFileExt :: FilePath -- ^ The path information to modify. -> String -- ^ The new extension (without a leading period). -- Specify an empty string to remove an existing -- extension from path. -> FilePath -- ^ A string containing the modified path information. changeFileExt fpath ext = joinFileExt name ext where (name,_) = splitFileExt fpath -- | The 'joinFileExt' function is the opposite of 'splitFileExt'. -- It joins a file name and an extension to form a complete file path. -- -- The general rule is: -- -- > filename `joinFileExt` ext == path -- > where -- > (filename,ext) = splitFileExt path joinFileExt :: String -> String -> FilePath joinFileExt fpath "" = fpath joinFileExt fpath ext = fpath ++ '.':ext -- | Split the path into file name and extension. If the file doesn\'t have extension, -- the function will return empty string. The extension doesn\'t include a leading period. -- -- Examples: -- -- > splitFileExt "foo.ext" == ("foo", "ext") -- > splitFileExt "foo" == ("foo", "") -- > splitFileExt "." == (".", "") -- > splitFileExt ".." == ("..", "") -- > splitFileExt "foo.bar."== ("foo.bar.", "") splitFileExt :: FilePath -> (String, String) splitFileExt p = case break (== '.') fname of (suf@(_:_),_:pre) -> (reverse (pre++fpath), reverse suf) _ -> (p, []) where (fname,fpath) = break isPathSeparator (reverse p) -- | Checks whether the character is a valid path separator for the host -- platform. The valid character is a 'pathSeparator' but since the Windows -- operating system also accepts a slash (\"\/\") since DOS 2, the function -- checks for it on this platform, too. isPathSeparator :: Char -> Bool isPathSeparator ch = #if defined(CYGWIN) || defined(__MINGW32__) ch == '/' || ch == '\\' #else ch == '/' #endif -- Code from Cabal end ------------------------------------ ----------------------------------------------------------- ------------------------------------------------------------------------ -- -- | is file1 newer than file2? -- -- needs some fixing to work with 6.0.x series. (is this true?) -- -- fileExist still seems to throw exceptions on some platforms: ia64 in -- particular. -- -- invarient : we already assume the first file, 'a', exists -- newer :: FilePath -> FilePath -> IO Bool newer a b = do aT <- getModificationTime a bExists <- doesFileExist b if not bExists then return True -- needs compiling else do bT <- getModificationTime b return ( aT > bT ) -- maybe need recompiling ------------------------------------------------------------------------ -- -- | return the Z-Encoding of the string. -- -- Stolen from GHC. Use -package ghc as soon as possible -- type EncodedString = String encode :: String -> EncodedString encode [] = [] encode (c:cs) = encodeCh c ++ encode cs unencodedChar :: Char -> Bool -- True for chars that don't need encoding unencodedChar 'Z' = False unencodedChar 'z' = False unencodedChar c = c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' -- -- Decode is used for user printing. -- decode :: EncodedString -> String decode [] = [] decode ('Z' : d : rest) | isDigit d = decodeTuple d rest | otherwise = decodeUpper d : decode rest decode ('z' : d : rest) | isDigit d = decodeNumEsc d rest | otherwise = decodeLower d : decode rest decode (c : rest) = c : decode rest decodeUpper, decodeLower :: Char -> Char decodeUpper 'L' = '(' decodeUpper 'R' = ')' decodeUpper 'M' = '[' decodeUpper 'N' = ']' decodeUpper 'C' = ':' decodeUpper 'Z' = 'Z' decodeUpper ch = error $ "decodeUpper can't handle this char `"++[ch]++"'" decodeLower 'z' = 'z' decodeLower 'a' = '&' decodeLower 'b' = '|' decodeLower 'c' = '^' decodeLower 'd' = '$' decodeLower 'e' = '=' decodeLower 'g' = '>' decodeLower 'h' = '#' decodeLower 'i' = '.' decodeLower 'l' = '<' decodeLower 'm' = '-' decodeLower 'n' = '!' decodeLower 'p' = '+' decodeLower 'q' = '\'' decodeLower 'r' = '\\' decodeLower 's' = '/' decodeLower 't' = '*' decodeLower 'u' = '_' decodeLower 'v' = '%' decodeLower ch = error $ "decodeLower can't handle this char `"++[ch]++"'" -- Characters not having a specific code are coded as z224U decodeNumEsc :: Char -> [Char] -> String decodeNumEsc d cs = go (digitToInt d) cs where go n (c : rest) | isDigit c = go (10*n + digitToInt c) rest go n ('U' : rest) = chr n : decode rest go _ other = error $ "decodeNumEsc can't handle this: \""++other++"\"" encodeCh :: Char -> EncodedString encodeCh c | unencodedChar c = [c] -- Common case first -- Constructors encodeCh '(' = "ZL" -- Needed for things like (,), and (->) encodeCh ')' = "ZR" -- For symmetry with ( encodeCh '[' = "ZM" encodeCh ']' = "ZN" encodeCh ':' = "ZC" encodeCh 'Z' = "ZZ" -- Variables encodeCh 'z' = "zz" encodeCh '&' = "za" encodeCh '|' = "zb" encodeCh '^' = "zc" encodeCh '$' = "zd" encodeCh '=' = "ze" encodeCh '>' = "zg" encodeCh '#' = "zh" encodeCh '.' = "zi" encodeCh '<' = "zl" encodeCh '-' = "zm" encodeCh '!' = "zn" encodeCh '+' = "zp" encodeCh '\'' = "zq" encodeCh '\\' = "zr" encodeCh '/' = "zs" encodeCh '*' = "zt" encodeCh '_' = "zu" encodeCh '%' = "zv" encodeCh c = 'z' : shows (ord c) "U" decodeTuple :: Char -> EncodedString -> String decodeTuple d cs = go (digitToInt d) cs where go n (c : rest) | isDigit c = go (10*n + digitToInt c) rest go 0 ['T'] = "()" go n ['T'] = '(' : replicate (n-1) ',' ++ ")" go 1 ['H'] = "(# #)" go n ['H'] = '(' : '#' : replicate (n-1) ',' ++ "#)" go _ other = error $ "decodeTuple \'"++other++"'" -- --------------------------------------------------------------------- -- -- 'isSublistOf' takes two arguments and returns 'True' iff the first -- list is a sublist of the second list. This means that the first list -- is wholly contained within the second list. Both lists must be -- finite. isSublistOf :: Eq a => [a] -> [a] -> Bool isSublistOf [] _ = True isSublistOf _ [] = False isSublistOf x y@(_:ys) | isPrefixOf x y = True | otherwise = isSublistOf x ys
Paow/encore
src/front/SystemUtils.hs
bsd-3-clause
10,330
0
15
2,550
2,452
1,317
1,135
187
6
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE JavaScriptFFI #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Reflex.Dom.SemanticUI.Input where ------------------------------------------------------------------------------ import Data.Default import Data.Maybe import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import Reflex.Dom.Core hiding (fromJSString) ------------------------------------------------------------------------------ import Reflex.Dom.SemanticUI.Common import Reflex.Dom.SemanticUI.Icon ------------------------------------------------------------------------------ data UiInput = UiInput { _uiInput_size :: Maybe UiSize , _uiInput_left :: Maybe UiLeft , _uiInput_loading :: Maybe UiLoading , _uiInput_disabled :: Maybe UiDisabled , _uiInput_error :: Maybe UiError , _uiInput_transparent :: Maybe UiTransparent , _uiInput_inverted :: Maybe UiInverted , _uiInput_fluid :: Maybe UiFluid , _uiInput_custom :: Maybe Text } deriving (Eq,Show) instance Default UiInput where def = UiInput def def def def def def def def def instance UiHasSize UiInput where uiSetSize s i = i { _uiInput_size = Just s } instance UiHasLeft UiInput where uiLeft i = i { _uiInput_left = Just UiLeft } instance UiHasLoading UiInput where loading i = i { _uiInput_loading = Just UiLoading } instance UiHasDisabled UiInput where disabled i = i { _uiInput_disabled = Just UiDisabled } instance UiHasError UiInput where hasError i = i { _uiInput_error = Just UiError } instance UiHasTransparent UiInput where transparent i = i { _uiInput_transparent = Just UiTransparent } instance UiHasInverted UiInput where inverted i = i { _uiInput_inverted = Just UiInverted } instance UiHasFluid UiInput where fluid i = i { _uiInput_fluid = Just UiFluid } instance UiHasCustom UiInput where custom s i = i { _uiInput_custom = addCustom s (_uiInput_custom i) } uiInputAttrs :: UiInput -> Text uiInputAttrs UiInput{..} = T.unwords $ catMaybes [ uiText <$> _uiInput_size , uiText <$> _uiInput_left , (<> " icon") . uiText <$> _uiInput_loading , uiText <$> _uiInput_disabled , uiText <$> _uiInput_error , uiText <$> _uiInput_transparent , uiText <$> _uiInput_inverted , uiText <$> _uiInput_fluid , _uiInput_custom ] uiInput :: MonadWidget t m => Dynamic t UiInput -> m a -> m a uiInput iDyn children = elDynAttr "div" (mkAttrs <$> iDyn) children where mkAttrs i = "class" =: T.unwords ["ui", uiInputAttrs i, "input"] uiTextInput' :: MonadWidget t m => Dynamic t UiInput -> TextInputConfig t -> m a -> m (TextInput t, a) uiTextInput' iDyn tic c = uiInput iDyn $ do iRes <- textInput tic cRes <- c return (iRes, cRes) uiTextInput :: MonadWidget t m => Dynamic t UiInput -> TextInputConfig t -> m (TextInput t) uiTextInput iDyn c = do (res,_) <- uiTextInput' iDyn c blank return res uiIconTextInput :: MonadWidget t m => Text -> Dynamic t UiIcon -> Dynamic t UiInput -> TextInputConfig t -> m (TextInput t, Event t ()) uiIconTextInput iconType iconDyn inputDyn c = uiTextInput' (modCustom (addCustom "icon") <$> inputDyn) c $ uiIcon iconType iconDyn where modCustom :: (Maybe Text -> Maybe Text) -> UiInput -> UiInput modCustom f i = i { _uiInput_custom = f (_uiInput_custom i) } -- TODO Add functions for labelled buttons and action buttons
et4te/zero
src/Reflex/Dom/SemanticUI/Input.hs
bsd-3-clause
4,039
0
13
977
992
522
470
102
1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.List -- Copyright : (c) David Himmelstrup 2005 -- Duncan Coutts 2008-2011 -- License : BSD-like -- -- Maintainer : cabal-devel@haskell.org -- -- Search for and print information about packages ----------------------------------------------------------------------------- module Distribution.Client.List ( list, info ) where import Distribution.Package ( PackageName(..), Package(..), packageName, packageVersion , Dependency(..), simplifyDependency , UnitId ) import Distribution.ModuleName (ModuleName) import Distribution.License (License) import qualified Distribution.InstalledPackageInfo as Installed import qualified Distribution.PackageDescription as Source import Distribution.PackageDescription ( Flag(..), FlagName(..) ) import Distribution.PackageDescription.Configuration ( flattenPackageDescription ) import Distribution.Simple.Compiler ( Compiler, PackageDBStack ) import Distribution.Simple.Program (ProgramConfiguration) import Distribution.Simple.Utils ( equating, comparing, die, notice ) import Distribution.Simple.Setup (fromFlag) import Distribution.Simple.PackageIndex (InstalledPackageIndex) import qualified Distribution.Simple.PackageIndex as InstalledPackageIndex import qualified Distribution.Client.PackageIndex as PackageIndex import Distribution.Version ( Version(..), VersionRange, withinRange, anyVersion , intersectVersionRanges, simplifyVersionRange ) import Distribution.Verbosity (Verbosity) import Distribution.Text ( Text(disp), display ) import Distribution.Client.Types ( SourcePackage(..), SourcePackageDb(..) , UnresolvedSourcePackage ) import Distribution.Client.Dependency.Types ( PackageConstraint(..) ) import Distribution.Client.Targets ( UserTarget, resolveUserTargets, PackageSpecifier(..) ) import Distribution.Client.Setup ( GlobalFlags(..), ListFlags(..), InfoFlags(..) , RepoContext(..) ) import Distribution.Client.Utils ( mergeBy, MergeResult(..) ) import Distribution.Client.IndexUtils as IndexUtils ( getSourcePackages, getInstalledPackages ) import Distribution.Client.FetchUtils ( isFetched ) import Data.List ( sortBy, groupBy, sort, nub, intersperse, maximumBy, partition ) import Data.Maybe ( listToMaybe, fromJust, fromMaybe, isJust ) import qualified Data.Map as Map import Data.Tree as Tree import Control.Monad ( MonadPlus(mplus), join ) import Control.Exception ( assert ) import Text.PrettyPrint as Disp import System.Directory ( doesDirectoryExist ) -- | Return a list of packages matching given search strings. getPkgList :: Verbosity -> PackageDBStack -> RepoContext -> Compiler -> ProgramConfiguration -> ListFlags -> [String] -> IO [PackageDisplayInfo] getPkgList verbosity packageDBs repoCtxt comp conf listFlags pats = do installedPkgIndex <- getInstalledPackages verbosity comp packageDBs conf sourcePkgDb <- getSourcePackages verbosity repoCtxt let sourcePkgIndex = packageIndex sourcePkgDb prefs name = fromMaybe anyVersion (Map.lookup name (packagePreferences sourcePkgDb)) pkgsInfo :: [(PackageName, [Installed.InstalledPackageInfo], [UnresolvedSourcePackage])] pkgsInfo -- gather info for all packages | null pats = mergePackages (InstalledPackageIndex.allPackages installedPkgIndex) ( PackageIndex.allPackages sourcePkgIndex) -- gather info for packages matching search term | otherwise = pkgsInfoMatching pkgsInfoMatching :: [(PackageName, [Installed.InstalledPackageInfo], [UnresolvedSourcePackage])] pkgsInfoMatching = let matchingInstalled = matchingPackages InstalledPackageIndex.searchByNameSubstring installedPkgIndex matchingSource = matchingPackages (\ idx n -> concatMap snd (PackageIndex.searchByNameSubstring idx n)) sourcePkgIndex in mergePackages matchingInstalled matchingSource matches :: [PackageDisplayInfo] matches = [ mergePackageInfo pref installedPkgs sourcePkgs selectedPkg False | (pkgname, installedPkgs, sourcePkgs) <- pkgsInfo , not onlyInstalled || not (null installedPkgs) , let pref = prefs pkgname selectedPkg = latestWithPref pref sourcePkgs ] return matches where onlyInstalled = fromFlag (listInstalled listFlags) matchingPackages search index = [ pkg | pat <- pats , pkg <- search index pat ] -- | Show information about packages. list :: Verbosity -> PackageDBStack -> RepoContext -> Compiler -> ProgramConfiguration -> ListFlags -> [String] -> IO () list verbosity packageDBs repos comp conf listFlags pats = do matches <- getPkgList verbosity packageDBs repos comp conf listFlags pats if simpleOutput then putStr $ unlines [ display (pkgName pkg) ++ " " ++ display version | pkg <- matches , version <- if onlyInstalled then installedVersions pkg else nub . sort $ installedVersions pkg ++ sourceVersions pkg ] -- Note: this only works because for 'list', one cannot currently -- specify any version constraints, so listing all installed -- and source ones works. else if null matches then notice verbosity "No matches found." else putStr $ unlines (map showPackageSummaryInfo matches) where onlyInstalled = fromFlag (listInstalled listFlags) simpleOutput = fromFlag (listSimpleOutput listFlags) info :: Verbosity -> PackageDBStack -> RepoContext -> Compiler -> ProgramConfiguration -> GlobalFlags -> InfoFlags -> [UserTarget] -> IO () info verbosity _ _ _ _ _ _ [] = notice verbosity "No packages requested. Nothing to do." info verbosity packageDBs repoCtxt comp conf globalFlags _listFlags userTargets = do installedPkgIndex <- getInstalledPackages verbosity comp packageDBs conf sourcePkgDb <- getSourcePackages verbosity repoCtxt let sourcePkgIndex = packageIndex sourcePkgDb prefs name = fromMaybe anyVersion (Map.lookup name (packagePreferences sourcePkgDb)) -- Users may specify names of packages that are only installed, not -- just available source packages, so we must resolve targets using -- the combination of installed and source packages. let sourcePkgs' = PackageIndex.fromList $ map packageId (InstalledPackageIndex.allPackages installedPkgIndex) ++ map packageId (PackageIndex.allPackages sourcePkgIndex) pkgSpecifiers <- resolveUserTargets verbosity repoCtxt (fromFlag $ globalWorldFile globalFlags) sourcePkgs' userTargets pkgsinfo <- sequence [ do pkginfo <- either die return $ gatherPkgInfo prefs installedPkgIndex sourcePkgIndex pkgSpecifier updateFileSystemPackageDetails pkginfo | pkgSpecifier <- pkgSpecifiers ] putStr $ unlines (map showPackageDetailedInfo pkgsinfo) where gatherPkgInfo :: (PackageName -> VersionRange) -> InstalledPackageIndex -> PackageIndex.PackageIndex UnresolvedSourcePackage -> PackageSpecifier UnresolvedSourcePackage -> Either String PackageDisplayInfo gatherPkgInfo prefs installedPkgIndex sourcePkgIndex (NamedPackage name constraints) | null (selectedInstalledPkgs) && null (selectedSourcePkgs) = Left $ "There is no available version of " ++ display name ++ " that satisfies " ++ display (simplifyVersionRange verConstraint) | otherwise = Right $ mergePackageInfo pref installedPkgs sourcePkgs selectedSourcePkg' showPkgVersion where (pref, installedPkgs, sourcePkgs) = sourcePkgsInfo prefs name installedPkgIndex sourcePkgIndex selectedInstalledPkgs = InstalledPackageIndex.lookupDependency installedPkgIndex (Dependency name verConstraint) selectedSourcePkgs = PackageIndex.lookupDependency sourcePkgIndex (Dependency name verConstraint) selectedSourcePkg' = latestWithPref pref selectedSourcePkgs -- display a specific package version if the user -- supplied a non-trivial version constraint showPkgVersion = not (null verConstraints) verConstraint = foldr intersectVersionRanges anyVersion verConstraints verConstraints = [ vr | PackageConstraintVersion _ vr <- constraints ] gatherPkgInfo prefs installedPkgIndex sourcePkgIndex (SpecificSourcePackage pkg) = Right $ mergePackageInfo pref installedPkgs sourcePkgs selectedPkg True where name = packageName pkg selectedPkg = Just pkg (pref, installedPkgs, sourcePkgs) = sourcePkgsInfo prefs name installedPkgIndex sourcePkgIndex sourcePkgsInfo :: (PackageName -> VersionRange) -> PackageName -> InstalledPackageIndex -> PackageIndex.PackageIndex UnresolvedSourcePackage -> (VersionRange, [Installed.InstalledPackageInfo], [UnresolvedSourcePackage]) sourcePkgsInfo prefs name installedPkgIndex sourcePkgIndex = (pref, installedPkgs, sourcePkgs) where pref = prefs name installedPkgs = concatMap snd (InstalledPackageIndex.lookupPackageName installedPkgIndex name) sourcePkgs = PackageIndex.lookupPackageName sourcePkgIndex name -- | The info that we can display for each package. It is information per -- package name and covers all installed and available versions. -- data PackageDisplayInfo = PackageDisplayInfo { pkgName :: PackageName, selectedVersion :: Maybe Version, selectedSourcePkg :: Maybe UnresolvedSourcePackage, installedVersions :: [Version], sourceVersions :: [Version], preferredVersions :: VersionRange, homepage :: String, bugReports :: String, sourceRepo :: String, synopsis :: String, description :: String, category :: String, license :: License, author :: String, maintainer :: String, dependencies :: [ExtDependency], flags :: [Flag], hasLib :: Bool, hasExe :: Bool, executables :: [String], modules :: [ModuleName], haddockHtml :: FilePath, haveTarball :: Bool } -- | Covers source dependencies and installed dependencies in -- one type. data ExtDependency = SourceDependency Dependency | InstalledDependency UnitId showPackageSummaryInfo :: PackageDisplayInfo -> String showPackageSummaryInfo pkginfo = renderStyle (style {lineLength = 80, ribbonsPerLine = 1}) $ char '*' <+> disp (pkgName pkginfo) $+$ (nest 4 $ vcat [ maybeShow (synopsis pkginfo) "Synopsis:" reflowParagraphs , text "Default available version:" <+> case selectedSourcePkg pkginfo of Nothing -> text "[ Not available from any configured repository ]" Just pkg -> disp (packageVersion pkg) , text "Installed versions:" <+> case installedVersions pkginfo of [] | hasLib pkginfo -> text "[ Not installed ]" | otherwise -> text "[ Unknown ]" versions -> dispTopVersions 4 (preferredVersions pkginfo) versions , maybeShow (homepage pkginfo) "Homepage:" text , text "License: " <+> text (display (license pkginfo)) ]) $+$ text "" where maybeShow [] _ _ = empty maybeShow l s f = text s <+> (f l) showPackageDetailedInfo :: PackageDisplayInfo -> String showPackageDetailedInfo pkginfo = renderStyle (style {lineLength = 80, ribbonsPerLine = 1}) $ char '*' <+> disp (pkgName pkginfo) <> maybe empty (\v -> char '-' <> disp v) (selectedVersion pkginfo) <+> text (replicate (16 - length (display (pkgName pkginfo))) ' ') <> parens pkgkind $+$ (nest 4 $ vcat [ entry "Synopsis" synopsis hideIfNull reflowParagraphs , entry "Versions available" sourceVersions (altText null "[ Not available from server ]") (dispTopVersions 9 (preferredVersions pkginfo)) , entry "Versions installed" installedVersions (altText null (if hasLib pkginfo then "[ Not installed ]" else "[ Unknown ]")) (dispTopVersions 4 (preferredVersions pkginfo)) , entry "Homepage" homepage orNotSpecified text , entry "Bug reports" bugReports orNotSpecified text , entry "Description" description hideIfNull reflowParagraphs , entry "Category" category hideIfNull text , entry "License" license alwaysShow disp , entry "Author" author hideIfNull reflowLines , entry "Maintainer" maintainer hideIfNull reflowLines , entry "Source repo" sourceRepo orNotSpecified text , entry "Executables" executables hideIfNull (commaSep text) , entry "Flags" flags hideIfNull (commaSep dispFlag) , entry "Dependencies" dependencies hideIfNull (commaSep dispExtDep) , entry "Documentation" haddockHtml showIfInstalled text , entry "Cached" haveTarball alwaysShow dispYesNo , if not (hasLib pkginfo) then empty else text "Modules:" $+$ nest 4 (vcat (map disp . sort . modules $ pkginfo)) ]) $+$ text "" where entry fname field cond format = case cond (field pkginfo) of Nothing -> label <+> format (field pkginfo) Just Nothing -> empty Just (Just other) -> label <+> text other where label = text fname <> char ':' <> padding padding = text (replicate (13 - length fname ) ' ') normal = Nothing hide = Just Nothing replace msg = Just (Just msg) alwaysShow = const normal hideIfNull v = if null v then hide else normal showIfInstalled v | not isInstalled = hide | null v = replace "[ Not installed ]" | otherwise = normal altText nul msg v = if nul v then replace msg else normal orNotSpecified = altText null "[ Not specified ]" commaSep f = Disp.fsep . Disp.punctuate (Disp.char ',') . map f dispFlag f = case flagName f of FlagName n -> text n dispYesNo True = text "Yes" dispYesNo False = text "No" dispExtDep (SourceDependency dep) = disp dep dispExtDep (InstalledDependency dep) = disp dep isInstalled = not (null (installedVersions pkginfo)) hasExes = length (executables pkginfo) >= 2 --TODO: exclude non-buildable exes pkgkind | hasLib pkginfo && hasExes = text "programs and library" | hasLib pkginfo && hasExe pkginfo = text "program and library" | hasLib pkginfo = text "library" | hasExes = text "programs" | hasExe pkginfo = text "program" | otherwise = empty reflowParagraphs :: String -> Doc reflowParagraphs = vcat . intersperse (text "") -- re-insert blank lines . map (fsep . map text . concatMap words) -- reflow paragraphs . filter (/= [""]) . groupBy (\x y -> "" `notElem` [x,y]) -- break on blank lines . lines reflowLines :: String -> Doc reflowLines = vcat . map text . lines -- | We get the 'PackageDisplayInfo' by combining the info for the installed -- and available versions of a package. -- -- * We're building info about a various versions of a single named package so -- the input package info records are all supposed to refer to the same -- package name. -- mergePackageInfo :: VersionRange -> [Installed.InstalledPackageInfo] -> [UnresolvedSourcePackage] -> Maybe UnresolvedSourcePackage -> Bool -> PackageDisplayInfo mergePackageInfo versionPref installedPkgs sourcePkgs selectedPkg showVer = assert (length installedPkgs + length sourcePkgs > 0) $ PackageDisplayInfo { pkgName = combine packageName source packageName installed, selectedVersion = if showVer then fmap packageVersion selectedPkg else Nothing, selectedSourcePkg = sourceSelected, installedVersions = map packageVersion installedPkgs, sourceVersions = map packageVersion sourcePkgs, preferredVersions = versionPref, license = combine Source.license source Installed.license installed, maintainer = combine Source.maintainer source Installed.maintainer installed, author = combine Source.author source Installed.author installed, homepage = combine Source.homepage source Installed.homepage installed, bugReports = maybe "" Source.bugReports source, sourceRepo = fromMaybe "" . join . fmap (uncons Nothing Source.repoLocation . sortBy (comparing Source.repoKind) . Source.sourceRepos) $ source, --TODO: installed package info is missing synopsis synopsis = maybe "" Source.synopsis source, description = combine Source.description source Installed.description installed, category = combine Source.category source Installed.category installed, flags = maybe [] Source.genPackageFlags sourceGeneric, hasLib = isJust installed || fromMaybe False (fmap (not . null . Source.condLibraries) sourceGeneric), hasExe = fromMaybe False (fmap (not . null . Source.condExecutables) sourceGeneric), executables = map fst (maybe [] Source.condExecutables sourceGeneric), modules = combine (map Installed.exposedName . Installed.exposedModules) installed (concatMap getListOfExposedModules . Source.libraries) source, dependencies = combine (map (SourceDependency . simplifyDependency) . Source.buildDepends) source (map InstalledDependency . Installed.depends) installed, haddockHtml = fromMaybe "" . join . fmap (listToMaybe . Installed.haddockHTMLs) $ installed, haveTarball = False } where combine f x g y = fromJust (fmap f x `mplus` fmap g y) installed :: Maybe Installed.InstalledPackageInfo installed = latestWithPref versionPref installedPkgs getListOfExposedModules lib = Source.exposedModules lib ++ map Source.moduleReexportName (Source.reexportedModules lib) sourceSelected | isJust selectedPkg = selectedPkg | otherwise = latestWithPref versionPref sourcePkgs sourceGeneric = fmap packageDescription sourceSelected source = fmap flattenPackageDescription sourceGeneric uncons :: b -> (a -> b) -> [a] -> b uncons z _ [] = z uncons _ f (x:_) = f x -- | Not all the info is pure. We have to check if the docs really are -- installed, because the registered package info lies. Similarly we have to -- check if the tarball has indeed been fetched. -- updateFileSystemPackageDetails :: PackageDisplayInfo -> IO PackageDisplayInfo updateFileSystemPackageDetails pkginfo = do fetched <- maybe (return False) (isFetched . packageSource) (selectedSourcePkg pkginfo) docsExist <- doesDirectoryExist (haddockHtml pkginfo) return pkginfo { haveTarball = fetched, haddockHtml = if docsExist then haddockHtml pkginfo else "" } latestWithPref :: Package pkg => VersionRange -> [pkg] -> Maybe pkg latestWithPref _ [] = Nothing latestWithPref pref pkgs = Just (maximumBy (comparing prefThenVersion) pkgs) where prefThenVersion pkg = let ver = packageVersion pkg in (withinRange ver pref, ver) -- | Rearrange installed and source packages into groups referring to the -- same package by name. In the result pairs, the lists are guaranteed to not -- both be empty. -- mergePackages :: [Installed.InstalledPackageInfo] -> [UnresolvedSourcePackage] -> [( PackageName , [Installed.InstalledPackageInfo] , [UnresolvedSourcePackage] )] mergePackages installedPkgs sourcePkgs = map collect $ mergeBy (\i a -> fst i `compare` fst a) (groupOn packageName installedPkgs) (groupOn packageName sourcePkgs) where collect (OnlyInLeft (name,is) ) = (name, is, []) collect ( InBoth (_,is) (name,as)) = (name, is, as) collect (OnlyInRight (name,as)) = (name, [], as) groupOn :: Ord key => (a -> key) -> [a] -> [(key,[a])] groupOn key = map (\xs -> (key (head xs), xs)) . groupBy (equating key) . sortBy (comparing key) dispTopVersions :: Int -> VersionRange -> [Version] -> Doc dispTopVersions n pref vs = (Disp.fsep . Disp.punctuate (Disp.char ',') . map (\ver -> if ispref ver then disp ver else parens (disp ver)) . sort . take n . interestingVersions ispref $ vs) <+> trailingMessage where ispref ver = withinRange ver pref extra = length vs - n trailingMessage | extra <= 0 = Disp.empty | otherwise = Disp.parens $ Disp.text "and" <+> Disp.int (length vs - n) <+> if extra == 1 then Disp.text "other" else Disp.text "others" -- | Reorder a bunch of versions to put the most interesting / significant -- versions first. A preferred version range is taken into account. -- -- This may be used in a user interface to select a small number of versions -- to present to the user, e.g. -- -- > let selectVersions = sort . take 5 . interestingVersions pref -- interestingVersions :: (Version -> Bool) -> [Version] -> [Version] interestingVersions pref = map ((\ns -> Version ns []) . fst) . filter snd . concat . Tree.levels . swizzleTree . reorderTree (\(Node (v,_) _) -> pref (Version v [])) . reverseTree . mkTree . map versionBranch where swizzleTree = unfoldTree (spine []) where spine ts' (Node x []) = (x, ts') spine ts' (Node x (t:ts)) = spine (Node x ts:ts') t reorderTree _ (Node x []) = Node x [] reorderTree p (Node x ts) = Node x (ts' ++ ts'') where (ts',ts'') = partition p (map (reorderTree p) ts) reverseTree (Node x cs) = Node x (reverse (map reverseTree cs)) mkTree xs = unfoldTree step (False, [], xs) where step (node,ns,vs) = ( (reverse ns, node) , [ (any null vs', n:ns, filter (not . null) vs') | (n, vs') <- groups vs ] ) groups = map (\g -> (head (head g), map tail g)) . groupBy (equating head)
gbaz/cabal
cabal-install/Distribution/Client/List.hs
bsd-3-clause
24,732
0
20
7,664
5,609
2,950
2,659
466
9
{-# LANGUAGE MagicHash, OverloadedStrings #-} module Eta.CodeGen.Name ( qualifiedName, fastStringText, fastZStringText, nameText, nameTypeText, nameTypeTable, idNameText, idClassText, moduleJavaClass, dataConClass, tyConClass, moduleClass, closure, classFilePath, labelToMethod, idFastString, filterDataTyCons ) where import Eta.Main.DynFlags import Eta.Types.TyCon import Eta.BasicTypes.DataCon import Eta.BasicTypes.Module import Eta.Utils.FastString import Eta.BasicTypes.Name hiding (pprOccName) import Eta.BasicTypes.Id import Data.Char as C import Data.Maybe import qualified Data.List as L import Data.Text as T hiding (map, init, last) import Data.Text.Encoding import Eta.Debug import Eta.Utils.Encoding import qualified Eta.Utils.Util as Split (split) import Codec.JVM qualifiedName :: Text -> Text -> Text qualifiedName modClass className = append modClass . cons '$' $ className subpackageName :: Text -> Text -> Text -> Text subpackageName subpkg modClass className = T.concat [T.toLower modClass, "/", subpkg, "/", className] -- TODO: Remove this entirely closure :: Text -> Text closure = id nameTypeText :: DynFlags -> Name -> Text nameTypeText dflags name | T.toLower res == "con" = T.concat ["Z", res, "Z"] | otherwise = res where res = nameText dflags False name nameTypeTable :: DynFlags -> Name -> Text nameTypeTable dflags = flip append "_table" . nameText dflags False nameText :: DynFlags -> Bool -> Name -> Text nameText dflags caseEncode = T.pack . maybeEncodeCase . zEncodeString . showSDoc dflags . pprName where maybeEncodeCase = if caseEncode then encodeCase else id encodeCase :: String -> String encodeCase str@(c:_) | isUpper c = 'D':str | otherwise = str encodeCase _ = "" -- NOTE: This must be kept in sync with the convention in nameText idFastString :: Id -> FastString idFastString id = mkFastString . map C.toLower . encodeCase . occNameString . nameOccName $ idName id idNameText :: DynFlags -> Id -> Text idNameText dflags = nameText dflags True . idName idClassText :: Id -> Text idClassText id = case nameModule_maybe (idName id) of Just mod -> modNameText mod Nothing -> error $ "idClassText: " fastStringText :: FastString -> Text fastStringText = decodeUtf8 . fastStringToByteString fastZStringText :: FastZString -> Text fastZStringText = decodeUtf8 . fastZStringToByteString modNameText :: Module -> Text modNameText = fastStringText . moduleNameFS . moduleName unitIdText :: Module -> Text unitIdText mod = T.pack . map C.toLower . L.intercalate "_" . L.takeWhile (not . L.all (\c -> C.isDigit c || c == '.')) $ Split.split '-' uid where uid = unitIdString $ moduleUnitId mod -- Codec.JVM.ASM -> "codec/jvm/ASM" moduleJavaClass :: Module -> Text moduleJavaClass mod = qClassName where mods = split (== '.') $ modNameText mod (parentMods, className') = (init mods, last mods) packageString = T.toLower . unitIdText $ mod package = if Prelude.null parentMods then packageString else append packageString . cons '/' . T.toLower . intercalate "/" $ parentMods className = upperFirst className' qClassName = append package . cons '/' $ className classFilePath :: ClassFile -> FilePath classFilePath ClassFile {..} = case thisClass of IClassName name -> unpack . append name $ ".class" upperFirst :: Text -> Text upperFirst str = case uncons str of Nothing -> str Just (c, str') -> cons (C.toUpper c) str' moduleClass :: Name -> Text -> Text moduleClass name = qualifiedName moduleClass where moduleClass = moduleJavaClass . fromMaybe (error "Failed") $ nameModule_maybe name submoduleClass :: Text -> Name -> Text -> Text submoduleClass subpkg name = subpackageName subpkg moduleClass where moduleClass = moduleJavaClass . fromMaybe (error "Failed") $ nameModule_maybe name dataConClass :: DynFlags -> DataCon -> Text dataConClass dflags dataCon = submoduleClass "datacons" dataName dataClass where dataName = dataConName dataCon dataClass = nameTypeText dflags dataName tyConClass :: DynFlags -> TyCon -> Text tyConClass dflags tyCon = submoduleClass "tycons" typeName typeClass where typeName = tyConName tyCon typeClass = nameTypeText dflags typeName labelToMethod :: String -> (Text, Text) labelToMethod s = ( T.replace "." "/" . T.dropEnd 1 . T.dropWhileEnd (/= '.') $ label , T.takeWhileEnd (/= '.') label ) where label = T.pack s pprName :: Name -> SDoc pprName name = ftext (occNameFS occ) where occ = nameOccName name filterDataTyCons :: Text -> Bool filterDataTyCons t | isLastOf "/datacons/" = True | isLastOf "/tycons/" = True | otherwise = False where isLastOf pat | (match, rest) <- T.breakOnEnd pat t = not (T.null match) && isNothing (T.find (== '/') rest)
rahulmutt/ghcvm
compiler/Eta/CodeGen/Name.hs
bsd-3-clause
5,202
0
16
1,260
1,508
790
718
-1
-1