copyleaks

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2026 License: MIT Imports: 13 Imported by: 0

README

Copyleaks Go SDK

Copyleaks is the integrity layer for your tech stack that helps organizations and individuals understand what's human-made and original, AI-generated, or manipulated across text, image, audio and video.

This SDK gives you access to the following Copyleaks products:

  • AI Text Detection
  • AI Image Detection
  • Plagiarism Checker
  • Grammar Checker
  • Text Moderation

Install

go get github.com/Copyleaks/copyleaks-go

The SDK needs Go 1.22 or later and has no dependencies outside the standard library.

You need a Copyleaks account and its API key, which you can find on the API Dashboard.

Get started: log in and detect AI text

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/Copyleaks/copyleaks-go"
)

const sample = "Lions are social animals, living in groups called prides, typically consisting of several females, " +
	"their offspring, and a few males. Female lions are the primary hunters, working together to catch prey. " +
	"Lions are known for their strength, teamwork, and complex social structures."

func main() {
	ctx := context.Background()
	client, err := copyleaks.NewClient()
	if err != nil {
		log.Fatal(err)
	}

	// The token is valid for 48 hours. Reuse it, and log in again when
	// copyleaks.VerifyAuthToken(token) reports that it expired.
	token, err := client.Login(ctx, os.Getenv("COPYLEAKS_EMAIL"), os.Getenv("COPYLEAKS_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}

	// The text must be 255 to 100,000 characters long.
	res, err := client.DetectAIText(ctx, token, "my-first-scan", &copyleaks.AITextDetectionRequest{
		Text:    sample,
		Sandbox: true, // free test mode with mock results; remove in production
	})
	if err != nil {
		log.Fatal(err)
	}
	if res.Summary != nil {
		fmt.Printf("human: %.2f, AI: %.2f\n", res.Summary.Human, res.Summary.AI)
	}
}

Every method takes a context.Context first. Scan IDs are chosen by you and must be 3 to 36 characters long.

AI Image Detection

image, err := os.ReadFile("photo.png") // at least 512x512 pixels
if err != nil {
	log.Fatal(err)
}
res, err := client.DetectAIImage(ctx, token, "my-image-scan", &copyleaks.AIImageDetectionRequest{
	Base64:   base64.StdEncoding.EncodeToString(image),
	Filename: "photo.png",
	Model:    copyleaks.AIImageModel1Ultra,
	Sandbox:  true,
})
if err != nil {
	log.Fatal(err)
}
fmt.Println("AI detected:", res.IsAIDetected)

Plagiarism Checker

A Plagiarism Checker scan runs in the background. Submit a file, an image (OCR) or a URL, and Copyleaks sends the results to your status webhook. The scan ID may only use the characters [a-z0-9!@$&=_()';:.,~-].

err := client.SubmitFile(ctx, token, "my-plagiarism-scan", &copyleaks.FileSubmission{
	Base64:   base64.StdEncoding.EncodeToString([]byte("Text to scan.")),
	Filename: "document.txt",
	Properties: copyleaks.ScanProperties{
		// {STATUS} becomes completed, error, creditschecked or indexed.
		Webhooks: copyleaks.SubmitWebhooks{Status: "https://your-server.example/webhook/{STATUS}"},
		Sandbox:  true,
		// Also run AI Text Detection; the result arrives in the completed webhook.
		AIGeneratedText: &copyleaks.AIGeneratedText{Detect: true},
	},
})
if err != nil {
	log.Fatal(err)
}

SubmitOCR and SubmitURL work the same way. Start, Delete, Export and ResendWebhook manage submitted scans, and CreditsBalance and UsagesHistoryCSV report on your account.

Parse the webhooks with the Parse...Webhook functions:

http.HandleFunc("POST /webhook/completed", func(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(io.LimitReader(r.Body, 10<<20))
	if err != nil {
		http.Error(w, "cannot read the body", http.StatusBadRequest)
		return
	}
	hook, err := copyleaks.ParseCompletedWebhook(body)
	if err != nil {
		http.Error(w, "bad payload", http.StatusBadRequest)
		return
	}
	if hook.Results != nil {
		fmt.Println("internet results:", len(hook.Results.Internet))
	}

	// The AI Text Detection result of the suspected-ai-text alert, or nil when there is none.
	if ai, err := hook.AIDetectionResult(); err == nil && ai != nil && ai.Summary != nil {
		fmt.Println("AI share:", ai.Summary.AI)
	}
})

Grammar Checker

res, err := client.CheckGrammar(ctx, token, "my-grammar-scan", &copyleaks.GrammarCheckRequest{
	Text:    "Its a text with a error.",
	Sandbox: true,
})
if err != nil {
	log.Fatal(err)
}
if res.Score != nil && res.Score.Corrections != nil {
	fmt.Println("overall score:", res.Score.Corrections.OverallScore)
}

// The names of the correction types in res.Corrections.Text.Chars.Types. This endpoint needs no login.
types, err := client.GrammarCorrectionTypes(ctx, "en")
if err != nil {
	log.Fatal(err)
}
for _, ct := range types.CorrectionTypes {
	fmt.Println(ct.ID, ct.Title)
}

Text Moderation

res, err := client.ModerateText(ctx, token, "my-moderation-scan", &copyleaks.TextModerationRequest{
	Text:    "Text to moderate.",
	Sandbox: true,
	Labels: []copyleaks.TextModerationLabel{
		{ID: copyleaks.TextModerationLabelToxicV1},
		{ID: copyleaks.TextModerationLabelHateSpeechV1},
	},
})
if err != nil {
	log.Fatal(err)
}
for _, label := range res.Legend {
	fmt.Println(label.Index, label.ID)
}

Errors

A request that the API rejects returns an *copyleaks.APIError with the status code and the response body. Check for common cases with errors.Is:

_, err := client.CreditsBalance(ctx, token)
switch {
case errors.Is(err, copyleaks.ErrTokenExpired):
	// Log in again.
case errors.Is(err, copyleaks.ErrUnauthorized):
	// The token or the API key was rejected.
case errors.Is(err, copyleaks.ErrRateLimited), errors.Is(err, copyleaks.ErrUnderMaintenance):
	// Retry later. The SDK never retries by itself.
case errors.Is(err, copyleaks.ErrInvalidArgument):
	// A client-side check failed; no request was sent.
}
var apiErr *copyleaks.APIError
if errors.As(err, &apiErr) {
	fmt.Println(apiErr.StatusCode, string(apiErr.Body))
}

A successful response larger than 16 MiB of JSON, or 64 MiB for the usage history CSV, fails with an error that matches copyleaks.ErrResponseTooLarge.

Options

client, err := copyleaks.NewClient(
	copyleaks.WithHTTPClient(&http.Client{Timeout: 30 * time.Second}),
	copyleaks.WithUserAgent("my-app/2.1"),
)
if err != nil {
	log.Fatal(err)
}

WithAPIBaseURL and WithIdentityBaseURL change the servers. They only accept https URLs, except for http://localhost, http://127.0.0.1 and http://[::1] for local test servers; NewClient returns an error that matches copyleaks.ErrInvalidArgument otherwise.

Examples

Runnable programs for each product are in examples:

export COPYLEAKS_EMAIL=you@example.com COPYLEAKS_API_KEY=your-api-key
go run ./examples/ai-text-detection

Documentation

License

MIT. See LICENSE.

Documentation

Overview

Package copyleaks is the official Go client for the Copyleaks API.

It covers AI Text Detection, AI Image Detection, Plagiarism Checker, Grammar Checker and Text Moderation, plus the account, scan management and miscellaneous endpoints, and the webhook payloads that Copyleaks sends to your server.

Create a Client once and reuse it. Log in to get an AuthToken, then pass the token to every authenticated call. Every method takes a context.Context first:

client, err := copyleaks.NewClient()
if err != nil {
	return err
}
token, err := client.Login(ctx, email, apiKey)
if err != nil {
	return err
}
res, err := client.DetectAIText(ctx, token, "my-scan-1", &copyleaks.AITextDetectionRequest{
	Text:    text,
	Sandbox: true,
})

Requests that the API rejects return an *APIError. Use errors.Is with ErrUnauthorized, ErrRateLimited or ErrUnderMaintenance to check for those cases. Arguments that fail the client-side checks return an error that matches ErrInvalidArgument, before any request is sent. The package never retries, never panics on bad input and never writes to standard output or standard error.

API reference: https://docs.copyleaks.com

Index

Constants

View Source
const (
	// DefaultAPIBaseURL is the base URL of the Copyleaks API.
	DefaultAPIBaseURL = "https://api.copyleaks.com"
	// DefaultIdentityBaseURL is the base URL of the Copyleaks identity server, used by Login.
	DefaultIdentityBaseURL = "https://id.copyleaks.com"
)
View Source
const (
	// TextModerationLabelAdultV1 flags adult content.
	TextModerationLabelAdultV1 = "adult-v1"
	// TextModerationLabelToxicV1 flags toxic content.
	TextModerationLabelToxicV1 = "toxic-v1"
	// TextModerationLabelViolentV1 flags violent content.
	TextModerationLabelViolentV1 = "violent-v1"
	// TextModerationLabelProfanityV1 flags profanity.
	TextModerationLabelProfanityV1 = "profanity-v1"
	// TextModerationLabelSelfHarmV1 flags self-harm content.
	TextModerationLabelSelfHarmV1 = "self-harm-v1"
	// TextModerationLabelHarassmentV1 flags harassment.
	TextModerationLabelHarassmentV1 = "harassment-v1"
	// TextModerationLabelHateSpeechV1 flags hate speech.
	TextModerationLabelHateSpeechV1 = "hate-speech-v1"
	// TextModerationLabelDrugsV1 flags drug-related content.
	TextModerationLabelDrugsV1 = "drugs-v1"
	// TextModerationLabelFirearmsV1 flags firearm-related content.
	TextModerationLabelFirearmsV1 = "firearms-v1"
	// TextModerationLabelCybersecurityV1 flags cybersecurity threats.
	TextModerationLabelCybersecurityV1 = "cybersecurity-v1"
)

Text Moderation label IDs. See https://docs.copyleaks.com/reference/data-types/moderation/text-moderation-labels.

View Source
const (
	// PDFReportVersionV1 is the first report layout.
	PDFReportVersionV1 = "v1"
	// PDFReportVersionV2 is the second report layout, which includes AI Text Detection
	// results and cheat detection alerts.
	PDFReportVersionV2 = "v2"
	// PDFReportVersionV3 is the third report layout.
	PDFReportVersionV3 = "v3"
	// PDFReportVersionLatest is the latest report layout, currently v3.
	PDFReportVersionLatest = "latest"
)

The values of PDF.ReportVersion.

View Source
const AIImageModel1Ultra = "ai-image-1-ultra"

AIImageModel1Ultra is the AI Image Detection model "ai-image-1-ultra". It produces a mask of the regions detected as AI-generated.

View Source
const AlertCodeSuspectedAIText = "suspected-ai-text"

AlertCodeSuspectedAIText is the code of the scan alert that carries the AI Text Detection result of a Plagiarism Checker scan that had ScanProperties.AIGeneratedText enabled.

View Source
const TextModerationLanguageEnglish = "en"

TextModerationLanguageEnglish is the language code of English, the only language that Text Moderation supports.

View Source
const Version = "1.0.0"

Version is the version of this SDK. It is sent in the User-Agent header.

Variables

View Source
var (
	// ErrUnauthorized matches an *APIError with HTTP status 401: the login token or the API
	// key was rejected. Check for it with errors.Is(err, ErrUnauthorized).
	ErrUnauthorized = errors.New("copyleaks: unauthorized")
	// ErrRateLimited matches an *APIError with HTTP status 429: too many requests were sent.
	// Wait before calling again.
	ErrRateLimited = errors.New("copyleaks: rate limited")
	// ErrUnderMaintenance matches an *APIError with HTTP status 503: the Copyleaks servers
	// are unavailable for maintenance. Retry later with exponential backoff.
	ErrUnderMaintenance = errors.New("copyleaks: under maintenance")
	// ErrTokenExpired is returned, before any request is sent, when the AuthToken passed to
	// a call has expired or expires within five minutes. Call Login again.
	ErrTokenExpired = errors.New("copyleaks: auth token expired")
	// ErrInvalidArgument is matched by the errors of the client-side checks, which run
	// before any request is sent: a missing required field, a malformed scan ID, a text
	// that is too short, a base URL that does not use https, and so on.
	ErrInvalidArgument = errors.New("copyleaks: invalid argument")
	// ErrResponseTooLarge is matched by the error of a call whose successful response body
	// is larger than the SDK accepts: 64 MiB for the usage history CSV and 16 MiB for
	// JSON. The body is not truncated; the call fails.
	ErrResponseTooLarge = errors.New("copyleaks: response too large")
)

Functions

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to v. Use it to set the optional pointer fields of the request types, such as Filters.IdenticalEnabled: copyleaks.Ptr(false).

func VerifyAuthToken

func VerifyAuthToken(token *AuthToken) error

VerifyAuthToken checks a token without calling the API. It returns nil when the token has an access token and does not expire within the next five minutes. It returns an error that matches ErrTokenExpired when the token expired or is about to, and one that matches ErrInvalidArgument when the token is nil or empty.

Every authenticated method runs this check before sending its request.

Types

type AIGeneratedText

type AIGeneratedText struct {
	// Detect detects whether the text was written by AI.
	Detect bool `json:"detect"`
}

AIGeneratedText adds AI Text Detection to a Plagiarism Checker scan.

type AIImageDetectionRequest

type AIImageDetectionRequest struct {
	// Base64 is the image, base64-encoded (required). The image must be at least 512x512
	// pixels and at most 27 megapixels, under 32 MB, in PNG, JPEG, BMP, WebP, HEIC/HEIF or
	// AVIF format. The server checks the size.
	Base64 string `json:"base64"`
	// Filename is the name of the image, 5 to 254 characters, ending with .png, .jpg,
	// .jpeg, .bmp, .webp, .heic, .heif or .avif (required).
	Filename string `json:"filename"`
	// Model is the detection model, such as AIImageModel1Ultra (required).
	Model string `json:"model"`
	// Sandbox runs a free test check that returns mock results.
	Sandbox bool `json:"sandbox,omitempty"`
}

AIImageDetectionRequest is the body of DetectAIImage.

type AIImageDetectionResponse

type AIImageDetectionResponse struct {
	// Model is the detection model that was used.
	Model string `json:"model"`
	// Result is the run-length encoded mask of the AI-generated regions, over the image
	// pixels flattened row by row.
	Result *AIImageDetectionResult `json:"result"`
	// Summary is the share of pixels detected as human-made and as AI-generated.
	Summary *AIImageDetectionSummary `json:"summary"`
	// IsAIDetected reports whether AI-generated content was detected in the image.
	IsAIDetected bool `json:"isAiDetected"`
	// ImageInfo is information about the image.
	ImageInfo *AIImageInfo `json:"imageInfo"`
	// ScannedDocument is general information about the check. TotalWords and
	// TotalExcluded are not used.
	ScannedDocument *ScannedDocument `json:"scannedDocument"`
}

AIImageDetectionResponse is the result of AI Image Detection.

See https://docs.copyleaks.com/reference/data-types/ai-detector/ai-image-detection-response.

type AIImageDetectionResult

type AIImageDetectionResult struct {
	// Starts are the start positions of the AI-generated runs.
	Starts []int `json:"starts"`
	// Lengths are the lengths of the AI-generated runs, one per start position.
	Lengths []int `json:"lengths"`
}

AIImageDetectionResult is a run-length encoded mask, as parallel start and length lists.

type AIImageDetectionSummary

type AIImageDetectionSummary struct {
	// Human is the share of human-made pixels.
	Human float64 `json:"human"`
	// AI is the share of AI-generated pixels.
	AI float64 `json:"ai"`
}

AIImageDetectionSummary is the share of pixels detected as human-made and as AI-generated, from 0 to 1.

type AIImageInfo

type AIImageInfo struct {
	// Shape is the size of the image.
	Shape *AIImageShape `json:"shape"`
	// Metadata is metadata read from the image, when it has any.
	Metadata *AIImageMetadata `json:"metadata"`
}

AIImageInfo is information about an analyzed image.

type AIImageMetadata

type AIImageMetadata struct {
	// IssuedTime is when the image was created.
	IssuedTime string `json:"issuedTime"`
	// IssuedBy is the AI service or tool that created the image.
	IssuedBy string `json:"issuedBy"`
	// AppOrDeviceUsed is the application or device that created the image.
	AppOrDeviceUsed string `json:"appOrDeviceUsed"`
	// ContentSummary describes how the content was created.
	ContentSummary string `json:"contentSummary"`
}

AIImageMetadata is metadata read from an image.

type AIImageShape

type AIImageShape struct {
	// Height is the height of the image.
	Height int `json:"height"`
	// Width is the width of the image.
	Width int `json:"width"`
}

AIImageShape is the size of an image, in pixels.

type AISourceMatch

type AISourceMatch struct {
	// Enable turns AI Source Match on. The server default is false.
	Enable bool `json:"enable"`
}

AISourceMatch identifies the online sources that are suspected of containing AI-generated text. See ScanProperties.AISourceMatch.

type AITextDetectionExplain

type AITextDetectionExplain struct {
	// Patterns are the AI patterns found in the text.
	Patterns *AITextDetectionPatterns `json:"patterns"`
}

AITextDetectionExplain explains the detection (AI Logic).

type AITextDetectionMatch

type AITextDetectionMatch struct {
	// Text locates the section in the plain text.
	Text *AITextLocation `json:"text"`
	// HTML locates the section in the HTML source, for HTML submissions.
	HTML *AITextLocation `json:"html"`
}

AITextDetectionMatch locates a classified section.

type AITextDetectionPatterns

type AITextDetectionPatterns struct {
	// Statistics are statistics of each pattern.
	Statistics *AITextPatternStatistics `json:"statistics"`
	// Text locates the patterns in the plain text.
	Text *AITextLocation `json:"text"`
	// HTML locates the patterns in the HTML source, for HTML submissions.
	HTML *AITextLocation `json:"html"`
}

AITextDetectionPatterns are the AI patterns found in the text.

type AITextDetectionRequest

type AITextDetectionRequest struct {
	// Text is the text to check, 255 to 100,000 characters (required).
	Text string `json:"text"`
	// Sandbox runs a free test check that returns mock results.
	Sandbox bool `json:"sandbox,omitempty"`
	// Language is the ISO 639-1 code of the text, such as "en". The server detects the
	// language when it is empty.
	Language string `json:"language,omitempty"`
	// Explain asks for an explanation of the detection (AI Logic), returned in
	// AITextDetectionResponse.Explain. Explanations are only returned for some languages.
	Explain bool `json:"explain,omitempty"`
	// Sensitivity controls the detection, from 1 to 3; higher values also catch AI text
	// that was edited more heavily. Nil keeps the server default, 2. Set it with Ptr.
	Sensitivity *int `json:"sensitivity,omitempty"`
}

AITextDetectionRequest is the body of DetectAIText.

type AITextDetectionResponse

type AITextDetectionResponse struct {
	// ModelVersion is the version of the detection model.
	ModelVersion string `json:"modelVersion"`
	// Results are the classified sections of the text.
	Results []AITextDetectionResult `json:"results"`
	// Summary is the share of the text classified as human-written and as AI-generated.
	Summary *AITextDetectionSummary `json:"summary"`
	// TranslationProvider is the machine translation provider used before the detection.
	// 0 means that the text was not translated.
	TranslationProvider int `json:"translationProvider"`
	// Translation is the machine-translated English text, when the text was translated.
	Translation string `json:"translation"`
	// Explain explains the detection (AI Logic). It is filled when the request set
	// AITextDetectionRequest.Explain, for the languages that AI Logic supports.
	Explain *AITextDetectionExplain `json:"explain"`
	// ScannedDocument is general information about the check.
	ScannedDocument *ScannedDocument `json:"scannedDocument"`
	// ScanType is "sandbox" for sandbox checks and empty otherwise.
	ScanType string `json:"scanType"`
}

AITextDetectionResponse is the result of AI Text Detection. The same structure is decoded from the suspected-ai-text alert of a completed scan (see CompletedWebhook.AIDetectionResult).

See https://docs.copyleaks.com/reference/data-types/ai-detector/ai-text-detector-response.

func (*AITextDetectionResponse) UnmarshalJSON

func (r *AITextDetectionResponse) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts modelVersion as a string or as a number.

type AITextDetectionResult

type AITextDetectionResult struct {
	// Classification is 1 for human-written text and 2 for AI-generated text.
	Classification int `json:"classification"`
	// Probability is the confidence of the classification. Deprecated by the server; it
	// may be missing.
	Probability float64 `json:"probability"`
	// Matches are the locations of the section in the text.
	Matches []AITextDetectionMatch `json:"matches"`
}

AITextDetectionResult is one classified section of the text.

type AITextDetectionSummary

type AITextDetectionSummary struct {
	// Human is the share of human-written text.
	Human float64 `json:"human"`
	// AI is the share of AI-generated text.
	AI float64 `json:"ai"`
}

AITextDetectionSummary is the share of the text classified as human-written and as AI-generated, from 0 to 1.

type AITextLocation

type AITextLocation struct {
	// Chars are character positions.
	Chars *AITextPositions `json:"chars"`
	// Words are word positions.
	Words *AITextPositions `json:"words"`
}

AITextLocation holds character and word positions in the text.

type AITextPatternStatistics

type AITextPatternStatistics struct {
	// AICount is how often each pattern appears in AI-generated text.
	AICount []float64 `json:"aiCount"`
	// HumanCount is how often each pattern appears in human-written text.
	HumanCount []float64 `json:"humanCount"`
	// Proportion is the ratio between the AI and the human frequency of each pattern.
	Proportion []float64 `json:"proportion"`
	// Source is the source of each pattern: 1 for AI, 2 for a humanizer.
	Source []int `json:"source"`
}

AITextPatternStatistics are statistics of each AI pattern, as parallel lists.

type AITextPositions

type AITextPositions struct {
	// Starts are the start positions of the segments.
	Starts []int `json:"starts"`
	// Lengths are the lengths of the segments, one per start position.
	Lengths []int `json:"lengths"`
	// GroupIDs are the HTML group IDs of the segments, for HTML positions.
	GroupIDs []int `json:"groupIds,omitempty"`
}

AITextPositions are segments of the text, as parallel start and length lists.

type APIError

type APIError struct {
	// StatusCode is the HTTP status code of the response.
	StatusCode int
	// Method is the HTTP method of the request.
	Method string
	// Endpoint is the URL path of the request, such as "/v3/scans/submit/file/my-scan".
	Endpoint string
	// Body is the response body, up to 1 MiB. The server usually explains the error here.
	Body []byte
}

APIError is returned when the Copyleaks API answers with a non-2xx HTTP status.

Use errors.Is with ErrUnauthorized, ErrRateLimited or ErrUnderMaintenance to check for those cases, and errors.As to read the status code and the response body.

func (*APIError) Error

func (e *APIError) Error() string

Error returns the method, endpoint and status of the failed request, and the start of the response body.

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is reports whether e matches target: ErrUnauthorized for status 401, ErrRateLimited for status 429 and ErrUnderMaintenance for status 503.

type Alert

type Alert struct {
	// Category is the alert category; 2 is AI Text Detection.
	Category int `json:"category"`
	// Code identifies the alert, such as AlertCodeSuspectedAIText.
	Code string `json:"code"`
	// Title is a human-readable title.
	Title string `json:"title"`
	// Message is a human-readable description.
	Message string `json:"message"`
	// HelpLink links to a description of the alert. Not every alert has one.
	HelpLink string `json:"helpLink"`
	// Severity is the importance of the alert, from 0 (very low) to 4 (very high).
	Severity int `json:"severity"`
	// AdditionalData is extra data about the alert, as a JSON string. For a
	// suspected-ai-text alert, decode it with AIDetectionResult.
	AdditionalData string `json:"additionalData"`
}

Alert is a scan alert.

See https://docs.copyleaks.com/reference/data-types/authenticity/scan-alerts.

func (*Alert) AIDetectionResult

func (a *Alert) AIDetectionResult() (*AITextDetectionResponse, error)

AIDetectionResult decodes the AdditionalData of a suspected-ai-text alert into the AI Text Detection result. Trailing NUL characters and ASCII whitespace are ignored.

It returns nil and no error when a is nil, when the alert is not a suspected-ai-text alert, when AdditionalData is empty, or when it is valid JSON that is not an object, such as null. It returns an error when AdditionalData is not valid JSON or a field has an unexpected type; AdditionalData keeps the raw string.

type AuthToken

type AuthToken struct {
	// AccessToken is the bearer token sent in the Authorization header.
	AccessToken string `json:"access_token"`
	// Issued is when the token was issued.
	Issued time.Time `json:".issued"`
	// Expires is when the token expires.
	Expires time.Time `json:".expires"`
}

AuthToken is the login token returned by Login. Pass it to every authenticated call.

A token is valid for 48 hours and can be reused for many calls; check it with VerifyAuthToken and log in again when it expires. Treat it like a password. It can be stored with encoding/json and read back; the JSON holds the access token. Printing it with the fmt package, with any verb, redacts the access token.

func (AuthToken) Format

func (t AuthToken) Format(f fmt.State, verb rune)

Format implements fmt.Formatter, so that every fmt verb and flag, such as %v, %+v, %#v, %s, %q, %x and %d, prints the redacted String form and never the access token.

func (AuthToken) String

func (t AuthToken) String() string

String returns the token with the access token redacted.

func (*AuthToken) UnmarshalJSON

func (t *AuthToken) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes a login response or a stored token. Times without a UTC offset are read as UTC.

type Author

type Author struct {
	// ID is a unique identifier of the author.
	ID string `json:"id,omitempty"`
}

Author identifies the author of the scanned content.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client calls the Copyleaks API.

A Client is safe for concurrent use by multiple goroutines. Create one with NewClient and reuse it. A Client holds no credentials: pass the AuthToken returned by Login to each authenticated call.

func NewClient

func NewClient(opts ...Option) (*Client, error)

NewClient returns a Client for the production Copyleaks API, configured by opts. It returns an error that matches ErrInvalidArgument when an option is invalid, such as a base URL that does not use https.

func (*Client) CheckGrammar

func (c *Client) CheckGrammar(ctx context.Context, token *AuthToken, scanID string, req *GrammarCheckRequest) (*GrammarCheckResponse, error)

CheckGrammar returns grammar, spelling and sentence structure corrections for a text. The scan ID must be 3 to 36 characters.

See https://docs.copyleaks.com/reference/actions/writing-assistant/check.

func (*Client) CreditsBalance

func (c *Client) CreditsBalance(ctx context.Context, token *AuthToken) (*CreditsBalance, error)

CreditsBalance returns the credit balance of the account.

See https://docs.copyleaks.com/reference/actions/admin/check-credits.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, token *AuthToken, req *DeleteRequest) error

Delete deletes completed scans, with their results and metadata. The deletion runs in the background and can take a few minutes.

See https://docs.copyleaks.com/reference/actions/authenticity/delete.

func (*Client) DetectAIImage

func (c *Client) DetectAIImage(ctx context.Context, token *AuthToken, scanID string, req *AIImageDetectionRequest) (*AIImageDetectionResponse, error)

DetectAIImage checks whether an image, or part of it, was generated by AI. The scan ID must be 3 to 36 characters.

See https://docs.copyleaks.com/reference/actions/ai-image-detector/check.

func (*Client) DetectAIText

func (c *Client) DetectAIText(ctx context.Context, token *AuthToken, scanID string, req *AITextDetectionRequest) (*AITextDetectionResponse, error)

DetectAIText checks whether a text was written by a human or generated by AI. The text must be 255 to 100,000 characters long. The scan ID must be 3 to 36 characters.

See https://docs.copyleaks.com/reference/actions/writer-detector/check.

func (*Client) Export

func (c *Client) Export(ctx context.Context, token *AuthToken, scanID, exportID string, req *ExportRequest) error

Export uploads the artifacts of a completed scan to your servers, then calls req.CompletionWebhook. exportID is a new ID for the export. Both IDs must be 3 to 36 characters from [a-z0-9!@$^&+%=_(){}<>'";:/.,~`|\-] and must not contain g, then o or 0, then gle (as in google).

See https://docs.copyleaks.com/reference/actions/downloads/export.

func (*Client) GrammarCorrectionTypes

func (c *Client) GrammarCorrectionTypes(ctx context.Context, language string) (*CorrectionTypes, error)

GrammarCorrectionTypes returns the correction types of the Grammar Checker, with texts in the given language, such as "en". It needs no login.

See https://docs.copyleaks.com/reference/actions/writing-assistant/correction-types.

func (*Client) Login

func (c *Client) Login(ctx context.Context, email, key string) (*AuthToken, error)

Login exchanges the email and the API key of a Copyleaks account for an AuthToken. The identity server allows 12 logins per account in 15 minutes, so reuse the token until it expires.

See https://docs.copyleaks.com/reference/actions/account/login.

func (*Client) ModerateText

func (c *Client) ModerateText(ctx context.Context, token *AuthToken, scanID string, req *TextModerationRequest) (*TextModerationResponse, error)

ModerateText flags hateful, explicit, toxic or otherwise risky content in a text. The scan ID must be 3 to 36 characters.

See https://docs.copyleaks.com/reference/actions/text-moderation/check.

func (*Client) OCRSupportedLanguages

func (c *Client) OCRSupportedLanguages(ctx context.Context) ([]string, error)

OCRSupportedLanguages returns the language codes that SubmitOCR accepts in OCRSubmission.LangCode. It needs no login.

See https://docs.copyleaks.com/reference/actions/miscellaneous/ocr-supported-languages.

func (*Client) ReleaseNotes

func (c *Client) ReleaseNotes(ctx context.Context) (*ReleaseNotes, error)

ReleaseNotes returns the release notes of the Copyleaks API. It needs no login.

func (*Client) ResendWebhook

func (c *Client) ResendWebhook(ctx context.Context, token *AuthToken, scanID string) error

ResendWebhook asks Copyleaks to send the status webhook of a finished scan again.

See https://docs.copyleaks.com/reference/actions/authenticity/resend-webhook.

func (*Client) Start

func (c *Client) Start(ctx context.Context, token *AuthToken, req *StartRequest) (*StartResponse, error)

Start starts scans that were submitted with SubmitActionCheckCredits or SubmitActionIndex.

See https://docs.copyleaks.com/reference/actions/authenticity/start.

func (*Client) SubmitFile

func (c *Client) SubmitFile(ctx context.Context, token *AuthToken, scanID string, req *FileSubmission) error

SubmitFile starts a Plagiarism Checker scan of a file. The scan runs in the background: Copyleaks reports its status and results to Properties.Webhooks.Status (see ParseCompletedWebhook).

The scan ID must be 3 to 36 characters from [a-z0-9!@$&=_()';:.,~-] and must not contain g, then o or 0, then gle (as in google).

See https://docs.copyleaks.com/reference/actions/authenticity/submit-file.

func (*Client) SubmitOCR

func (c *Client) SubmitOCR(ctx context.Context, token *AuthToken, scanID string, req *OCRSubmission) error

SubmitOCR starts a Plagiarism Checker scan of the text in an image. It works like SubmitFile.

See https://docs.copyleaks.com/reference/actions/authenticity/submit-ocr.

func (*Client) SubmitURL

func (c *Client) SubmitURL(ctx context.Context, token *AuthToken, scanID string, req *URLSubmission) error

SubmitURL starts a Plagiarism Checker scan of a web page. It works like SubmitFile.

See https://docs.copyleaks.com/reference/actions/authenticity/submit-url.

func (*Client) SupportedFileTypes

func (c *Client) SupportedFileTypes(ctx context.Context) (*SupportedFileTypes, error)

SupportedFileTypes returns the file types that the Plagiarism Checker can scan. It needs no login.

See https://docs.copyleaks.com/reference/actions/miscellaneous/supported-plagiarism-file-types.

func (*Client) UsagesHistoryCSV

func (c *Client) UsagesHistoryCSV(ctx context.Context, token *AuthToken, start, end time.Time) ([]byte, error)

UsagesHistoryCSV returns the usage history of the account between two dates, inclusive, as a CSV file. Only the dates of start and end are used.

See https://docs.copyleaks.com/reference/actions/admin/usage-history.

type CompletedWebhook

type CompletedWebhook struct {
	// Status is the scan status: 0 for success.
	Status int `json:"status"`
	// DeveloperPayload is the ScanProperties.DeveloperPayload of the scan.
	DeveloperPayload string `json:"developerPayload"`
	// ScannedDocument is general information about the scanned document.
	ScannedDocument *WebhookScannedDocument `json:"scannedDocument"`
	// Results are the results that were found, by source, and the aggregated score.
	Results *Results `json:"results"`
	// Notifications are the scan alerts.
	Notifications *Notifications `json:"notifications"`
}

CompletedWebhook is the payload of the completed webhook, which Copyleaks sends to the status webhook URL when a Plagiarism Checker scan finishes successfully.

See https://docs.copyleaks.com/reference/data-types/authenticity/webhooks/scan-completed.

func ParseCompletedWebhook

func ParseCompletedWebhook(body []byte) (*CompletedWebhook, error)

ParseCompletedWebhook decodes the body of a completed webhook.

func (*CompletedWebhook) AIDetectionAlert

func (w *CompletedWebhook) AIDetectionAlert() *Alert

AIDetectionAlert returns the first suspected-ai-text alert of the scan, or nil when the completed webhook has none.

func (*CompletedWebhook) AIDetectionResult

func (w *CompletedWebhook) AIDetectionResult() (*AITextDetectionResponse, error)

AIDetectionResult decodes the AI Text Detection result of the scan from its suspected-ai-text alert. It is the same as calling AIDetectionResult on the alert that AIDetectionAlert returns.

It returns nil and no error when there is no such alert, or when the alert carries no result; use AIDetectionAlert to tell these cases apart.

type CopyleaksDB

type CopyleaksDB struct {
	// IncludeMySubmissions compares against content that you added to the Shared Data Hub.
	IncludeMySubmissions bool `json:"includeMySubmissions,omitempty"`
	// IncludeOthersSubmissions compares against content that other users added to the
	// Shared Data Hub.
	IncludeOthersSubmissions bool `json:"includeOthersSubmissions,omitempty"`
}

CopyleaksDB sets how the content is compared against the Shared Data Hub.

type CorrectionType

type CorrectionType struct {
	// ID is the correction type ID, as used in GrammarCorrectionRanges.Types.
	ID int `json:"id"`
	// Category is the ID of the correction category.
	Category int `json:"category"`
	// Title is the name of the correction type.
	Title string `json:"title"`
	// Message is a short message about the correction.
	Message string `json:"message"`
	// Description describes the correction type.
	Description string `json:"description"`
}

CorrectionType is one type of Grammar Checker correction.

type CorrectionTypes

type CorrectionTypes struct {
	// CorrectionTypes are the correction types.
	CorrectionTypes []CorrectionType `json:"correctionTypes"`
}

CorrectionTypes are the correction types of the Grammar Checker.

type CreditsBalance

type CreditsBalance struct {
	// Amount is the number of remaining credits. A credit covers up to 250 words.
	Amount int `json:"Amount"`
}

CreditsBalance is the credit balance of an account.

type CreditsCheckedWebhook

type CreditsCheckedWebhook struct {
	// Status is the scan status: 2 for credits checked.
	Status int `json:"status"`
	// DeveloperPayload is the ScanProperties.DeveloperPayload of the scan.
	DeveloperPayload string `json:"developerPayload"`
	// Credits is the cost of the scan, if you start it with Client.Start.
	Credits int `json:"credits"`
	// ScannedDocument is general information about the scanned document.
	ScannedDocument *WebhookScannedDocument `json:"scannedDocument"`
}

CreditsCheckedWebhook is the payload of the creditsChecked webhook, sent for a scan submitted with SubmitActionCheckCredits.

See https://docs.copyleaks.com/reference/data-types/authenticity/webhooks/credits-checked.

func ParseCreditsCheckedWebhook

func ParseCreditsCheckedWebhook(body []byte) (*CreditsCheckedWebhook, error)

ParseCreditsCheckedWebhook decodes the body of a creditsChecked webhook.

type CrossLanguage

type CrossLanguage struct {
	// Code is the language code, such as "fr".
	Code string `json:"code"`
}

CrossLanguage is one language of a cross-language scan.

type CrossLanguages

type CrossLanguages struct {
	// Languages are the languages to compare the content against, besides its own.
	Languages []CrossLanguage `json:"languages"`
}

CrossLanguages sets the extra languages of a cross-language scan.

type CustomMetadata

type CustomMetadata struct {
	// Key is the name of the property.
	Key string `json:"key"`
	// Value is the value of the property.
	Value string `json:"value"`
}

CustomMetadata is a key-value pair attached to a document in a Private Cloud Hub.

type DatabaseResult

type DatabaseResult struct {
	// ID is the result ID, used by Client.Export.
	ID string `json:"id"`
	// Title is the title of the source.
	Title string `json:"title"`
	// Introduction is a short introduction of the source.
	Introduction string `json:"introduction"`
	// MatchedWords is the number of words that match the scanned document.
	MatchedWords int `json:"matchedWords"`
	// ScanID is the scan ID of the source, when you submitted it.
	ScanID string `json:"scanId"`
	// Metadata is metadata of the source.
	Metadata *ResultMetadata `json:"metadata"`
	// Tags are the tags of the result.
	Tags []ResultTag `json:"tags"`
}

DatabaseResult is a result found in the Shared Data Hub or in the same batch of scans.

type DeleteRequest

type DeleteRequest struct {
	// Scans are the completed scans to delete, up to 10,000 (required).
	Scans []DeleteScan `json:"scans"`
	// Purge also removes every trace of the scans from the Shared Data Hub and the Private
	// Cloud Hubs, so they are never found as results again.
	Purge bool `json:"purge,omitempty"`
	// CompletionWebhook is called with a POST request, without a body, when the deletion
	// is done.
	CompletionWebhook string `json:"completionWebhook,omitempty"`
	// Headers are extra headers of the CompletionWebhook request, as [name, value] pairs.
	Headers [][]string `json:"headers,omitempty"`
}

DeleteRequest is the body of Delete.

type DeleteScan

type DeleteScan struct {
	// ID is the scan ID.
	ID string `json:"id"`
}

DeleteScan is one scan to delete.

type DomainsMode

type DomainsMode int

DomainsMode sets whether Filters.Domains are included or excluded.

const (
	// DomainsModeInclude only keeps results from Filters.Domains.
	DomainsModeInclude DomainsMode = 0
	// DomainsModeExclude drops results from Filters.Domains. It is the server default.
	DomainsModeExclude DomainsMode = 1
)

type ErrorWebhook

type ErrorWebhook struct {
	// Status is the scan status: 1 for error.
	Status int `json:"status"`
	// DeveloperPayload is the ScanProperties.DeveloperPayload of the scan.
	DeveloperPayload string `json:"developerPayload"`
	// Error describes the error.
	Error *WebhookError `json:"error"`
}

ErrorWebhook is the payload of the error webhook, sent when a scan ends with an error.

See https://docs.copyleaks.com/reference/data-types/authenticity/webhooks/error.

func ParseErrorWebhook

func ParseErrorWebhook(body []byte) (*ErrorWebhook, error)

ParseErrorWebhook decodes the body of an error webhook.

type Exclude

type Exclude struct {
	// Quotes excludes quoted text.
	Quotes bool `json:"quotes,omitempty"`
	// Citations excludes citations.
	Citations bool `json:"citations,omitempty"`
	// References excludes referenced text.
	References bool `json:"references,omitempty"`
	// TableOfContents excludes the table of contents.
	TableOfContents bool `json:"tableOfContents,omitempty"`
	// Titles excludes the titles of an HTML document.
	Titles bool `json:"titles,omitempty"`
	// HTMLTemplate excludes the text that repeats across the pages of a site, such as the
	// header and the footer.
	HTMLTemplate bool `json:"htmlTemplate,omitempty"`
	// DocumentTemplateIDs excludes the template text found in up to three other scans.
	DocumentTemplateIDs []string `json:"documentTemplateIds,omitempty"`
	// Code sets what is excluded from source code files.
	Code *ExcludeCode `json:"code,omitempty"`
}

Exclude sets the parts of the content that a scan does not compare.

type ExcludeCode

type ExcludeCode struct {
	// Comments excludes code comments.
	Comments bool `json:"comments,omitempty"`
}

ExcludeCode sets what is excluded from source code files.

type ExportCompletedWebhook

type ExportCompletedWebhook struct {
	// Completed reports whether the export finished without internal errors.
	Completed bool `json:"completed"`
	// DeveloperPayload is the ExportRequest.DeveloperPayload of the export.
	DeveloperPayload string `json:"developerPayload"`
	// Tasks are the uploads of the export.
	Tasks []ExportTask `json:"tasks"`
}

ExportCompletedWebhook is the payload of the webhook that Copyleaks sends to ExportRequest.CompletionWebhook when an export is done. Check that Completed is true and that every task is healthy with a 2xx HTTPStatusCode.

See https://docs.copyleaks.com/reference/data-types/authenticity/webhooks/export-completed.

func ParseExportCompletedWebhook

func ParseExportCompletedWebhook(body []byte) (*ExportCompletedWebhook, error)

ParseExportCompletedWebhook decodes the body of an export-completed webhook.

type ExportRequest

type ExportRequest struct {
	// CompletionWebhook is called when the export is done (required); see
	// ParseExportCompletedWebhook.
	CompletionWebhook string `json:"completionWebhook"`
	// MaxRetries is how many times each upload is retried, from 1 to 12. The server
	// default is 3.
	MaxRetries int `json:"maxRetries,omitempty"`
	// DeveloperPayload is sent back in the export-completed webhook.
	DeveloperPayload string `json:"developerPayload,omitempty"`
	// Results are the results to export, by result ID from the completed webhook.
	Results []ExportResult `json:"results,omitempty"`
	// PDFReport exports the PDF report. It requires ScanProperties.PDF.Create on submit.
	PDFReport *ExportTarget `json:"pdfReport,omitempty"`
	// CrawledVersion exports the crawled version of the submitted content.
	CrawledVersion *ExportTarget `json:"crawledVersion,omitempty"`
}

ExportRequest is the body of Export. It lists the artifacts of a scan to upload to your servers.

type ExportResult

type ExportResult struct {
	// ID is the result ID, from the completed webhook (required).
	ID string `json:"id"`
	// Endpoint is the URL to upload the result to (required).
	Endpoint string `json:"endpoint"`
	// Verb is the HTTP method of the upload, such as "POST" (required).
	Verb string `json:"verb"`
	// Headers are extra headers of the upload, as [name, value] pairs.
	Headers [][]string `json:"headers,omitempty"`
}

ExportResult uploads one result of a scan.

type ExportTarget

type ExportTarget struct {
	// Endpoint is the URL to upload the artifact to (required).
	Endpoint string `json:"endpoint"`
	// Verb is the HTTP method of the upload, such as "POST" (required).
	Verb string `json:"verb"`
	// Headers are extra headers of the upload, as [name, value] pairs.
	Headers [][]string `json:"headers,omitempty"`
}

ExportTarget is where to upload one artifact of a scan.

type ExportTask

type ExportTask struct {
	// Endpoint is the URL that the artifact was uploaded to.
	Endpoint string `json:"endpoint"`
	// IsHealthy reports whether the upload succeeded.
	IsHealthy bool `json:"isHealthy"`
	// HTTPStatusCode is the status code that your server answered with.
	HTTPStatusCode int `json:"httpStatusCode"`
}

ExportTask is one upload of an export.

type FileSubmission

type FileSubmission struct {
	// Base64 is the content of the file, base64-encoded (required). To scan plain text,
	// encode the text.
	Base64 string `json:"base64"`
	// Filename is the name of the file with its extension, up to 255 characters (required).
	Filename string `json:"filename"`
	// Properties configures the scan (required).
	Properties ScanProperties `json:"properties"`
}

FileSubmission is the body of SubmitFile.

type Filters

type Filters struct {
	// IdenticalEnabled matches exact words. The server default is true.
	IdenticalEnabled *bool `json:"identicalEnabled,omitempty"`
	// MinorChangesEnabled matches nearly identical words, such as slow and slowly.
	// The server default is true.
	MinorChangesEnabled *bool `json:"minorChangesEnabled,omitempty"`
	// RelatedMeaningEnabled matches paraphrased content. The server default is true.
	RelatedMeaningEnabled *bool `json:"relatedMeaningEnabled,omitempty"`
	// MinCopiedWords only keeps results with at least this many copied words.
	MinCopiedWords int `json:"minCopiedWords,omitempty"`
	// SafeSearch blocks explicit adult content from the results.
	SafeSearch bool `json:"safeSearch,omitempty"`
	// Domains are domains to include in or exclude from the results; see DomainsMode.
	Domains []string `json:"domains,omitempty"`
	// DomainsMode sets whether Domains are included or excluded. The server default is
	// DomainsModeExclude.
	DomainsMode *DomainsMode `json:"domainsMode,omitempty"`
	// AllowSameDomain allows results from the domain of the submitted URL.
	AllowSameDomain bool `json:"allowSameDomain,omitempty"`
}

Filters fine-tunes which results are included in a scan report.

type GrammarCheckRequest

type GrammarCheckRequest struct {
	// Text is the text to check, up to 25,000 characters (required).
	Text string `json:"text"`
	// Sandbox runs a free test check that returns mock results.
	Sandbox bool `json:"sandbox,omitempty"`
	// Language is the language code of the text, such as "en". The server detects the
	// language when it is empty.
	Language string `json:"language,omitempty"`
	// Score sets the weight of each correction category in the overall score.
	Score *GrammarScoreWeights `json:"score,omitempty"`
}

GrammarCheckRequest is the body of CheckGrammar.

type GrammarCheckResponse

type GrammarCheckResponse struct {
	// Score holds the writing scores, the readability and statistics of the text.
	Score *GrammarScore `json:"score"`
	// Corrections are the suggested corrections.
	Corrections *GrammarCorrections `json:"corrections"`
	// ScannedDocument is general information about the check.
	ScannedDocument *ScannedDocument `json:"scannedDocument"`
	// ScanType is "sandbox" for sandbox checks and empty otherwise.
	ScanType string `json:"scanType"`
}

GrammarCheckResponse is the result of the Grammar Checker.

See https://docs.copyleaks.com/reference/data-types/writing/writing-assistant.

type GrammarCorrectionRanges

type GrammarCorrectionRanges struct {
	// Types are the correction type IDs; see Client.GrammarCorrectionTypes.
	Types []int `json:"types"`
	// Starts are the start positions of the corrected segments.
	Starts []int `json:"starts"`
	// Lengths are the lengths of the corrected segments.
	Lengths []int `json:"lengths"`
	// OperationTexts are the suggested replacement texts.
	OperationTexts []string `json:"operationTexts"`
}

GrammarCorrectionRanges are corrections as parallel lists: the correction at index i replaces Lengths[i] characters at Starts[i] with OperationTexts[i].

type GrammarCorrections

type GrammarCorrections struct {
	// Text holds the corrections of the plain text.
	Text *GrammarCorrectionsText `json:"text"`
}

GrammarCorrections are the corrections suggested for a text.

type GrammarCorrectionsText

type GrammarCorrectionsText struct {
	// Chars are the corrections, by character position.
	Chars *GrammarCorrectionRanges `json:"chars"`
}

GrammarCorrectionsText holds the corrections of the plain text.

type GrammarReadability

type GrammarReadability struct {
	// Score is the readability score.
	Score int `json:"score"`
	// ReadabilityLevel is the readability level.
	ReadabilityLevel int `json:"readabilityLevel"`
	// ReadabilityLevelText is the readability level as text, such as "10th to 12th Grader".
	ReadabilityLevelText string `json:"readabilityLevelText"`
	// ReadabilityLevelDescription describes the readability level, such as
	// "Fairly difficult to read".
	ReadabilityLevelDescription string `json:"readabilityLevelDescription"`
}

GrammarReadability is the readability of a text.

type GrammarScore

type GrammarScore struct {
	// Corrections are the correction counts and scores of each category, and the overall
	// score.
	Corrections *GrammarScoreCorrections `json:"corrections"`
	// Readability is the readability of the text.
	Readability *GrammarReadability `json:"readability"`
	// Statistics are statistics of the text.
	Statistics *GrammarStatistics `json:"statistics"`
}

GrammarScore holds the writing scores, the readability and statistics of a text.

type GrammarScoreCorrections

type GrammarScoreCorrections struct {
	// GrammarCorrectionsCount is the number of grammar corrections.
	GrammarCorrectionsCount int `json:"grammarCorrectionsCount"`
	// GrammarCorrectionsScore is the grammar score.
	GrammarCorrectionsScore int `json:"grammarCorrectionsScore"`
	// GrammarScoreWeight is the weight of the grammar score in the overall score.
	GrammarScoreWeight float64 `json:"grammarScoreWeight"`
	// MechanicsCorrectionsCount is the number of mechanics corrections.
	MechanicsCorrectionsCount int `json:"mechanicsCorrectionsCount"`
	// MechanicsCorrectionsScore is the mechanics score.
	MechanicsCorrectionsScore int `json:"mechanicsCorrectionsScore"`
	// MechanicsScoreWeight is the weight of the mechanics score in the overall score.
	MechanicsScoreWeight float64 `json:"mechanicsScoreWeight"`
	// SentenceStructureCorrectionsCount is the number of sentence structure corrections.
	SentenceStructureCorrectionsCount int `json:"sentenceStructureCorrectionsCount"`
	// SentenceStructureCorrectionsScore is the sentence structure score.
	SentenceStructureCorrectionsScore int `json:"sentenceStructureCorrectionsScore"`
	// SentenceStructureScoreWeight is the weight of the sentence structure score in the
	// overall score.
	SentenceStructureScoreWeight float64 `json:"sentenceStructureScoreWeight"`
	// WordChoiceCorrectionsCount is the number of word choice corrections.
	WordChoiceCorrectionsCount int `json:"wordChoiceCorrectionsCount"`
	// WordChoiceCorrectionsScore is the word choice score.
	WordChoiceCorrectionsScore int `json:"wordChoiceCorrectionsScore"`
	// WordChoiceScoreWeight is the weight of the word choice score in the overall score.
	WordChoiceScoreWeight float64 `json:"wordChoiceScoreWeight"`
	// OverallScore is the overall writing score.
	OverallScore int `json:"overallScore"`
}

GrammarScoreCorrections are the correction counts and scores of each category.

type GrammarScoreWeights

type GrammarScoreWeights struct {
	// GrammarScoreWeight is the weight of grammar corrections.
	GrammarScoreWeight *float64 `json:"grammarScoreWeight,omitempty"`
	// MechanicsScoreWeight is the weight of mechanics corrections.
	MechanicsScoreWeight *float64 `json:"mechanicsScoreWeight,omitempty"`
	// SentenceStructureScoreWeight is the weight of sentence structure corrections.
	SentenceStructureScoreWeight *float64 `json:"sentenceStructureScoreWeight,omitempty"`
	// WordChoiceScoreWeight is the weight of word choice corrections.
	WordChoiceScoreWeight *float64 `json:"wordChoiceScoreWeight,omitempty"`
}

GrammarScoreWeights sets the weight of each correction category in the overall score, from 0.0 to 1.0. A nil weight keeps the server default, 1.0.

type GrammarStatistics

type GrammarStatistics struct {
	// SentenceCount is the number of sentences.
	SentenceCount int `json:"sentenceCount"`
	// AverageSentenceLength is the average sentence length, in words.
	AverageSentenceLength float64 `json:"averageSentenceLength"`
	// AverageWordLength is the average word length, in characters.
	AverageWordLength float64 `json:"averageWordLength"`
	// ReadingTimeSeconds is the estimated reading time, in seconds.
	ReadingTimeSeconds float64 `json:"readingTimeSeconds"`
	// SpeakingTimeSeconds is the estimated speaking time, in seconds.
	SpeakingTimeSeconds float64 `json:"speakingTimeSeconds"`
}

GrammarStatistics are statistics of a text.

type IndexedWebhook

type IndexedWebhook struct {
	// Status is the scan status: 3 for indexed.
	Status int `json:"status"`
	// DeveloperPayload is the ScanProperties.DeveloperPayload of the scan.
	DeveloperPayload string `json:"developerPayload"`
}

IndexedWebhook is the payload of the indexed webhook, sent for a scan submitted with SubmitActionIndex.

See https://docs.copyleaks.com/reference/data-types/authenticity/webhooks/indexed.

func ParseIndexedWebhook

func ParseIndexedWebhook(body []byte) (*IndexedWebhook, error)

ParseIndexedWebhook decodes the body of an indexed webhook.

type Indexing

type Indexing struct {
	// Repositories are the Private Cloud Hubs to index the content in.
	Repositories []IndexingRepository `json:"repositories,omitempty"`
}

Indexing sets where the submitted content is indexed.

type IndexingRepository

type IndexingRepository struct {
	// ID is the repository ID of the Private Cloud Hub.
	ID string `json:"id"`
	// MaskingPolicy sets who sees the content of this document in their results.
	MaskingPolicy *MaskingPolicy `json:"maskingPolicy,omitempty"`
}

IndexingRepository is a Private Cloud Hub to index the content in.

type InternetResult

type InternetResult struct {
	// ID is the result ID, used by Client.Export.
	ID string `json:"id"`
	// Title is the title of the source.
	Title string `json:"title"`
	// Introduction is a short introduction of the source.
	Introduction string `json:"introduction"`
	// MatchedWords is the number of words that match the scanned document.
	MatchedWords int `json:"matchedWords"`
	// URL is the public URL of the source.
	URL string `json:"url"`
	// Metadata is metadata of the source.
	Metadata *ResultMetadata `json:"metadata"`
	// Tags are the tags of the result.
	Tags []ResultTag `json:"tags"`
}

InternetResult is a result found on the internet.

type MaskingPolicy

type MaskingPolicy int

MaskingPolicy sets who sees the content of a document indexed in a Private Cloud Hub when it is found as a result.

const (
	// MaskingPolicyNoMask shows the content to everyone.
	MaskingPolicyNoMask MaskingPolicy = 0
	// MaskingPolicyMaskOtherUsersFiles masks the content from other users.
	MaskingPolicyMaskOtherUsersFiles MaskingPolicy = 1
	// MaskingPolicyMaskAllFiles masks the content from everyone.
	MaskingPolicyMaskAllFiles MaskingPolicy = 2
)

type NewResultWebhook

type NewResultWebhook struct {
	// DeveloperPayload is the ScanProperties.DeveloperPayload of the scan.
	DeveloperPayload string `json:"developerPayload"`
	// Score is the score of the scan so far.
	Score *ResultsScore `json:"score"`
	// Internet are the new results from the internet.
	Internet []InternetResult `json:"internet"`
	// Database are the new results from the Shared Data Hub.
	Database []DatabaseResult `json:"database"`
	// Batch are the new results from the same batch of scans.
	Batch []DatabaseResult `json:"batch"`
	// Repositories are the new results from Private Cloud Hubs.
	Repositories []RepositoryResult `json:"repositories"`
}

NewResultWebhook is the payload of the new-result webhook, sent to SubmitWebhooks.NewResult each time a result is found while the scan still runs.

See https://docs.copyleaks.com/reference/data-types/authenticity/results/new-result.

func ParseNewResultWebhook

func ParseNewResultWebhook(body []byte) (*NewResultWebhook, error)

ParseNewResultWebhook decodes the body of a new-result webhook.

type Notifications

type Notifications struct {
	// Alerts are the scan alerts.
	Alerts []Alert `json:"alerts"`
}

Notifications are the scan alerts of a completed scan.

type OCRSubmission

type OCRSubmission struct {
	// Base64 is the content of the image, base64-encoded (required).
	Base64 string `json:"base64"`
	// Filename is the name of the image with its extension, up to 255 characters (required).
	Filename string `json:"filename"`
	// LangCode is the language of the text in the image (required). See
	// Client.OCRSupportedLanguages.
	LangCode string `json:"langCode"`
	// Properties configures the scan (required).
	Properties ScanProperties `json:"properties"`
}

OCRSubmission is the body of SubmitOCR.

type Option

type Option func(*Client) error

Option configures a Client. Pass options to NewClient.

func WithAPIBaseURL

func WithAPIBaseURL(baseURL string) Option

WithAPIBaseURL replaces DefaultAPIBaseURL. The URL must use https; plain http is only accepted for the hosts localhost, 127.0.0.1 and ::1, for local test servers.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient makes the Client send its requests with hc instead of a default http.Client that has a two-minute timeout. Use it to set timeouts or a proxy, or to add retries with a custom Transport; the SDK itself never retries. A nil hc is ignored.

func WithIdentityBaseURL

func WithIdentityBaseURL(baseURL string) Option

WithIdentityBaseURL replaces DefaultIdentityBaseURL, the server that Login calls. The URL must use https; plain http is only accepted for the hosts localhost, 127.0.0.1 and ::1, for local test servers.

func WithUserAgent

func WithUserAgent(userAgent string) Option

WithUserAgent adds an application product token, such as "my-app/2.1", in front of the SDK's own User-Agent token "copyleaks-go-sdk/<Version>", which is always sent.

type PDF

type PDF struct {
	// Create generates a PDF report.
	Create bool `json:"create,omitempty"`
	// Title is the title of the report, up to 256 characters.
	Title string `json:"title,omitempty"`
	LargeLogo string `json:"largeLogo,omitempty"`
	// RTL aligns the text of the report from right to left.
	RTL bool `json:"rtl,omitempty"`
	// Version is the version of the report layout. ReportVersion overrides it, and the API
	// reference recommends ReportVersion instead.
	Version PDFVersion `json:"version,omitempty"`
	// ReportVersion is the version of the report layout: PDFReportVersionV1,
	// PDFReportVersionV2, PDFReportVersionV3 or PDFReportVersionLatest. The values are
	// lowercase and case-sensitive. It overrides Version when both are set. When neither
	// is set, accounts created before 2025-05-15 get v1 and newer accounts get the latest.
	ReportVersion string `json:"reportVersion,omitempty"`
	// Colors customizes the colors of the report.
	Colors *PDFColors `json:"colors,omitempty"`
}

PDF requests and customizes the PDF report of a scan.

type PDFColors

type PDFColors struct {
	// MainStrip is the color of the main strip.
	MainStrip string `json:"mainStrip,omitempty"`
	// Titles is the color of the titles.
	Titles string `json:"titles,omitempty"`
	// Identical is the highlight color of identical matches.
	Identical string `json:"identical,omitempty"`
	// MinorChanges is the highlight color of minor changes.
	MinorChanges string `json:"minorChanges,omitempty"`
	// RelatedMeaning is the highlight color of paraphrased matches.
	RelatedMeaning string `json:"relatedMeaning,omitempty"`
}

PDFColors customizes the colors of a PDF report. Colors are in HEX format, such as "#FE5758".

type PDFVersion

type PDFVersion int

PDFVersion is the layout version of a PDF report. See PDF.Version.

const (
	// PDFVersion1 is the first report layout. It is the server default for accounts
	// created before 2025-05-15; see PDF.ReportVersion.
	PDFVersion1 PDFVersion = 1
	// PDFVersion2 is the second report layout, which includes AI Text Detection results
	// and cheat detection alerts.
	PDFVersion2 PDFVersion = 2
	// PDFVersion3 is the third report layout.
	PDFVersion3 PDFVersion = 3
)

type ReleaseNote

type ReleaseNote struct {
	// MsgType is the kind of change, such as "NEW".
	MsgType string `json:"msgType"`
	// Date is when the change was released, in ISO 8601 format.
	Date string `json:"date"`
	// HTMLDescription describes the change, as HTML.
	HTMLDescription string `json:"htmlDescription"`
}

ReleaseNote is one release note of the Copyleaks API.

type ReleaseNotes

type ReleaseNotes struct {
	// Updates are the release notes, newest first.
	Updates []ReleaseNote `json:"updates"`
}

ReleaseNotes are the release notes of the Copyleaks API.

type RepositoryResult

type RepositoryResult struct {
	// ID is the result ID, used by Client.Export.
	ID string `json:"id"`
	// Title is the title of the source.
	Title string `json:"title"`
	// Introduction is a short introduction of the source.
	Introduction string `json:"introduction"`
	// MatchedWords is the number of words that match the scanned document.
	MatchedWords int `json:"matchedWords"`
	// RepositoryID is the ID of the Private Cloud Hub.
	RepositoryID string `json:"repositoryId"`
	// ScanID is the scan ID of the source in the Private Cloud Hub.
	ScanID string `json:"scanId"`
	// Metadata is metadata of the source.
	Metadata *ResultMetadata `json:"metadata"`
	// Tags are the tags of the result.
	Tags []ResultTag `json:"tags"`
}

RepositoryResult is a result found in a Private Cloud Hub.

type ResultMetadata

type ResultMetadata struct {
	// FinalURL is the URL after all HTTP redirects.
	FinalURL string `json:"finalUrl"`
	// CanonicalURL is the canonical URL of the page.
	CanonicalURL string `json:"canonicalUrl"`
	// PublishDate is the publication date.
	PublishDate string `json:"publishDate"`
	// CreationDate is the creation date.
	CreationDate string `json:"creationDate"`
	// LastModificationDate is the last modification date.
	LastModificationDate string `json:"lastModificationDate"`
	// Author is the author.
	Author string `json:"author"`
	// Organization is the organization.
	Organization string `json:"organization"`
	// Filename is the file name.
	Filename string `json:"filename"`
	// SubmittedBy is the email of the user who added the document to the Private Cloud
	// Hub. Only Private Cloud Hub results have it.
	SubmittedBy string `json:"submittedBy"`
}

ResultMetadata is metadata of a scanned document or of a result.

type ResultTag

type ResultTag struct {
	// Code identifies the kind of tag.
	Code string `json:"code"`
	// Title is a short name of the tag.
	Title string `json:"title"`
	// Description describes the tag.
	Description string `json:"description"`
}

ResultTag is a tag of a result.

type Results

type Results struct {
	// Internet are the results from the internet.
	Internet []InternetResult `json:"internet"`
	// Database are the results from the Shared Data Hub.
	Database []DatabaseResult `json:"database"`
	// Batch are the results from the same batch of scans.
	Batch []DatabaseResult `json:"batch"`
	// Repositories are the results from Private Cloud Hubs.
	Repositories []RepositoryResult `json:"repositories"`
	// Score is the aggregated score of all results.
	Score *ResultsScore `json:"score"`
}

Results are the results of a scan, by source.

type ResultsScore

type ResultsScore struct {
	// IdenticalWords is the number of words that match exactly.
	IdenticalWords int `json:"identicalWords"`
	// MinorChangedWords is the number of nearly identical words, such as slow and slowly.
	MinorChangedWords int `json:"minorChangedWords"`
	// RelatedMeaningWords is the number of paraphrased words.
	RelatedMeaningWords int `json:"relatedMeaningWords"`
	// AggregatedScore is the percentage of similar words from all results.
	AggregatedScore float64 `json:"aggregatedScore"`
}

ResultsScore is the aggregated score of the results of a scan.

func (*ResultsScore) UnmarshalJSON

func (s *ResultsScore) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes a score object, which the server sends. It also accepts a bare number, the shape that the API reference shows for the new-result webhook, as the AggregatedScore.

type ScanMethodAlgorithm

type ScanMethodAlgorithm int

ScanMethodAlgorithm is the goal of the scan algorithm. See ScanProperties.ScanMethodAlgorithm.

const (
	// ScanMethodMaximumCoverage prioritizes a higher similarity score. It is the default.
	ScanMethodMaximumCoverage ScanMethodAlgorithm = 0
	// ScanMethodMaximumResults prioritizes finding more sources.
	ScanMethodMaximumResults ScanMethodAlgorithm = 1
)

type ScanProperties

type ScanProperties struct {
	// Webhooks sets the URLs that Copyleaks calls with the scan status (required).
	Webhooks SubmitWebhooks `json:"webhooks"`
	// Sandbox submits a free test scan that returns mock results.
	Sandbox bool `json:"sandbox,omitempty"`
	// Action is what the submit does. The default, SubmitActionScan, starts the scan.
	Action SubmitAction `json:"action,omitempty"`
	// IncludeHTML also generates the report in HTML format, when possible.
	IncludeHTML bool `json:"includeHtml,omitempty"`
	// DeveloperPayload is sent back in the webhooks of the scan. Up to 512 characters.
	DeveloperPayload string `json:"developerPayload,omitempty"`
	// Expiration is how many hours the scan is kept after it completes, from 1 to 2880.
	// The server default is 2880.
	Expiration int `json:"expiration,omitempty"`
	// Author identifies the author of the content.
	Author *Author `json:"author,omitempty"`
	// Filters fine-tunes which results are included.
	Filters *Filters `json:"filters,omitempty"`
	// Scanning sets the sources that the content is compared against.
	Scanning *Scanning `json:"scanning,omitempty"`
	// Indexing sets the Private Cloud Hubs that the content is indexed in.
	Indexing *Indexing `json:"indexing,omitempty"`
	// Exclude sets the parts of the content that are not scanned.
	Exclude *Exclude `json:"exclude,omitempty"`
	// PDF requests and customizes a PDF report.
	PDF *PDF `json:"pdf,omitempty"`
	// DisplayLanguage is the language of the scan's PDF report: "en" (the server default),
	// "es", "pt", "fr", "de" or "it". The codes are lowercase and case-sensitive. It is
	// stored with the scan, so it also applies to a PDF report requested later.
	DisplayLanguage string `json:"displayLanguage,omitempty"`
	// SensitivityLevel trades speed for coverage, from 1 (fastest) to 5 (most thorough).
	// The server default is 3.
	SensitivityLevel int `json:"sensitivityLevel,omitempty"`
	// CheatDetection checks the content for text manipulation and reports it as scan
	// alerts in the completed webhook.
	CheatDetection bool `json:"cheatDetection,omitempty"`
	// ScanMethodAlgorithm chooses between maximum coverage (the default) and maximum results.
	ScanMethodAlgorithm ScanMethodAlgorithm `json:"scanMethodAlgorithm,omitempty"`
	// AIGeneratedText adds AI Text Detection to the scan. The result arrives as a
	// suspected-ai-text alert in the completed webhook; see CompletedWebhook.AIDetectionResult.
	AIGeneratedText *AIGeneratedText `json:"aiGeneratedText,omitempty"`
	// AISourceMatch identifies the online sources that are suspected of containing
	// AI-generated text. It only applies to documents detected as English.
	AISourceMatch *AISourceMatch `json:"aiSourceMatch,omitempty"`
	// CustomMetadata is attached to the document in a Private Cloud Hub and added to the
	// results that match it.
	CustomMetadata []CustomMetadata `json:"customMetadata,omitempty"`
}

ScanProperties configures a Plagiarism Checker scan. Only Webhooks.Status is required. Every other field is optional and is left out of the request when it has its zero value, so the server default applies. Pointer fields are pointers because their zero value differs from the server default; set them with Ptr.

See https://docs.copyleaks.com/reference/actions/authenticity/submit-file.

type ScannedDocument

type ScannedDocument struct {
	// ScanID is the scan ID given by you.
	ScanID string `json:"scanId"`
	// TotalWords is the number of words in the text.
	TotalWords int `json:"totalWords"`
	// TotalExcluded is the number of excluded words.
	TotalExcluded int `json:"totalExcluded"`
	// ActualCredits is the number of credits that the check used.
	ActualCredits int `json:"actualCredits"`
	// ExpectedCredits is the number of credits that the check was expected to use.
	ExpectedCredits int `json:"expectedCredits"`
	// CreationTime is when the check was created, in ISO 8601 format (UTC).
	CreationTime string `json:"creationTime"`
}

ScannedDocument is general information about an AI Text Detection, AI Image Detection, Grammar Checker or Text Moderation check.

type Scanning

type Scanning struct {
	// Internet compares the content with online sources. The server default is true.
	Internet *bool `json:"internet,omitempty"`
	// Exclude leaves matching submissions out of the results.
	Exclude *ScanningExclude `json:"exclude,omitempty"`
	// Repositories are the Private Cloud Hubs to compare the content against.
	Repositories []ScanningRepository `json:"repositories,omitempty"`
	// CopyleaksDB compares the content against the Shared Data Hub.
	CopyleaksDB *CopyleaksDB `json:"copyleaksDb,omitempty"`
	// CrossLanguages also compares the content against sources in other languages.
	CrossLanguages *CrossLanguages `json:"crossLanguages,omitempty"`
}

Scanning sets the sources that a scan compares the content against.

type ScanningExclude

type ScanningExclude struct {
	// IDPattern excludes the submissions whose scan ID matches the pattern, 1 to 36
	// characters. A * matches any number of characters and a . matches exactly one
	// non-whitespace character.
	IDPattern string `json:"idPattern,omitempty"`
}

ScanningExclude leaves submissions out of the results.

type ScanningRepository

type ScanningRepository struct {
	// ID is the repository ID of the Private Cloud Hub.
	ID string `json:"id"`
	// IncludeMySubmissions compares against your own submissions in the hub.
	IncludeMySubmissions bool `json:"includeMySubmissions,omitempty"`
	// IncludeOthersSubmissions compares against other users' submissions in the hub.
	IncludeOthersSubmissions bool `json:"includeOthersSubmissions,omitempty"`
}

ScanningRepository is a Private Cloud Hub to compare the content against.

type StartErrorHandling

type StartErrorHandling int

StartErrorHandling is what Start does when some of the scans are in error.

const (
	// StartErrorHandlingCancel cancels the request. It is the default.
	StartErrorHandlingCancel StartErrorHandling = 0
	// StartErrorHandlingIgnore starts the scans that are not in error.
	StartErrorHandlingIgnore StartErrorHandling = 1
)

type StartRequest

type StartRequest struct {
	// Trigger lists the IDs of up to 100 scans, submitted with SubmitActionCheckCredits or
	// SubmitActionIndex, to start (required).
	Trigger []string `json:"trigger"`
	// ErrorHandling is what happens when some of the scans are in error. The default,
	// StartErrorHandlingCancel, cancels the request.
	ErrorHandling StartErrorHandling `json:"errorHandling"`
}

StartRequest is the body of Start.

type StartResponse

type StartResponse struct {
	// Success are the scans that started.
	Success []StartedScan `json:"success"`
	// Failed are the scans that did not start.
	Failed []StartedScan `json:"failed"`
}

StartResponse lists the scans that Start started and those it could not start.

type StartedScan

type StartedScan struct {
	// ID is the scan ID.
	ID string `json:"id"`
}

StartedScan is one scan of a StartResponse.

func (*StartedScan) UnmarshalJSON

func (s *StartedScan) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts a scan as an object with an id, which the server sends, or as a bare scan ID string, as the API reference shows it.

type SubmitAction

type SubmitAction int

SubmitAction is what a submit does. See ScanProperties.Action.

const (
	// SubmitActionScan starts the scan right away. It is the default.
	SubmitActionScan SubmitAction = 0
	// SubmitActionCheckCredits only reports the cost of the scan, in a credits-checked
	// webhook. Start the scan later with Client.Start.
	SubmitActionCheckCredits SubmitAction = 1
	// SubmitActionIndex only indexes the content, for free, in the Shared Data Hub or a
	// Private Cloud Hub.
	SubmitActionIndex SubmitAction = 2
)

type SubmitWebhooks

type SubmitWebhooks struct {
	// Status is called when the scan status changes (required). Its {STATUS} placeholder
	// is replaced with completed, error, creditschecked or indexed.
	Status string `json:"status"`
	// StatusHeaders are extra headers for the status webhook, as [name, value] pairs.
	StatusHeaders [][]string `json:"statusHeaders,omitempty"`
	// NewResult is called each time a result is found while the scan runs.
	NewResult string `json:"newResult,omitempty"`
	// NewResultHeaders are extra headers for the new-result webhook, as [name, value] pairs.
	NewResultHeaders [][]string `json:"newResultHeaders,omitempty"`
}

SubmitWebhooks sets the webhook URLs of a scan.

type SupportedFileTypes

type SupportedFileTypes struct {
	// Textual are the extensions of the text files that SubmitFile accepts.
	Textual []string `json:"textual"`
	// OCR are the extensions of the image files that SubmitOCR accepts.
	OCR []string `json:"ocr"`
}

SupportedFileTypes lists the file types that the Plagiarism Checker can scan.

type TextModerationChars

type TextModerationChars struct {
	// Labels are the label values of the segments; see TextModerationResponse.Legend.
	Labels []int `json:"labels"`
	// Starts are the start positions of the segments.
	Starts []int `json:"starts"`
	// Lengths are the lengths of the segments.
	Lengths []int `json:"lengths"`
}

TextModerationChars are flagged segments as parallel lists: the segment at index i starts at Starts[i], is Lengths[i] characters long and has label value Labels[i].

type TextModerationLabel

type TextModerationLabel struct {
	// ID is the label ID.
	ID string `json:"id"`
}

TextModerationLabel is a category to check the text for, such as TextModerationLabelToxicV1.

type TextModerationLegend

type TextModerationLegend struct {
	// Index is the label value used in TextModerationChars.Labels.
	Index int `json:"index"`
	// ID is the label ID, such as TextModerationLabelToxicV1.
	ID string `json:"id"`
}

TextModerationLegend maps a label value to a label ID.

type TextModerationRequest

type TextModerationRequest struct {
	// Text is the text to moderate, 2 to 25,000 characters (required).
	Text string `json:"text"`
	// Sandbox runs a free test check that returns mock results.
	Sandbox bool `json:"sandbox,omitempty"`
	// Language is the language code of the text. Only TextModerationLanguageEnglish is
	// supported. The server detects the language when it is empty.
	Language string `json:"language,omitempty"`
	// Labels are the 1 to 16 categories to check the text for (required). The label value
	// of each flagged segment in the response is the index of its label in this list.
	Labels []TextModerationLabel `json:"labels"`
}

TextModerationRequest is the body of ModerateText.

type TextModerationResponse

type TextModerationResponse struct {
	// ModelVersion is the version of the moderation model.
	ModelVersion string `json:"modelVersion"`
	// Moderations are the flagged segments of the text.
	Moderations *TextModerations `json:"moderations"`
	// Legend maps the label values of Moderations to label IDs.
	Legend []TextModerationLegend `json:"legend"`
	// ScannedDocument is general information about the check.
	ScannedDocument *ScannedDocument `json:"scannedDocument"`
}

TextModerationResponse is the result of Text Moderation.

type TextModerationText

type TextModerationText struct {
	// Chars are the flagged segments, by character position.
	Chars *TextModerationChars `json:"chars"`
}

TextModerationText holds the flagged segments of the plain text.

type TextModerations

type TextModerations struct {
	// Text holds the flagged segments of the plain text.
	Text *TextModerationText `json:"text"`
}

TextModerations are the flagged segments of a text.

type URLSubmission

type URLSubmission struct {
	// URL is the address of the page to scan (required).
	URL string `json:"url"`
	// Properties configures the scan (required).
	Properties ScanProperties `json:"properties"`
}

URLSubmission is the body of SubmitURL.

type WebhookError

type WebhookError struct {
	// Type is the error type, such as "invalid_request_error".
	Type string `json:"type"`
	// ID is the machine-readable error ID, such as "insufficient_credits".
	ID string `json:"id"`
	// Code is the numeric error code.
	Code int `json:"code"`
	// Message is a human-readable description of the error.
	Message string `json:"message"`
	// URL links to the documentation of the error.
	URL string `json:"url"`
	// Details describe the request parameters that caused the error.
	Details []WebhookErrorDetail `json:"details"`
}

WebhookError describes why a scan failed.

type WebhookErrorDetail

type WebhookErrorDetail struct {
	// Param is the name of the parameter.
	Param string `json:"param"`
	// Message describes the problem with the parameter.
	Message string `json:"message"`
}

WebhookErrorDetail describes one request parameter that caused an error.

type WebhookScannedDocument

type WebhookScannedDocument struct {
	// ScanID is the scan ID given by you.
	ScanID string `json:"scanId"`
	// TotalWords is the number of words in the document.
	TotalWords int `json:"totalWords"`
	// TotalExcluded is the number of excluded words.
	TotalExcluded int `json:"totalExcluded"`
	// Credits is the number of credits that the scan used.
	Credits int `json:"credits"`
	// CreationTime is when the scan was created, in ISO 8601 format (UTC).
	CreationTime string `json:"creationTime"`
	// Metadata is metadata of the scanned document.
	Metadata *ResultMetadata `json:"metadata"`
}

WebhookScannedDocument is general information about a scanned document.

Directories

Path Synopsis
examples
ai-image-detection command
Command ai-image-detection checks whether an image was generated by AI, in sandbox mode.
Command ai-image-detection checks whether an image was generated by AI, in sandbox mode.
ai-text-detection command
Command ai-text-detection logs in and checks a text with AI Text Detection, in sandbox mode, which is free and returns mock results.
Command ai-text-detection logs in and checks a text with AI Text Detection, in sandbox mode, which is free and returns mock results.
grammar-checker command
Command grammar-checker checks a text with the Grammar Checker, in sandbox mode, and prints the suggested corrections.
Command grammar-checker checks a text with the Grammar Checker, in sandbox mode, and prints the suggested corrections.
plagiarism-checker command
Command plagiarism-checker submits a text to the Plagiarism Checker, with AI Text Detection, in sandbox mode.
Command plagiarism-checker submits a text to the Plagiarism Checker, with AI Text Detection, in sandbox mode.
text-moderation command
Command text-moderation checks a text with Text Moderation for every supported label, in sandbox mode, and prints the flagged segments.
Command text-moderation checks a text with Text Moderation for every supported label, in sandbox mode, and prints the flagged segments.
webhooks command
Command webhooks is a server that receives the Copyleaks webhooks of Plagiarism Checker scans and exports, and reads the AI Text Detection result of completed scans.
Command webhooks is a server that receives the Copyleaks webhooks of Plagiarism Checker scans and exports, and reads the AI Text Detection result of completed scans.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL