ImageProcessing.ts
1 'use server'; 2 3 import _lodash from 'lodash'; 4 import seedrandom from 'seedrandom'; 5 import {imageHash} from '@luludev/image-hash' 6 7 // Resolve 8 // const imageBuffer = fs.readFileSync('./example.png') 9 // const hash = imageHash(imageBuffer) 10 // => ffee6f66ea356e6c6d5... 11 12 import Papa from 'papaparse'; 13 import {promises as fs} from 'fs'; 14 import path from 'path'; 15 16 async function getCSV(filename: string) : Promise<Array<string>> { 17 const data = Papa.parse( 18 await fs.readFile(path.resolve('public/', filename), {encoding: 'utf-8'}), 19 { 20 header: true, 21 complete: (results: any) => { 22 console.log(results); 23 }, 24 }, 25 ); 26 return data.data as Array<string>; 27 } 28 29 // create a new lodash instance with the given seed 30 // https://stackoverflow.com/questions/76705788/how-to-seed-lodash-random-number-generator 31 const seedLodash = (seed: string) => { 32 return new Promise((resolve, reject) => { 33 try { 34 // take a snapshot of the current Math.random() fn 35 const orig = Math.random; 36 // replace Math.random with the seeded random 37 seedrandom(seed, {global: true}); 38 // runInContext() creates a new lodash instance using the seeded Math.random() 39 // the context is a snapshot of the state of the global javascript environment, i.e. Math.random() updated to the seedrandom instance 40 const lodash = _lodash.runInContext(); 41 // restore the original Math.random() fn 42 Math.random = orig; 43 // return the lodash instance with the seeded Math.random() 44 return lodash; 45 } catch (error) { 46 reject(console.log('IMAGE HASHING ERROR :: ', error)); 47 } 48 }); 49 }; 50 51 async function calcHashWords(hash: string): Promise<Array<string>> { 52 let words = await getCSV('../assets/words.csv'); // TODO: Jason's seed file here 53 let hashWords: Array<string> = []; 54 // const random = await seedLodash(hash).random(6); 55 const randomGenerator: any = await seedLodash(hash); 56 for (let i = 0; i < 6; i++) { 57 let r: number = Number(randomGenerator.random(words.length)); 58 hashWords[i] = words[r]; 59 } 60 return hashWords; 61 } 62 63 async function CalcImageWords(image: any) { 64 const hashedImage = await imageHash(image); 65 return await calcHashWords(hashedImage); 66 } 67 68 export default CalcImageWords;