Skip to content

Commit

Permalink
refactor(cli.go, translate.go): simplify translation logic and improv…
Browse files Browse the repository at this point in the history
…e code readability

- Removed unnecessary string manipulation and chunk processing in `cli.go` to streamline translation process.
- Updated `translate.go` to enhance the `trimDividers` function, making it more efficient and straightforward.
  • Loading branch information
bounoable committed Apr 26, 2024
1 parent 4c17993 commit 2a8b983
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 25 deletions.
31 changes: 11 additions & 20 deletions internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"io/fs"
"os"
"os/signal"
"strings"
"syscall"
"time"

Expand Down Expand Up @@ -196,25 +195,17 @@ func (app *App) translate() {
options.Translate.SourceLang = ""
}

chunks := getChunks(string(source), options.Translate.SplitChunks, options.Verbose)

var results []string
for _, chunk := range chunks {
chunkResult, err := translator.Translate(
ctx,
dragoman.TranslateParams{
Document: chunk,
Source: options.Translate.SourceLang,
Target: options.Translate.TargetLang,
Preserve: options.Translate.Preserve,
Instructions: options.Translate.Instructions,
},
)
app.kong.FatalIfErrorf(err)
results = append(results, chunkResult)
}

result := strings.Join(results, "\n\n")
result, err := translator.Translate(
ctx,
dragoman.TranslateParams{
Document: string(source),
Source: options.Translate.SourceLang,
Target: options.Translate.TargetLang,
Preserve: options.Translate.Preserve,
Instructions: options.Translate.Instructions,
},
)
app.kong.FatalIfErrorf(err, "failed to translate document")

if options.Translate.Dry {
fmt.Fprintf(os.Stdout, "%s\n", result)
Expand Down
8 changes: 3 additions & 5 deletions translate.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,16 +118,14 @@ func (t *Translator) translateChunk(ctx context.Context, chunk string, params Tr
return "", err
}

response = trimDividers(response)

return response, nil
return trimDividers(response), nil
}

func trimDividers(text string) string {
lines := strings.Split(text, "\n")

if len(lines) < 1 {
return strings.TrimSpace(text)
if len(lines) == 0 {
return text
}

out := slices.Clone(lines)
Expand Down

0 comments on commit 2a8b983

Please sign in to comment.