Skip to content

Instantly share code, notes, and snippets.

@Weiyuan-Lane
Created March 12, 2023 12:09
Show Gist options
  • Select an option

  • Save Weiyuan-Lane/5ec3cc2ec84c8c3a277eb2af93785aeb to your computer and use it in GitHub Desktop.

Select an option

Save Weiyuan-Lane/5ec3cc2ec84c8c3a277eb2af93785aeb to your computer and use it in GitHub Desktop.
package googletranslatewrapper
import (
"context"
"fmt"
"cloud.google.com/go/translate"
"github.com/weiyuan-lane/google-translate-api/internal/utils/errorhandlers"
)
func (t TranslateV2Wrapper) DetectionsFromText(ctx context.Context, text string) ([]Detection, error) {
googleDetections, err := t.translateClient.DetectLanguage(
ctx,
[]string{text},
)
if err != nil {
return []Detection{}, errorhandlers.Wrap(
errorhandlers.ErrGoogleTranslateV2DetectErrResponse,
fmt.Sprintf("Google translate detection returned error %s", err.Error()),
)
}
if len(googleDetections) == 0 {
return []Detection{}, errorhandlers.Wrap(
errorhandlers.ErrGoogleTranslateV2EmptyDetectionResponse,
"Google translate not returning any results",
)
}
detections := t.makeDetectionsResponse(googleDetections[0])
return detections, nil
}
func (t TranslateV2Wrapper) makeDetectionsResponse(googleDetections []translate.Detection) []Detection {
detections := make([]Detection, len(googleDetections))
for i, googleDetection := range googleDetections {
detections[i] = Detection{
Confidence: googleDetection.Confidence,
IsReliable: googleDetection.IsReliable,
Language: googleDetection.Language,
}
}
return detections
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment