copyleaks

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 20 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
  • AI Video Detection
  • Plagiarism Checker
  • Image Plagiarism Detector
  • 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.DetectAIImageUpload(ctx, token, "my-image-scan", &copyleaks.AIImageUploadRequest{
	Image:    image,
	Filename: "photo.png",
	Model:    copyleaks.AIImageModel1Ultra,
	Sandbox:  true,
	// Optional: a confidence band for each region, and masks of objects to locate.
	MaskType:        copyleaks.AIImageMaskHeatmap,
	ObjectDetection: []copyleaks.AIImageObject{{Object: "face"}, {Object: "hand"}},
})
if err != nil {
	log.Fatal(err)
}
fmt.Println("AI detected:", res.IsAIDetected)
if res.DetectedObjects != nil {
	for _, object := range *res.DetectedObjects {
		fmt.Println("found", object.Object)
	}
}

DetectAIImageUpload uploads the image as multipart/form-data, which the API recommends. DetectAIImage sends the same check as base64 in JSON (AIImageDetectionRequest.Base64).

To check an image at a URL in the background, submit it with SubmitAIImageAsync. Copyleaks posts the result, which has the shape of the DetectAIImage response, to your webhook. Decode it with ParseAIImageWebhook. When the check fails, the webhook carries Error instead of a result, so check res.Error first.

err := client.SubmitAIImageAsync(ctx, token, "my-async-image-scan", &copyleaks.AIImageAsyncSubmission{
	URL:      "https://your-server.example/images/photo.png",
	FileName: "photo.png",
	Model:    copyleaks.AIImageModel1Ultra,
	Webhooks: copyleaks.ResultWebhook{URL: "https://your-server.example/ai-image/result"},
	Sandbox:  true,
})

AI Video Detection

AI Video Detection runs in the background. Submit the URL of a video, and Copyleaks posts the result to your webhook:

err := client.SubmitAIVideo(ctx, token, "my-video-scan", &copyleaks.AIVideoSubmission{
	URL:      "https://your-server.example/videos/clip.mp4",
	Filename: "clip.mp4",
	Model:    copyleaks.AIVideoModel1Pro,
	Webhooks: copyleaks.ResultWebhook{URL: "https://your-server.example/ai-video/result"},
	Sandbox:  true,
})
if err != nil {
	log.Fatal(err)
}

// In the webhook handler:
res, err := copyleaks.ParseAIVideoWebhook(body)
switch {
case err != nil:
	log.Print(err)
case res.Error != nil: // the check failed, for example because the video was too short
	fmt.Println("AI video check failed:", res.Error.Message)
case res.Summary != nil:
	fmt.Printf("AI detected: %v, overall AI ratio: %.2f\n", res.IsAIDetected, res.Summary.OverallAIRatio)
}

Image Plagiarism Detector

Search the web for copies of an image, full or modified, and for the pages that show them:

image, err := os.ReadFile("photo.jpg")
if err != nil {
	log.Fatal(err)
}
res, err := client.CheckImagePlagiarism(ctx, token, "my-image-plagiarism-scan", &copyleaks.ImagePlagiarismRequest{
	Image:    image,
	Filename: "photo.jpg",
	Sandbox:  true,
})
if err != nil {
	log.Fatal(err)
}
if res.Matches != nil && res.Matches.Score != nil {
	fmt.Println("matches:", res.Matches.Score.TotalMatches)
}

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{
	Content:  []byte("Text to scan."), // or Base64: the content, base64-encoded
	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. URLSubmission.Verb and URLSubmission.Headers set how Copyleaks fetches the page. Start, Delete, Export and ResendWebhook manage submitted scans.

Set Content to the file as it is rather than Base64: the SDK then encodes it while it builds the request, and a large upload needs about 1.4 times the file size in memory.

ScanProperties turns on more features of a scan, such as:

copyleaks.ScanProperties{
	Webhooks: copyleaks.SubmitWebhooks{Status: "https://your-server.example/webhook/{STATUS}"},
	// AI Text Detection with AI Logic.
	AIGeneratedText: &copyleaks.AIGeneratedText{Detect: true, Explain: &copyleaks.AIGeneratedTextExplain{Enable: true}},
	// Grammar Checker, Gen-AI Overview and Citation Checker.
	WritingFeedback: &copyleaks.ScanWritingFeedback{Enable: true},
	Overview:        &copyleaks.ScanOverview{Enable: true},
	References:      &copyleaks.References{Validate: true},
	// Matches in the Copyleaks internal AI database, and masking of sensitive data.
	InternalAISourceMatch:   &copyleaks.InternalAISourceMatch{Enable: true},
	SensitiveDataProtection: &copyleaks.SensitiveDataProtection{EmailAddress: true, PhoneNumber: true},
	// Analytics IDs and the time zone of the PDF report.
	Course:       &copyleaks.Course{ID: "course-101"},
	ScanTimeZone: "America/New_York",
}

Export uploads the artifacts of a completed scan to your servers: results, the crawled version, the PDF report, and the AI Text Detection, Grammar Checker and Gen-AI Overview reports. Decode the uploaded files with ParseExportedResult, ParseExportedCrawledVersion, ParseExportedAIDetection, ParseExportedWritingFeedback and ParseExportedOverview.

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

http.HandleFunc("POST /webhook/completed", func(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(http.MaxBytesReader(w, 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)
}

Account and lookups

credits, err := client.CreditsBalance(ctx, token)            // Plagiarism Checker credits
aiCredits, err := client.AITextCreditsBalance(ctx, token)    // AI Text Detection credits
csv, err := client.UsagesHistoryCSV(ctx, token, start, end)  // usage history
hub, err := client.RepositoryInfo(ctx, token, "my-repo-id")  // a Private Cloud Hub; needs the Admin role

These lookups need no login: SupportedFileTypes, SupportedAITextFileTypes, OCRSupportedLanguages, AllowedCrossLanguages and GrammarCorrectionTypes.

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, or turn on WithRetry (see Options).
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))
	// The Retry-After delay of the response, when it has one.
	fmt.Println(apiErr.RetryAfter)
}

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. WithMaxJSONResponseSize raises the JSON limit.

Options

client, err := copyleaks.NewClient(
	copyleaks.WithRetry(copyleaks.RetryPolicy{MaxAttempts: 4}),
	copyleaks.WithTimeout(5*time.Minute),
	copyleaks.WithUserAgent("my-app/2.1"),
)
if err != nil {
	log.Fatal(err)
}
  • WithRetry turns on retries, which are off by default. A call is retried after HTTP 429, HTTP 503 and connection errors (a timeout, or a refused, reset or dropped connection; not an invalid TLS certificate or an unknown host), waiting for the server's Retry-After delay when it sends one, and otherwise for an exponential backoff with jitter (BaseDelay, 1 second by default, doubling up to MaxDelay, 30 seconds by default). Only calls that are safe to repeat are retried: the GET calls, Login, the submits that carry your scan ID (SubmitFile, SubmitOCR, SubmitURL, SubmitAIImageAsync, SubmitAIVideo) and Export, which is not retried after HTTP 503, as the failed export keeps its export ID. The checks that charge for each request (DetectAIText, DetectAIImage, DetectAIImageUpload, CheckImagePlagiarism, CheckGrammar, ModerateText), Start, Delete and ResendWebhook are never retried. The context of each call bounds the whole call, retries included.
  • WithTimeout sets the timeout of each request of the default HTTP client: two minutes by default, from connecting to reading the whole response. Raise it to upload large files over slow links, or set 0 to rely on the context only.
  • WithHTTPClient sends the requests with your own *http.Client, for example to use a proxy. The SDK uses it as it is and never changes it; WithTimeout does not apply to it. The default client sends the requests through http.DefaultTransport.
  • WithMaxJSONResponseSize raises the 16 MiB limit of JSON responses, for example for the AI Image Detection masks of large, detailed images.
  • WithUserAgent adds your application's token in front of the SDK's User-Agent.

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, Image and Video Detection, Plagiarism Checker, Image Plagiarism Detector, Grammar Checker, Text Moderation, account and scan management, and parsers for webhooks and exported files. Create one Client, log in, and pass the AuthToken to each call:

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})

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

Index

Constants

View Source
const (
	// AIImageMaskBinary returns a run-length encoded mask of the AI-generated regions. It is the default.
	AIImageMaskBinary = "binary"
	// AIImageMaskHeatmap also returns a confidence band per mask run in AIImageDetectionResult.Labels.
	AIImageMaskHeatmap = "heatmap"
	// AIImageMaskNone returns no mask: AIImageDetectionResponse.Result is nil.
	AIImageMaskNone = "none"
)

The values of AIImageDetectionRequest.MaskType.

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 (
	// ImageMatchFull is an exact or near-exact copy of the image.
	ImageMatchFull = 0
	// ImageMatchPartial is a cropped, resized, recolored or otherwise modified copy.
	ImageMatchPartial = 1
)

The values of ImagePlagiarismMatch.MatchType.

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, with 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", which masks AI-generated regions.

View Source
const AIVideoModel1Pro = "ai-video-1-pro"

AIVideoModel1Pro is the AI Video Detection model "ai-video-1-pro".

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

AlertCodeSuspectedAIText is the code of the alert that carries the AI Text Detection result of a scan with ScanProperties.AIGeneratedText.

View Source
const TextModerationLanguageEnglish = "en"

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

View Source
const Version = "1.1.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 401: the login token or the API key was rejected.
	ErrUnauthorized = errors.New("copyleaks: unauthorized")
	// ErrRateLimited matches an *APIError with HTTP 429. Wait before calling again (see APIError.RetryAfter).
	ErrRateLimited = errors.New("copyleaks: rate limited")
	// ErrUnderMaintenance matches an *APIError with HTTP 503 (maintenance); retry later, or use WithRetry.
	ErrUnderMaintenance = errors.New("copyleaks: under maintenance")
	// ErrTokenExpired is returned, before any request, when the AuthToken expired or expires within five minutes.
	ErrTokenExpired = errors.New("copyleaks: auth token expired")
	// ErrInvalidArgument matches the client-side checks that fail before any request: a missing required field,
	// a malformed scan ID, a too-short text, a non-https base URL, and so on.
	ErrInvalidArgument = errors.New("copyleaks: invalid argument")
	// ErrResponseTooLarge matches a 2xx body over 64 MiB (usage CSV) or 16 MiB (JSON); it is not truncated.
	ErrResponseTooLarge = errors.New("copyleaks: response too large")
)

Functions

func Ptr

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

Ptr returns a pointer to v, for optional pointer fields such as Filters.IdenticalEnabled: copyleaks.Ptr(false).

func VerifyAuthToken

func VerifyAuthToken(token *AuthToken) error

VerifyAuthToken checks a token locally: ErrInvalidArgument when it is nil or empty, ErrTokenExpired when it expired or expires within five minutes. Every authenticated method runs it first.

Types

type AIGeneratedText

type AIGeneratedText struct {
	// Detect detects whether the text was written by AI.
	Detect bool `json:"detect"`
	// Sensitivity is 1 to 3; see AITextDetectionRequest.Sensitivity. Zero keeps the default.
	Sensitivity int `json:"sensitivity,omitempty"`
	// Explain adds AI Logic, an explanation of the detection, for the languages that support it.
	Explain *AIGeneratedTextExplain `json:"explain,omitempty"`
}

AIGeneratedText adds AI Text Detection to a Plagiarism Checker scan.

type AIGeneratedTextExplain added in v1.1.0

type AIGeneratedTextExplain struct {
	// Enable turns AI Logic on.
	Enable bool `json:"enable"`
}

AIGeneratedTextExplain turns AI Logic on in a Plagiarism Checker scan.

type AIImageAsyncSubmission added in v1.1.0

type AIImageAsyncSubmission struct {
	// URL is the public address of the image to check (required).
	URL string `json:"url"`
	// FileName is the image name (required), up to 254 characters; see AIImageDetectionRequest.Filename.
	FileName string `json:"fileName"`
	// Model is the detection model, such as AIImageModel1Ultra (required).
	Model string `json:"model"`
	// MaskType is AIImageMaskBinary (default) or AIImageMaskHeatmap.
	MaskType string `json:"maskType,omitempty"`
	// ObjectDetection lists up to 3 objects to locate; see AIImageDetectionRequest.ObjectDetection.
	ObjectDetection []AIImageObject `json:"objectDetection,omitempty"`
	// Headers are the headers that Copyleaks sends to fetch URL, as [name, value] pairs.
	Headers [][]string `json:"headers,omitempty"`
	// Webhooks is where Copyleaks sends the result (required); see ParseAIImageWebhook.
	Webhooks ResultWebhook `json:"webhooks"`
	// Sandbox runs a free test check that returns mock results.
	Sandbox bool `json:"sandbox,omitempty"`
	// DeveloperPayload is sent back with the result; up to 511 characters.
	DeveloperPayload string `json:"developerPayload,omitempty"`
}

AIImageAsyncSubmission is the body of SubmitAIImageAsync.

type AIImageDetectedObject added in v1.1.0

type AIImageDetectedObject struct {
	// Object is the name of the object, as in the request.
	Object string `json:"object"`
	// Mask is the run-length encoded mask of the object, over the pixels flattened row by row.
	Mask *AIImageDetectionResult `json:"mask"`
}

AIImageDetectedObject is an object found in an image.

type AIImageDetectionRequest

type AIImageDetectionRequest struct {
	// Base64 is the image, base64-encoded (required): 512x512 pixels to 27 megapixels, under 32 MB.
	Base64 string `json:"base64"`
	// Filename is the image name (required), 5 to 254 characters, ending with .png, .bmp, .jpg, .jpeg, .webp,
	// .heic, .heif or .avif.
	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"`
	// MaskType is AIImageMaskBinary (default), AIImageMaskHeatmap or AIImageMaskNone.
	MaskType string `json:"maskType,omitempty"`
	// ObjectDetection lists up to 3 objects to locate, such as "face", at no extra cost; see
	// AIImageDetectionResponse.DetectedObjects. It is a pointer, so that AIImageDetectionRequest stays comparable.
	ObjectDetection *[]AIImageObject `json:"objectDetection,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 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"`
	// DetectedObjects are the requested objects that were found, each with its mask; look them up by Object.
	// Nil without ObjectDetection. It is a pointer, so that AIImageDetectionResponse stays comparable.
	DetectedObjects *[]AIImageDetectedObject `json:"detectedObjects"`
	// DeveloperPayload is the DeveloperPayload of an AIImageAsyncSubmission, when the webhook carries it.
	DeveloperPayload string `json:"developerPayload,omitempty"`
	// Error tells why a SubmitAIImageAsync check failed; when it is set, only Error and DeveloperPayload are
	// filled. DetectAIImage and DetectAIImageUpload return an *APIError instead.
	Error *WebhookError `json:"error,omitempty"`
}

AIImageDetectionResponse is the result of AI Image Detection. See https://docs.copyleaks.com/reference/data-types/ai-detector/ai-image-detection-response.

func ParseAIImageWebhook added in v1.1.0

func ParseAIImageWebhook(body []byte) (*AIImageDetectionResponse, error)

ParseAIImageWebhook decodes the SubmitAIImageAsync result posted to the webhook. Check Error first. 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"`
	// Labels are the confidence bands of the runs, 0 (lowest) to 4 (highest); only for AIImageMaskHeatmap.
	Labels []int `json:"labels,omitempty"`
}

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, 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 AIImageObject added in v1.1.0

type AIImageObject struct {
	// Object names the object, 1 to 32 characters.
	Object string `json:"object"`
}

AIImageObject is an object to locate in an image, such as "face"; see AIImageDetectionRequest.ObjectDetection.

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 AIImageUploadRequest added in v1.1.0

type AIImageUploadRequest struct {
	// Image is the image file (required), with the limits of AIImageDetectionRequest.Base64.
	Image []byte
	// Filename is the image name (required); see AIImageDetectionRequest.Filename.
	Filename string
	// Model is the detection model, such as AIImageModel1Ultra (required).
	Model string
	// Sandbox runs a free test check that returns mock results.
	Sandbox bool
	// MaskType is the kind of mask; see AIImageDetectionRequest.MaskType.
	MaskType string
	// ObjectDetection lists up to 3 objects to locate; see AIImageDetectionRequest.ObjectDetection.
	ObjectDetection []AIImageObject
}

AIImageUploadRequest is the request of DetectAIImageUpload: the options of AIImageDetectionRequest, raw image.

type AISourceMatch

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

AISourceMatch configures ScanProperties.AISourceMatch.

type AITextCreditsBalance added in v1.1.0

type AITextCreditsBalance struct {
	// Credits is the number of remaining credits.
	Credits int `json:"credits"`
}

AITextCreditsBalance is the AI Text Detection credit balance of an account.

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"; empty lets the server detect it.
	Language string `json:"language,omitempty"`
	// Explain asks for AI Logic, an explanation of the detection, for the languages that support it.
	Explain bool `json:"explain,omitempty"`
	// Sensitivity is 1 to 3; higher also catches more heavily edited AI text. Nil keeps 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 if not translated.
	TranslationProvider int `json:"translationProvider"`
	// Translation is the machine-translated English text, when the text was translated.
	Translation string `json:"translation"`
	// Explain is AI Logic, when AITextDetectionRequest.Explain was set.
	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 DetectAIText, and of CompletedWebhook.AIDetectionResult. See https://docs.copyleaks.com/reference/data-types/ai-detector/ai-text-detector-response.

func ParseExportedAIDetection added in v1.1.0

func ParseExportedAIDetection(body []byte) (*AITextDetectionResponse, error)

ParseExportedAIDetection decodes the AI Text Detection report uploaded for ExportRequest.AIDetection. See https://docs.copyleaks.com/reference/data-types/authenticity/results/ai-detection.

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, or 0 when the server leaves it out.
	//
	// Deprecated: The API reference deprecates it. Use Classification and AITextDetectionResponse.Summary.
	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, 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 AIVideoDetectionResponse added in v1.1.0

type AIVideoDetectionResponse struct {
	// Model is the detection model that was used.
	Model string `json:"model"`
	// AudioResult are the AI-generated segments of the audio track.
	AudioResult *AIVideoTrackResult `json:"audioResult"`
	// VisualResult are the AI-generated segments of the visual track.
	VisualResult *AIVideoTrackResult `json:"visualResult"`
	// Summary is the share of the video detected as AI-generated.
	Summary *AIVideoDetectionSummary `json:"summary"`
	// IsAIDetected reports whether the video contains AI-generated content; prefer it to the Summary ratios.
	IsAIDetected bool `json:"isAiDetected"`
	// VideoInfo is information about the video.
	VideoInfo *AIVideoInfo `json:"videoInfo"`
	// ScannedVideo is general information about the check.
	ScannedVideo *ScannedVideo `json:"scannedVideo"`
	// DeveloperPayload is the DeveloperPayload of the submit, when the webhook carries it.
	DeveloperPayload string `json:"developerPayload,omitempty"`
	// Error tells why the check failed; when it is set, only Error and DeveloperPayload are filled.
	Error *WebhookError `json:"error,omitempty"`
}

AIVideoDetectionResponse is the AI Video Detection result posted to the SubmitAIVideo webhook. See https://docs.copyleaks.com/reference/data-types/ai-detector/ai-video-detection-response.

func ParseAIVideoWebhook added in v1.1.0

func ParseAIVideoWebhook(body []byte) (*AIVideoDetectionResponse, error)

ParseAIVideoWebhook decodes the SubmitAIVideo result posted to the webhook. Check Error first.

type AIVideoDetectionSummary added in v1.1.0

type AIVideoDetectionSummary struct {
	// AudioAIRatio is the share of the audible duration detected as AI-generated.
	AudioAIRatio float64 `json:"audioAIRatio"`
	// VisualAIRatio is the share of the visible duration detected as AI-generated.
	VisualAIRatio float64 `json:"visualAIRatio"`
	// OverallAIRatio is the share of the whole video detected as AI-generated, over both tracks.
	OverallAIRatio float64 `json:"overallAIRatio"`
}

AIVideoDetectionSummary is the share of a video detected as AI-generated, 0 to 1, over scored segments only.

type AIVideoInfo added in v1.1.0

type AIVideoInfo struct {
	// Duration is the duration of the video, in seconds.
	Duration float64 `json:"duration"`
	// Metadata is metadata read from the video, such as C2PA provenance data, when it has any.
	Metadata *AIVideoMetadata `json:"metadata"`
}

AIVideoInfo is information about an analyzed video.

type AIVideoMetadata added in v1.1.0

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

AIVideoMetadata is metadata read from a video.

type AIVideoRanges added in v1.1.0

type AIVideoRanges struct {
	// Starts are the start positions of the segments.
	Starts []int `json:"starts"`
	// Lengths are the durations of the segments, one per start position.
	Lengths []int `json:"lengths"`
}

AIVideoRanges are segments of a video, as parallel start and length lists in milliseconds.

type AIVideoSubmission added in v1.1.0

type AIVideoSubmission struct {
	// URL is the public address of the video to check (required).
	URL string `json:"url"`
	// Headers are the headers that Copyleaks sends to fetch URL, as [name, value] pairs.
	Headers [][]string `json:"headers,omitempty"`
	// Verb is the HTTP method used to fetch URL: "GET" (default), "POST" or "PUT".
	Verb string `json:"verb,omitempty"`
	// Filename is the video name (required), up to 254 characters, ending with .mp4, .avi, .mov, .mkv, .webm,
	// .flv, .wmv, .mpg, .m4v, .3gp or .mxf.
	Filename string `json:"filename"`
	// Model is the detection model, such as AIVideoModel1Pro (required).
	Model string `json:"model"`
	// Webhooks is where Copyleaks sends the result (required); see ParseAIVideoWebhook.
	Webhooks ResultWebhook `json:"webhooks"`
	// Sandbox runs a free test check that returns mock results.
	Sandbox bool `json:"sandbox,omitempty"`
	// DeveloperPayload is sent back with the result; up to 511 characters.
	DeveloperPayload string `json:"developerPayload,omitempty"`
}

AIVideoSubmission is the body of SubmitAIVideo.

type AIVideoTrackResult added in v1.1.0

type AIVideoTrackResult struct {
	// Starts are the start positions of the AI-generated segments.
	Starts []int `json:"starts"`
	// Lengths are the durations of the AI-generated segments, one per start position.
	Lengths []int `json:"lengths"`
	// Exclude are the segments that were not scored, and do not count in the ratios.
	Exclude *AIVideoRanges `json:"exclude"`
}

AIVideoTrackResult are the AI-generated segments of a video track, as start and length lists in milliseconds.

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
	// RetryAfter is the Retry-After delay of the response, or 0 without one; mostly set on HTTP 429 and 503.
	RetryAfter time.Duration
}

APIError is returned for a non-2xx HTTP status. Match it with errors.Is (ErrUnauthorized, ErrRateLimited, ErrUnderMaintenance) or read it with errors.As.

func (*APIError) Error

func (e *APIError) Error() string

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

func (*APIError) Is

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

Is matches ErrUnauthorized (401), ErrRateLimited (429) and ErrUnderMaintenance (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 as a JSON string; decode a suspected-ai-text alert's 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, ignoring trailing NULs and ASCII whitespace. It returns nil and no error for a nil or other alert, empty data, or JSON that is not an object (such as null), and an error for invalid JSON or a mistyped field; AdditionalData keeps the raw string.

type AllowedCrossLanguages added in v1.1.0

type AllowedCrossLanguages struct {
	// DocumentLanguages are the languages that a scanned document can be in.
	DocumentLanguages LanguageCodes `json:"documentLanguages"`
	// ResultLanguages are the languages that the document can be compared against.
	ResultLanguages LanguageCodes `json:"resultLanguages"`
}

AllowedCrossLanguages lists the languages of cross-language scans (see Scanning.CrossLanguages).

type Assignment added in v1.1.0

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

Assignment identifies the assignment of the scanned content, for analytics.

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. It is valid for 48 hours; reuse it until it expires. Treat it like a password: fmt prints it redacted, but its JSON (for storing it) holds the access token.

func (AuthToken) Format

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

Format implements fmt.Formatter: every verb and flag prints the redacted String form.

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 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. It is safe for concurrent use: create one with NewClient and reuse it. It holds no credentials; pass the AuthToken from Login to each authenticated call.

func NewClient

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

NewClient returns a Client for the production API; an invalid option gives ErrInvalidArgument.

func (*Client) AITextCreditsBalance added in v1.1.0

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

AITextCreditsBalance returns the AI Text Detection credit balance of the account. See https://docs.copyleaks.com/reference/actions/writer-detector/credits.

func (*Client) AllowedCrossLanguages added in v1.1.0

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

AllowedCrossLanguages returns the languages of cross-language scans. No login needed. See https://docs.copyleaks.com/reference/actions/miscellaneous/supported-cross-languages.

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. Scan ID: 3 to 36 characters. See https://docs.copyleaks.com/reference/actions/writing-assistant/check.

func (*Client) CheckImagePlagiarism added in v1.1.0

func (c *Client) CheckImagePlagiarism(ctx context.Context, token *AuthToken, scanID string, req *ImagePlagiarismRequest) (*ImagePlagiarismResponse, error)

CheckImagePlagiarism searches the web for full or modified copies of an image and the pages that show them. Scan ID: 3 to 36 characters. See https://docs.copyleaks.com/reference/actions/image-plagiarism-detector/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, in the background (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. Scan ID: 3 to 36 characters. See https://docs.copyleaks.com/reference/actions/ai-image-detector/check.

func (*Client) DetectAIImageUpload added in v1.1.0

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

DetectAIImageUpload is DetectAIImage with a multipart/form-data upload, the format that the API recommends: the request is a third smaller than base64 and the SDK holds about one copy of the image. 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. Scan ID: 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 new. 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 Grammar Checker correction types, with texts in language, such as "en". No login needed. 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 an account email and API key for an AuthToken. Only 12 logins per account are allowed in 15 minutes, so reuse the token. 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. Scan ID: 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 codes accepted in OCRSubmission.LangCode. No login needed. 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 API release notes. No login needed. The endpoint is undocumented and may change.

func (*Client) RepositoryInfo added in v1.1.0

func (c *Client) RepositoryInfo(ctx context.Context, token *AuthToken, repositoryID string) (*RepositoryInfo, error)

RepositoryInfo returns the credits, metadata and status of a Private Cloud Hub. It needs the Admin or Super Admin role; the repository ID is in the Copyleaks Admin Dashboard. See https://docs.copyleaks.com/reference/actions/private-cloud-hub/info.

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) SubmitAIImageAsync added in v1.1.0

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

