google_language1/
api.rs

1#![allow(clippy::ptr_arg)]
2
3use std::collections::{BTreeSet, HashMap};
4
5use tokio::time::sleep;
6
7// ##############
8// UTILITIES ###
9// ############
10
11/// Identifies the an OAuth2 authorization scope.
12/// A scope is needed when requesting an
13/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
14#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
15pub enum Scope {
16    /// Apply machine learning models to reveal the structure and meaning of text
17    CloudLanguage,
18
19    /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.
20    CloudPlatform,
21}
22
23impl AsRef<str> for Scope {
24    fn as_ref(&self) -> &str {
25        match *self {
26            Scope::CloudLanguage => "https://www.googleapis.com/auth/cloud-language",
27            Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
28        }
29    }
30}
31
32#[allow(clippy::derivable_impls)]
33impl Default for Scope {
34    fn default() -> Scope {
35        Scope::CloudLanguage
36    }
37}
38
39// ########
40// HUB ###
41// ######
42
43/// Central instance to access all CloudNaturalLanguage related resource activities
44///
45/// # Examples
46///
47/// Instantiate a new hub
48///
49/// ```test_harness,no_run
50/// extern crate hyper;
51/// extern crate hyper_rustls;
52/// extern crate google_language1 as language1;
53/// use language1::api::AnalyzeEntitiesRequest;
54/// use language1::{Result, Error};
55/// # async fn dox() {
56/// use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
57///
58/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
59/// // `client_secret`, among other things.
60/// let secret: yup_oauth2::ApplicationSecret = Default::default();
61/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
62/// // unless you replace  `None` with the desired Flow.
63/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
64/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
65/// // retrieve them from storage.
66/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
67///     secret,
68///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
69/// ).build().await.unwrap();
70///
71/// let client = hyper_util::client::legacy::Client::builder(
72///     hyper_util::rt::TokioExecutor::new()
73/// )
74/// .build(
75///     hyper_rustls::HttpsConnectorBuilder::new()
76///         .with_native_roots()
77///         .unwrap()
78///         .https_or_http()
79///         .enable_http1()
80///         .build()
81/// );
82/// let mut hub = CloudNaturalLanguage::new(client, auth);
83/// // As the method needs a request, you would usually fill it with the desired information
84/// // into the respective structure. Some of the parts shown here might not be applicable !
85/// // Values shown here are possibly random and not representative !
86/// let mut req = AnalyzeEntitiesRequest::default();
87///
88/// // You can configure optional parameters by calling the respective setters at will, and
89/// // execute the final call using `doit()`.
90/// // Values shown here are possibly random and not representative !
91/// let result = hub.documents().analyze_entities(req)
92///              .doit().await;
93///
94/// match result {
95///     Err(e) => match e {
96///         // The Error enum provides details about what exactly happened.
97///         // You can also just use its `Debug`, `Display` or `Error` traits
98///          Error::HttpError(_)
99///         |Error::Io(_)
100///         |Error::MissingAPIKey
101///         |Error::MissingToken(_)
102///         |Error::Cancelled
103///         |Error::UploadSizeLimitExceeded(_, _)
104///         |Error::Failure(_)
105///         |Error::BadRequest(_)
106///         |Error::FieldClash(_)
107///         |Error::JsonDecodeError(_, _) => println!("{}", e),
108///     },
109///     Ok(res) => println!("Success: {:?}", res),
110/// }
111/// # }
112/// ```
113#[derive(Clone)]
114pub struct CloudNaturalLanguage<C> {
115    pub client: common::Client<C>,
116    pub auth: Box<dyn common::GetToken>,
117    _user_agent: String,
118    _base_url: String,
119    _root_url: String,
120}
121
122impl<C> common::Hub for CloudNaturalLanguage<C> {}
123
124impl<'a, C> CloudNaturalLanguage<C> {
125    pub fn new<A: 'static + common::GetToken>(
126        client: common::Client<C>,
127        auth: A,
128    ) -> CloudNaturalLanguage<C> {
129        CloudNaturalLanguage {
130            client,
131            auth: Box::new(auth),
132            _user_agent: "google-api-rust-client/6.0.0".to_string(),
133            _base_url: "https://language.googleapis.com/".to_string(),
134            _root_url: "https://language.googleapis.com/".to_string(),
135        }
136    }
137
138    pub fn documents(&'a self) -> DocumentMethods<'a, C> {
139        DocumentMethods { hub: self }
140    }
141
142    /// Set the user-agent header field to use in all requests to the server.
143    /// It defaults to `google-api-rust-client/6.0.0`.
144    ///
145    /// Returns the previously set user-agent.
146    pub fn user_agent(&mut self, agent_name: String) -> String {
147        std::mem::replace(&mut self._user_agent, agent_name)
148    }
149
150    /// Set the base url to use in all requests to the server.
151    /// It defaults to `https://language.googleapis.com/`.
152    ///
153    /// Returns the previously set base url.
154    pub fn base_url(&mut self, new_base_url: String) -> String {
155        std::mem::replace(&mut self._base_url, new_base_url)
156    }
157
158    /// Set the root url to use in all requests to the server.
159    /// It defaults to `https://language.googleapis.com/`.
160    ///
161    /// Returns the previously set root url.
162    pub fn root_url(&mut self, new_root_url: String) -> String {
163        std::mem::replace(&mut self._root_url, new_root_url)
164    }
165}
166
167// ############
168// SCHEMAS ###
169// ##########
170/// The entity analysis request message.
171///
172/// # Activities
173///
174/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
175/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
176///
177/// * [analyze entities documents](DocumentAnalyzeEntityCall) (request)
178#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
179#[serde_with::serde_as]
180#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
181pub struct AnalyzeEntitiesRequest {
182    /// Required. Input document.
183    pub document: Option<Document>,
184    /// The encoding type used by the API to calculate offsets.
185    #[serde(rename = "encodingType")]
186    pub encoding_type: Option<String>,
187}
188
189impl common::RequestValue for AnalyzeEntitiesRequest {}
190
191/// The entity analysis response message.
192///
193/// # Activities
194///
195/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
196/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
197///
198/// * [analyze entities documents](DocumentAnalyzeEntityCall) (response)
199#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
200#[serde_with::serde_as]
201#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
202pub struct AnalyzeEntitiesResponse {
203    /// The recognized entities in the input document.
204    pub entities: Option<Vec<Entity>>,
205    /// The language of the text, which will be the same as the language specified in the request or, if not specified, the automatically-detected language. See Document.language field for more details.
206    pub language: Option<String>,
207}
208
209impl common::ResponseResult for AnalyzeEntitiesResponse {}
210
211/// The entity-level sentiment analysis request message.
212///
213/// # Activities
214///
215/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
216/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
217///
218/// * [analyze entity sentiment documents](DocumentAnalyzeEntitySentimentCall) (request)
219#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
220#[serde_with::serde_as]
221#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
222pub struct AnalyzeEntitySentimentRequest {
223    /// Required. Input document.
224    pub document: Option<Document>,
225    /// The encoding type used by the API to calculate offsets.
226    #[serde(rename = "encodingType")]
227    pub encoding_type: Option<String>,
228}
229
230impl common::RequestValue for AnalyzeEntitySentimentRequest {}
231
232/// The entity-level sentiment analysis response message.
233///
234/// # Activities
235///
236/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
237/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
238///
239/// * [analyze entity sentiment documents](DocumentAnalyzeEntitySentimentCall) (response)
240#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
241#[serde_with::serde_as]
242#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
243pub struct AnalyzeEntitySentimentResponse {
244    /// The recognized entities in the input document with associated sentiments.
245    pub entities: Option<Vec<Entity>>,
246    /// The language of the text, which will be the same as the language specified in the request or, if not specified, the automatically-detected language. See Document.language field for more details.
247    pub language: Option<String>,
248}
249
250impl common::ResponseResult for AnalyzeEntitySentimentResponse {}
251
252/// The sentiment analysis request message.
253///
254/// # Activities
255///
256/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
257/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
258///
259/// * [analyze sentiment documents](DocumentAnalyzeSentimentCall) (request)
260#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
261#[serde_with::serde_as]
262#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
263pub struct AnalyzeSentimentRequest {
264    /// Required. Input document.
265    pub document: Option<Document>,
266    /// The encoding type used by the API to calculate sentence offsets.
267    #[serde(rename = "encodingType")]
268    pub encoding_type: Option<String>,
269}
270
271impl common::RequestValue for AnalyzeSentimentRequest {}
272
273/// The sentiment analysis response message.
274///
275/// # Activities
276///
277/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
278/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
279///
280/// * [analyze sentiment documents](DocumentAnalyzeSentimentCall) (response)
281#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
282#[serde_with::serde_as]
283#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
284pub struct AnalyzeSentimentResponse {
285    /// The overall sentiment of the input document.
286    #[serde(rename = "documentSentiment")]
287    pub document_sentiment: Option<Sentiment>,
288    /// The language of the text, which will be the same as the language specified in the request or, if not specified, the automatically-detected language. See Document.language field for more details.
289    pub language: Option<String>,
290    /// The sentiment for all the sentences in the document.
291    pub sentences: Option<Vec<Sentence>>,
292}
293
294impl common::ResponseResult for AnalyzeSentimentResponse {}
295
296/// The syntax analysis request message.
297///
298/// # Activities
299///
300/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
301/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
302///
303/// * [analyze syntax documents](DocumentAnalyzeSyntaxCall) (request)
304#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
305#[serde_with::serde_as]
306#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
307pub struct AnalyzeSyntaxRequest {
308    /// Required. Input document.
309    pub document: Option<Document>,
310    /// The encoding type used by the API to calculate offsets.
311    #[serde(rename = "encodingType")]
312    pub encoding_type: Option<String>,
313}
314
315impl common::RequestValue for AnalyzeSyntaxRequest {}
316
317/// The syntax analysis response message.
318///
319/// # Activities
320///
321/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
322/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
323///
324/// * [analyze syntax documents](DocumentAnalyzeSyntaxCall) (response)
325#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
326#[serde_with::serde_as]
327#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
328pub struct AnalyzeSyntaxResponse {
329    /// The language of the text, which will be the same as the language specified in the request or, if not specified, the automatically-detected language. See Document.language field for more details.
330    pub language: Option<String>,
331    /// Sentences in the input document.
332    pub sentences: Option<Vec<Sentence>>,
333    /// Tokens, along with their syntactic information, in the input document.
334    pub tokens: Option<Vec<Token>>,
335}
336
337impl common::ResponseResult for AnalyzeSyntaxResponse {}
338
339/// The request message for the text annotation API, which can perform multiple analysis types (sentiment, entities, and syntax) in one call.
340///
341/// # Activities
342///
343/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
344/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
345///
346/// * [annotate text documents](DocumentAnnotateTextCall) (request)
347#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
348#[serde_with::serde_as]
349#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
350pub struct AnnotateTextRequest {
351    /// Required. Input document.
352    pub document: Option<Document>,
353    /// The encoding type used by the API to calculate offsets.
354    #[serde(rename = "encodingType")]
355    pub encoding_type: Option<String>,
356    /// Required. The enabled features.
357    pub features: Option<AnnotateTextRequestFeatures>,
358}
359
360impl common::RequestValue for AnnotateTextRequest {}
361
362/// All available features for sentiment, syntax, and semantic analysis. Setting each one to true will enable that specific analysis for the input.
363///
364/// This type is not used in any activity, and only used as *part* of another schema.
365///
366#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
367#[serde_with::serde_as]
368#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
369pub struct AnnotateTextRequestFeatures {
370    /// Optional. The model options to use for classification. Defaults to v1 options if not specified. Only used if `classify_text` is set to true.
371    #[serde(rename = "classificationModelOptions")]
372    pub classification_model_options: Option<ClassificationModelOptions>,
373    /// Classify the full document into categories.
374    #[serde(rename = "classifyText")]
375    pub classify_text: Option<bool>,
376    /// Extract document-level sentiment.
377    #[serde(rename = "extractDocumentSentiment")]
378    pub extract_document_sentiment: Option<bool>,
379    /// Extract entities.
380    #[serde(rename = "extractEntities")]
381    pub extract_entities: Option<bool>,
382    /// Extract entities and their associated sentiment.
383    #[serde(rename = "extractEntitySentiment")]
384    pub extract_entity_sentiment: Option<bool>,
385    /// Extract syntax information.
386    #[serde(rename = "extractSyntax")]
387    pub extract_syntax: Option<bool>,
388    /// Moderate the document for harmful and sensitive categories.
389    #[serde(rename = "moderateText")]
390    pub moderate_text: Option<bool>,
391}
392
393impl common::Part for AnnotateTextRequestFeatures {}
394
395/// The text annotations response message.
396///
397/// # Activities
398///
399/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
400/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
401///
402/// * [annotate text documents](DocumentAnnotateTextCall) (response)
403#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
404#[serde_with::serde_as]
405#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
406pub struct AnnotateTextResponse {
407    /// Categories identified in the input document.
408    pub categories: Option<Vec<ClassificationCategory>>,
409    /// The overall sentiment for the document. Populated if the user enables AnnotateTextRequest.Features.extract_document_sentiment.
410    #[serde(rename = "documentSentiment")]
411    pub document_sentiment: Option<Sentiment>,
412    /// Entities, along with their semantic information, in the input document. Populated if the user enables AnnotateTextRequest.Features.extract_entities.
413    pub entities: Option<Vec<Entity>>,
414    /// The language of the text, which will be the same as the language specified in the request or, if not specified, the automatically-detected language. See Document.language field for more details.
415    pub language: Option<String>,
416    /// Harmful and sensitive categories identified in the input document.
417    #[serde(rename = "moderationCategories")]
418    pub moderation_categories: Option<Vec<ClassificationCategory>>,
419    /// Sentences in the input document. Populated if the user enables AnnotateTextRequest.Features.extract_syntax.
420    pub sentences: Option<Vec<Sentence>>,
421    /// Tokens, along with their syntactic information, in the input document. Populated if the user enables AnnotateTextRequest.Features.extract_syntax.
422    pub tokens: Option<Vec<Token>>,
423}
424
425impl common::ResponseResult for AnnotateTextResponse {}
426
427/// Represents a category returned from the text classifier.
428///
429/// This type is not used in any activity, and only used as *part* of another schema.
430///
431#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
432#[serde_with::serde_as]
433#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
434pub struct ClassificationCategory {
435    /// The classifier's confidence of the category. Number represents how certain the classifier is that this category represents the given text.
436    pub confidence: Option<f32>,
437    /// The name of the category representing the document.
438    pub name: Option<String>,
439}
440
441impl common::Part for ClassificationCategory {}
442
443/// Model options available for classification requests.
444///
445/// This type is not used in any activity, and only used as *part* of another schema.
446///
447#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
448#[serde_with::serde_as]
449#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
450pub struct ClassificationModelOptions {
451    /// Setting this field will use the V1 model and V1 content categories version. The V1 model is a legacy model; support for this will be discontinued in the future.
452    #[serde(rename = "v1Model")]
453    pub v1_model: Option<ClassificationModelOptionsV1Model>,
454    /// Setting this field will use the V2 model with the appropriate content categories version. The V2 model is a better performing model.
455    #[serde(rename = "v2Model")]
456    pub v2_model: Option<ClassificationModelOptionsV2Model>,
457}
458
459impl common::Part for ClassificationModelOptions {}
460
461/// Options for the V1 model.
462///
463/// This type is not used in any activity, and only used as *part* of another schema.
464///
465#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
466#[serde_with::serde_as]
467#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
468pub struct ClassificationModelOptionsV1Model {
469    _never_set: Option<bool>,
470}
471
472impl common::Part for ClassificationModelOptionsV1Model {}
473
474/// Options for the V2 model.
475///
476/// This type is not used in any activity, and only used as *part* of another schema.
477///
478#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
479#[serde_with::serde_as]
480#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
481pub struct ClassificationModelOptionsV2Model {
482    /// The content categories used for classification.
483    #[serde(rename = "contentCategoriesVersion")]
484    pub content_categories_version: Option<String>,
485}
486
487impl common::Part for ClassificationModelOptionsV2Model {}
488
489/// The document classification request message.
490///
491/// # Activities
492///
493/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
494/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
495///
496/// * [classify text documents](DocumentClassifyTextCall) (request)
497#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
498#[serde_with::serde_as]
499#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
500pub struct ClassifyTextRequest {
501    /// Optional. Model options to use for classification. Defaults to v1 options if not specified.
502    #[serde(rename = "classificationModelOptions")]
503    pub classification_model_options: Option<ClassificationModelOptions>,
504    /// Required. Input document.
505    pub document: Option<Document>,
506}
507
508impl common::RequestValue for ClassifyTextRequest {}
509
510/// The document classification response message.
511///
512/// # Activities
513///
514/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
515/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
516///
517/// * [classify text documents](DocumentClassifyTextCall) (response)
518#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
519#[serde_with::serde_as]
520#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
521pub struct ClassifyTextResponse {
522    /// Categories representing the input document.
523    pub categories: Option<Vec<ClassificationCategory>>,
524}
525
526impl common::ResponseResult for ClassifyTextResponse {}
527
528/// Represents dependency parse tree information for a token. (For more information on dependency labels, see http://www.aclweb.org/anthology/P13-2017
529///
530/// This type is not used in any activity, and only used as *part* of another schema.
531///
532#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
533#[serde_with::serde_as]
534#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
535pub struct DependencyEdge {
536    /// Represents the head of this token in the dependency tree. This is the index of the token which has an arc going to this token. The index is the position of the token in the array of tokens returned by the API method. If this token is a root token, then the `head_token_index` is its own index.
537    #[serde(rename = "headTokenIndex")]
538    pub head_token_index: Option<i32>,
539    /// The parse label for the token.
540    pub label: Option<String>,
541}
542
543impl common::Part for DependencyEdge {}
544
545/// Represents the input to API methods.
546///
547/// # Activities
548///
549/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
550/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
551///
552/// * [analyze entities documents](DocumentAnalyzeEntityCall) (none)
553/// * [analyze entity sentiment documents](DocumentAnalyzeEntitySentimentCall) (none)
554/// * [analyze sentiment documents](DocumentAnalyzeSentimentCall) (none)
555/// * [analyze syntax documents](DocumentAnalyzeSyntaxCall) (none)
556/// * [annotate text documents](DocumentAnnotateTextCall) (none)
557/// * [classify text documents](DocumentClassifyTextCall) (none)
558/// * [moderate text documents](DocumentModerateTextCall) (none)
559#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
560#[serde_with::serde_as]
561#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
562pub struct Document {
563    /// The content of the input in string format. Cloud audit logging exempt since it is based on user data.
564    pub content: Option<String>,
565    /// The Google Cloud Storage URI where the file content is located. This URI must be of the form: gs://bucket_name/object_name. For more details, see https://cloud.google.com/storage/docs/reference-uris. NOTE: Cloud Storage object versioning is not supported.
566    #[serde(rename = "gcsContentUri")]
567    pub gcs_content_uri: Option<String>,
568    /// The language of the document (if not specified, the language is automatically detected). Both ISO and BCP-47 language codes are accepted. [Language Support](https://cloud.google.com/natural-language/docs/languages) lists currently supported languages for each API method. If the language (either specified by the caller or automatically detected) is not supported by the called API method, an `INVALID_ARGUMENT` error is returned.
569    pub language: Option<String>,
570    /// Required. If the type is not set or is `TYPE_UNSPECIFIED`, returns an `INVALID_ARGUMENT` error.
571    #[serde(rename = "type")]
572    pub type_: Option<String>,
573}
574
575impl common::Resource for Document {}
576
577/// Represents a phrase in the text that is a known entity, such as a person, an organization, or location. The API associates information, such as salience and mentions, with entities.
578///
579/// This type is not used in any activity, and only used as *part* of another schema.
580///
581#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
582#[serde_with::serde_as]
583#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
584pub struct Entity {
585    /// The mentions of this entity in the input document. The API currently supports proper noun mentions.
586    pub mentions: Option<Vec<EntityMention>>,
587    /// Metadata associated with the entity. For most entity types, the metadata is a Wikipedia URL (`wikipedia_url`) and Knowledge Graph MID (`mid`), if they are available. For the metadata associated with other entity types, see the Type table below.
588    pub metadata: Option<HashMap<String, String>>,
589    /// The representative name for the entity.
590    pub name: Option<String>,
591    /// The salience score associated with the entity in the [0, 1.0] range. The salience score for an entity provides information about the importance or centrality of that entity to the entire document text. Scores closer to 0 are less salient, while scores closer to 1.0 are highly salient.
592    pub salience: Option<f32>,
593    /// For calls to AnalyzeEntitySentiment or if AnnotateTextRequest.Features.extract_entity_sentiment is set to true, this field will contain the aggregate sentiment expressed for this entity in the provided document.
594    pub sentiment: Option<Sentiment>,
595    /// The entity type.
596    #[serde(rename = "type")]
597    pub type_: Option<String>,
598}
599
600impl common::Part for Entity {}
601
602/// Represents a mention for an entity in the text. Currently, proper noun mentions are supported.
603///
604/// This type is not used in any activity, and only used as *part* of another schema.
605///
606#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
607#[serde_with::serde_as]
608#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
609pub struct EntityMention {
610    /// For calls to AnalyzeEntitySentiment or if AnnotateTextRequest.Features.extract_entity_sentiment is set to true, this field will contain the sentiment expressed for this mention of the entity in the provided document.
611    pub sentiment: Option<Sentiment>,
612    /// The mention text.
613    pub text: Option<TextSpan>,
614    /// The type of the entity mention.
615    #[serde(rename = "type")]
616    pub type_: Option<String>,
617}
618
619impl common::Part for EntityMention {}
620
621/// The document moderation request message.
622///
623/// # Activities
624///
625/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
626/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
627///
628/// * [moderate text documents](DocumentModerateTextCall) (request)
629#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
630#[serde_with::serde_as]
631#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
632pub struct ModerateTextRequest {
633    /// Required. Input document.
634    pub document: Option<Document>,
635}
636
637impl common::RequestValue for ModerateTextRequest {}
638
639/// The document moderation response message.
640///
641/// # Activities
642///
643/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
644/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
645///
646/// * [moderate text documents](DocumentModerateTextCall) (response)
647#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
648#[serde_with::serde_as]
649#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
650pub struct ModerateTextResponse {
651    /// Harmful and sensitive categories representing the input document.
652    #[serde(rename = "moderationCategories")]
653    pub moderation_categories: Option<Vec<ClassificationCategory>>,
654}
655
656impl common::ResponseResult for ModerateTextResponse {}
657
658/// Represents part of speech information for a token. Parts of speech are as defined in http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf
659///
660/// This type is not used in any activity, and only used as *part* of another schema.
661///
662#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
663#[serde_with::serde_as]
664#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
665pub struct PartOfSpeech {
666    /// The grammatical aspect.
667    pub aspect: Option<String>,
668    /// The grammatical case.
669    pub case: Option<String>,
670    /// The grammatical form.
671    pub form: Option<String>,
672    /// The grammatical gender.
673    pub gender: Option<String>,
674    /// The grammatical mood.
675    pub mood: Option<String>,
676    /// The grammatical number.
677    pub number: Option<String>,
678    /// The grammatical person.
679    pub person: Option<String>,
680    /// The grammatical properness.
681    pub proper: Option<String>,
682    /// The grammatical reciprocity.
683    pub reciprocity: Option<String>,
684    /// The part of speech tag.
685    pub tag: Option<String>,
686    /// The grammatical tense.
687    pub tense: Option<String>,
688    /// The grammatical voice.
689    pub voice: Option<String>,
690}
691
692impl common::Part for PartOfSpeech {}
693
694/// Represents a sentence in the input document.
695///
696/// This type is not used in any activity, and only used as *part* of another schema.
697///
698#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
699#[serde_with::serde_as]
700#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
701pub struct Sentence {
702    /// For calls to AnalyzeSentiment or if AnnotateTextRequest.Features.extract_document_sentiment is set to true, this field will contain the sentiment for the sentence.
703    pub sentiment: Option<Sentiment>,
704    /// The sentence text.
705    pub text: Option<TextSpan>,
706}
707
708impl common::Part for Sentence {}
709
710/// Represents the feeling associated with the entire text or entities in the text.
711///
712/// This type is not used in any activity, and only used as *part* of another schema.
713///
714#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
715#[serde_with::serde_as]
716#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
717pub struct Sentiment {
718    /// A non-negative number in the [0, +inf) range, which represents the absolute magnitude of sentiment regardless of score (positive or negative).
719    pub magnitude: Option<f32>,
720    /// Sentiment score between -1.0 (negative sentiment) and 1.0 (positive sentiment).
721    pub score: Option<f32>,
722}
723
724impl common::Part for Sentiment {}
725
726/// Represents a text span in the input document.
727///
728/// This type is not used in any activity, and only used as *part* of another schema.
729///
730#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
731#[serde_with::serde_as]
732#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
733pub struct TextSpan {
734    /// The API calculates the beginning offset of the content in the original document according to the EncodingType specified in the API request.
735    #[serde(rename = "beginOffset")]
736    pub begin_offset: Option<i32>,
737    /// The content of the text span, which is a substring of the document.
738    pub content: Option<String>,
739}
740
741impl common::Part for TextSpan {}
742
743/// Represents the smallest syntactic building block of the text.
744///
745/// This type is not used in any activity, and only used as *part* of another schema.
746///
747#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
748#[serde_with::serde_as]
749#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
750pub struct Token {
751    /// Dependency tree parse for this token.
752    #[serde(rename = "dependencyEdge")]
753    pub dependency_edge: Option<DependencyEdge>,
754    /// [Lemma](https://en.wikipedia.org/wiki/Lemma_%28morphology%29) of the token.
755    pub lemma: Option<String>,
756    /// Parts of speech tag for this token.
757    #[serde(rename = "partOfSpeech")]
758    pub part_of_speech: Option<PartOfSpeech>,
759    /// The token text.
760    pub text: Option<TextSpan>,
761}
762
763impl common::Part for Token {}
764
765// ###################
766// MethodBuilders ###
767// #################
768
769/// A builder providing access to all methods supported on *document* resources.
770/// It is not used directly, but through the [`CloudNaturalLanguage`] hub.
771///
772/// # Example
773///
774/// Instantiate a resource builder
775///
776/// ```test_harness,no_run
777/// extern crate hyper;
778/// extern crate hyper_rustls;
779/// extern crate google_language1 as language1;
780///
781/// # async fn dox() {
782/// use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
783///
784/// let secret: yup_oauth2::ApplicationSecret = Default::default();
785/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
786///     secret,
787///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
788/// ).build().await.unwrap();
789///
790/// let client = hyper_util::client::legacy::Client::builder(
791///     hyper_util::rt::TokioExecutor::new()
792/// )
793/// .build(
794///     hyper_rustls::HttpsConnectorBuilder::new()
795///         .with_native_roots()
796///         .unwrap()
797///         .https_or_http()
798///         .enable_http1()
799///         .build()
800/// );
801/// let mut hub = CloudNaturalLanguage::new(client, auth);
802/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
803/// // like `analyze_entities(...)`, `analyze_entity_sentiment(...)`, `analyze_sentiment(...)`, `analyze_syntax(...)`, `annotate_text(...)`, `classify_text(...)` and `moderate_text(...)`
804/// // to build up your call.
805/// let rb = hub.documents();
806/// # }
807/// ```
808pub struct DocumentMethods<'a, C>
809where
810    C: 'a,
811{
812    hub: &'a CloudNaturalLanguage<C>,
813}
814
815impl<'a, C> common::MethodsBuilder for DocumentMethods<'a, C> {}
816
817impl<'a, C> DocumentMethods<'a, C> {
818    /// Create a builder to help you perform the following task:
819    ///
820    /// Finds named entities (currently proper names and common nouns) in the text along with entity types, salience, mentions for each entity, and other properties.
821    ///
822    /// # Arguments
823    ///
824    /// * `request` - No description provided.
825    pub fn analyze_entities(
826        &self,
827        request: AnalyzeEntitiesRequest,
828    ) -> DocumentAnalyzeEntityCall<'a, C> {
829        DocumentAnalyzeEntityCall {
830            hub: self.hub,
831            _request: request,
832            _delegate: Default::default(),
833            _additional_params: Default::default(),
834            _scopes: Default::default(),
835        }
836    }
837
838    /// Create a builder to help you perform the following task:
839    ///
840    /// Finds entities, similar to AnalyzeEntities in the text and analyzes sentiment associated with each entity and its mentions.
841    ///
842    /// # Arguments
843    ///
844    /// * `request` - No description provided.
845    pub fn analyze_entity_sentiment(
846        &self,
847        request: AnalyzeEntitySentimentRequest,
848    ) -> DocumentAnalyzeEntitySentimentCall<'a, C> {
849        DocumentAnalyzeEntitySentimentCall {
850            hub: self.hub,
851            _request: request,
852            _delegate: Default::default(),
853            _additional_params: Default::default(),
854            _scopes: Default::default(),
855        }
856    }
857
858    /// Create a builder to help you perform the following task:
859    ///
860    /// Analyzes the sentiment of the provided text.
861    ///
862    /// # Arguments
863    ///
864    /// * `request` - No description provided.
865    pub fn analyze_sentiment(
866        &self,
867        request: AnalyzeSentimentRequest,
868    ) -> DocumentAnalyzeSentimentCall<'a, C> {
869        DocumentAnalyzeSentimentCall {
870            hub: self.hub,
871            _request: request,
872            _delegate: Default::default(),
873            _additional_params: Default::default(),
874            _scopes: Default::default(),
875        }
876    }
877
878    /// Create a builder to help you perform the following task:
879    ///
880    /// Analyzes the syntax of the text and provides sentence boundaries and tokenization along with part of speech tags, dependency trees, and other properties.
881    ///
882    /// # Arguments
883    ///
884    /// * `request` - No description provided.
885    pub fn analyze_syntax(
886        &self,
887        request: AnalyzeSyntaxRequest,
888    ) -> DocumentAnalyzeSyntaxCall<'a, C> {
889        DocumentAnalyzeSyntaxCall {
890            hub: self.hub,
891            _request: request,
892            _delegate: Default::default(),
893            _additional_params: Default::default(),
894            _scopes: Default::default(),
895        }
896    }
897
898    /// Create a builder to help you perform the following task:
899    ///
900    /// A convenience method that provides all the features that analyzeSentiment, analyzeEntities, and analyzeSyntax provide in one call.
901    ///
902    /// # Arguments
903    ///
904    /// * `request` - No description provided.
905    pub fn annotate_text(&self, request: AnnotateTextRequest) -> DocumentAnnotateTextCall<'a, C> {
906        DocumentAnnotateTextCall {
907            hub: self.hub,
908            _request: request,
909            _delegate: Default::default(),
910            _additional_params: Default::default(),
911            _scopes: Default::default(),
912        }
913    }
914
915    /// Create a builder to help you perform the following task:
916    ///
917    /// Classifies a document into categories.
918    ///
919    /// # Arguments
920    ///
921    /// * `request` - No description provided.
922    pub fn classify_text(&self, request: ClassifyTextRequest) -> DocumentClassifyTextCall<'a, C> {
923        DocumentClassifyTextCall {
924            hub: self.hub,
925            _request: request,
926            _delegate: Default::default(),
927            _additional_params: Default::default(),
928            _scopes: Default::default(),
929        }
930    }
931
932    /// Create a builder to help you perform the following task:
933    ///
934    /// Moderates a document for harmful and sensitive categories.
935    ///
936    /// # Arguments
937    ///
938    /// * `request` - No description provided.
939    pub fn moderate_text(&self, request: ModerateTextRequest) -> DocumentModerateTextCall<'a, C> {
940        DocumentModerateTextCall {
941            hub: self.hub,
942            _request: request,
943            _delegate: Default::default(),
944            _additional_params: Default::default(),
945            _scopes: Default::default(),
946        }
947    }
948}
949
950// ###################
951// CallBuilders   ###
952// #################
953
954/// Finds named entities (currently proper names and common nouns) in the text along with entity types, salience, mentions for each entity, and other properties.
955///
956/// A builder for the *analyzeEntities* method supported by a *document* resource.
957/// It is not used directly, but through a [`DocumentMethods`] instance.
958///
959/// # Example
960///
961/// Instantiate a resource method builder
962///
963/// ```test_harness,no_run
964/// # extern crate hyper;
965/// # extern crate hyper_rustls;
966/// # extern crate google_language1 as language1;
967/// use language1::api::AnalyzeEntitiesRequest;
968/// # async fn dox() {
969/// # use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
970///
971/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
972/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
973/// #     secret,
974/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
975/// # ).build().await.unwrap();
976///
977/// # let client = hyper_util::client::legacy::Client::builder(
978/// #     hyper_util::rt::TokioExecutor::new()
979/// # )
980/// # .build(
981/// #     hyper_rustls::HttpsConnectorBuilder::new()
982/// #         .with_native_roots()
983/// #         .unwrap()
984/// #         .https_or_http()
985/// #         .enable_http1()
986/// #         .build()
987/// # );
988/// # let mut hub = CloudNaturalLanguage::new(client, auth);
989/// // As the method needs a request, you would usually fill it with the desired information
990/// // into the respective structure. Some of the parts shown here might not be applicable !
991/// // Values shown here are possibly random and not representative !
992/// let mut req = AnalyzeEntitiesRequest::default();
993///
994/// // You can configure optional parameters by calling the respective setters at will, and
995/// // execute the final call using `doit()`.
996/// // Values shown here are possibly random and not representative !
997/// let result = hub.documents().analyze_entities(req)
998///              .doit().await;
999/// # }
1000/// ```
1001pub struct DocumentAnalyzeEntityCall<'a, C>
1002where
1003    C: 'a,
1004{
1005    hub: &'a CloudNaturalLanguage<C>,
1006    _request: AnalyzeEntitiesRequest,
1007    _delegate: Option<&'a mut dyn common::Delegate>,
1008    _additional_params: HashMap<String, String>,
1009    _scopes: BTreeSet<String>,
1010}
1011
1012impl<'a, C> common::CallBuilder for DocumentAnalyzeEntityCall<'a, C> {}
1013
1014impl<'a, C> DocumentAnalyzeEntityCall<'a, C>
1015where
1016    C: common::Connector,
1017{
1018    /// Perform the operation you have build so far.
1019    pub async fn doit(mut self) -> common::Result<(common::Response, AnalyzeEntitiesResponse)> {
1020        use std::borrow::Cow;
1021        use std::io::{Read, Seek};
1022
1023        use common::{url::Params, ToParts};
1024        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1025
1026        let mut dd = common::DefaultDelegate;
1027        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1028        dlg.begin(common::MethodInfo {
1029            id: "language.documents.analyzeEntities",
1030            http_method: hyper::Method::POST,
1031        });
1032
1033        for &field in ["alt"].iter() {
1034            if self._additional_params.contains_key(field) {
1035                dlg.finished(false);
1036                return Err(common::Error::FieldClash(field));
1037            }
1038        }
1039
1040        let mut params = Params::with_capacity(3 + self._additional_params.len());
1041
1042        params.extend(self._additional_params.iter());
1043
1044        params.push("alt", "json");
1045        let mut url = self.hub._base_url.clone() + "v1/documents:analyzeEntities";
1046        if self._scopes.is_empty() {
1047            self._scopes
1048                .insert(Scope::CloudLanguage.as_ref().to_string());
1049        }
1050
1051        let url = params.parse_with_url(&url);
1052
1053        let mut json_mime_type = mime::APPLICATION_JSON;
1054        let mut request_value_reader = {
1055            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1056            common::remove_json_null_values(&mut value);
1057            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1058            serde_json::to_writer(&mut dst, &value).unwrap();
1059            dst
1060        };
1061        let request_size = request_value_reader
1062            .seek(std::io::SeekFrom::End(0))
1063            .unwrap();
1064        request_value_reader
1065            .seek(std::io::SeekFrom::Start(0))
1066            .unwrap();
1067
1068        loop {
1069            let token = match self
1070                .hub
1071                .auth
1072                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1073                .await
1074            {
1075                Ok(token) => token,
1076                Err(e) => match dlg.token(e) {
1077                    Ok(token) => token,
1078                    Err(e) => {
1079                        dlg.finished(false);
1080                        return Err(common::Error::MissingToken(e));
1081                    }
1082                },
1083            };
1084            request_value_reader
1085                .seek(std::io::SeekFrom::Start(0))
1086                .unwrap();
1087            let mut req_result = {
1088                let client = &self.hub.client;
1089                dlg.pre_request();
1090                let mut req_builder = hyper::Request::builder()
1091                    .method(hyper::Method::POST)
1092                    .uri(url.as_str())
1093                    .header(USER_AGENT, self.hub._user_agent.clone());
1094
1095                if let Some(token) = token.as_ref() {
1096                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1097                }
1098
1099                let request = req_builder
1100                    .header(CONTENT_TYPE, json_mime_type.to_string())
1101                    .header(CONTENT_LENGTH, request_size as u64)
1102                    .body(common::to_body(
1103                        request_value_reader.get_ref().clone().into(),
1104                    ));
1105
1106                client.request(request.unwrap()).await
1107            };
1108
1109            match req_result {
1110                Err(err) => {
1111                    if let common::Retry::After(d) = dlg.http_error(&err) {
1112                        sleep(d).await;
1113                        continue;
1114                    }
1115                    dlg.finished(false);
1116                    return Err(common::Error::HttpError(err));
1117                }
1118                Ok(res) => {
1119                    let (mut parts, body) = res.into_parts();
1120                    let mut body = common::Body::new(body);
1121                    if !parts.status.is_success() {
1122                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1123                        let error = serde_json::from_str(&common::to_string(&bytes));
1124                        let response = common::to_response(parts, bytes.into());
1125
1126                        if let common::Retry::After(d) =
1127                            dlg.http_failure(&response, error.as_ref().ok())
1128                        {
1129                            sleep(d).await;
1130                            continue;
1131                        }
1132
1133                        dlg.finished(false);
1134
1135                        return Err(match error {
1136                            Ok(value) => common::Error::BadRequest(value),
1137                            _ => common::Error::Failure(response),
1138                        });
1139                    }
1140                    let response = {
1141                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1142                        let encoded = common::to_string(&bytes);
1143                        match serde_json::from_str(&encoded) {
1144                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1145                            Err(error) => {
1146                                dlg.response_json_decode_error(&encoded, &error);
1147                                return Err(common::Error::JsonDecodeError(
1148                                    encoded.to_string(),
1149                                    error,
1150                                ));
1151                            }
1152                        }
1153                    };
1154
1155                    dlg.finished(true);
1156                    return Ok(response);
1157                }
1158            }
1159        }
1160    }
1161
1162    ///
1163    /// Sets the *request* property to the given value.
1164    ///
1165    /// Even though the property as already been set when instantiating this call,
1166    /// we provide this method for API completeness.
1167    pub fn request(
1168        mut self,
1169        new_value: AnalyzeEntitiesRequest,
1170    ) -> DocumentAnalyzeEntityCall<'a, C> {
1171        self._request = new_value;
1172        self
1173    }
1174    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1175    /// while executing the actual API request.
1176    ///
1177    /// ````text
1178    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1179    /// ````
1180    ///
1181    /// Sets the *delegate* property to the given value.
1182    pub fn delegate(
1183        mut self,
1184        new_value: &'a mut dyn common::Delegate,
1185    ) -> DocumentAnalyzeEntityCall<'a, C> {
1186        self._delegate = Some(new_value);
1187        self
1188    }
1189
1190    /// Set any additional parameter of the query string used in the request.
1191    /// It should be used to set parameters which are not yet available through their own
1192    /// setters.
1193    ///
1194    /// Please note that this method must not be used to set any of the known parameters
1195    /// which have their own setter method. If done anyway, the request will fail.
1196    ///
1197    /// # Additional Parameters
1198    ///
1199    /// * *$.xgafv* (query-string) - V1 error format.
1200    /// * *access_token* (query-string) - OAuth access token.
1201    /// * *alt* (query-string) - Data format for response.
1202    /// * *callback* (query-string) - JSONP
1203    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1204    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
1205    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1206    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1207    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
1208    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1209    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1210    pub fn param<T>(mut self, name: T, value: T) -> DocumentAnalyzeEntityCall<'a, C>
1211    where
1212        T: AsRef<str>,
1213    {
1214        self._additional_params
1215            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1216        self
1217    }
1218
1219    /// Identifies the authorization scope for the method you are building.
1220    ///
1221    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1222    /// [`Scope::CloudLanguage`].
1223    ///
1224    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1225    /// tokens for more than one scope.
1226    ///
1227    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1228    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1229    /// sufficient, a read-write scope will do as well.
1230    pub fn add_scope<St>(mut self, scope: St) -> DocumentAnalyzeEntityCall<'a, C>
1231    where
1232        St: AsRef<str>,
1233    {
1234        self._scopes.insert(String::from(scope.as_ref()));
1235        self
1236    }
1237    /// Identifies the authorization scope(s) for the method you are building.
1238    ///
1239    /// See [`Self::add_scope()`] for details.
1240    pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentAnalyzeEntityCall<'a, C>
1241    where
1242        I: IntoIterator<Item = St>,
1243        St: AsRef<str>,
1244    {
1245        self._scopes
1246            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1247        self
1248    }
1249
1250    /// Removes all scopes, and no default scope will be used either.
1251    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1252    /// for details).
1253    pub fn clear_scopes(mut self) -> DocumentAnalyzeEntityCall<'a, C> {
1254        self._scopes.clear();
1255        self
1256    }
1257}
1258
1259/// Finds entities, similar to AnalyzeEntities in the text and analyzes sentiment associated with each entity and its mentions.
1260///
1261/// A builder for the *analyzeEntitySentiment* method supported by a *document* resource.
1262/// It is not used directly, but through a [`DocumentMethods`] instance.
1263///
1264/// # Example
1265///
1266/// Instantiate a resource method builder
1267///
1268/// ```test_harness,no_run
1269/// # extern crate hyper;
1270/// # extern crate hyper_rustls;
1271/// # extern crate google_language1 as language1;
1272/// use language1::api::AnalyzeEntitySentimentRequest;
1273/// # async fn dox() {
1274/// # use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1275///
1276/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1277/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1278/// #     secret,
1279/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1280/// # ).build().await.unwrap();
1281///
1282/// # let client = hyper_util::client::legacy::Client::builder(
1283/// #     hyper_util::rt::TokioExecutor::new()
1284/// # )
1285/// # .build(
1286/// #     hyper_rustls::HttpsConnectorBuilder::new()
1287/// #         .with_native_roots()
1288/// #         .unwrap()
1289/// #         .https_or_http()
1290/// #         .enable_http1()
1291/// #         .build()
1292/// # );
1293/// # let mut hub = CloudNaturalLanguage::new(client, auth);
1294/// // As the method needs a request, you would usually fill it with the desired information
1295/// // into the respective structure. Some of the parts shown here might not be applicable !
1296/// // Values shown here are possibly random and not representative !
1297/// let mut req = AnalyzeEntitySentimentRequest::default();
1298///
1299/// // You can configure optional parameters by calling the respective setters at will, and
1300/// // execute the final call using `doit()`.
1301/// // Values shown here are possibly random and not representative !
1302/// let result = hub.documents().analyze_entity_sentiment(req)
1303///              .doit().await;
1304/// # }
1305/// ```
1306pub struct DocumentAnalyzeEntitySentimentCall<'a, C>
1307where
1308    C: 'a,
1309{
1310    hub: &'a CloudNaturalLanguage<C>,
1311    _request: AnalyzeEntitySentimentRequest,
1312    _delegate: Option<&'a mut dyn common::Delegate>,
1313    _additional_params: HashMap<String, String>,
1314    _scopes: BTreeSet<String>,
1315}
1316
1317impl<'a, C> common::CallBuilder for DocumentAnalyzeEntitySentimentCall<'a, C> {}
1318
1319impl<'a, C> DocumentAnalyzeEntitySentimentCall<'a, C>
1320where
1321    C: common::Connector,
1322{
1323    /// Perform the operation you have build so far.
1324    pub async fn doit(
1325        mut self,
1326    ) -> common::Result<(common::Response, AnalyzeEntitySentimentResponse)> {
1327        use std::borrow::Cow;
1328        use std::io::{Read, Seek};
1329
1330        use common::{url::Params, ToParts};
1331        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1332
1333        let mut dd = common::DefaultDelegate;
1334        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1335        dlg.begin(common::MethodInfo {
1336            id: "language.documents.analyzeEntitySentiment",
1337            http_method: hyper::Method::POST,
1338        });
1339
1340        for &field in ["alt"].iter() {
1341            if self._additional_params.contains_key(field) {
1342                dlg.finished(false);
1343                return Err(common::Error::FieldClash(field));
1344            }
1345        }
1346
1347        let mut params = Params::with_capacity(3 + self._additional_params.len());
1348
1349        params.extend(self._additional_params.iter());
1350
1351        params.push("alt", "json");
1352        let mut url = self.hub._base_url.clone() + "v1/documents:analyzeEntitySentiment";
1353        if self._scopes.is_empty() {
1354            self._scopes
1355                .insert(Scope::CloudLanguage.as_ref().to_string());
1356        }
1357
1358        let url = params.parse_with_url(&url);
1359
1360        let mut json_mime_type = mime::APPLICATION_JSON;
1361        let mut request_value_reader = {
1362            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1363            common::remove_json_null_values(&mut value);
1364            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1365            serde_json::to_writer(&mut dst, &value).unwrap();
1366            dst
1367        };
1368        let request_size = request_value_reader
1369            .seek(std::io::SeekFrom::End(0))
1370            .unwrap();
1371        request_value_reader
1372            .seek(std::io::SeekFrom::Start(0))
1373            .unwrap();
1374
1375        loop {
1376            let token = match self
1377                .hub
1378                .auth
1379                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1380                .await
1381            {
1382                Ok(token) => token,
1383                Err(e) => match dlg.token(e) {
1384                    Ok(token) => token,
1385                    Err(e) => {
1386                        dlg.finished(false);
1387                        return Err(common::Error::MissingToken(e));
1388                    }
1389                },
1390            };
1391            request_value_reader
1392                .seek(std::io::SeekFrom::Start(0))
1393                .unwrap();
1394            let mut req_result = {
1395                let client = &self.hub.client;
1396                dlg.pre_request();
1397                let mut req_builder = hyper::Request::builder()
1398                    .method(hyper::Method::POST)
1399                    .uri(url.as_str())
1400                    .header(USER_AGENT, self.hub._user_agent.clone());
1401
1402                if let Some(token) = token.as_ref() {
1403                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1404                }
1405
1406                let request = req_builder
1407                    .header(CONTENT_TYPE, json_mime_type.to_string())
1408                    .header(CONTENT_LENGTH, request_size as u64)
1409                    .body(common::to_body(
1410                        request_value_reader.get_ref().clone().into(),
1411                    ));
1412
1413                client.request(request.unwrap()).await
1414            };
1415
1416            match req_result {
1417                Err(err) => {
1418                    if let common::Retry::After(d) = dlg.http_error(&err) {
1419                        sleep(d).await;
1420                        continue;
1421                    }
1422                    dlg.finished(false);
1423                    return Err(common::Error::HttpError(err));
1424                }
1425                Ok(res) => {
1426                    let (mut parts, body) = res.into_parts();
1427                    let mut body = common::Body::new(body);
1428                    if !parts.status.is_success() {
1429                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1430                        let error = serde_json::from_str(&common::to_string(&bytes));
1431                        let response = common::to_response(parts, bytes.into());
1432
1433                        if let common::Retry::After(d) =
1434                            dlg.http_failure(&response, error.as_ref().ok())
1435                        {
1436                            sleep(d).await;
1437                            continue;
1438                        }
1439
1440                        dlg.finished(false);
1441
1442                        return Err(match error {
1443                            Ok(value) => common::Error::BadRequest(value),
1444                            _ => common::Error::Failure(response),
1445                        });
1446                    }
1447                    let response = {
1448                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1449                        let encoded = common::to_string(&bytes);
1450                        match serde_json::from_str(&encoded) {
1451                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1452                            Err(error) => {
1453                                dlg.response_json_decode_error(&encoded, &error);
1454                                return Err(common::Error::JsonDecodeError(
1455                                    encoded.to_string(),
1456                                    error,
1457                                ));
1458                            }
1459                        }
1460                    };
1461
1462                    dlg.finished(true);
1463                    return Ok(response);
1464                }
1465            }
1466        }
1467    }
1468
1469    ///
1470    /// Sets the *request* property to the given value.
1471    ///
1472    /// Even though the property as already been set when instantiating this call,
1473    /// we provide this method for API completeness.
1474    pub fn request(
1475        mut self,
1476        new_value: AnalyzeEntitySentimentRequest,
1477    ) -> DocumentAnalyzeEntitySentimentCall<'a, C> {
1478        self._request = new_value;
1479        self
1480    }
1481    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1482    /// while executing the actual API request.
1483    ///
1484    /// ````text
1485    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1486    /// ````
1487    ///
1488    /// Sets the *delegate* property to the given value.
1489    pub fn delegate(
1490        mut self,
1491        new_value: &'a mut dyn common::Delegate,
1492    ) -> DocumentAnalyzeEntitySentimentCall<'a, C> {
1493        self._delegate = Some(new_value);
1494        self
1495    }
1496
1497    /// Set any additional parameter of the query string used in the request.
1498    /// It should be used to set parameters which are not yet available through their own
1499    /// setters.
1500    ///
1501    /// Please note that this method must not be used to set any of the known parameters
1502    /// which have their own setter method. If done anyway, the request will fail.
1503    ///
1504    /// # Additional Parameters
1505    ///
1506    /// * *$.xgafv* (query-string) - V1 error format.
1507    /// * *access_token* (query-string) - OAuth access token.
1508    /// * *alt* (query-string) - Data format for response.
1509    /// * *callback* (query-string) - JSONP
1510    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1511    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
1512    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1513    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1514    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
1515    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1516    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1517    pub fn param<T>(mut self, name: T, value: T) -> DocumentAnalyzeEntitySentimentCall<'a, C>
1518    where
1519        T: AsRef<str>,
1520    {
1521        self._additional_params
1522            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1523        self
1524    }
1525
1526    /// Identifies the authorization scope for the method you are building.
1527    ///
1528    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1529    /// [`Scope::CloudLanguage`].
1530    ///
1531    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1532    /// tokens for more than one scope.
1533    ///
1534    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1535    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1536    /// sufficient, a read-write scope will do as well.
1537    pub fn add_scope<St>(mut self, scope: St) -> DocumentAnalyzeEntitySentimentCall<'a, C>
1538    where
1539        St: AsRef<str>,
1540    {
1541        self._scopes.insert(String::from(scope.as_ref()));
1542        self
1543    }
1544    /// Identifies the authorization scope(s) for the method you are building.
1545    ///
1546    /// See [`Self::add_scope()`] for details.
1547    pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentAnalyzeEntitySentimentCall<'a, C>
1548    where
1549        I: IntoIterator<Item = St>,
1550        St: AsRef<str>,
1551    {
1552        self._scopes
1553            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1554        self
1555    }
1556
1557    /// Removes all scopes, and no default scope will be used either.
1558    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1559    /// for details).
1560    pub fn clear_scopes(mut self) -> DocumentAnalyzeEntitySentimentCall<'a, C> {
1561        self._scopes.clear();
1562        self
1563    }
1564}
1565
1566/// Analyzes the sentiment of the provided text.
1567///
1568/// A builder for the *analyzeSentiment* method supported by a *document* resource.
1569/// It is not used directly, but through a [`DocumentMethods`] instance.
1570///
1571/// # Example
1572///
1573/// Instantiate a resource method builder
1574///
1575/// ```test_harness,no_run
1576/// # extern crate hyper;
1577/// # extern crate hyper_rustls;
1578/// # extern crate google_language1 as language1;
1579/// use language1::api::AnalyzeSentimentRequest;
1580/// # async fn dox() {
1581/// # use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1582///
1583/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1584/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1585/// #     secret,
1586/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1587/// # ).build().await.unwrap();
1588///
1589/// # let client = hyper_util::client::legacy::Client::builder(
1590/// #     hyper_util::rt::TokioExecutor::new()
1591/// # )
1592/// # .build(
1593/// #     hyper_rustls::HttpsConnectorBuilder::new()
1594/// #         .with_native_roots()
1595/// #         .unwrap()
1596/// #         .https_or_http()
1597/// #         .enable_http1()
1598/// #         .build()
1599/// # );
1600/// # let mut hub = CloudNaturalLanguage::new(client, auth);
1601/// // As the method needs a request, you would usually fill it with the desired information
1602/// // into the respective structure. Some of the parts shown here might not be applicable !
1603/// // Values shown here are possibly random and not representative !
1604/// let mut req = AnalyzeSentimentRequest::default();
1605///
1606/// // You can configure optional parameters by calling the respective setters at will, and
1607/// // execute the final call using `doit()`.
1608/// // Values shown here are possibly random and not representative !
1609/// let result = hub.documents().analyze_sentiment(req)
1610///              .doit().await;
1611/// # }
1612/// ```
1613pub struct DocumentAnalyzeSentimentCall<'a, C>
1614where
1615    C: 'a,
1616{
1617    hub: &'a CloudNaturalLanguage<C>,
1618    _request: AnalyzeSentimentRequest,
1619    _delegate: Option<&'a mut dyn common::Delegate>,
1620    _additional_params: HashMap<String, String>,
1621    _scopes: BTreeSet<String>,
1622}
1623
1624impl<'a, C> common::CallBuilder for DocumentAnalyzeSentimentCall<'a, C> {}
1625
1626impl<'a, C> DocumentAnalyzeSentimentCall<'a, C>
1627where
1628    C: common::Connector,
1629{
1630    /// Perform the operation you have build so far.
1631    pub async fn doit(mut self) -> common::Result<(common::Response, AnalyzeSentimentResponse)> {
1632        use std::borrow::Cow;
1633        use std::io::{Read, Seek};
1634
1635        use common::{url::Params, ToParts};
1636        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1637
1638        let mut dd = common::DefaultDelegate;
1639        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1640        dlg.begin(common::MethodInfo {
1641            id: "language.documents.analyzeSentiment",
1642            http_method: hyper::Method::POST,
1643        });
1644
1645        for &field in ["alt"].iter() {
1646            if self._additional_params.contains_key(field) {
1647                dlg.finished(false);
1648                return Err(common::Error::FieldClash(field));
1649            }
1650        }
1651
1652        let mut params = Params::with_capacity(3 + self._additional_params.len());
1653
1654        params.extend(self._additional_params.iter());
1655
1656        params.push("alt", "json");
1657        let mut url = self.hub._base_url.clone() + "v1/documents:analyzeSentiment";
1658        if self._scopes.is_empty() {
1659            self._scopes
1660                .insert(Scope::CloudLanguage.as_ref().to_string());
1661        }
1662
1663        let url = params.parse_with_url(&url);
1664
1665        let mut json_mime_type = mime::APPLICATION_JSON;
1666        let mut request_value_reader = {
1667            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1668            common::remove_json_null_values(&mut value);
1669            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1670            serde_json::to_writer(&mut dst, &value).unwrap();
1671            dst
1672        };
1673        let request_size = request_value_reader
1674            .seek(std::io::SeekFrom::End(0))
1675            .unwrap();
1676        request_value_reader
1677            .seek(std::io::SeekFrom::Start(0))
1678            .unwrap();
1679
1680        loop {
1681            let token = match self
1682                .hub
1683                .auth
1684                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1685                .await
1686            {
1687                Ok(token) => token,
1688                Err(e) => match dlg.token(e) {
1689                    Ok(token) => token,
1690                    Err(e) => {
1691                        dlg.finished(false);
1692                        return Err(common::Error::MissingToken(e));
1693                    }
1694                },
1695            };
1696            request_value_reader
1697                .seek(std::io::SeekFrom::Start(0))
1698                .unwrap();
1699            let mut req_result = {
1700                let client = &self.hub.client;
1701                dlg.pre_request();
1702                let mut req_builder = hyper::Request::builder()
1703                    .method(hyper::Method::POST)
1704                    .uri(url.as_str())
1705                    .header(USER_AGENT, self.hub._user_agent.clone());
1706
1707                if let Some(token) = token.as_ref() {
1708                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1709                }
1710
1711                let request = req_builder
1712                    .header(CONTENT_TYPE, json_mime_type.to_string())
1713                    .header(CONTENT_LENGTH, request_size as u64)
1714                    .body(common::to_body(
1715                        request_value_reader.get_ref().clone().into(),
1716                    ));
1717
1718                client.request(request.unwrap()).await
1719            };
1720
1721            match req_result {
1722                Err(err) => {
1723                    if let common::Retry::After(d) = dlg.http_error(&err) {
1724                        sleep(d).await;
1725                        continue;
1726                    }
1727                    dlg.finished(false);
1728                    return Err(common::Error::HttpError(err));
1729                }
1730                Ok(res) => {
1731                    let (mut parts, body) = res.into_parts();
1732                    let mut body = common::Body::new(body);
1733                    if !parts.status.is_success() {
1734                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1735                        let error = serde_json::from_str(&common::to_string(&bytes));
1736                        let response = common::to_response(parts, bytes.into());
1737
1738                        if let common::Retry::After(d) =
1739                            dlg.http_failure(&response, error.as_ref().ok())
1740                        {
1741                            sleep(d).await;
1742                            continue;
1743                        }
1744
1745                        dlg.finished(false);
1746
1747                        return Err(match error {
1748                            Ok(value) => common::Error::BadRequest(value),
1749                            _ => common::Error::Failure(response),
1750                        });
1751                    }
1752                    let response = {
1753                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1754                        let encoded = common::to_string(&bytes);
1755                        match serde_json::from_str(&encoded) {
1756                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1757                            Err(error) => {
1758                                dlg.response_json_decode_error(&encoded, &error);
1759                                return Err(common::Error::JsonDecodeError(
1760                                    encoded.to_string(),
1761                                    error,
1762                                ));
1763                            }
1764                        }
1765                    };
1766
1767                    dlg.finished(true);
1768                    return Ok(response);
1769                }
1770            }
1771        }
1772    }
1773
1774    ///
1775    /// Sets the *request* property to the given value.
1776    ///
1777    /// Even though the property as already been set when instantiating this call,
1778    /// we provide this method for API completeness.
1779    pub fn request(
1780        mut self,
1781        new_value: AnalyzeSentimentRequest,
1782    ) -> DocumentAnalyzeSentimentCall<'a, C> {
1783        self._request = new_value;
1784        self
1785    }
1786    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1787    /// while executing the actual API request.
1788    ///
1789    /// ````text
1790    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1791    /// ````
1792    ///
1793    /// Sets the *delegate* property to the given value.
1794    pub fn delegate(
1795        mut self,
1796        new_value: &'a mut dyn common::Delegate,
1797    ) -> DocumentAnalyzeSentimentCall<'a, C> {
1798        self._delegate = Some(new_value);
1799        self
1800    }
1801
1802    /// Set any additional parameter of the query string used in the request.
1803    /// It should be used to set parameters which are not yet available through their own
1804    /// setters.
1805    ///
1806    /// Please note that this method must not be used to set any of the known parameters
1807    /// which have their own setter method. If done anyway, the request will fail.
1808    ///
1809    /// # Additional Parameters
1810    ///
1811    /// * *$.xgafv* (query-string) - V1 error format.
1812    /// * *access_token* (query-string) - OAuth access token.
1813    /// * *alt* (query-string) - Data format for response.
1814    /// * *callback* (query-string) - JSONP
1815    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1816    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
1817    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1818    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1819    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
1820    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1821    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1822    pub fn param<T>(mut self, name: T, value: T) -> DocumentAnalyzeSentimentCall<'a, C>
1823    where
1824        T: AsRef<str>,
1825    {
1826        self._additional_params
1827            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1828        self
1829    }
1830
1831    /// Identifies the authorization scope for the method you are building.
1832    ///
1833    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1834    /// [`Scope::CloudLanguage`].
1835    ///
1836    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1837    /// tokens for more than one scope.
1838    ///
1839    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1840    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1841    /// sufficient, a read-write scope will do as well.
1842    pub fn add_scope<St>(mut self, scope: St) -> DocumentAnalyzeSentimentCall<'a, C>
1843    where
1844        St: AsRef<str>,
1845    {
1846        self._scopes.insert(String::from(scope.as_ref()));
1847        self
1848    }
1849    /// Identifies the authorization scope(s) for the method you are building.
1850    ///
1851    /// See [`Self::add_scope()`] for details.
1852    pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentAnalyzeSentimentCall<'a, C>
1853    where
1854        I: IntoIterator<Item = St>,
1855        St: AsRef<str>,
1856    {
1857        self._scopes
1858            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1859        self
1860    }
1861
1862    /// Removes all scopes, and no default scope will be used either.
1863    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1864    /// for details).
1865    pub fn clear_scopes(mut self) -> DocumentAnalyzeSentimentCall<'a, C> {
1866        self._scopes.clear();
1867        self
1868    }
1869}
1870
1871/// Analyzes the syntax of the text and provides sentence boundaries and tokenization along with part of speech tags, dependency trees, and other properties.
1872///
1873/// A builder for the *analyzeSyntax* method supported by a *document* resource.
1874/// It is not used directly, but through a [`DocumentMethods`] instance.
1875///
1876/// # Example
1877///
1878/// Instantiate a resource method builder
1879///
1880/// ```test_harness,no_run
1881/// # extern crate hyper;
1882/// # extern crate hyper_rustls;
1883/// # extern crate google_language1 as language1;
1884/// use language1::api::AnalyzeSyntaxRequest;
1885/// # async fn dox() {
1886/// # use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1887///
1888/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1889/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1890/// #     secret,
1891/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1892/// # ).build().await.unwrap();
1893///
1894/// # let client = hyper_util::client::legacy::Client::builder(
1895/// #     hyper_util::rt::TokioExecutor::new()
1896/// # )
1897/// # .build(
1898/// #     hyper_rustls::HttpsConnectorBuilder::new()
1899/// #         .with_native_roots()
1900/// #         .unwrap()
1901/// #         .https_or_http()
1902/// #         .enable_http1()
1903/// #         .build()
1904/// # );
1905/// # let mut hub = CloudNaturalLanguage::new(client, auth);
1906/// // As the method needs a request, you would usually fill it with the desired information
1907/// // into the respective structure. Some of the parts shown here might not be applicable !
1908/// // Values shown here are possibly random and not representative !
1909/// let mut req = AnalyzeSyntaxRequest::default();
1910///
1911/// // You can configure optional parameters by calling the respective setters at will, and
1912/// // execute the final call using `doit()`.
1913/// // Values shown here are possibly random and not representative !
1914/// let result = hub.documents().analyze_syntax(req)
1915///              .doit().await;
1916/// # }
1917/// ```
1918pub struct DocumentAnalyzeSyntaxCall<'a, C>
1919where
1920    C: 'a,
1921{
1922    hub: &'a CloudNaturalLanguage<C>,
1923    _request: AnalyzeSyntaxRequest,
1924    _delegate: Option<&'a mut dyn common::Delegate>,
1925    _additional_params: HashMap<String, String>,
1926    _scopes: BTreeSet<String>,
1927}
1928
1929impl<'a, C> common::CallBuilder for DocumentAnalyzeSyntaxCall<'a, C> {}
1930
1931impl<'a, C> DocumentAnalyzeSyntaxCall<'a, C>
1932where
1933    C: common::Connector,
1934{
1935    /// Perform the operation you have build so far.
1936    pub async fn doit(mut self) -> common::Result<(common::Response, AnalyzeSyntaxResponse)> {
1937        use std::borrow::Cow;
1938        use std::io::{Read, Seek};
1939
1940        use common::{url::Params, ToParts};
1941        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1942
1943        let mut dd = common::DefaultDelegate;
1944        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1945        dlg.begin(common::MethodInfo {
1946            id: "language.documents.analyzeSyntax",
1947            http_method: hyper::Method::POST,
1948        });
1949
1950        for &field in ["alt"].iter() {
1951            if self._additional_params.contains_key(field) {
1952                dlg.finished(false);
1953                return Err(common::Error::FieldClash(field));
1954            }
1955        }
1956
1957        let mut params = Params::with_capacity(3 + self._additional_params.len());
1958
1959        params.extend(self._additional_params.iter());
1960
1961        params.push("alt", "json");
1962        let mut url = self.hub._base_url.clone() + "v1/documents:analyzeSyntax";
1963        if self._scopes.is_empty() {
1964            self._scopes
1965                .insert(Scope::CloudLanguage.as_ref().to_string());
1966        }
1967
1968        let url = params.parse_with_url(&url);
1969
1970        let mut json_mime_type = mime::APPLICATION_JSON;
1971        let mut request_value_reader = {
1972            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1973            common::remove_json_null_values(&mut value);
1974            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1975            serde_json::to_writer(&mut dst, &value).unwrap();
1976            dst
1977        };
1978        let request_size = request_value_reader
1979            .seek(std::io::SeekFrom::End(0))
1980            .unwrap();
1981        request_value_reader
1982            .seek(std::io::SeekFrom::Start(0))
1983            .unwrap();
1984
1985        loop {
1986            let token = match self
1987                .hub
1988                .auth
1989                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1990                .await
1991            {
1992                Ok(token) => token,
1993                Err(e) => match dlg.token(e) {
1994                    Ok(token) => token,
1995                    Err(e) => {
1996                        dlg.finished(false);
1997                        return Err(common::Error::MissingToken(e));
1998                    }
1999                },
2000            };
2001            request_value_reader
2002                .seek(std::io::SeekFrom::Start(0))
2003                .unwrap();
2004            let mut req_result = {
2005                let client = &self.hub.client;
2006                dlg.pre_request();
2007                let mut req_builder = hyper::Request::builder()
2008                    .method(hyper::Method::POST)
2009                    .uri(url.as_str())
2010                    .header(USER_AGENT, self.hub._user_agent.clone());
2011
2012                if let Some(token) = token.as_ref() {
2013                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2014                }
2015
2016                let request = req_builder
2017                    .header(CONTENT_TYPE, json_mime_type.to_string())
2018                    .header(CONTENT_LENGTH, request_size as u64)
2019                    .body(common::to_body(
2020                        request_value_reader.get_ref().clone().into(),
2021                    ));
2022
2023                client.request(request.unwrap()).await
2024            };
2025
2026            match req_result {
2027                Err(err) => {
2028                    if let common::Retry::After(d) = dlg.http_error(&err) {
2029                        sleep(d).await;
2030                        continue;
2031                    }
2032                    dlg.finished(false);
2033                    return Err(common::Error::HttpError(err));
2034                }
2035                Ok(res) => {
2036                    let (mut parts, body) = res.into_parts();
2037                    let mut body = common::Body::new(body);
2038                    if !parts.status.is_success() {
2039                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2040                        let error = serde_json::from_str(&common::to_string(&bytes));
2041                        let response = common::to_response(parts, bytes.into());
2042
2043                        if let common::Retry::After(d) =
2044                            dlg.http_failure(&response, error.as_ref().ok())
2045                        {
2046                            sleep(d).await;
2047                            continue;
2048                        }
2049
2050                        dlg.finished(false);
2051
2052                        return Err(match error {
2053                            Ok(value) => common::Error::BadRequest(value),
2054                            _ => common::Error::Failure(response),
2055                        });
2056                    }
2057                    let response = {
2058                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2059                        let encoded = common::to_string(&bytes);
2060                        match serde_json::from_str(&encoded) {
2061                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2062                            Err(error) => {
2063                                dlg.response_json_decode_error(&encoded, &error);
2064                                return Err(common::Error::JsonDecodeError(
2065                                    encoded.to_string(),
2066                                    error,
2067                                ));
2068                            }
2069                        }
2070                    };
2071
2072                    dlg.finished(true);
2073                    return Ok(response);
2074                }
2075            }
2076        }
2077    }
2078
2079    ///
2080    /// Sets the *request* property to the given value.
2081    ///
2082    /// Even though the property as already been set when instantiating this call,
2083    /// we provide this method for API completeness.
2084    pub fn request(mut self, new_value: AnalyzeSyntaxRequest) -> DocumentAnalyzeSyntaxCall<'a, C> {
2085        self._request = new_value;
2086        self
2087    }
2088    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2089    /// while executing the actual API request.
2090    ///
2091    /// ````text
2092    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
2093    /// ````
2094    ///
2095    /// Sets the *delegate* property to the given value.
2096    pub fn delegate(
2097        mut self,
2098        new_value: &'a mut dyn common::Delegate,
2099    ) -> DocumentAnalyzeSyntaxCall<'a, C> {
2100        self._delegate = Some(new_value);
2101        self
2102    }
2103
2104    /// Set any additional parameter of the query string used in the request.
2105    /// It should be used to set parameters which are not yet available through their own
2106    /// setters.
2107    ///
2108    /// Please note that this method must not be used to set any of the known parameters
2109    /// which have their own setter method. If done anyway, the request will fail.
2110    ///
2111    /// # Additional Parameters
2112    ///
2113    /// * *$.xgafv* (query-string) - V1 error format.
2114    /// * *access_token* (query-string) - OAuth access token.
2115    /// * *alt* (query-string) - Data format for response.
2116    /// * *callback* (query-string) - JSONP
2117    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2118    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
2119    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2120    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2121    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
2122    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2123    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2124    pub fn param<T>(mut self, name: T, value: T) -> DocumentAnalyzeSyntaxCall<'a, C>
2125    where
2126        T: AsRef<str>,
2127    {
2128        self._additional_params
2129            .insert(name.as_ref().to_string(), value.as_ref().to_string());
2130        self
2131    }
2132
2133    /// Identifies the authorization scope for the method you are building.
2134    ///
2135    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2136    /// [`Scope::CloudLanguage`].
2137    ///
2138    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2139    /// tokens for more than one scope.
2140    ///
2141    /// Usually there is more than one suitable scope to authorize an operation, some of which may
2142    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2143    /// sufficient, a read-write scope will do as well.
2144    pub fn add_scope<St>(mut self, scope: St) -> DocumentAnalyzeSyntaxCall<'a, C>
2145    where
2146        St: AsRef<str>,
2147    {
2148        self._scopes.insert(String::from(scope.as_ref()));
2149        self
2150    }
2151    /// Identifies the authorization scope(s) for the method you are building.
2152    ///
2153    /// See [`Self::add_scope()`] for details.
2154    pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentAnalyzeSyntaxCall<'a, C>
2155    where
2156        I: IntoIterator<Item = St>,
2157        St: AsRef<str>,
2158    {
2159        self._scopes
2160            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2161        self
2162    }
2163
2164    /// Removes all scopes, and no default scope will be used either.
2165    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2166    /// for details).
2167    pub fn clear_scopes(mut self) -> DocumentAnalyzeSyntaxCall<'a, C> {
2168        self._scopes.clear();
2169        self
2170    }
2171}
2172
2173/// A convenience method that provides all the features that analyzeSentiment, analyzeEntities, and analyzeSyntax provide in one call.
2174///
2175/// A builder for the *annotateText* method supported by a *document* resource.
2176/// It is not used directly, but through a [`DocumentMethods`] instance.
2177///
2178/// # Example
2179///
2180/// Instantiate a resource method builder
2181///
2182/// ```test_harness,no_run
2183/// # extern crate hyper;
2184/// # extern crate hyper_rustls;
2185/// # extern crate google_language1 as language1;
2186/// use language1::api::AnnotateTextRequest;
2187/// # async fn dox() {
2188/// # use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2189///
2190/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2191/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
2192/// #     secret,
2193/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2194/// # ).build().await.unwrap();
2195///
2196/// # let client = hyper_util::client::legacy::Client::builder(
2197/// #     hyper_util::rt::TokioExecutor::new()
2198/// # )
2199/// # .build(
2200/// #     hyper_rustls::HttpsConnectorBuilder::new()
2201/// #         .with_native_roots()
2202/// #         .unwrap()
2203/// #         .https_or_http()
2204/// #         .enable_http1()
2205/// #         .build()
2206/// # );
2207/// # let mut hub = CloudNaturalLanguage::new(client, auth);
2208/// // As the method needs a request, you would usually fill it with the desired information
2209/// // into the respective structure. Some of the parts shown here might not be applicable !
2210/// // Values shown here are possibly random and not representative !
2211/// let mut req = AnnotateTextRequest::default();
2212///
2213/// // You can configure optional parameters by calling the respective setters at will, and
2214/// // execute the final call using `doit()`.
2215/// // Values shown here are possibly random and not representative !
2216/// let result = hub.documents().annotate_text(req)
2217///              .doit().await;
2218/// # }
2219/// ```
2220pub struct DocumentAnnotateTextCall<'a, C>
2221where
2222    C: 'a,
2223{
2224    hub: &'a CloudNaturalLanguage<C>,
2225    _request: AnnotateTextRequest,
2226    _delegate: Option<&'a mut dyn common::Delegate>,
2227    _additional_params: HashMap<String, String>,
2228    _scopes: BTreeSet<String>,
2229}
2230
2231impl<'a, C> common::CallBuilder for DocumentAnnotateTextCall<'a, C> {}
2232
2233impl<'a, C> DocumentAnnotateTextCall<'a, C>
2234where
2235    C: common::Connector,
2236{
2237    /// Perform the operation you have build so far.
2238    pub async fn doit(mut self) -> common::Result<(common::Response, AnnotateTextResponse)> {
2239        use std::borrow::Cow;
2240        use std::io::{Read, Seek};
2241
2242        use common::{url::Params, ToParts};
2243        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2244
2245        let mut dd = common::DefaultDelegate;
2246        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2247        dlg.begin(common::MethodInfo {
2248            id: "language.documents.annotateText",
2249            http_method: hyper::Method::POST,
2250        });
2251
2252        for &field in ["alt"].iter() {
2253            if self._additional_params.contains_key(field) {
2254                dlg.finished(false);
2255                return Err(common::Error::FieldClash(field));
2256            }
2257        }
2258
2259        let mut params = Params::with_capacity(3 + self._additional_params.len());
2260
2261        params.extend(self._additional_params.iter());
2262
2263        params.push("alt", "json");
2264        let mut url = self.hub._base_url.clone() + "v1/documents:annotateText";
2265        if self._scopes.is_empty() {
2266            self._scopes
2267                .insert(Scope::CloudLanguage.as_ref().to_string());
2268        }
2269
2270        let url = params.parse_with_url(&url);
2271
2272        let mut json_mime_type = mime::APPLICATION_JSON;
2273        let mut request_value_reader = {
2274            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2275            common::remove_json_null_values(&mut value);
2276            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2277            serde_json::to_writer(&mut dst, &value).unwrap();
2278            dst
2279        };
2280        let request_size = request_value_reader
2281            .seek(std::io::SeekFrom::End(0))
2282            .unwrap();
2283        request_value_reader
2284            .seek(std::io::SeekFrom::Start(0))
2285            .unwrap();
2286
2287        loop {
2288            let token = match self
2289                .hub
2290                .auth
2291                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2292                .await
2293            {
2294                Ok(token) => token,
2295                Err(e) => match dlg.token(e) {
2296                    Ok(token) => token,
2297                    Err(e) => {
2298                        dlg.finished(false);
2299                        return Err(common::Error::MissingToken(e));
2300                    }
2301                },
2302            };
2303            request_value_reader
2304                .seek(std::io::SeekFrom::Start(0))
2305                .unwrap();
2306            let mut req_result = {
2307                let client = &self.hub.client;
2308                dlg.pre_request();
2309                let mut req_builder = hyper::Request::builder()
2310                    .method(hyper::Method::POST)
2311                    .uri(url.as_str())
2312                    .header(USER_AGENT, self.hub._user_agent.clone());
2313
2314                if let Some(token) = token.as_ref() {
2315                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2316                }
2317
2318                let request = req_builder
2319                    .header(CONTENT_TYPE, json_mime_type.to_string())
2320                    .header(CONTENT_LENGTH, request_size as u64)
2321                    .body(common::to_body(
2322                        request_value_reader.get_ref().clone().into(),
2323                    ));
2324
2325                client.request(request.unwrap()).await
2326            };
2327
2328            match req_result {
2329                Err(err) => {
2330                    if let common::Retry::After(d) = dlg.http_error(&err) {
2331                        sleep(d).await;
2332                        continue;
2333                    }
2334                    dlg.finished(false);
2335                    return Err(common::Error::HttpError(err));
2336                }
2337                Ok(res) => {
2338                    let (mut parts, body) = res.into_parts();
2339                    let mut body = common::Body::new(body);
2340                    if !parts.status.is_success() {
2341                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2342                        let error = serde_json::from_str(&common::to_string(&bytes));
2343                        let response = common::to_response(parts, bytes.into());
2344
2345                        if let common::Retry::After(d) =
2346                            dlg.http_failure(&response, error.as_ref().ok())
2347                        {
2348                            sleep(d).await;
2349                            continue;
2350                        }
2351
2352                        dlg.finished(false);
2353
2354                        return Err(match error {
2355                            Ok(value) => common::Error::BadRequest(value),
2356                            _ => common::Error::Failure(response),
2357                        });
2358                    }
2359                    let response = {
2360                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2361                        let encoded = common::to_string(&bytes);
2362                        match serde_json::from_str(&encoded) {
2363                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2364                            Err(error) => {
2365                                dlg.response_json_decode_error(&encoded, &error);
2366                                return Err(common::Error::JsonDecodeError(
2367                                    encoded.to_string(),
2368                                    error,
2369                                ));
2370                            }
2371                        }
2372                    };
2373
2374                    dlg.finished(true);
2375                    return Ok(response);
2376                }
2377            }
2378        }
2379    }
2380
2381    ///
2382    /// Sets the *request* property to the given value.
2383    ///
2384    /// Even though the property as already been set when instantiating this call,
2385    /// we provide this method for API completeness.
2386    pub fn request(mut self, new_value: AnnotateTextRequest) -> DocumentAnnotateTextCall<'a, C> {
2387        self._request = new_value;
2388        self
2389    }
2390    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2391    /// while executing the actual API request.
2392    ///
2393    /// ````text
2394    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
2395    /// ````
2396    ///
2397    /// Sets the *delegate* property to the given value.
2398    pub fn delegate(
2399        mut self,
2400        new_value: &'a mut dyn common::Delegate,
2401    ) -> DocumentAnnotateTextCall<'a, C> {
2402        self._delegate = Some(new_value);
2403        self
2404    }
2405
2406    /// Set any additional parameter of the query string used in the request.
2407    /// It should be used to set parameters which are not yet available through their own
2408    /// setters.
2409    ///
2410    /// Please note that this method must not be used to set any of the known parameters
2411    /// which have their own setter method. If done anyway, the request will fail.
2412    ///
2413    /// # Additional Parameters
2414    ///
2415    /// * *$.xgafv* (query-string) - V1 error format.
2416    /// * *access_token* (query-string) - OAuth access token.
2417    /// * *alt* (query-string) - Data format for response.
2418    /// * *callback* (query-string) - JSONP
2419    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2420    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
2421    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2422    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2423    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
2424    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2425    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2426    pub fn param<T>(mut self, name: T, value: T) -> DocumentAnnotateTextCall<'a, C>
2427    where
2428        T: AsRef<str>,
2429    {
2430        self._additional_params
2431            .insert(name.as_ref().to_string(), value.as_ref().to_string());
2432        self
2433    }
2434
2435    /// Identifies the authorization scope for the method you are building.
2436    ///
2437    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2438    /// [`Scope::CloudLanguage`].
2439    ///
2440    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2441    /// tokens for more than one scope.
2442    ///
2443    /// Usually there is more than one suitable scope to authorize an operation, some of which may
2444    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2445    /// sufficient, a read-write scope will do as well.
2446    pub fn add_scope<St>(mut self, scope: St) -> DocumentAnnotateTextCall<'a, C>
2447    where
2448        St: AsRef<str>,
2449    {
2450        self._scopes.insert(String::from(scope.as_ref()));
2451        self
2452    }
2453    /// Identifies the authorization scope(s) for the method you are building.
2454    ///
2455    /// See [`Self::add_scope()`] for details.
2456    pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentAnnotateTextCall<'a, C>
2457    where
2458        I: IntoIterator<Item = St>,
2459        St: AsRef<str>,
2460    {
2461        self._scopes
2462            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2463        self
2464    }
2465
2466    /// Removes all scopes, and no default scope will be used either.
2467    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2468    /// for details).
2469    pub fn clear_scopes(mut self) -> DocumentAnnotateTextCall<'a, C> {
2470        self._scopes.clear();
2471        self
2472    }
2473}
2474
2475/// Classifies a document into categories.
2476///
2477/// A builder for the *classifyText* method supported by a *document* resource.
2478/// It is not used directly, but through a [`DocumentMethods`] instance.
2479///
2480/// # Example
2481///
2482/// Instantiate a resource method builder
2483///
2484/// ```test_harness,no_run
2485/// # extern crate hyper;
2486/// # extern crate hyper_rustls;
2487/// # extern crate google_language1 as language1;
2488/// use language1::api::ClassifyTextRequest;
2489/// # async fn dox() {
2490/// # use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2491///
2492/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2493/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
2494/// #     secret,
2495/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2496/// # ).build().await.unwrap();
2497///
2498/// # let client = hyper_util::client::legacy::Client::builder(
2499/// #     hyper_util::rt::TokioExecutor::new()
2500/// # )
2501/// # .build(
2502/// #     hyper_rustls::HttpsConnectorBuilder::new()
2503/// #         .with_native_roots()
2504/// #         .unwrap()
2505/// #         .https_or_http()
2506/// #         .enable_http1()
2507/// #         .build()
2508/// # );
2509/// # let mut hub = CloudNaturalLanguage::new(client, auth);
2510/// // As the method needs a request, you would usually fill it with the desired information
2511/// // into the respective structure. Some of the parts shown here might not be applicable !
2512/// // Values shown here are possibly random and not representative !
2513/// let mut req = ClassifyTextRequest::default();
2514///
2515/// // You can configure optional parameters by calling the respective setters at will, and
2516/// // execute the final call using `doit()`.
2517/// // Values shown here are possibly random and not representative !
2518/// let result = hub.documents().classify_text(req)
2519///              .doit().await;
2520/// # }
2521/// ```
2522pub struct DocumentClassifyTextCall<'a, C>
2523where
2524    C: 'a,
2525{
2526    hub: &'a CloudNaturalLanguage<C>,
2527    _request: ClassifyTextRequest,
2528    _delegate: Option<&'a mut dyn common::Delegate>,
2529    _additional_params: HashMap<String, String>,
2530    _scopes: BTreeSet<String>,
2531}
2532
2533impl<'a, C> common::CallBuilder for DocumentClassifyTextCall<'a, C> {}
2534
2535impl<'a, C> DocumentClassifyTextCall<'a, C>
2536where
2537    C: common::Connector,
2538{
2539    /// Perform the operation you have build so far.
2540    pub async fn doit(mut self) -> common::Result<(common::Response, ClassifyTextResponse)> {
2541        use std::borrow::Cow;
2542        use std::io::{Read, Seek};
2543
2544        use common::{url::Params, ToParts};
2545        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2546
2547        let mut dd = common::DefaultDelegate;
2548        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2549        dlg.begin(common::MethodInfo {
2550            id: "language.documents.classifyText",
2551            http_method: hyper::Method::POST,
2552        });
2553
2554        for &field in ["alt"].iter() {
2555            if self._additional_params.contains_key(field) {
2556                dlg.finished(false);
2557                return Err(common::Error::FieldClash(field));
2558            }
2559        }
2560
2561        let mut params = Params::with_capacity(3 + self._additional_params.len());
2562
2563        params.extend(self._additional_params.iter());
2564
2565        params.push("alt", "json");
2566        let mut url = self.hub._base_url.clone() + "v1/documents:classifyText";
2567        if self._scopes.is_empty() {
2568            self._scopes
2569                .insert(Scope::CloudLanguage.as_ref().to_string());
2570        }
2571
2572        let url = params.parse_with_url(&url);
2573
2574        let mut json_mime_type = mime::APPLICATION_JSON;
2575        let mut request_value_reader = {
2576            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2577            common::remove_json_null_values(&mut value);
2578            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2579            serde_json::to_writer(&mut dst, &value).unwrap();
2580            dst
2581        };
2582        let request_size = request_value_reader
2583            .seek(std::io::SeekFrom::End(0))
2584            .unwrap();
2585        request_value_reader
2586            .seek(std::io::SeekFrom::Start(0))
2587            .unwrap();
2588
2589        loop {
2590            let token = match self
2591                .hub
2592                .auth
2593                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2594                .await
2595            {
2596                Ok(token) => token,
2597                Err(e) => match dlg.token(e) {
2598                    Ok(token) => token,
2599                    Err(e) => {
2600                        dlg.finished(false);
2601                        return Err(common::Error::MissingToken(e));
2602                    }
2603                },
2604            };
2605            request_value_reader
2606                .seek(std::io::SeekFrom::Start(0))
2607                .unwrap();
2608            let mut req_result = {
2609                let client = &self.hub.client;
2610                dlg.pre_request();
2611                let mut req_builder = hyper::Request::builder()
2612                    .method(hyper::Method::POST)
2613                    .uri(url.as_str())
2614                    .header(USER_AGENT, self.hub._user_agent.clone());
2615
2616                if let Some(token) = token.as_ref() {
2617                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2618                }
2619
2620                let request = req_builder
2621                    .header(CONTENT_TYPE, json_mime_type.to_string())
2622                    .header(CONTENT_LENGTH, request_size as u64)
2623                    .body(common::to_body(
2624                        request_value_reader.get_ref().clone().into(),
2625                    ));
2626
2627                client.request(request.unwrap()).await
2628            };
2629
2630            match req_result {
2631                Err(err) => {
2632                    if let common::Retry::After(d) = dlg.http_error(&err) {
2633                        sleep(d).await;
2634                        continue;
2635                    }
2636                    dlg.finished(false);
2637                    return Err(common::Error::HttpError(err));
2638                }
2639                Ok(res) => {
2640                    let (mut parts, body) = res.into_parts();
2641                    let mut body = common::Body::new(body);
2642                    if !parts.status.is_success() {
2643                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2644                        let error = serde_json::from_str(&common::to_string(&bytes));
2645                        let response = common::to_response(parts, bytes.into());
2646
2647                        if let common::Retry::After(d) =
2648                            dlg.http_failure(&response, error.as_ref().ok())
2649                        {
2650                            sleep(d).await;
2651                            continue;
2652                        }
2653
2654                        dlg.finished(false);
2655
2656                        return Err(match error {
2657                            Ok(value) => common::Error::BadRequest(value),
2658                            _ => common::Error::Failure(response),
2659                        });
2660                    }
2661                    let response = {
2662                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2663                        let encoded = common::to_string(&bytes);
2664                        match serde_json::from_str(&encoded) {
2665                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2666                            Err(error) => {
2667                                dlg.response_json_decode_error(&encoded, &error);
2668                                return Err(common::Error::JsonDecodeError(
2669                                    encoded.to_string(),
2670                                    error,
2671                                ));
2672                            }
2673                        }
2674                    };
2675
2676                    dlg.finished(true);
2677                    return Ok(response);
2678                }
2679            }
2680        }
2681    }
2682
2683    ///
2684    /// Sets the *request* property to the given value.
2685    ///
2686    /// Even though the property as already been set when instantiating this call,
2687    /// we provide this method for API completeness.
2688    pub fn request(mut self, new_value: ClassifyTextRequest) -> DocumentClassifyTextCall<'a, C> {
2689        self._request = new_value;
2690        self
2691    }
2692    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2693    /// while executing the actual API request.
2694    ///
2695    /// ````text
2696    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
2697    /// ````
2698    ///
2699    /// Sets the *delegate* property to the given value.
2700    pub fn delegate(
2701        mut self,
2702        new_value: &'a mut dyn common::Delegate,
2703    ) -> DocumentClassifyTextCall<'a, C> {
2704        self._delegate = Some(new_value);
2705        self
2706    }
2707
2708    /// Set any additional parameter of the query string used in the request.
2709    /// It should be used to set parameters which are not yet available through their own
2710    /// setters.
2711    ///
2712    /// Please note that this method must not be used to set any of the known parameters
2713    /// which have their own setter method. If done anyway, the request will fail.
2714    ///
2715    /// # Additional Parameters
2716    ///
2717    /// * *$.xgafv* (query-string) - V1 error format.
2718    /// * *access_token* (query-string) - OAuth access token.
2719    /// * *alt* (query-string) - Data format for response.
2720    /// * *callback* (query-string) - JSONP
2721    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2722    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
2723    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2724    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2725    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
2726    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2727    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2728    pub fn param<T>(mut self, name: T, value: T) -> DocumentClassifyTextCall<'a, C>
2729    where
2730        T: AsRef<str>,
2731    {
2732        self._additional_params
2733            .insert(name.as_ref().to_string(), value.as_ref().to_string());
2734        self
2735    }
2736
2737    /// Identifies the authorization scope for the method you are building.
2738    ///
2739    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2740    /// [`Scope::CloudLanguage`].
2741    ///
2742    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2743    /// tokens for more than one scope.
2744    ///
2745    /// Usually there is more than one suitable scope to authorize an operation, some of which may
2746    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2747    /// sufficient, a read-write scope will do as well.
2748    pub fn add_scope<St>(mut self, scope: St) -> DocumentClassifyTextCall<'a, C>
2749    where
2750        St: AsRef<str>,
2751    {
2752        self._scopes.insert(String::from(scope.as_ref()));
2753        self
2754    }
2755    /// Identifies the authorization scope(s) for the method you are building.
2756    ///
2757    /// See [`Self::add_scope()`] for details.
2758    pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentClassifyTextCall<'a, C>
2759    where
2760        I: IntoIterator<Item = St>,
2761        St: AsRef<str>,
2762    {
2763        self._scopes
2764            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2765        self
2766    }
2767
2768    /// Removes all scopes, and no default scope will be used either.
2769    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2770    /// for details).
2771    pub fn clear_scopes(mut self) -> DocumentClassifyTextCall<'a, C> {
2772        self._scopes.clear();
2773        self
2774    }
2775}
2776
2777/// Moderates a document for harmful and sensitive categories.
2778///
2779/// A builder for the *moderateText* method supported by a *document* resource.
2780/// It is not used directly, but through a [`DocumentMethods`] instance.
2781///
2782/// # Example
2783///
2784/// Instantiate a resource method builder
2785///
2786/// ```test_harness,no_run
2787/// # extern crate hyper;
2788/// # extern crate hyper_rustls;
2789/// # extern crate google_language1 as language1;
2790/// use language1::api::ModerateTextRequest;
2791/// # async fn dox() {
2792/// # use language1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
2793///
2794/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
2795/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
2796/// #     secret,
2797/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
2798/// # ).build().await.unwrap();
2799///
2800/// # let client = hyper_util::client::legacy::Client::builder(
2801/// #     hyper_util::rt::TokioExecutor::new()
2802/// # )
2803/// # .build(
2804/// #     hyper_rustls::HttpsConnectorBuilder::new()
2805/// #         .with_native_roots()
2806/// #         .unwrap()
2807/// #         .https_or_http()
2808/// #         .enable_http1()
2809/// #         .build()
2810/// # );
2811/// # let mut hub = CloudNaturalLanguage::new(client, auth);
2812/// // As the method needs a request, you would usually fill it with the desired information
2813/// // into the respective structure. Some of the parts shown here might not be applicable !
2814/// // Values shown here are possibly random and not representative !
2815/// let mut req = ModerateTextRequest::default();
2816///
2817/// // You can configure optional parameters by calling the respective setters at will, and
2818/// // execute the final call using `doit()`.
2819/// // Values shown here are possibly random and not representative !
2820/// let result = hub.documents().moderate_text(req)
2821///              .doit().await;
2822/// # }
2823/// ```
2824pub struct DocumentModerateTextCall<'a, C>
2825where
2826    C: 'a,
2827{
2828    hub: &'a CloudNaturalLanguage<C>,
2829    _request: ModerateTextRequest,
2830    _delegate: Option<&'a mut dyn common::Delegate>,
2831    _additional_params: HashMap<String, String>,
2832    _scopes: BTreeSet<String>,
2833}
2834
2835impl<'a, C> common::CallBuilder for DocumentModerateTextCall<'a, C> {}
2836
2837impl<'a, C> DocumentModerateTextCall<'a, C>
2838where
2839    C: common::Connector,
2840{
2841    /// Perform the operation you have build so far.
2842    pub async fn doit(mut self) -> common::Result<(common::Response, ModerateTextResponse)> {
2843        use std::borrow::Cow;
2844        use std::io::{Read, Seek};
2845
2846        use common::{url::Params, ToParts};
2847        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
2848
2849        let mut dd = common::DefaultDelegate;
2850        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
2851        dlg.begin(common::MethodInfo {
2852            id: "language.documents.moderateText",
2853            http_method: hyper::Method::POST,
2854        });
2855
2856        for &field in ["alt"].iter() {
2857            if self._additional_params.contains_key(field) {
2858                dlg.finished(false);
2859                return Err(common::Error::FieldClash(field));
2860            }
2861        }
2862
2863        let mut params = Params::with_capacity(3 + self._additional_params.len());
2864
2865        params.extend(self._additional_params.iter());
2866
2867        params.push("alt", "json");
2868        let mut url = self.hub._base_url.clone() + "v1/documents:moderateText";
2869        if self._scopes.is_empty() {
2870            self._scopes
2871                .insert(Scope::CloudLanguage.as_ref().to_string());
2872        }
2873
2874        let url = params.parse_with_url(&url);
2875
2876        let mut json_mime_type = mime::APPLICATION_JSON;
2877        let mut request_value_reader = {
2878            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2879            common::remove_json_null_values(&mut value);
2880            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2881            serde_json::to_writer(&mut dst, &value).unwrap();
2882            dst
2883        };
2884        let request_size = request_value_reader
2885            .seek(std::io::SeekFrom::End(0))
2886            .unwrap();
2887        request_value_reader
2888            .seek(std::io::SeekFrom::Start(0))
2889            .unwrap();
2890
2891        loop {
2892            let token = match self
2893                .hub
2894                .auth
2895                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2896                .await
2897            {
2898                Ok(token) => token,
2899                Err(e) => match dlg.token(e) {
2900                    Ok(token) => token,
2901                    Err(e) => {
2902                        dlg.finished(false);
2903                        return Err(common::Error::MissingToken(e));
2904                    }
2905                },
2906            };
2907            request_value_reader
2908                .seek(std::io::SeekFrom::Start(0))
2909                .unwrap();
2910            let mut req_result = {
2911                let client = &self.hub.client;
2912                dlg.pre_request();
2913                let mut req_builder = hyper::Request::builder()
2914                    .method(hyper::Method::POST)
2915                    .uri(url.as_str())
2916                    .header(USER_AGENT, self.hub._user_agent.clone());
2917
2918                if let Some(token) = token.as_ref() {
2919                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2920                }
2921
2922                let request = req_builder
2923                    .header(CONTENT_TYPE, json_mime_type.to_string())
2924                    .header(CONTENT_LENGTH, request_size as u64)
2925                    .body(common::to_body(
2926                        request_value_reader.get_ref().clone().into(),
2927                    ));
2928
2929                client.request(request.unwrap()).await
2930            };
2931
2932            match req_result {
2933                Err(err) => {
2934                    if let common::Retry::After(d) = dlg.http_error(&err) {
2935                        sleep(d).await;
2936                        continue;
2937                    }
2938                    dlg.finished(false);
2939                    return Err(common::Error::HttpError(err));
2940                }
2941                Ok(res) => {
2942                    let (mut parts, body) = res.into_parts();
2943                    let mut body = common::Body::new(body);
2944                    if !parts.status.is_success() {
2945                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2946                        let error = serde_json::from_str(&common::to_string(&bytes));
2947                        let response = common::to_response(parts, bytes.into());
2948
2949                        if let common::Retry::After(d) =
2950                            dlg.http_failure(&response, error.as_ref().ok())
2951                        {
2952                            sleep(d).await;
2953                            continue;
2954                        }
2955
2956                        dlg.finished(false);
2957
2958                        return Err(match error {
2959                            Ok(value) => common::Error::BadRequest(value),
2960                            _ => common::Error::Failure(response),
2961                        });
2962                    }
2963                    let response = {
2964                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2965                        let encoded = common::to_string(&bytes);
2966                        match serde_json::from_str(&encoded) {
2967                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2968                            Err(error) => {
2969                                dlg.response_json_decode_error(&encoded, &error);
2970                                return Err(common::Error::JsonDecodeError(
2971                                    encoded.to_string(),
2972                                    error,
2973                                ));
2974                            }
2975                        }
2976                    };
2977
2978                    dlg.finished(true);
2979                    return Ok(response);
2980                }
2981            }
2982        }
2983    }
2984
2985    ///
2986    /// Sets the *request* property to the given value.
2987    ///
2988    /// Even though the property as already been set when instantiating this call,
2989    /// we provide this method for API completeness.
2990    pub fn request(mut self, new_value: ModerateTextRequest) -> DocumentModerateTextCall<'a, C> {
2991        self._request = new_value;
2992        self
2993    }
2994    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2995    /// while executing the actual API request.
2996    ///
2997    /// ````text
2998    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
2999    /// ````
3000    ///
3001    /// Sets the *delegate* property to the given value.
3002    pub fn delegate(
3003        mut self,
3004        new_value: &'a mut dyn common::Delegate,
3005    ) -> DocumentModerateTextCall<'a, C> {
3006        self._delegate = Some(new_value);
3007        self
3008    }
3009
3010    /// Set any additional parameter of the query string used in the request.
3011    /// It should be used to set parameters which are not yet available through their own
3012    /// setters.
3013    ///
3014    /// Please note that this method must not be used to set any of the known parameters
3015    /// which have their own setter method. If done anyway, the request will fail.
3016    ///
3017    /// # Additional Parameters
3018    ///
3019    /// * *$.xgafv* (query-string) - V1 error format.
3020    /// * *access_token* (query-string) - OAuth access token.
3021    /// * *alt* (query-string) - Data format for response.
3022    /// * *callback* (query-string) - JSONP
3023    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
3024    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
3025    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
3026    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
3027    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
3028    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
3029    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
3030    pub fn param<T>(mut self, name: T, value: T) -> DocumentModerateTextCall<'a, C>
3031    where
3032        T: AsRef<str>,
3033    {
3034        self._additional_params
3035            .insert(name.as_ref().to_string(), value.as_ref().to_string());
3036        self
3037    }
3038
3039    /// Identifies the authorization scope for the method you are building.
3040    ///
3041    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
3042    /// [`Scope::CloudLanguage`].
3043    ///
3044    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
3045    /// tokens for more than one scope.
3046    ///
3047    /// Usually there is more than one suitable scope to authorize an operation, some of which may
3048    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
3049    /// sufficient, a read-write scope will do as well.
3050    pub fn add_scope<St>(mut self, scope: St) -> DocumentModerateTextCall<'a, C>
3051    where
3052        St: AsRef<str>,
3053    {
3054        self._scopes.insert(String::from(scope.as_ref()));
3055        self
3056    }
3057    /// Identifies the authorization scope(s) for the method you are building.
3058    ///
3059    /// See [`Self::add_scope()`] for details.
3060    pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentModerateTextCall<'a, C>
3061    where
3062        I: IntoIterator<Item = St>,
3063        St: AsRef<str>,
3064    {
3065        self._scopes
3066            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
3067        self
3068    }
3069
3070    /// Removes all scopes, and no default scope will be used either.
3071    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
3072    /// for details).
3073    pub fn clear_scopes(mut self) -> DocumentModerateTextCall<'a, C> {
3074        self._scopes.clear();
3075        self
3076    }
3077}