packages feed

perceptual-hash (empty) → 0.1.0.0

raw patch · 10 files changed

+345/−0 lines, 10 filesdep +basedep +containersdep +criterion

Dependencies added: base, containers, criterion, filepath, hip, optparse-applicative, par-traverse, perceptual-hash, primitive, stm, vector, vector-algorithms

Files

+ CHANGELOG.md view
@@ -0,0 +1,5 @@+# phash++## 0.1.0.0++Initial release
+ LICENSE view
@@ -0,0 +1,11 @@+Copyright Vanessa McHale (c) 2019++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.++3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.++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.
+ README.md view
@@ -0,0 +1,42 @@+# phash++[![Build Status](https://travis-ci.org/vmchale/phash.svg?branch=master)](https://travis-ci.org/vmchale/phash)+[![Windows build status](https://ci.appveyor.com/api/projects/status/github/vmchale/phash?svg=true)](https://ci.appveyor.com/project/vmchale/phash)+[![Hackage CI](https://matrix.hackage.haskell.org/api/v2/packages/perceptual-hash/badge)](https://matrix.hackage.haskell.org/package/perceptual-hash)+[![Hackage](https://img.shields.io/hackage/v/perceptual-hash.svg)](http://hackage.haskell.org/package/perceptual-hash)+[![Dependencies of latest version on Hackage](https://img.shields.io/hackage-deps/v/perceptual-hash.svg)](https://hackage.haskell.org/package/perceptual-hash)++This is a command-line tool to detect (potential) duplicate images.++## Use++Use it on one or more directories:++```+phash ~/Pictures ~/Downloads+~/Pictures/frog.jpeg, ~/Downloads/frog.png+```++## Installation++### Script++On many platforms, you can install with a script, viz.++```+curl -sSl https://raw.githubusercontent.com/vmchale/phash/master/bash/install.sh | sh -s+```++### Pre-Built Release++Download the latest release from+[here](https://github.com/vmchale/phash/releases).++### Source++Download [cabal-install](https://www.haskell.org/cabal/download.html) and+[GHC](https://www.haskell.org/ghc/download.html). Then:++```+cabal new-install perceptual-hash+```
+ app/Main.hs view
@@ -0,0 +1,39 @@+module Main (main) where++import           Data.Foldable       (toList)+import           Data.List           (intercalate)+import           Data.List.NonEmpty  (NonEmpty (..))+import qualified Data.Map            as M+import           Data.Word           (Word64)+import           Options.Applicative (execParser)+import           Parallel+import           Parser++displayPaths :: NonEmpty FilePath -> String+displayPaths = intercalate ", " . toList++displayHash :: NonEmpty FilePath -> Word64 -> String+displayHash fps h = show h ++ " " ++ displayPaths fps++filterDup :: M.Map Word64 (NonEmpty FilePath) -> M.Map Word64 (NonEmpty FilePath)+filterDup = M.filter p+    where p :: NonEmpty FilePath -> Bool+          p (_ :| (_:_)) = True+          p _            = False++displayDebug :: M.Map Word64 (NonEmpty FilePath) -> String+displayDebug hashes = intercalate "\n" (mkLine <$> M.toList hashes)+    where mkLine (h, fps) = displayHash fps h++displayAll :: M.Map a (NonEmpty FilePath) -> String+displayAll fps = intercalate "\n" (displayPaths <$> toList fps)++main :: IO ()+main = run =<< execParser wrapper++run :: ([FilePath], Bool) -> IO ()+run (fps, debug) = do+    let displayF = if debug+        then displayDebug+        else displayAll . filterDup+    putStrLn . displayF =<< pathMaps fps
+ app/Parallel.hs view
@@ -0,0 +1,39 @@+module Parallel ( pathMaps ) where++import           Control.Concurrent.STM      (atomically)+import           Control.Concurrent.STM.TVar (TVar, modifyTVar', newTVarIO,+                                              readTVarIO)+import           Data.List.NonEmpty          (NonEmpty (..), (<|))+import qualified Data.Map                    as M+import           Data.Word                   (Word64)+import           PerceptualHash              (fileHash)+import           System.Directory.Parallel   (parTraverse)+import           System.FilePath             (takeExtension)++imgExtension :: String -> Bool+imgExtension ".jpg"  = True+imgExtension ".jpeg" = True+imgExtension ".png"  = True+imgExtension _       = False -- gif doesn't work with CImg AFAICT++insertHash :: FilePath -> IO (M.Map Word64 (NonEmpty FilePath) -> M.Map Word64 (NonEmpty FilePath))+insertHash fp = do+    hash <- fileHash fp+    pure $ \hashes ->+        case M.lookup hash hashes of+            Just others -> M.insert hash (fp <| others) hashes+            Nothing     -> M.insert hash (fp :| []) hashes++stepMap :: TVar (M.Map Word64 (NonEmpty FilePath)) -> FilePath -> IO ()+stepMap var fp = do+    mod' <- insertHash fp+    atomically $ modifyTVar' var mod'++pathMaps :: [FilePath] -> IO (M.Map Word64 (NonEmpty FilePath))+pathMaps fps = do+    total <- newTVarIO mempty+    parTraverse (stepMap total) fileFilter fps+    readTVarIO total++    where fileFilter = pure . imgExtension . takeExtension+
+ app/Parser.hs view
@@ -0,0 +1,31 @@+module Parser ( wrapper ) where++import           Data.Semigroup        ((<>))+import           Data.Version          as V+import           Options.Applicative+import qualified Paths_perceptual_hash as P++phashVersion :: V.Version+phashVersion = P.version++debug :: Parser Bool+debug =+    switch+    (long "debug"+    <> help "Show debug output")++targets :: Parser ([FilePath], Bool)+targets = (,)+    <$> some (argument str+             (metavar "DIRECTORY"+             <> help "Directory to include"))+    <*> debug++wrapper :: ParserInfo ([FilePath], Bool)+wrapper = info (helper <* versionInfo <*> targets)+    (fullDesc+    <> progDesc "A command-line tool to detect duplicate images."+    <> header "phash - find duplicates using perceptual hashes")++versionInfo :: Parser (a -> a)+versionInfo = infoOption ("phash version: " ++ V.showVersion phashVersion) (short 'V' <> long "version" <> help "Show version")
+ bench/Bench.hs view
@@ -0,0 +1,14 @@+module Main (main) where++import           Criterion.Main+import           Graphics.Image (VU (..), readImageY)+import           PerceptualHash (imgHash)++main :: IO ()+main =+    defaultMain [ env img $ \ f ->+                  bgroup "imgHash"+                      [ bench "cat.png" $ nf imgHash f ]+                ]+    where img = readImageY VU catPath+          catPath = "demo-data/cat.png"
+ perceptual-hash.cabal view
@@ -0,0 +1,85 @@+cabal-version: 2.0+name: perceptual-hash+version: 0.1.0.0+license: BSD3+license-file: LICENSE+copyright: Copyright: (c) 2019 Vanessa McHale+maintainer: vamchale@gmail.com+author: Vanessa McHale+synopsis: Find duplicate images+description:+    Find similar images using perceptual hashes+category: Application, CommandLine, Images+build-type: Simple+extra-doc-files: README.md+                 CHANGELOG.md++source-repository head+    type: git+    location: https://github.com/vmchale/phash++library+    exposed-modules:+        PerceptualHash+    hs-source-dirs: src+    other-modules:+        Median+    default-language: Haskell2010+    other-extensions: FlexibleContexts+    ghc-options: -Wall+    build-depends:+        base >=4.3 && <5,+        hip -any,+        vector-algorithms -any,+        vector -any,+        primitive -any+    +    if impl(ghc >=8.0)+        ghc-options: -Wincomplete-uni-patterns -Wincomplete-record-updates+                     -Wredundant-constraints -Widentities+    +    if impl(ghc >=8.4)+        ghc-options: -Wmissing-export-lists++executable phash+    main-is: Main.hs+    hs-source-dirs: app+    other-modules:+        Paths_perceptual_hash+        Parser+        Parallel+    autogen-modules:+        Paths_perceptual_hash+    default-language: Haskell2010+    ghc-options: -threaded -rtsopts -with-rtsopts=-N -Wall+    build-depends:+        base >=4.9 && <5,+        perceptual-hash -any,+        containers -any,+        filepath -any,+        optparse-applicative >=0.13.0.0,+        par-traverse -any,+        stm >=2.3+    +    if impl(ghc >=8.0)+        ghc-options: -Wincomplete-uni-patterns -Wincomplete-record-updates+                     -Wredundant-constraints -Widentities+    +    if impl(ghc >=8.4)+        ghc-options: -Wmissing-export-lists++benchmark phash-bench+    type: exitcode-stdio-1.0+    main-is: Bench.hs+    hs-source-dirs: bench+    default-language: Haskell2010+    ghc-options: -Wall -Wincomplete-uni-patterns+                 -Wincomplete-record-updates -Wredundant-constraints+    build-depends:+        base -any,+        perceptual-hash -any,+        criterion -any,+        hip -any+    +    if impl(ghc >=8.4)+        ghc-options: -Wmissing-export-lists
+ src/Median.hs view
@@ -0,0 +1,17 @@+module Median ( median ) where++import           Control.Monad.Primitive      (PrimMonad, PrimState)+import qualified Data.Vector.Algorithms.Merge as Merge+import           Data.Vector.Generic.Mutable  (MVector)+import qualified Data.Vector.Generic.Mutable  as MV++median :: (PrimMonad m, MVector v e, Ord e, Fractional e) => v (PrimState m) e -> m e+median v = do+    Merge.sort v+    let l = MV.length v+    if odd l+        then v `MV.read` ((l - 1) `div` 2)+        else do+            x0 <- v `MV.read` ((l `div` 2) - 1)+            x1 <- v `MV.read` (l `div` 2)+            pure $ (x0 + x1) / 2
+ src/PerceptualHash.hs view
@@ -0,0 +1,62 @@+{-# LANGUAGE FlexibleContexts #-}++module PerceptualHash ( imgHash+                      , fileHash+                      ) where++import           Control.Applicative      (pure)+import           Control.Monad.ST         (runST)+import           Data.Bits                (shiftL, (.|.))+import qualified Data.Vector.Unboxed      as V+import           Data.Word                (Word64)+import           Graphics.Image           (Array, Bilinear (..), Border (Edge),+                                           Image, Pixel (PixelX, PixelY),+                                           VU (..), X, Y, convolve, crop,+                                           makeImage, readImageY, resize,+                                           transpose, (|*|))+import           Graphics.Image.Interface (toVector)+import           Median                   (median)++dct32 :: (Floating e, Array arr Y e) => Image arr Y e+dct32 = makeImage (32,32) gen+    where gen (i,j) = PixelY $ sqrt(2/n) * cos((fromIntegral ((2*i+1) * j) * pi)/(2*n))+          n = 32++idMat :: (Fractional e, Array arr X e) => Image arr X e+idMat = makeImage (7,7) gen+    where gen (i,j) = PixelX $ if i == j then 1/7 else 0++meanFilter :: (Fractional e, Array arr X e, Array arr cs e) => Image arr cs e -> Image arr cs e+meanFilter = convolve Edge idMat++size32 :: Array arr cs e => Image arr cs e -> Image arr cs e+size32 = resize Bilinear Edge (32,32)++crop8 :: Array arr cs e => Image arr cs e -> Image arr cs e+crop8 = crop (0,0) (8,8)++medianImmut :: (Ord e, V.Unbox e, Fractional e) => V.Vector e -> e+medianImmut v = runST $+    median =<< V.thaw v++dct :: (Floating e, Array arr Y e) => Image arr Y e -> Image arr Y e+dct img = dct32 |*| img |*| transpose dct32++imgHash :: Image VU Y Double -> Word64+imgHash = asWord64 . aboveMed . V.map d . toVector . crop8 . dct . size32 . meanFilter+    where d :: Pixel Y Double -> Double+          d (PixelY x) = x++          asWord64 :: V.Vector Bool -> Word64+          asWord64 = V.foldl' (\acc x -> (acc `shiftL` 1) .|. boolToWord64 x) 0++          boolToWord64 :: Bool -> Word64+          boolToWord64 False = 0+          boolToWord64 True  = 1++          aboveMed v =+            let med = medianImmut v+            in V.map (<med) v++fileHash :: FilePath -> IO Word64+fileHash = fmap imgHash . readImageY VU