SubmitAIImageAsync submits the image at a URL to AI Image Detection; the result is posted to req.Webhooks.URL (decode it with ParseAIImageWebhook). Scan ID: 3 to 36 characters. See https://docs.copyleaks.com/reference/actions/ai-image-detector/submit.

func (*Client) SubmitAIVideo added in v1.1.0

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

SubmitAIVideo submits the video at a URL to AI Video Detection; the result is posted to req.Webhooks.URL (decode it with ParseAIVideoWebhook). Scan ID: 3 to 36 characters. The video must be 2 s to 1 h, up to 512 MiB, at least 360x360 px and 16 fps; Copyleaks checks this after download and reports failures to the webhook. See https://docs.copyleaks.com/reference/actions/ai-video-detector/submit.

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. It runs in the background and reports 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, 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, like SubmitFile. See https://docs.copyleaks.com/reference/actions/authenticity/submit-url.

func (*Client) SupportedAITextFileTypes added in v1.1.0

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

SupportedAITextFileTypes returns the file types that AI Text Detection can scan. No login needed. See https://docs.copyleaks.com/reference/actions/miscellaneous/supported-ai-text-detection-file-types.

func (*Client) SupportedFileTypes

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

SupportedFileTypes returns the file types that the Plagiarism Checker can scan. No login needed. 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 account's usage history from start to end (dates only, inclusive) as CSV. See https://docs.copyleaks.com/reference/actions/admin/usage-history.

type ComparisonLocation added in v1.1.0

type ComparisonLocation struct {
	// Chars are the character positions of the matches.
	Chars *TextRanges `json:"chars"`
	// Words are the word positions of the matches.
	Words *TextRanges `json:"words"`
}

ComparisonLocation locates matches by character and by word.

type ComparisonMatches added in v1.1.0

type ComparisonMatches struct {
	// GroupID are the HTML group IDs of the matches, in the HTML comparison only.
	GroupID []int `json:"groupId,omitempty"`
	// Source locates the matches in the result source.
	Source *ComparisonLocation `json:"source"`
	// Suspected locates the matches in the scanned document.
	Suspected *ComparisonLocation `json:"suspected"`
}

ComparisonMatches are matches of one kind in the source and the scanned document, as parallel lists.

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"`
	// ReferencesValidation is the Citation Checker summary; per-reference results are in
	// ExportedCrawledVersion.ReferencesValidation.
	ReferencesValidation *ReferencesValidation `json:"referencesValidation"`
	// WritingFeedback is the Grammar Checker summary; export the full report with ExportRequest.WritingFeedback.
	WritingFeedback *WebhookWritingFeedback `json:"writingFeedback"`
}

CompletedWebhook is sent to the status webhook when a Plagiarism Checker scan succeeds. 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.

func (*CompletedWebhook) AIDetectionResult

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

AIDetectionResult is AIDetectionAlert().AIDetectionResult(). It returns nil and no error when there is no alert or no result; use AIDetectionAlert to tell these 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 Course added in v1.1.0

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

Course identifies the course of the scanned content, for analytics.

type CrawledVersionHTML added in v1.1.0

type CrawledVersionHTML struct {
	// Value is the HTML.
	Value string `json:"value"`
	// Exclude are the parts of the HTML that were not scanned.
	Exclude *ExcludedRanges `json:"exclude"`
}

CrawledVersionHTML is a crawled document as HTML.

type CrawledVersionMetadata added in v1.1.0

type CrawledVersionMetadata struct {
	// Words is the number of words.
	Words int `json:"words"`
	// Excluded is the number of excluded words.
	Excluded int `json:"excluded"`
}

CrawledVersionMetadata counts the words of a crawled document.

type CrawledVersionText added in v1.1.0

type CrawledVersionText struct {
	// Value is the text.
	Value string `json:"value"`
	// Exclude are the parts of the text that were not scanned.
	Exclude *ExcludedRanges `json:"exclude"`
	// Pages are the pages of the text.
	Pages *TextPages `json:"pages"`
}

CrawledVersionText is a crawled document as plain text.

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 creditsChecked webhook payload of 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 the scans from the Shared Data Hub and Private Cloud Hubs, so they never match 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 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 ExcludedRanges added in v1.1.0

type ExcludedRanges struct {
	// Starts are the start positions of the parts.
	Starts []int `json:"starts"`
	// Lengths are the lengths of the parts, in characters.
	Lengths []int `json:"lengths"`
	// Reasons are the reasons why the parts were excluded.
	Reasons []int `json:"reasons"`
	// GroupIDs are the HTML group IDs of the parts, in the HTML version only.
	GroupIDs []int `json:"groupIds,omitempty"`
}

ExcludedRanges are the parts of a document that were not scanned, as parallel lists.

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 sent 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"`
	// CompletionWebhookHeaders are extra headers of the CompletionWebhook request, as [name, value] pairs.
	CompletionWebhookHeaders [][]string `json:"completionWebhookHeaders,omitempty"`
	// MaxRetries is how many times each upload is retried, 1 to 12 (default 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; see ParseExportedResult.
	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; see ParseExportedCrawledVersion.
	CrawledVersion *ExportTarget `json:"crawledVersion,omitempty"`
	// AIDetection exports the AI Text Detection report, with AI Logic when it was on. It requires
	// ScanProperties.AIGeneratedText.Detect on submit. See ParseExportedAIDetection.
	AIDetection *ExportTarget `json:"aiDetection,omitempty"`
	// WritingFeedback exports the Grammar Checker report; it requires ScanProperties.WritingFeedback.Enable.
	// See ParseExportedWritingFeedback.
	WritingFeedback *ExportTarget `json:"writingFeedback,omitempty"`
	// Overview exports the Gen-AI Overview. It requires ScanProperties.Overview.Enable on submit.
	// See ParseExportedOverview.
	Overview *ExportTarget `json:"overview,omitempty"`
}

ExportRequest is the body of Export: 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 ExportedCrawledVersion added in v1.1.0

type ExportedCrawledVersion struct {
	// Metadata counts the words of the document.
	Metadata *CrawledVersionMetadata `json:"metadata"`
	// Text is the document as plain text.
	Text *CrawledVersionText `json:"text"`
	// HTML is the document as HTML, when the scan set ScanProperties.IncludeHTML.
	HTML *CrawledVersionHTML `json:"html"`
	// ReferencesValidation is the Citation Checker result, when the scan set ScanProperties.References.Validate.
	ReferencesValidation *ReferencesValidation `json:"referencesValidation"`
}

ExportedCrawledVersion is the document as Copyleaks read it, uploaded for ExportRequest.CrawledVersion. See https://docs.copyleaks.com/reference/data-types/authenticity/results/crawled-version.

