-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
209 lines (169 loc) · 5.25 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
// Copyright © 2022 Rak Laptudirm <raklaptudirm@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bufio"
"crypto/sha256"
"fmt"
"math/big"
"math/rand"
"os"
"strings"
"time"
"github.com/qeesung/image2ascii/ascii"
"github.com/qeesung/image2ascii/convert"
"laptudirm.com/x/terminal"
)
var errUsage = fmt.Errorf("usage: itp <image path>")
func main() {
if err := mainFunc(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func mainFunc() error {
// itp picture.jpg
if len(os.Args) != 2 {
return errUsage
}
fileName := os.Args[1]
// only use numbers in the image
// 7 is darkest and 8 is brightest
// assumed black background with white text
ascii.DefaultOptions.Pixels = []byte("7772299408")
converter := convert.NewImageConverter()
options := convert.DefaultOptions
options.Colored = false // no ansi escapes
formatted := converter.ImageFile2ASCIIString(fileName, &options)
term := terminal.New(os.Stdout)
reader := bufio.NewReader(os.Stdin)
term.SaveCursorPosition()
term.Println(formatted) // show preview
term.Print("\nProceed with prime search? [y/N] ")
response, err := reader.ReadString('\n')
if err != nil {
return err
}
term.RestoreCursorPosition()
term.EraseTillScreenEnd()
if response = strings.Trim(response, " \n\r\t"); response != "y" {
term.Println("Prime search aborted.")
return nil
}
img, width := formatImage(formatted) // remove word wrapping
prime := searchPrime(img) // search for similar prime
// display
term.Println()
term.Println(formatToImage(prime, width)) // number with wrapping
term.Println(string(prime)) // raw number
return nil
}
// formatImage removes word wrapping from the image and returns it as a
// []byte, along with the width of the word wrapping. It changes the last
// digit so that the number can be a prime, and also replaces any leading
// 0s with an 8.
func formatImage(img string) ([]byte, int) {
// remove word wrapping line breaks
raw := []byte(strings.ReplaceAll(img, "\n", ""))
// prime numbers can't have 0, 2, 4, 5, 6, or 8 as their last digit,
// therefore replace it with a digit of similar brightness if so
lastDigitReplace := map[byte]byte{
'0': '3',
'2': '3',
'4': '9',
'6': '9',
'8': '9',
'5': '3',
}
lastIndex := len(raw) - 1
lastDigit := raw[lastIndex]
// selectively replace last digit
if sub, notPrime := lastDigitReplace[lastDigit]; notPrime {
raw[lastIndex] = sub
}
// make sure number does not have leading zeros
if raw[0] == '0' {
raw[0] = '8' // use digit with similar brightness
}
// get width from index of wrapping line break
width := strings.Index(img, "\n")
return raw, width
}
// formatToImage adds word wrapping to the given prime at the given width,
// essentially undoing what formatImage did.
func formatToImage(prime []byte, width int) string {
var img string
length := len(prime)
// add word wrapping line breaks
for i := 0; i < length; i += width {
img += string(prime[i:i+width]) + "\n"
}
return img
}
// searchPrime searches for a prime number which "looks similar" to the
// given number. The []byte contains the ascii values of each digit of the
// number. The returned number is also in the same format.
func searchPrime(raw []byte) []byte {
term := terminal.New(os.Stdout)
// seed the prng
rand.Seed(time.Now().Unix())
// iterations of Miller-Rabin to use for testing
testCount := 100
// create a copy to prevent manipulating the source slice
img := make([]byte, len(raw))
copy(img, raw)
var n big.Int
for i := 0; ; i++ {
term.EraseLine()
term.MoveCursorToColumn(1)
term.Printf("Searching for primes: try #%d | %x", i, sha256.Sum256(img))
// check if number is prime
if n.SetString(string(img), 10); n.ProbablyPrime(testCount) {
term.EraseLine()
term.MoveCursorToColumn(1)
term.Printf("Prime found after %d tries: %x\n", i, sha256.Sum256(img))
return img
}
// slightly change number
replaceRandomDigit(img)
}
}
// replaceRandomDigit replaces a random digit of the given number with a
// digit of similar brightness. This excludes the digits at indexes 0 and
// len(number)-1, to prevent leading 0s and non-prime last digits.
func replaceRandomDigit(img []byte) {
retry:
// replacement table with digits of similar brightness
replacementTable := map[byte][]byte{
'0': {'8', '9', '5'},
'1': {'7'},
'2': {'6'},
'5': {'0'},
'8': {'0', '9', '5'},
'6': {'2'},
'9': {'4', '3'},
'4': {'9'},
}
// generate random index excluding 0 and len-1
index := rand.Int()%(len(img)-2) + 1
// if replacement found replace digit, or try again
if subList, ok := replacementTable[img[index]]; ok {
// select random entry
subN := rand.Int() % len(subList)
// replace digit
sub := subList[subN]
img[index] = sub
} else {
goto retry
}
}