Skip to content

Commit

Permalink
Merge branch '32-add-limts-to-crop-page'
Browse files Browse the repository at this point in the history
  • Loading branch information
celogeek committed Apr 28, 2024
2 parents ab62692 + 7b30414 commit 897efdc
Show file tree
Hide file tree
Showing 18 changed files with 208 additions and 115 deletions.
8 changes: 4 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ require (
github.com/hashicorp/go-version v1.6.0 // indirect
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/stretchr/testify v1.8.4 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/sys v0.17.0 // indirect
golang.org/x/term v0.17.0 // indirect
github.com/stretchr/testify v1.9.0 // indirect
golang.org/x/net v0.24.0 // indirect
golang.org/x/sys v0.19.0 // indirect
golang.org/x/term v0.19.0 // indirect
)
14 changes: 8 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -35,19 +35,21 @@ github.com/schollz/progressbar/v3 v3.14.2 h1:EducH6uNLIWsr560zSV1KrTeUb/wZGAHqyM
github.com/schollz/progressbar/v3 v3.14.2/go.mod h1:aQAZQnhF4JGFtRJiw/eobaXpsqpVQAftEQ+hLGXaRc4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tcnksm/go-latest v0.0.0-20170313132115-e3007ae9052e h1:IWllFTiDjjLIf2oeKxpIUmtiDV5sn71VgeQgg6vcE7k=
github.com/tcnksm/go-latest v0.0.0-20170313132115-e3007ae9052e/go.mod h1:d7u6HkTYKSv5m6MCKkOQlHwaShTMl3HjqSGW3XtVhXM=
golang.org/x/image v0.15.0 h1:kOELfmgrmJlw4Cdb7g/QGuB3CvDrXbqEIww/pNtNBm8=
golang.org/x/image v0.15.0/go.mod h1:HUYqC05R2ZcZ3ejNQsIHQDQiwWM4JBqmm6MKANTp4LE=
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w=
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.17.0 h1:mkTF7LCd6WGJNL3K1Ad7kwxNfYAW6a8a8QqtMblp/4U=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.19.0 h1:+ThwsDv+tYfnJFhF4L8jITxu1tdTWRTZpdsWgEgjL6Q=
golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
Expand Down
31 changes: 19 additions & 12 deletions internal/converter/converter.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"time"

"github.com/celogeek/go-comic-converter/v2/internal/converter/options"
"github.com/celogeek/go-comic-converter/v2/internal/utils"
)

type Converter struct {
Expand All @@ -44,17 +45,17 @@ func New() *Converter {
var cmdOutput strings.Builder
cmd.SetOutput(&cmdOutput)
cmd.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", filepath.Base(os.Args[0]))
utils.Printf("Usage of %s:\n", filepath.Base(os.Args[0]))
for _, o := range conv.order {
switch v := o.(type) {
case converterOrderSection:
fmt.Fprintf(os.Stderr, "\n%s:\n", o.Value())
utils.Printf("\n%s:\n", o.Value())
case converterOrderName:
fmt.Fprintln(os.Stderr, conv.Usage(v.isString, cmd.Lookup(v.Value())))
utils.Println(conv.Usage(v.isString, cmd.Lookup(v.Value())))
}
}
if cmdOutput.Len() > 0 {
fmt.Fprintf(os.Stderr, "\nError: %s", cmdOutput.String())
utils.Printf("\nError: %s", cmdOutput.String())
}
}

Expand Down Expand Up @@ -113,6 +114,8 @@ func (c *Converter) InitParse() {
c.AddIntParam(&c.Options.CropRatioUp, "crop-ratio-up", c.Options.CropRatioUp, "Crop ratio up: ratio of pixels allow to be non blank while cutting on the top.")
c.AddIntParam(&c.Options.CropRatioRight, "crop-ratio-right", c.Options.CropRatioRight, "Crop ratio right: ratio of pixels allow to be non blank while cutting on the right.")
c.AddIntParam(&c.Options.CropRatioBottom, "crop-ratio-bottom", c.Options.CropRatioBottom, "Crop ratio bottom: ratio of pixels allow to be non blank while cutting on the bottom.")
c.AddIntParam(&c.Options.CropLimit, "crop-limit", c.Options.CropLimit, "Crop limit: maximum number of cropping in percentage allowed. 0 mean unlimited.")
c.AddBoolParam(&c.Options.CropSkipIfLimitReached, "crop-skip-if-limit-reached", c.Options.CropSkipIfLimitReached, "Crop skip if limit reached.")
c.AddIntParam(&c.Options.Brightness, "brightness", c.Options.Brightness, "Brightness readjustment: between -100 and 100, > 0 lighter, < 0 darker")
c.AddIntParam(&c.Options.Contrast, "contrast", c.Options.Contrast, "Contrast readjustment: between -100 and 100, > 0 more contrast, < 0 less contrast")
c.AddBoolParam(&c.Options.AutoContrast, "autocontrast", c.Options.AutoContrast, "Improve contrast automatically")
Expand Down Expand Up @@ -162,7 +165,7 @@ func (c *Converter) InitParse() {
// Usage Customize version of FlagSet.PrintDefaults
func (c *Converter) Usage(isString bool, f *flag.Flag) string {
var b strings.Builder
fmt.Fprintf(&b, " -%s", f.Name) // Two spaces before -; see next two comments.
b.WriteString(" -" + f.Name)
name, usage := flag.UnquoteUsage(f)
if len(name) > 0 {
b.WriteString(" ")
Expand All @@ -174,9 +177,9 @@ func (c *Converter) Usage(isString bool, f *flag.Flag) string {
c.isZeroValueErrs = append(c.isZeroValueErrs, err)
} else if !isZero {
if isString {
fmt.Fprintf(&b, " (default %q)", f.DefValue)
b.WriteString(fmt.Sprintf(" (default %q)", f.DefValue))
} else {
fmt.Fprintf(&b, " (default %v)", f.DefValue)
b.WriteString(fmt.Sprintf(" (default %v)", f.DefValue))
}
}

Expand Down Expand Up @@ -225,7 +228,7 @@ func (c *Converter) isZeroValue(f *flag.Flag, value string) (ok bool, err error)

// Parse all parameters
func (c *Converter) Parse() {
c.Cmd.Parse(os.Args[1:])
_ = c.Cmd.Parse(os.Args[1:])
if c.Options.Help {
c.Cmd.Usage()
os.Exit(0)
Expand Down Expand Up @@ -388,13 +391,18 @@ func (c *Converter) Validate() error {
return errors.New("grayscale mode should be 0, 1 or 2")
}

// crop
if c.Options.CropLimit < 0 || c.Options.CropLimit > 100 {
return errors.New("crop limit should be between 0 and 100")
}

return nil
}

// Fatal Helper to show usage, err and exit 1
func (c *Converter) Fatal(err error) {
c.Cmd.Usage()
fmt.Fprintf(os.Stderr, "\nError: %s\n", err)
utils.Printf("\nError: %s\n", err)
os.Exit(1)
}

Expand All @@ -405,16 +413,15 @@ func (c *Converter) Stats() {
runtime.ReadMemStats(&mem)

if c.Options.Json {
json.NewEncoder(os.Stdout).Encode(map[string]any{
_ = json.NewEncoder(os.Stdout).Encode(map[string]any{
"type": "stats",
"data": map[string]any{
"elapse_ms": elapse.Milliseconds(),
"memory_usage_mb": mem.Sys / 1024 / 1024,
},
})
} else {
fmt.Fprintf(
os.Stderr,
utils.Printf(
"Completed in %s, Memory usage %d Mb\n",
elapse,
mem.Sys/1024/1024,
Expand Down
63 changes: 40 additions & 23 deletions internal/converter/options/converter_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ import (
"path/filepath"
"strings"

"github.com/celogeek/go-comic-converter/v2/internal/converter/profiles"
"gopkg.in/yaml.v3"

"github.com/celogeek/go-comic-converter/v2/internal/converter/profiles"
)

type Options struct {
Expand All @@ -29,6 +30,8 @@ type Options struct {
CropRatioUp int `yaml:"crop_ratio_up"`
CropRatioRight int `yaml:"crop_ratio_right"`
CropRatioBottom int `yaml:"crop_ratio_bottom"`
CropLimit int `yaml:"crop_limit"`
CropSkipIfLimitReached bool `yaml:"crop_skip_if_limit_reached"`
Brightness int `yaml:"brightness"`
Contrast int `yaml:"contrast"`
AutoContrast bool `yaml:"auto_contrast"`
Expand Down Expand Up @@ -79,23 +82,25 @@ type Options struct {
// New Initialize default options.
func New() *Options {
return &Options{
Profile: "SR",
Quality: 85,
Grayscale: true,
Crop: true,
CropRatioLeft: 1,
CropRatioUp: 1,
CropRatioRight: 1,
CropRatioBottom: 3,
NoBlankImage: true,
HasCover: true,
KeepDoublePageIfSplit: true,
SortPathMode: 1,
ForegroundColor: "000",
BackgroundColor: "FFF",
Format: "jpeg",
TitlePage: 1,
profiles: profiles.New(),
Profile: "SR",
Quality: 85,
Grayscale: true,
Crop: true,
CropRatioLeft: 1,
CropRatioUp: 1,
CropRatioRight: 1,
CropRatioBottom: 3,
CropLimit: 10,
CropSkipIfLimitReached: true,
NoBlankImage: true,
HasCover: true,
KeepDoublePageIfSplit: true,
SortPathMode: 1,
ForegroundColor: "000",
BackgroundColor: "FFF",
Format: "jpeg",
TitlePage: 1,
profiles: profiles.New(),
}
}

Expand Down Expand Up @@ -161,6 +166,8 @@ func (o *Options) MarshalJSON() ([]byte, error) {
"up": o.CropRatioUp,
"bottom": o.CropRatioBottom,
}
out["crop_limit"] = o.CropLimit
out["crop_skip_if_limit_reached"] = o.CropSkipIfLimitReached
}
if o.Brightness != 0 {
out["brightness"] = o.Brightness
Expand Down Expand Up @@ -195,7 +202,9 @@ func (o *Options) LoadConfig() error {
if err != nil {
return nil
}
defer f.Close()
defer func(f *os.File) {
_ = f.Close()
}(f)
err = yaml.NewDecoder(f).Decode(o)
if err != nil && err.Error() != "EOF" {
return err
Expand Down Expand Up @@ -232,7 +241,11 @@ func (o *Options) ShowConfig() string {
if o.AspectRatio > 0 {
aspectRatio = fmt.Sprintf("1:%.02f", o.AspectRatio)
} else if o.AspectRatio < 0 {
aspectRatio = fmt.Sprintf("1:%0.2f (device)", float64(profile.Height)/float64(profile.Width))
if profile != nil {
aspectRatio = fmt.Sprintf("1:%0.2f (device)", float64(profile.Height)/float64(profile.Width))
} else {
aspectRatio = "1:?? (device)"
}
}

titlePage := ""
Expand Down Expand Up @@ -265,7 +278,7 @@ func (o *Options) ShowConfig() string {
{"Grayscale", o.Grayscale, true},
{"Grayscale mode", grayscaleMode, o.Grayscale},
{"Crop", o.Crop, true},
{"Crop ratio", fmt.Sprintf("%d Left - %d Up - %d Right - %d Bottom", o.CropRatioLeft, o.CropRatioUp, o.CropRatioRight, o.CropRatioBottom), o.Crop},
{"Crop ratio", fmt.Sprintf("%d Left - %d Up - %d Right - %d Bottom - Limit %d%% - Skip %v", o.CropRatioLeft, o.CropRatioUp, o.CropRatioRight, o.CropRatioBottom, o.CropLimit, o.CropSkipIfLimitReached), o.Crop},
{"Brightness", o.Brightness, o.Brightness != 0},
{"Contrast", o.Contrast, o.Contrast != 0},
{"Auto contrast", o.AutoContrast, true},
Expand Down Expand Up @@ -295,7 +308,9 @@ func (o *Options) ShowConfig() string {

// ResetConfig reset all settings to default value
func (o *Options) ResetConfig() error {
New().SaveConfig()
if err := New().SaveConfig(); err != nil {
return err
}
return o.LoadConfig()
}

Expand All @@ -305,7 +320,9 @@ func (o *Options) SaveConfig() error {
if err != nil {
return err
}
defer f.Close()
defer func(f *os.File) {
_ = f.Close()
}(f)
return yaml.NewEncoder(f).Encode(o)
}

Expand Down
31 changes: 17 additions & 14 deletions internal/epub/epub.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,23 @@ import (
"archive/zip"
"fmt"
"math"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"text/template"
"time"

"github.com/gofrs/uuid"

epubimage "github.com/celogeek/go-comic-converter/v2/internal/epub/image"
epubimageprocessor "github.com/celogeek/go-comic-converter/v2/internal/epub/imageprocessor"
epuboptions "github.com/celogeek/go-comic-converter/v2/internal/epub/options"
epubprogress "github.com/celogeek/go-comic-converter/v2/internal/epub/progress"
epubtemplates "github.com/celogeek/go-comic-converter/v2/internal/epub/templates"
epubtree "github.com/celogeek/go-comic-converter/v2/internal/epub/tree"
epubzip "github.com/celogeek/go-comic-converter/v2/internal/epub/zip"
"github.com/gofrs/uuid"
"github.com/celogeek/go-comic-converter/v2/internal/utils"
)

type EPub struct {
Expand Down Expand Up @@ -338,7 +339,9 @@ func (e *EPub) writePart(path string, currentPart, totalParts int, part *epubPar
if err != nil {
return err
}
defer wz.Close()
defer func(wz *epubzip.EPUBZip) {
_ = wz.Close()
}(wz)

title := e.Title
if totalParts > 1 {
Expand Down Expand Up @@ -418,18 +421,18 @@ func (e *EPub) Write() error {

if e.Dry {
p := epubParts[0]
fmt.Fprintf(os.Stderr, "TOC:\n - %s\n%s\n", e.Title, e.getTree(p.Images, true))
utils.Printf("TOC:\n - %s\n%s\n", e.Title, e.getTree(p.Images, true))
if e.DryVerbose {
if e.Image.HasCover {
fmt.Fprintf(os.Stderr, "Cover:\n%s\n", e.getTree([]*epubimage.Image{p.Cover}, false))
utils.Printf("Cover:\n%s\n", e.getTree([]*epubimage.Image{p.Cover}, false))
}
fmt.Fprintf(os.Stderr, "Files:\n%s\n", e.getTree(p.Images, false))
utils.Printf("Files:\n%s\n", e.getTree(p.Images, false))
}
return nil
}
defer func() {
imgStorage.Close()
imgStorage.Remove()
_ = imgStorage.Close()
_ = imgStorage.Remove()
}()

totalParts := len(epubParts)
Expand Down Expand Up @@ -465,29 +468,29 @@ func (e *EPub) Write() error {
return err
}

bar.Add(1)
_ = bar.Add(1)
}
bar.Close()
_ = bar.Close()
if !e.Json {
fmt.Fprintln(os.Stderr)
utils.Println()
}

// display corrupted images
hasError := false
for pId, part := range epubParts {
if pId == 0 && e.Image.HasCover && part.Cover.Error != nil {
hasError = true
fmt.Fprintf(os.Stderr, "Error on image %s: %v\n", filepath.Join(part.Cover.Path, part.Cover.Name), part.Cover.Error)
utils.Printf("Error on image %s: %v\n", filepath.Join(part.Cover.Path, part.Cover.Name), part.Cover.Error)
}
for _, img := range part.Images {
if img.Part == 0 && img.Error != nil {
hasError = true
fmt.Fprintf(os.Stderr, "Error on image %s: %v\n", filepath.Join(img.Path, img.Name), img.Error)
utils.Printf("Error on image %s: %v\n", filepath.Join(img.Path, img.Name), img.Error)
}
}
}
if hasError {
fmt.Fprintln(os.Stderr)
utils.Println()
}

return nil
Expand Down
Loading

0 comments on commit 897efdc

Please sign in to comment.