func ParseExportedCrawledVersion added in v1.1.0

func ParseExportedCrawledVersion(body []byte) (*ExportedCrawledVersion, error)

ParseExportedCrawledVersion decodes the crawled version that Export uploaded for ExportRequest.CrawledVersion.

type ExportedOverview added in v1.1.0

type ExportedOverview struct {
	// Overview is the overview of the scan, in Markdown.
	Overview string `json:"overview"`
	// ModelVersion is the version of the model that wrote the overview.
	ModelVersion string `json:"modelVersion"`
}

ExportedOverview is the Gen-AI Overview that Export uploads for ExportRequest.Overview. See https://docs.copyleaks.com/reference/data-types/authenticity/results/ai-overview.

func ParseExportedOverview added in v1.1.0

func ParseExportedOverview(body []byte) (*ExportedOverview, error)

ParseExportedOverview decodes the Gen-AI Overview that Export uploaded for ExportRequest.Overview.

type ExportedResult added in v1.1.0

type ExportedResult struct {
	// Statistics count the matching words, by kind of match.
	Statistics *ExportedResultStatistics `json:"statistics"`
	// Text is the source as plain text, with the matches.
	Text *ExportedResultText `json:"text"`
	// HTML is the source as HTML, with the matches, when the scan set ScanProperties.IncludeHTML.
	HTML *ExportedResultHTML `json:"html"`
}

ExportedResult is a result file that Export uploads for ExportRequest.Results: a source and its matches. See https://docs.copyleaks.com/reference/data-types/authenticity/results/new-plagiarism-result.

func ParseExportedResult added in v1.1.0

func ParseExportedResult(body []byte) (*ExportedResult, error)

ParseExportedResult decodes a result file that Export uploaded for ExportRequest.Results.

type ExportedResultHTML added in v1.1.0

type ExportedResultHTML struct {
	// Value is the HTML of the source.
	Value string `json:"value"`
	// Comparison locates the matches, by kind of match.
	Comparison *ResultComparison `json:"comparison"`
}

ExportedResultHTML is the HTML of a result source, with the matches.

type ExportedResultStatistics added in v1.1.0

type ExportedResultStatistics struct {
	// Identical is the number of identical words.
	Identical int `json:"identical"`
	// MinorChanges is the number of nearly identical words, such as slow and slowly.
	MinorChanges int `json:"minorChanges"`
	// RelatedMeaning is the number of paraphrased words.
	RelatedMeaning int `json:"relatedMeaning"`
}

ExportedResultStatistics count the matching words of a result, by kind of match.

type ExportedResultText added in v1.1.0

type ExportedResultText struct {
	// Value is the text of the source.
	Value string `json:"value"`
	// Pages are the pages of the text.
	Pages *TextPages `json:"pages"`
	// Comparison locates the matches, by kind of match.
	Comparison *ResultComparison `json:"comparison"`
}

ExportedResultText is the plain text of a result source, with the matches.

type FileSubmission

type FileSubmission struct {
	// Base64 is the file, base64-encoded; set it or Content. 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"`
	// Content is the raw file; set it or Base64. The SDK encodes it while building the request, which needs less
	// memory (about 1.4 times the file size) than encoding it into Base64 yourself.
	Content []byte `json:"-"`
}

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.
	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"; empty lets the server detect it.
	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.

func ParseExportedWritingFeedback added in v1.1.0

func ParseExportedWritingFeedback(body []byte) (*GrammarCheckResponse, error)

ParseExportedWritingFeedback decodes the Grammar Checker report uploaded for ExportRequest.WritingFeedback. 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 weighs each correction category in the overall score, 0.0 to 1.0; nil keeps 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 HTMLRanges added in v1.1.0

type HTMLRanges struct {
	// Starts are the start positions of the ranges.
	Starts []int `json:"starts"`
	// Lengths are the lengths of the ranges, in characters.
	Lengths []int `json:"lengths"`
	// GroupIDs group the ranges of one reference.
	GroupIDs []int `json:"groupIds"`
}

HTMLRanges are ranges of an HTML document, as parallel lists.

func (*HTMLRanges) UnmarshalJSON added in v1.1.0

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

UnmarshalJSON decodes the ranges; it also accepts an empty list, for no ranges.

type ImagePlagiarismMatch added in v1.1.0

type ImagePlagiarismMatch struct {
	// URL is the address of the matching image.
	URL string `json:"url"`
	// MatchType is ImageMatchFull or ImageMatchPartial.
	MatchType int `json:"matchType"`
	// WebPages are the pages that show the image. It is empty when no page was found.
	WebPages []ImagePlagiarismWebPage `json:"webPages"`
}

ImagePlagiarismMatch is a copy of an image found on the web.

type ImagePlagiarismMatches added in v1.1.0

type ImagePlagiarismMatches struct {
	// Internet are the matching images, full matches first, each URL once. Empty means no copy was found.
	Internet []ImagePlagiarismMatch `json:"internet"`
	// Score counts the matches.
	Score *ImagePlagiarismScore `json:"score"`
}

ImagePlagiarismMatches are the copies of an image found on the web.

type ImagePlagiarismRequest added in v1.1.0

type ImagePlagiarismRequest struct {
	// Image is the image file (required), under 20 MB and at most 75 megapixels.
	Image []byte
	// Filename is the image name (required), up to 255 characters: .jpg, .jpeg, .png, .gif, .bmp, .webp or .ico.
	Filename string
	// Sandbox runs a free test check that returns mock results.
	Sandbox bool
	// DeveloperPayload is sent back as it is in ImagePlagiarismResponse.DeveloperPayload.
	DeveloperPayload string
}

ImagePlagiarismRequest is the request of CheckImagePlagiarism.

type ImagePlagiarismResponse added in v1.1.0

type ImagePlagiarismResponse struct {
	// DeveloperPayload is the DeveloperPayload of the request.
	DeveloperPayload string `json:"developerPayload"`
	// ScannedImage is information about the image and the check.
	ScannedImage *ScannedImage `json:"scannedImage"`
	// Matches are the copies of the image found on the web.
	Matches *ImagePlagiarismMatches `json:"matches"`
}

ImagePlagiarismResponse is the result of the Image Plagiarism Detector. See https://docs.copyleaks.com/reference/data-types/authenticity/results/image-plagiarism-response.

type ImagePlagiarismScore added in v1.1.0

type ImagePlagiarismScore struct {
	// TotalMatches is the number of matching images.
	TotalMatches int `json:"totalMatches"`
	// FullMatches is the number of full matches.
	FullMatches int `json:"fullMatches"`
	// PartialMatches is the number of partial matches.
	PartialMatches int `json:"partialMatches"`
}

ImagePlagiarismScore counts the matches of an Image Plagiarism Detector check.

type ImagePlagiarismWebPage added in v1.1.0

type ImagePlagiarismWebPage struct {
	// URL is the address of the page.
	URL string `json:"url"`
}

ImagePlagiarismWebPage is a web page that shows a matching image.

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 indexed webhook payload of 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"`
	// CopyleaksDB adds the content to the Shared Data Hub. Nil keeps the default: added when Scanning.CopyleaksDB
	// compares it against any submissions.
	CopyleaksDB *bool `json:"copyleaksDb,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 Institution added in v1.1.0

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

Institution identifies the institution of the scanned content, for analytics.

type InternalAIResult added in v1.1.0

type InternalAIResult struct {
	// ID is the result ID.
	ID string `json:"id"`
	// Title is the title of the matching entry.
	Title string `json:"title"`
	// Introduction is an excerpt of the matching content.
	Introduction string `json:"introduction"`
	// MatchedWords is the number of words that match the scanned document.
	MatchedWords int `json:"matchedWords"`
	// IdenticalWords is the number of identical words.
	IdenticalWords int `json:"identicalWords"`
	// SimilarWords is the number of similar, but not identical, words.
	SimilarWords int `json:"similarWords"`
	// ParaphrasedWords is the number of paraphrased words.
	ParaphrasedWords int `json:"paraphrasedWords"`
	// TotalWords is the number of words in the matching entry.
	TotalWords int `json:"totalWords"`
	// Tags are the tags of the result.
	Tags []ResultTag `json:"tags"`
}

InternalAIResult is a result found in the Copyleaks internal AI database.

type InternalAISourceMatch added in v1.1.0

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

InternalAISourceMatch configures ScanProperties.InternalAISourceMatch.

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 LanguageCodes added in v1.1.0

type LanguageCodes map[string]string

LanguageCodes maps language names, such as "english", to ISO 639-1 codes, such as "en".

func (LanguageCodes) Codes added in v1.1.0

func (l LanguageCodes) Codes() []string

Codes returns the codes, sorted and deduplicated, for use in CrossLanguage.Code.

func (*LanguageCodes) UnmarshalJSON added in v1.1.0

func (l *LanguageCodes) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the name-to-code object that the server sends, or a list of codes (as the API reference shows), mapping each code to itself.

type MaskingPolicy

type MaskingPolicy int

MaskingPolicy sets who sees the content of a Private Cloud Hub document 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"`
	// InternalAIData are the new results from the Copyleaks internal AI database.
	InternalAIData []InternalAIResult `json:"internalAIData"`
}

NewResultWebhook is sent to SubmitWebhooks.NewResult each time a result is found while the scan 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 image, base64-encoded; set it or Content.
	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"`
	// Content is the raw image; set it or Base64. See FileSubmission.Content.
	Content []byte `json:"-"`
}

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. It must use https; http is only accepted for localhost, 127.0.0.1 and ::1.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sends requests with hc instead of the default http.Client, e.g. for a proxy or custom Transport. hc is used as is and never changed; nil is ignored.

func WithIdentityBaseURL

func WithIdentityBaseURL(baseURL string) Option

WithIdentityBaseURL replaces DefaultIdentityBaseURL, with the same https rule as WithAPIBaseURL.

func WithMaxJSONResponseSize added in v1.1.0

func WithMaxJSONResponseSize(size int64) Option

WithMaxJSONResponseSize sets the largest JSON response body accepted, in bytes (default 16 MiB, minimum 1). A larger body gives ErrResponseTooLarge; raise it for the AI Image Detection masks of large images.

func WithRetry added in v1.1.0

func WithRetry(policy RetryPolicy) Option

WithRetry turns on retries of transient failures (off by default). The context bounds the whole call, retries included; a delay that ends after its deadline is not waited for. Negative fields give ErrInvalidArgument.

func WithTimeout added in v1.1.0

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the per-request timeout of the default http.Client, up to the end of the response body (default two minutes; 0 means none, so only the context bounds it). Each WithRetry attempt gets the full timeout. It has no effect with WithHTTPClient. A negative timeout gives ErrInvalidArgument.

func WithUserAgent

func WithUserAgent(userAgent string) Option

WithUserAgent prepends an application token, such as "my-app/2.1", to the SDK's "copyleaks-go-sdk/<Version>".

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.
	//
	// Deprecated: The API reference deprecates pdf.version. Use ReportVersion.
	Version PDFVersion `json:"version,omitempty"`
	// ReportVersion is a PDFReportVersion constant (case-sensitive) and overrides Version. 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"`
	// AIDetection is the highlight color of AI-generated text.
	AIDetection string `json:"aiDetection,omitempty"`
	// WritingFeedback is the highlight color of Grammar Checker corrections.
	WritingFeedback string `json:"writingFeedback,omitempty"`
}

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

type PDFVersion deprecated

type PDFVersion int

PDFVersion is the layout version of a PDF report; see PDF.Version.

Deprecated: Only the deprecated PDF.Version uses it. Use PDF.ReportVersion and the PDFReportVersion constants.

const (
	// PDFVersion1 is the first report layout.
	PDFVersion1 PDFVersion = 1
	// PDFVersion2 is the second report layout, with AI Text Detection results and cheat detection alerts.
	PDFVersion2 PDFVersion = 2
	// PDFVersion3 is the third report layout.
	PDFVersion3 PDFVersion = 3
)

type ParsedReference added in v1.1.0

type ParsedReference struct {
	// Title is the cited title.
	Title string `json:"title"`
	// Authors are the cited authors.
	Authors []string `json:"authors"`
	// Year is the cited year.
	Year int `json:"year"`
	// Journal is the cited journal or publication. It may be empty.
	Journal string `json:"journal"`
	// URL is the cited link, for non-academic references.
	URL string `json:"url"`
}

ParsedReference are the fields that the Citation Checker read from a reference.

type ReferenceSignals added in v1.1.0

type ReferenceSignals struct {
	// Title reports whether the title matches.
	Title *bool `json:"title"`
	// Year reports whether the cited year is the published or the modified year of the source.
	Year *bool `json:"year"`
	// Authors reports whether the authors match.
	Authors *bool `json:"authors"`
}

ReferenceSignals report which reference fields a source corroborates; a nil field was not checked.

type ReferenceSuggestion added in v1.1.0

type ReferenceSuggestion struct {
	// URL is the address of the source.
	URL string `json:"url"`
	// DOI is the DOI of the source. It may be empty.
	DOI string `json:"doi"`
	// Title is the title of the source.
	Title string `json:"title"`
	// Authors are the authors of the source.
	Authors []string `json:"authors"`
	// PublishedYear is the year the source was published, or 0 when unknown.
	PublishedYear int `json:"publishedYear"`
	// ModifiedYear is the year the source was last modified, or 0 when unknown.
	ModifiedYear int `json:"modifiedYear"`
	// Journal is the journal or publication of the source. It may be empty.
	Journal string `json:"journal"`
	// Signals report which fields of the reference the source corroborates.
	Signals *ReferenceSignals `json:"signals"`
}

ReferenceSuggestion is a source found for a reference.

type ReferenceValidation added in v1.1.0

type ReferenceValidation struct {
	// Type is "academic" (checked against an academic citation index) or "nonAcademic" (against the cited page).
	Type string `json:"type"`
	// TextRanges locate the reference in the text.
	TextRanges *TextRanges `json:"textRanges"`
	// HTMLRanges locate the reference in the HTML. They are empty for plain text scans.
	HTMLRanges *HTMLRanges `json:"htmlRanges"`
	// Parsed are the fields that Copyleaks read from the reference.
	Parsed *ParsedReference `json:"parsed"`
	// Suggestions are the sources found for the reference, if any.
	Suggestions []ReferenceSuggestion `json:"suggestions"`
}

ReferenceValidation is the validation of one reference by the Citation Checker.

type References added in v1.1.0

type References struct {
	// Validate detects, parses and validates every reference in the text.
	Validate bool `json:"validate"`
}

References configures the Citation Checker. See ScanProperties.References.

type ReferencesValidation added in v1.1.0

type ReferencesValidation struct {
	// Summary counts the references that were found and validated.
	Summary *ReferencesValidationSummary `json:"summary"`
	// Results are the validated references; only the crawled version has them, not the completed webhook.
	Results []ReferenceValidation `json:"results,omitempty"`
}

ReferencesValidation is the result of the Citation Checker.

type ReferencesValidationSummary added in v1.1.0

type ReferencesValidationSummary struct {
	// Total is the number of references found.
	Total int `json:"total"`
	// Academic is the number of references found to be academic.
	Academic int `json:"academic"`
	// AcademicValidated is the number of academic references that were fully corroborated.
	AcademicValidated int `json:"academicValidated"`
	// NonAcademicValidated is the number of other references fully corroborated by their cited source.
	NonAcademicValidated int `json:"nonAcademicValidated"`
}

ReferencesValidationSummary counts the references that the Citation Checker found and validated.

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 RepositoryInfo added in v1.1.0

type RepositoryInfo struct {
	// ID is the repository ID.
	ID string `json:"id"`
	// Name is the name of the hub.
	Name string `json:"name"`
	// Description is the description of the hub.
	Description string `json:"description"`
	// Permission is the role of the caller in the hub.
	Permission RepositoryRole `json:"permission"`
	// Status is the state of the hub.
	Status RepositoryStatus `json:"status"`
	// MaxCredits is the credit limit of the hub.
	MaxCredits int `json:"maxCredits"`
	// CurrentCredits is the number of credits that the hub has.
	CurrentCredits int `json:"currentCredits"`
	// MaskingPolicy sets who sees the content of the hub's documents in their results.
	MaskingPolicy MaskingPolicy `json:"maskingPolicy"`
	// CreationTime is when the hub was created, in ISO 8601 format.
	CreationTime string `json:"creationTime"`
}

RepositoryInfo is information about a Private Cloud Hub.

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 RepositoryRole added in v1.1.0

type RepositoryRole int

RepositoryRole is the role of a user in a Private Cloud Hub. See https://docs.copyleaks.com/reference/data-types/authenticity/private-cloud-hub/roles.

const (
	// RepositoryRoleViewer can see part of the hub metadata and scan against the hub.
	RepositoryRoleViewer RepositoryRole = 1
	// RepositoryRoleContributor can also add documents, and delete their own.
	RepositoryRoleContributor RepositoryRole = 2
	// RepositoryRoleAdmin can also invite users and delete any document.
	RepositoryRoleAdmin RepositoryRole = 3
	// RepositoryRoleSuperAdmin can also delete the hub and manage its billing.
	RepositoryRoleSuperAdmin RepositoryRole = 4
)

type RepositoryStatus added in v1.1.0

type RepositoryStatus int

RepositoryStatus is the state of a Private Cloud Hub. See https://docs.copyleaks.com/reference/data-types/authenticity/private-cloud-hub/status.

const (
	// RepositoryStatusRunning is a healthy hub.
	RepositoryStatusRunning RepositoryStatus = 0
	// RepositoryStatusPendingForDeletion is a hub about to be deleted with all its documents; it cannot be used.
	RepositoryStatusPendingForDeletion RepositoryStatus = 1
	// RepositoryStatusError is a hub that is not healthy. Contact Copyleaks support.
	RepositoryStatusError RepositoryStatus = 2
	// RepositoryStatusUpdating is a hub under maintenance. It may not be available.
	RepositoryStatusUpdating RepositoryStatus = 3
	// RepositoryStatusPaymentRequired is a hub suspended for a missing or failed payment.
	RepositoryStatusPaymentRequired RepositoryStatus = 4
)

type ResultComparison added in v1.1.0

type ResultComparison struct {
	// Identical are the identical matches.
	Identical *ComparisonMatches `json:"identical"`
	// MinorChanges are the nearly identical matches.
	MinorChanges *ComparisonMatches `json:"minorChanges"`
	// RelatedMeaning are the paraphrased matches.
	RelatedMeaning *ComparisonMatches `json:"relatedMeaning"`
}

ResultComparison locates the matches between a result source and the scanned document, by kind of match.

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; 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 ResultWebhook added in v1.1.0

type ResultWebhook struct {
	// URL is called with a POST request that carries the result (required).
	URL string `json:"url"`
	// Headers are extra headers of the webhook request, as [name, value] pairs.
	Headers [][]string `json:"headers,omitempty"`
}

ResultWebhook receives the result of an asynchronous check (SubmitAIImageAsync, SubmitAIVideo).

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"`
	// InternalAIData are the results from the Copyleaks internal AI database.
	InternalAIData []InternalAIResult `json:"internalAIData"`
}

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 (as the server sends) or a bare number as AggregatedScore (as the API reference shows for the new-result webhook).

type RetryPolicy added in v1.1.0

type RetryPolicy struct {
	// MaxAttempts counts the attempts of each call, the first included; below 2 turns retries off.
	MaxAttempts int
	// BaseDelay is the delay before the first retry, before jitter (default one second).
	BaseDelay time.Duration
	// MaxDelay caps each delay (default 30 seconds); a longer Retry-After ends the call with its error.
	MaxDelay time.Duration
}

RetryPolicy configures WithRetry. Only calls that are safe to send twice are retried: every GET, Login, the submits that carry your scan ID (SubmitFile, SubmitOCR, SubmitURL, SubmitAIImageAsync, SubmitAIVideo; the server rejects a duplicate ID) and Export, except after HTTP 503 (a failed export keeps its ID, so a retry would get 409). Calls that charge credits per request (DetectAIText, DetectAIImage, CheckGrammar, ModerateText, CheckImagePlagiarism), Start, Delete and ResendWebhook are never retried; their *APIError still has RetryAfter.

Retries follow HTTP 429, HTTP 503 and connection errors (timeout, refused, reset or dropped connection, HTTP/2 shutdown), not TLS or unknown-host errors. Each waits for Retry-After, or else for exponential backoff with jitter from BaseDelay up to MaxDelay. A 409 after an attempt the server may have processed counts as success.

type ScanEnabledFeatures added in v1.1.0

type ScanEnabledFeatures struct {
	// PlagiarismDetection reports the Plagiarism Checker.
	PlagiarismDetection bool `json:"plagiarismDetection"`
	// AIDetection reports AI Text Detection.
	AIDetection bool `json:"aiDetection"`
	// ExplainableAI reports AI Logic.
	ExplainableAI bool `json:"explainableAi"`
	// WritingFeedback reports the Grammar Checker.
	WritingFeedback bool `json:"writingFeedback"`
	// PDFReport reports the PDF report.
	PDFReport bool `json:"pdfReport"`
	// CheatDetection reports cheat detection.
	CheatDetection bool `json:"cheatDetection"`
	// Overview reports the Gen-AI Overview.
	Overview bool `json:"overview"`
	// ReferencesValidation reports the Citation Checker.
	ReferencesValidation bool `json:"referencesValidation"`
	// AISourceMatch reports AI Source Match.
	AISourceMatch bool `json:"aiSourceMatch"`
	// InternalAISourceMatch reports Internal AI Source Match.
	InternalAISourceMatch bool `json:"internalAiSourceMatch"`
}

ScanEnabledFeatures reports the features that a scan ran.

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 ScanOverview added in v1.1.0

type ScanOverview struct {
	// Enable turns the overview on.
	Enable bool `json:"enable"`
	// IgnoreAIDetection leaves the AI Text Detection results out of the overview.
	IgnoreAIDetection bool `json:"ignoreAIDetection,omitempty"`
	// IgnorePlagiarismDetection leaves the plagiarism results out of the overview.
	IgnorePlagiarismDetection bool `json:"ignorePlagiarismDetection,omitempty"`
	// IgnoreWritingFeedback leaves the Grammar Checker results out of the overview.
	IgnoreWritingFeedback bool `json:"ignoreWritingFeedback,omitempty"`
	// IgnoreAuthorData leaves the author's earlier scans out of the overview.
	IgnoreAuthorData bool `json:"ignoreAuthorData,omitempty"`
}

ScanOverview adds a Gen-AI Overview, a summary of the key insights of the scan.

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, 1 to 2880 (default 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 PDF report language: "en" (default), "es", "pt", "fr", "de" or "it", lowercase.
	// 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, 1 (fastest) to 5 (most thorough); default 3.
	SensitivityLevel int `json:"sensitivityLevel,omitempty"`
	// CheatDetection reports text manipulation 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; see CompletedWebhook.AIDetectionResult.
	AIGeneratedText *AIGeneratedText `json:"aiGeneratedText,omitempty"`
	// AISourceMatch finds online sources suspected of containing AI-generated text (English documents only).
	AISourceMatch *AISourceMatch `json:"aiSourceMatch,omitempty"`
	// CustomMetadata is attached to the document in a Private Cloud Hub and to the results that match it.
	CustomMetadata []CustomMetadata `json:"customMetadata,omitempty"`
	// ScanTimeZone is the IANA time zone of the PDF report's scan time, such as "America/New_York".
	// It is case-sensitive; the default is the time zone of the account's country, or UTC.
	ScanTimeZone string `json:"scanTimeZone,omitempty"`
	// Course identifies the course of the content, for analytics.
	Course *Course `json:"course,omitempty"`
	// Assignment identifies the assignment of the content, for analytics.
	Assignment *Assignment `json:"assignment,omitempty"`
	// Institution identifies the institution of the content, for analytics.
	Institution *Institution `json:"institution,omitempty"`
	// SensitiveDataProtection masks sensitive data with # characters (plans of 2,500 pages or more).
	SensitiveDataProtection *SensitiveDataProtection `json:"sensitiveDataProtection,omitempty"`
	// WritingFeedback adds the Grammar Checker to the scan.
	WritingFeedback *ScanWritingFeedback `json:"writingFeedback,omitempty"`
	// Overview adds a Gen-AI Overview of the scan results; export it with ExportRequest.Overview.
	Overview *ScanOverview `json:"overview,omitempty"`
	// InternalAISourceMatch finds sources in the Copyleaks internal AI database; see Results.InternalAIData.
	InternalAISourceMatch *InternalAISourceMatch `json:"internalAiSourceMatch,omitempty"`
	// References turns on the Citation Checker; see CompletedWebhook.ReferencesValidation.
	References *References `json:"references,omitempty"`
}

ScanProperties configures a Plagiarism Checker scan. Only Webhooks.Status is required; zero values are left out, so server defaults apply. Pointer fields have non-zero server defaults; set them with Ptr. See https://docs.copyleaks.com/reference/actions/authenticity/submit-file.

type ScanWritingFeedback added in v1.1.0

type ScanWritingFeedback struct {
	// Enable turns the Grammar Checker on.
	Enable bool `json:"enable"`
	// Score sets the weight of each correction category in the overall writing score.
	Score *GrammarScoreWeights `json:"score,omitempty"`
}

ScanWritingFeedback adds the Grammar Checker to a Plagiarism Checker scan.

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, AI Image, Grammar Checker or Text Moderation check.

type ScannedImage added in v1.1.0

type ScannedImage struct {
	// ScanID is the scan ID given by you.
	ScanID string `json:"scanId"`
	// ExpectedCredits is the number of credits that the check was expected to use.
	ExpectedCredits int `json:"expectedCredits"`
	// ActualCredits is the number of credits that the check used.
	ActualCredits int `json:"actualCredits"`
	// CreationTime is when the check was created, in ISO 8601 format (UTC).
	CreationTime string `json:"creationTime"`
	// Width is the width of the image, in pixels.
	Width int `json:"width"`
	// Height is the height of the image, in pixels.
	Height int `json:"height"`
	// Filename is the Filename of the request.
	Filename string `json:"filename"`
}

ScannedImage is information about the image of an Image Plagiarism Detector check.

type ScannedVideo added in v1.1.0

type ScannedVideo struct {
	// ScanID is the scan ID given by you.
	ScanID string `json:"scanId"`
	// 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"`
}

ScannedVideo is general information about an AI Video Detection 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"`
	// Include keeps only matching submissions in the results.
	Include *ScanningInclude `json:"include,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 submissions whose scan ID matches it, 1 to 36 characters; * matches any number of
	// characters and . exactly one non-whitespace character. ScanningInclude.IDPattern uses the same syntax.
	IDPattern string `json:"idPattern,omitempty"`
	// BacklinksDomains excludes results that link back to up to 10 domains, 1 to 256 characters each.
	BacklinksDomains *[]string `json:"backlinksDomains,omitempty"`
	// Text excludes results that contain up to 5 phrases, 1 to 30 characters each.
	Text *[]string `json:"text,omitempty"`
}

ScanningExclude leaves submissions out of the results. Its lists are pointers, so that it stays comparable.

type ScanningInclude added in v1.1.0

type ScanningInclude struct {
	// IDPattern keeps only Shared Data Hub and Private Cloud Hub results whose scan ID matches it; same syntax
	// as ScanningExclude.IDPattern.
	IDPattern string `json:"idPattern,omitempty"`
}

ScanningInclude keeps only some submissions in 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 SensitiveDataProtection added in v1.1.0

type SensitiveDataProtection struct {
	// DriversLicense masks driver's license numbers.
	DriversLicense bool `json:"driversLicense,omitempty"`
	// Credentials masks credentials, such as passwords, authentication tokens and cloud keys.
	Credentials bool `json:"credentials,omitempty"`
	// Passport masks passport numbers.
	Passport bool `json:"passport,omitempty"`
	// Network masks network identifiers, such as IP and MAC addresses.
	Network bool `json:"network,omitempty"`
	// URL masks URLs.
	URL bool `json:"url,omitempty"`
	// EmailAddress masks email addresses.
	EmailAddress bool `json:"emailAddress,omitempty"`
	// CreditCard masks credit card numbers.
	CreditCard bool `json:"creditCard,omitempty"`
	// PhoneNumber masks phone numbers.
	PhoneNumber bool `json:"phoneNumber,omitempty"`
}

SensitiveDataProtection masks kinds of sensitive data in the scanned document, one per field.

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 up to 100 scan IDs to start (required).
	Trigger []string `json:"trigger"`
	// ErrorHandling is what happens when some of the scans are in error.
	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 an object with an id (as the server sends) or a bare scan ID (as the API reference shows).

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 in a credits-checked webhook; start it 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); {STATUS} becomes 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 SupportedAITextFileTypes added in v1.1.0

type SupportedAITextFileTypes struct {
	// FileTypes are the file extensions, such as "pdf" and "docx".
	FileTypes []string `json:"supportedAiFileTypes"`
}

SupportedAITextFileTypes lists the file types that AI Text Detection can 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: TextModerationLanguageEnglish, or empty to let the server detect it.
	Language string `json:"language,omitempty"`
	// Labels are 1 to 16 categories to check for (required); a flagged segment's label value indexes 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 TextPages added in v1.1.0

type TextPages struct {
	// StartPosition are the character positions where the pages start.
	StartPosition []int `json:"startPosition"`
}

TextPages are the pages of a text.

type TextRanges added in v1.1.0

type TextRanges struct {
	// Starts are the start positions of the ranges.
	Starts []int `json:"starts"`
	// Lengths are the lengths of the ranges, one per start position.
	Lengths []int `json:"lengths"`
}

TextRanges are ranges of a text, as parallel start and length lists.

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"`
	// Verb is the HTTP method used to fetch URL: "GET" (default), "POST" or "PUT".
	Verb string `json:"verb,omitempty"`
	// Headers are the headers sent to fetch URL, as [name, value] pairs, replacing Copyleaks' own.
	// Use Set-Cookie for cookies.
	Headers [][]string `json:"headers,omitempty"`
}

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"`
	// ExpectedCredits is the number of credits that the scan was expected to use.
	ExpectedCredits int `json:"expectedCredits"`
	// DetectedLanguage is the language code of the document, such as "en", when the server reports it.
	DetectedLanguage string `json:"detectedLanguage"`
	// Enabled reports the features that the scan ran, when the server reports them.
	Enabled *ScanEnabledFeatures `json:"enabled"`
}

WebhookScannedDocument is general information about a scanned document.

type WebhookWritingFeedback added in v1.1.0

type WebhookWritingFeedback struct {
	// TextStatistics are statistics of the text.
	TextStatistics *GrammarStatistics `json:"textStatistics"`
	// Score holds the correction counts and scores of each category, and the overall score.
	Score *GrammarScoreCorrections `json:"score"`
	// Readability is the readability of the text.
	Readability *GrammarReadability `json:"readability"`
}

WebhookWritingFeedback is the Grammar Checker summary of a completed scan.

Directories

Path Synopsis
examples
ai-image-detection command
Command ai-image-detection checks whether an image (at least 512x512 pixels) is AI-generated, in sandbox mode.
Command ai-image-detection checks whether an image (at least 512x512 pixels) is AI-generated, in sandbox mode.
ai-text-detection command
Command ai-text-detection checks a text with AI Text Detection in sandbox mode, which is free (mock results).
Command ai-text-detection checks a text with AI Text Detection in sandbox mode, which is free (mock results).
grammar-checker command
Command grammar-checker checks a text with the Grammar Checker, in sandbox mode, and prints the corrections.
Command grammar-checker checks a text with the Grammar Checker, in sandbox mode, and prints the corrections.
image-plagiarism command
Command image-plagiarism searches the web for copies of an image, in sandbox mode.
Command image-plagiarism searches the web for copies of an image, in sandbox mode.
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 for every Text Moderation label, in sandbox mode.
Command text-moderation checks a text for every Text Moderation label, in sandbox mode.
webhooks command
Command webhooks receives the Copyleaks webhooks of Plagiarism Checker scans (with their AI Text Detection result) and exports, and the results of asynchronous AI Image and AI Video Detection.
Command webhooks receives the Copyleaks webhooks of Plagiarism Checker scans (with their AI Text Detection result) and exports, and the results of asynchronous AI Image and AI Video Detection.
internal
netretry
Package netretry tells the connection errors that a retry may fix, such as a reset connection, from the ones that it cannot, such as an invalid TLS certificate.
Package netretry tells the connection errors that a retry may fix, such as a reset connection, from the ones that it cannot, such as an invalid TLS certificate.
upload
Package upload builds upload request bodies (JSON with base64, or multipart/form-data), each in one buffer, so that a large upload costs about one copy of the file.
Package upload builds upload request bodies (JSON with base64, or multipart/form-data), each in one buffer, so that a large upload costs about one copy of the file.
validate
Package validate holds the client-side checks of IDs, file names and uploads.
Package validate holds the client-side checks of IDs, file names and uploads.

Jump to

Keyboard shortcuts

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