google_language1_beta1/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_beta1 as language1_beta1;
53/// use language1_beta1::api::AnalyzeEntitiesRequest;
54/// use language1_beta1::{Result, Error};
55/// # async fn dox() {
56/// use language1_beta1::{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 /// 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 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 sentiment documents](DocumentAnalyzeSentimentCall) (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 AnalyzeSentimentRequest {
223 /// Input document.
224 pub document: Option<Document>,
225 /// The encoding type used by the API to calculate sentence offsets for the sentence sentiment.
226 #[serde(rename = "encodingType")]
227 pub encoding_type: Option<String>,
228}
229
230impl common::RequestValue for AnalyzeSentimentRequest {}
231
232/// The 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 sentiment documents](DocumentAnalyzeSentimentCall) (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 AnalyzeSentimentResponse {
244 /// The overall sentiment of the input document.
245 #[serde(rename = "documentSentiment")]
246 pub document_sentiment: Option<Sentiment>,
247 /// 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.
248 pub language: Option<String>,
249 /// The sentiment for all the sentences in the document.
250 pub sentences: Option<Vec<Sentence>>,
251}
252
253impl common::ResponseResult for AnalyzeSentimentResponse {}
254
255/// The syntax analysis request message.
256///
257/// # Activities
258///
259/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
260/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
261///
262/// * [analyze syntax documents](DocumentAnalyzeSyntaxCall) (request)
263#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
264#[serde_with::serde_as]
265#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
266pub struct AnalyzeSyntaxRequest {
267 /// Input document.
268 pub document: Option<Document>,
269 /// The encoding type used by the API to calculate offsets.
270 #[serde(rename = "encodingType")]
271 pub encoding_type: Option<String>,
272}
273
274impl common::RequestValue for AnalyzeSyntaxRequest {}
275
276/// The syntax analysis response message.
277///
278/// # Activities
279///
280/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
281/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
282///
283/// * [analyze syntax documents](DocumentAnalyzeSyntaxCall) (response)
284#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
285#[serde_with::serde_as]
286#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
287pub struct AnalyzeSyntaxResponse {
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 /// Sentences in the input document.
291 pub sentences: Option<Vec<Sentence>>,
292 /// Tokens, along with their syntactic information, in the input document.
293 pub tokens: Option<Vec<Token>>,
294}
295
296impl common::ResponseResult for AnalyzeSyntaxResponse {}
297
298/// The request message for the text annotation API, which can perform multiple analysis types (sentiment, entities, and syntax) in one call.
299///
300/// # Activities
301///
302/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
303/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
304///
305/// * [annotate text documents](DocumentAnnotateTextCall) (request)
306#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
307#[serde_with::serde_as]
308#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
309pub struct AnnotateTextRequest {
310 /// Input document.
311 pub document: Option<Document>,
312 /// The encoding type used by the API to calculate offsets.
313 #[serde(rename = "encodingType")]
314 pub encoding_type: Option<String>,
315 /// The enabled features.
316 pub features: Option<Features>,
317}
318
319impl common::RequestValue for AnnotateTextRequest {}
320
321/// The text annotations response message.
322///
323/// # Activities
324///
325/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
326/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
327///
328/// * [annotate text documents](DocumentAnnotateTextCall) (response)
329#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
330#[serde_with::serde_as]
331#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
332pub struct AnnotateTextResponse {
333 /// The overall sentiment for the document. Populated if the user enables AnnotateTextRequest.Features.extract_document_sentiment.
334 #[serde(rename = "documentSentiment")]
335 pub document_sentiment: Option<Sentiment>,
336 /// Entities, along with their semantic information, in the input document. Populated if the user enables AnnotateTextRequest.Features.extract_entities.
337 pub entities: Option<Vec<Entity>>,
338 /// 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.
339 pub language: Option<String>,
340 /// Sentences in the input document. Populated if the user enables AnnotateTextRequest.Features.extract_syntax.
341 pub sentences: Option<Vec<Sentence>>,
342 /// Tokens, along with their syntactic information, in the input document. Populated if the user enables AnnotateTextRequest.Features.extract_syntax.
343 pub tokens: Option<Vec<Token>>,
344}
345
346impl common::ResponseResult for AnnotateTextResponse {}
347
348/// Represents dependency parse tree information for a token.
349///
350/// This type is not used in any activity, and only used as *part* of another schema.
351///
352#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
353#[serde_with::serde_as]
354#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
355pub struct DependencyEdge {
356 /// 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.
357 #[serde(rename = "headTokenIndex")]
358 pub head_token_index: Option<i32>,
359 /// The parse label for the token.
360 pub label: Option<String>,
361}
362
363impl common::Part for DependencyEdge {}
364
365/// \################################################################ # Represents the input to API methods.
366///
367/// # Activities
368///
369/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
370/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
371///
372/// * [analyze entities documents](DocumentAnalyzeEntityCall) (none)
373/// * [analyze sentiment documents](DocumentAnalyzeSentimentCall) (none)
374/// * [analyze syntax documents](DocumentAnalyzeSyntaxCall) (none)
375/// * [annotate text documents](DocumentAnnotateTextCall) (none)
376#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
377#[serde_with::serde_as]
378#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
379pub struct Document {
380 /// The content of the input in string format. Cloud audit logging exempt since it is based on user data.
381 pub content: Option<String>,
382 /// 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.
383 #[serde(rename = "gcsContentUri")]
384 pub gcs_content_uri: Option<String>,
385 /// 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.
386 pub language: Option<String>,
387 /// Required. If the type is not set or is `TYPE_UNSPECIFIED`, returns an `INVALID_ARGUMENT` error.
388 #[serde(rename = "type")]
389 pub type_: Option<String>,
390}
391
392impl common::Resource for Document {}
393
394/// 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.
395///
396/// This type is not used in any activity, and only used as *part* of another schema.
397///
398#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
399#[serde_with::serde_as]
400#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
401pub struct Entity {
402 /// The mentions of this entity in the input document. The API currently supports proper noun mentions.
403 pub mentions: Option<Vec<EntityMention>>,
404 /// Metadata associated with the entity. Currently, Wikipedia URLs and Knowledge Graph MIDs are provided, if available. The associated keys are "wikipedia_url" and "mid", respectively.
405 pub metadata: Option<HashMap<String, String>>,
406 /// The representative name for the entity.
407 pub name: Option<String>,
408 /// 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.
409 pub salience: Option<f32>,
410 /// The entity type.
411 #[serde(rename = "type")]
412 pub type_: Option<String>,
413}
414
415impl common::Part for Entity {}
416
417/// Represents a mention for an entity in the text. Currently, proper noun mentions are supported.
418///
419/// This type is not used in any activity, and only used as *part* of another schema.
420///
421#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
422#[serde_with::serde_as]
423#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
424pub struct EntityMention {
425 /// The mention text.
426 pub text: Option<TextSpan>,
427 /// The type of the entity mention.
428 #[serde(rename = "type")]
429 pub type_: Option<String>,
430}
431
432impl common::Part for EntityMention {}
433
434/// All available features for sentiment, syntax, and semantic analysis. Setting each one to true will enable that specific analysis for the input.
435///
436/// This type is not used in any activity, and only used as *part* of another schema.
437///
438#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
439#[serde_with::serde_as]
440#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
441pub struct Features {
442 /// Extract document-level sentiment.
443 #[serde(rename = "extractDocumentSentiment")]
444 pub extract_document_sentiment: Option<bool>,
445 /// Extract entities.
446 #[serde(rename = "extractEntities")]
447 pub extract_entities: Option<bool>,
448 /// Extract syntax information.
449 #[serde(rename = "extractSyntax")]
450 pub extract_syntax: Option<bool>,
451}
452
453impl common::Part for Features {}
454
455/// Represents part of speech information for a token.
456///
457/// This type is not used in any activity, and only used as *part* of another schema.
458///
459#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
460#[serde_with::serde_as]
461#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
462pub struct PartOfSpeech {
463 /// The grammatical aspect.
464 pub aspect: Option<String>,
465 /// The grammatical case.
466 pub case: Option<String>,
467 /// The grammatical form.
468 pub form: Option<String>,
469 /// The grammatical gender.
470 pub gender: Option<String>,
471 /// The grammatical mood.
472 pub mood: Option<String>,
473 /// The grammatical number.
474 pub number: Option<String>,
475 /// The grammatical person.
476 pub person: Option<String>,
477 /// The grammatical properness.
478 pub proper: Option<String>,
479 /// The grammatical reciprocity.
480 pub reciprocity: Option<String>,
481 /// The part of speech tag.
482 pub tag: Option<String>,
483 /// The grammatical tense.
484 pub tense: Option<String>,
485 /// The grammatical voice.
486 pub voice: Option<String>,
487}
488
489impl common::Part for PartOfSpeech {}
490
491/// Represents a sentence in the input document.
492///
493/// This type is not used in any activity, and only used as *part* of another schema.
494///
495#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
496#[serde_with::serde_as]
497#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
498pub struct Sentence {
499 /// For calls to AnalyzeSentiment or if AnnotateTextRequest.Features.extract_document_sentiment is set to true, this field will contain the sentiment for the sentence.
500 pub sentiment: Option<Sentiment>,
501 /// The sentence text.
502 pub text: Option<TextSpan>,
503}
504
505impl common::Part for Sentence {}
506
507/// Represents the feeling associated with the entire text or entities in the text.
508///
509/// This type is not used in any activity, and only used as *part* of another schema.
510///
511#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
512#[serde_with::serde_as]
513#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
514pub struct Sentiment {
515 /// A non-negative number in the [0, +inf) range, which represents the absolute magnitude of sentiment regardless of score (positive or negative).
516 pub magnitude: Option<f32>,
517 /// DEPRECATED FIELD - This field is being deprecated in favor of score. Please refer to our documentation at https://cloud.google.com/natural-language/docs for more information.
518 pub polarity: Option<f32>,
519 /// Sentiment score between -1.0 (negative sentiment) and 1.0 (positive sentiment).
520 pub score: Option<f32>,
521}
522
523impl common::Part for Sentiment {}
524
525/// Represents an output piece of text.
526///
527/// This type is not used in any activity, and only used as *part* of another schema.
528///
529#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
530#[serde_with::serde_as]
531#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
532pub struct TextSpan {
533 /// The API calculates the beginning offset of the content in the original document according to the EncodingType specified in the API request.
534 #[serde(rename = "beginOffset")]
535 pub begin_offset: Option<i32>,
536 /// The content of the output text.
537 pub content: Option<String>,
538}
539
540impl common::Part for TextSpan {}
541
542/// Represents the smallest syntactic building block of the text.
543///
544/// This type is not used in any activity, and only used as *part* of another schema.
545///
546#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
547#[serde_with::serde_as]
548#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
549pub struct Token {
550 /// Dependency tree parse for this token.
551 #[serde(rename = "dependencyEdge")]
552 pub dependency_edge: Option<DependencyEdge>,
553 /// [Lemma](https://en.wikipedia.org/wiki/Lemma_%28morphology%29) of the token.
554 pub lemma: Option<String>,
555 /// Parts of speech tag for this token.
556 #[serde(rename = "partOfSpeech")]
557 pub part_of_speech: Option<PartOfSpeech>,
558 /// The token text.
559 pub text: Option<TextSpan>,
560}
561
562impl common::Part for Token {}
563
564// ###################
565// MethodBuilders ###
566// #################
567
568/// A builder providing access to all methods supported on *document* resources.
569/// It is not used directly, but through the [`CloudNaturalLanguage`] hub.
570///
571/// # Example
572///
573/// Instantiate a resource builder
574///
575/// ```test_harness,no_run
576/// extern crate hyper;
577/// extern crate hyper_rustls;
578/// extern crate google_language1_beta1 as language1_beta1;
579///
580/// # async fn dox() {
581/// use language1_beta1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
582///
583/// let secret: yup_oauth2::ApplicationSecret = Default::default();
584/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
585/// secret,
586/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
587/// ).build().await.unwrap();
588///
589/// let client = hyper_util::client::legacy::Client::builder(
590/// hyper_util::rt::TokioExecutor::new()
591/// )
592/// .build(
593/// hyper_rustls::HttpsConnectorBuilder::new()
594/// .with_native_roots()
595/// .unwrap()
596/// .https_or_http()
597/// .enable_http1()
598/// .build()
599/// );
600/// let mut hub = CloudNaturalLanguage::new(client, auth);
601/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
602/// // like `analyze_entities(...)`, `analyze_sentiment(...)`, `analyze_syntax(...)` and `annotate_text(...)`
603/// // to build up your call.
604/// let rb = hub.documents();
605/// # }
606/// ```
607pub struct DocumentMethods<'a, C>
608where
609 C: 'a,
610{
611 hub: &'a CloudNaturalLanguage<C>,
612}
613
614impl<'a, C> common::MethodsBuilder for DocumentMethods<'a, C> {}
615
616impl<'a, C> DocumentMethods<'a, C> {
617 /// Create a builder to help you perform the following task:
618 ///
619 /// Finds named entities (currently proper names and common nouns) in the text along with entity types, salience, mentions for each entity, and other properties.
620 ///
621 /// # Arguments
622 ///
623 /// * `request` - No description provided.
624 pub fn analyze_entities(
625 &self,
626 request: AnalyzeEntitiesRequest,
627 ) -> DocumentAnalyzeEntityCall<'a, C> {
628 DocumentAnalyzeEntityCall {
629 hub: self.hub,
630 _request: request,
631 _delegate: Default::default(),
632 _additional_params: Default::default(),
633 _scopes: Default::default(),
634 }
635 }
636
637 /// Create a builder to help you perform the following task:
638 ///
639 /// Analyzes the sentiment of the provided text.
640 ///
641 /// # Arguments
642 ///
643 /// * `request` - No description provided.
644 pub fn analyze_sentiment(
645 &self,
646 request: AnalyzeSentimentRequest,
647 ) -> DocumentAnalyzeSentimentCall<'a, C> {
648 DocumentAnalyzeSentimentCall {
649 hub: self.hub,
650 _request: request,
651 _delegate: Default::default(),
652 _additional_params: Default::default(),
653 _scopes: Default::default(),
654 }
655 }
656
657 /// Create a builder to help you perform the following task:
658 ///
659 /// Analyzes the syntax of the text and provides sentence boundaries and tokenization along with part of speech tags, dependency trees, and other properties.
660 ///
661 /// # Arguments
662 ///
663 /// * `request` - No description provided.
664 pub fn analyze_syntax(
665 &self,
666 request: AnalyzeSyntaxRequest,
667 ) -> DocumentAnalyzeSyntaxCall<'a, C> {
668 DocumentAnalyzeSyntaxCall {
669 hub: self.hub,
670 _request: request,
671 _delegate: Default::default(),
672 _additional_params: Default::default(),
673 _scopes: Default::default(),
674 }
675 }
676
677 /// Create a builder to help you perform the following task:
678 ///
679 /// A convenience method that provides all the features that analyzeSentiment, analyzeEntities, and analyzeSyntax provide in one call.
680 ///
681 /// # Arguments
682 ///
683 /// * `request` - No description provided.
684 pub fn annotate_text(&self, request: AnnotateTextRequest) -> DocumentAnnotateTextCall<'a, C> {
685 DocumentAnnotateTextCall {
686 hub: self.hub,
687 _request: request,
688 _delegate: Default::default(),
689 _additional_params: Default::default(),
690 _scopes: Default::default(),
691 }
692 }
693}
694
695// ###################
696// CallBuilders ###
697// #################
698
699/// Finds named entities (currently proper names and common nouns) in the text along with entity types, salience, mentions for each entity, and other properties.
700///
701/// A builder for the *analyzeEntities* method supported by a *document* resource.
702/// It is not used directly, but through a [`DocumentMethods`] instance.
703///
704/// # Example
705///
706/// Instantiate a resource method builder
707///
708/// ```test_harness,no_run
709/// # extern crate hyper;
710/// # extern crate hyper_rustls;
711/// # extern crate google_language1_beta1 as language1_beta1;
712/// use language1_beta1::api::AnalyzeEntitiesRequest;
713/// # async fn dox() {
714/// # use language1_beta1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
715///
716/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
717/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
718/// # secret,
719/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
720/// # ).build().await.unwrap();
721///
722/// # let client = hyper_util::client::legacy::Client::builder(
723/// # hyper_util::rt::TokioExecutor::new()
724/// # )
725/// # .build(
726/// # hyper_rustls::HttpsConnectorBuilder::new()
727/// # .with_native_roots()
728/// # .unwrap()
729/// # .https_or_http()
730/// # .enable_http1()
731/// # .build()
732/// # );
733/// # let mut hub = CloudNaturalLanguage::new(client, auth);
734/// // As the method needs a request, you would usually fill it with the desired information
735/// // into the respective structure. Some of the parts shown here might not be applicable !
736/// // Values shown here are possibly random and not representative !
737/// let mut req = AnalyzeEntitiesRequest::default();
738///
739/// // You can configure optional parameters by calling the respective setters at will, and
740/// // execute the final call using `doit()`.
741/// // Values shown here are possibly random and not representative !
742/// let result = hub.documents().analyze_entities(req)
743/// .doit().await;
744/// # }
745/// ```
746pub struct DocumentAnalyzeEntityCall<'a, C>
747where
748 C: 'a,
749{
750 hub: &'a CloudNaturalLanguage<C>,
751 _request: AnalyzeEntitiesRequest,
752 _delegate: Option<&'a mut dyn common::Delegate>,
753 _additional_params: HashMap<String, String>,
754 _scopes: BTreeSet<String>,
755}
756
757impl<'a, C> common::CallBuilder for DocumentAnalyzeEntityCall<'a, C> {}
758
759impl<'a, C> DocumentAnalyzeEntityCall<'a, C>
760where
761 C: common::Connector,
762{
763 /// Perform the operation you have build so far.
764 pub async fn doit(mut self) -> common::Result<(common::Response, AnalyzeEntitiesResponse)> {
765 use std::borrow::Cow;
766 use std::io::{Read, Seek};
767
768 use common::{url::Params, ToParts};
769 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
770
771 let mut dd = common::DefaultDelegate;
772 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
773 dlg.begin(common::MethodInfo {
774 id: "language.documents.analyzeEntities",
775 http_method: hyper::Method::POST,
776 });
777
778 for &field in ["alt"].iter() {
779 if self._additional_params.contains_key(field) {
780 dlg.finished(false);
781 return Err(common::Error::FieldClash(field));
782 }
783 }
784
785 let mut params = Params::with_capacity(3 + self._additional_params.len());
786
787 params.extend(self._additional_params.iter());
788
789 params.push("alt", "json");
790 let mut url = self.hub._base_url.clone() + "v1beta1/documents:analyzeEntities";
791 if self._scopes.is_empty() {
792 self._scopes
793 .insert(Scope::CloudLanguage.as_ref().to_string());
794 }
795
796 let url = params.parse_with_url(&url);
797
798 let mut json_mime_type = mime::APPLICATION_JSON;
799 let mut request_value_reader = {
800 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
801 common::remove_json_null_values(&mut value);
802 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
803 serde_json::to_writer(&mut dst, &value).unwrap();
804 dst
805 };
806 let request_size = request_value_reader
807 .seek(std::io::SeekFrom::End(0))
808 .unwrap();
809 request_value_reader
810 .seek(std::io::SeekFrom::Start(0))
811 .unwrap();
812
813 loop {
814 let token = match self
815 .hub
816 .auth
817 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
818 .await
819 {
820 Ok(token) => token,
821 Err(e) => match dlg.token(e) {
822 Ok(token) => token,
823 Err(e) => {
824 dlg.finished(false);
825 return Err(common::Error::MissingToken(e));
826 }
827 },
828 };
829 request_value_reader
830 .seek(std::io::SeekFrom::Start(0))
831 .unwrap();
832 let mut req_result = {
833 let client = &self.hub.client;
834 dlg.pre_request();
835 let mut req_builder = hyper::Request::builder()
836 .method(hyper::Method::POST)
837 .uri(url.as_str())
838 .header(USER_AGENT, self.hub._user_agent.clone());
839
840 if let Some(token) = token.as_ref() {
841 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
842 }
843
844 let request = req_builder
845 .header(CONTENT_TYPE, json_mime_type.to_string())
846 .header(CONTENT_LENGTH, request_size as u64)
847 .body(common::to_body(
848 request_value_reader.get_ref().clone().into(),
849 ));
850
851 client.request(request.unwrap()).await
852 };
853
854 match req_result {
855 Err(err) => {
856 if let common::Retry::After(d) = dlg.http_error(&err) {
857 sleep(d).await;
858 continue;
859 }
860 dlg.finished(false);
861 return Err(common::Error::HttpError(err));
862 }
863 Ok(res) => {
864 let (mut parts, body) = res.into_parts();
865 let mut body = common::Body::new(body);
866 if !parts.status.is_success() {
867 let bytes = common::to_bytes(body).await.unwrap_or_default();
868 let error = serde_json::from_str(&common::to_string(&bytes));
869 let response = common::to_response(parts, bytes.into());
870
871 if let common::Retry::After(d) =
872 dlg.http_failure(&response, error.as_ref().ok())
873 {
874 sleep(d).await;
875 continue;
876 }
877
878 dlg.finished(false);
879
880 return Err(match error {
881 Ok(value) => common::Error::BadRequest(value),
882 _ => common::Error::Failure(response),
883 });
884 }
885 let response = {
886 let bytes = common::to_bytes(body).await.unwrap_or_default();
887 let encoded = common::to_string(&bytes);
888 match serde_json::from_str(&encoded) {
889 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
890 Err(error) => {
891 dlg.response_json_decode_error(&encoded, &error);
892 return Err(common::Error::JsonDecodeError(
893 encoded.to_string(),
894 error,
895 ));
896 }
897 }
898 };
899
900 dlg.finished(true);
901 return Ok(response);
902 }
903 }
904 }
905 }
906
907 ///
908 /// Sets the *request* property to the given value.
909 ///
910 /// Even though the property as already been set when instantiating this call,
911 /// we provide this method for API completeness.
912 pub fn request(
913 mut self,
914 new_value: AnalyzeEntitiesRequest,
915 ) -> DocumentAnalyzeEntityCall<'a, C> {
916 self._request = new_value;
917 self
918 }
919 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
920 /// while executing the actual API request.
921 ///
922 /// ````text
923 /// It should be used to handle progress information, and to implement a certain level of resilience.
924 /// ````
925 ///
926 /// Sets the *delegate* property to the given value.
927 pub fn delegate(
928 mut self,
929 new_value: &'a mut dyn common::Delegate,
930 ) -> DocumentAnalyzeEntityCall<'a, C> {
931 self._delegate = Some(new_value);
932 self
933 }
934
935 /// Set any additional parameter of the query string used in the request.
936 /// It should be used to set parameters which are not yet available through their own
937 /// setters.
938 ///
939 /// Please note that this method must not be used to set any of the known parameters
940 /// which have their own setter method. If done anyway, the request will fail.
941 ///
942 /// # Additional Parameters
943 ///
944 /// * *$.xgafv* (query-string) - V1 error format.
945 /// * *access_token* (query-string) - OAuth access token.
946 /// * *alt* (query-string) - Data format for response.
947 /// * *callback* (query-string) - JSONP
948 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
949 /// * *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.
950 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
951 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
952 /// * *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.
953 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
954 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
955 pub fn param<T>(mut self, name: T, value: T) -> DocumentAnalyzeEntityCall<'a, C>
956 where
957 T: AsRef<str>,
958 {
959 self._additional_params
960 .insert(name.as_ref().to_string(), value.as_ref().to_string());
961 self
962 }
963
964 /// Identifies the authorization scope for the method you are building.
965 ///
966 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
967 /// [`Scope::CloudLanguage`].
968 ///
969 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
970 /// tokens for more than one scope.
971 ///
972 /// Usually there is more than one suitable scope to authorize an operation, some of which may
973 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
974 /// sufficient, a read-write scope will do as well.
975 pub fn add_scope<St>(mut self, scope: St) -> DocumentAnalyzeEntityCall<'a, C>
976 where
977 St: AsRef<str>,
978 {
979 self._scopes.insert(String::from(scope.as_ref()));
980 self
981 }
982 /// Identifies the authorization scope(s) for the method you are building.
983 ///
984 /// See [`Self::add_scope()`] for details.
985 pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentAnalyzeEntityCall<'a, C>
986 where
987 I: IntoIterator<Item = St>,
988 St: AsRef<str>,
989 {
990 self._scopes
991 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
992 self
993 }
994
995 /// Removes all scopes, and no default scope will be used either.
996 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
997 /// for details).
998 pub fn clear_scopes(mut self) -> DocumentAnalyzeEntityCall<'a, C> {
999 self._scopes.clear();
1000 self
1001 }
1002}
1003
1004/// Analyzes the sentiment of the provided text.
1005///
1006/// A builder for the *analyzeSentiment* method supported by a *document* resource.
1007/// It is not used directly, but through a [`DocumentMethods`] instance.
1008///
1009/// # Example
1010///
1011/// Instantiate a resource method builder
1012///
1013/// ```test_harness,no_run
1014/// # extern crate hyper;
1015/// # extern crate hyper_rustls;
1016/// # extern crate google_language1_beta1 as language1_beta1;
1017/// use language1_beta1::api::AnalyzeSentimentRequest;
1018/// # async fn dox() {
1019/// # use language1_beta1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1020///
1021/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1022/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1023/// # secret,
1024/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1025/// # ).build().await.unwrap();
1026///
1027/// # let client = hyper_util::client::legacy::Client::builder(
1028/// # hyper_util::rt::TokioExecutor::new()
1029/// # )
1030/// # .build(
1031/// # hyper_rustls::HttpsConnectorBuilder::new()
1032/// # .with_native_roots()
1033/// # .unwrap()
1034/// # .https_or_http()
1035/// # .enable_http1()
1036/// # .build()
1037/// # );
1038/// # let mut hub = CloudNaturalLanguage::new(client, auth);
1039/// // As the method needs a request, you would usually fill it with the desired information
1040/// // into the respective structure. Some of the parts shown here might not be applicable !
1041/// // Values shown here are possibly random and not representative !
1042/// let mut req = AnalyzeSentimentRequest::default();
1043///
1044/// // You can configure optional parameters by calling the respective setters at will, and
1045/// // execute the final call using `doit()`.
1046/// // Values shown here are possibly random and not representative !
1047/// let result = hub.documents().analyze_sentiment(req)
1048/// .doit().await;
1049/// # }
1050/// ```
1051pub struct DocumentAnalyzeSentimentCall<'a, C>
1052where
1053 C: 'a,
1054{
1055 hub: &'a CloudNaturalLanguage<C>,
1056 _request: AnalyzeSentimentRequest,
1057 _delegate: Option<&'a mut dyn common::Delegate>,
1058 _additional_params: HashMap<String, String>,
1059 _scopes: BTreeSet<String>,
1060}
1061
1062impl<'a, C> common::CallBuilder for DocumentAnalyzeSentimentCall<'a, C> {}
1063
1064impl<'a, C> DocumentAnalyzeSentimentCall<'a, C>
1065where
1066 C: common::Connector,
1067{
1068 /// Perform the operation you have build so far.
1069 pub async fn doit(mut self) -> common::Result<(common::Response, AnalyzeSentimentResponse)> {
1070 use std::borrow::Cow;
1071 use std::io::{Read, Seek};
1072
1073 use common::{url::Params, ToParts};
1074 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1075
1076 let mut dd = common::DefaultDelegate;
1077 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1078 dlg.begin(common::MethodInfo {
1079 id: "language.documents.analyzeSentiment",
1080 http_method: hyper::Method::POST,
1081 });
1082
1083 for &field in ["alt"].iter() {
1084 if self._additional_params.contains_key(field) {
1085 dlg.finished(false);
1086 return Err(common::Error::FieldClash(field));
1087 }
1088 }
1089
1090 let mut params = Params::with_capacity(3 + self._additional_params.len());
1091
1092 params.extend(self._additional_params.iter());
1093
1094 params.push("alt", "json");
1095 let mut url = self.hub._base_url.clone() + "v1beta1/documents:analyzeSentiment";
1096 if self._scopes.is_empty() {
1097 self._scopes
1098 .insert(Scope::CloudLanguage.as_ref().to_string());
1099 }
1100
1101 let url = params.parse_with_url(&url);
1102
1103 let mut json_mime_type = mime::APPLICATION_JSON;
1104 let mut request_value_reader = {
1105 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1106 common::remove_json_null_values(&mut value);
1107 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1108 serde_json::to_writer(&mut dst, &value).unwrap();
1109 dst
1110 };
1111 let request_size = request_value_reader
1112 .seek(std::io::SeekFrom::End(0))
1113 .unwrap();
1114 request_value_reader
1115 .seek(std::io::SeekFrom::Start(0))
1116 .unwrap();
1117
1118 loop {
1119 let token = match self
1120 .hub
1121 .auth
1122 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1123 .await
1124 {
1125 Ok(token) => token,
1126 Err(e) => match dlg.token(e) {
1127 Ok(token) => token,
1128 Err(e) => {
1129 dlg.finished(false);
1130 return Err(common::Error::MissingToken(e));
1131 }
1132 },
1133 };
1134 request_value_reader
1135 .seek(std::io::SeekFrom::Start(0))
1136 .unwrap();
1137 let mut req_result = {
1138 let client = &self.hub.client;
1139 dlg.pre_request();
1140 let mut req_builder = hyper::Request::builder()
1141 .method(hyper::Method::POST)
1142 .uri(url.as_str())
1143 .header(USER_AGENT, self.hub._user_agent.clone());
1144
1145 if let Some(token) = token.as_ref() {
1146 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1147 }
1148
1149 let request = req_builder
1150 .header(CONTENT_TYPE, json_mime_type.to_string())
1151 .header(CONTENT_LENGTH, request_size as u64)
1152 .body(common::to_body(
1153 request_value_reader.get_ref().clone().into(),
1154 ));
1155
1156 client.request(request.unwrap()).await
1157 };
1158
1159 match req_result {
1160 Err(err) => {
1161 if let common::Retry::After(d) = dlg.http_error(&err) {
1162 sleep(d).await;
1163 continue;
1164 }
1165 dlg.finished(false);
1166 return Err(common::Error::HttpError(err));
1167 }
1168 Ok(res) => {
1169 let (mut parts, body) = res.into_parts();
1170 let mut body = common::Body::new(body);
1171 if !parts.status.is_success() {
1172 let bytes = common::to_bytes(body).await.unwrap_or_default();
1173 let error = serde_json::from_str(&common::to_string(&bytes));
1174 let response = common::to_response(parts, bytes.into());
1175
1176 if let common::Retry::After(d) =
1177 dlg.http_failure(&response, error.as_ref().ok())
1178 {
1179 sleep(d).await;
1180 continue;
1181 }
1182
1183 dlg.finished(false);
1184
1185 return Err(match error {
1186 Ok(value) => common::Error::BadRequest(value),
1187 _ => common::Error::Failure(response),
1188 });
1189 }
1190 let response = {
1191 let bytes = common::to_bytes(body).await.unwrap_or_default();
1192 let encoded = common::to_string(&bytes);
1193 match serde_json::from_str(&encoded) {
1194 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1195 Err(error) => {
1196 dlg.response_json_decode_error(&encoded, &error);
1197 return Err(common::Error::JsonDecodeError(
1198 encoded.to_string(),
1199 error,
1200 ));
1201 }
1202 }
1203 };
1204
1205 dlg.finished(true);
1206 return Ok(response);
1207 }
1208 }
1209 }
1210 }
1211
1212 ///
1213 /// Sets the *request* property to the given value.
1214 ///
1215 /// Even though the property as already been set when instantiating this call,
1216 /// we provide this method for API completeness.
1217 pub fn request(
1218 mut self,
1219 new_value: AnalyzeSentimentRequest,
1220 ) -> DocumentAnalyzeSentimentCall<'a, C> {
1221 self._request = new_value;
1222 self
1223 }
1224 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1225 /// while executing the actual API request.
1226 ///
1227 /// ````text
1228 /// It should be used to handle progress information, and to implement a certain level of resilience.
1229 /// ````
1230 ///
1231 /// Sets the *delegate* property to the given value.
1232 pub fn delegate(
1233 mut self,
1234 new_value: &'a mut dyn common::Delegate,
1235 ) -> DocumentAnalyzeSentimentCall<'a, C> {
1236 self._delegate = Some(new_value);
1237 self
1238 }
1239
1240 /// Set any additional parameter of the query string used in the request.
1241 /// It should be used to set parameters which are not yet available through their own
1242 /// setters.
1243 ///
1244 /// Please note that this method must not be used to set any of the known parameters
1245 /// which have their own setter method. If done anyway, the request will fail.
1246 ///
1247 /// # Additional Parameters
1248 ///
1249 /// * *$.xgafv* (query-string) - V1 error format.
1250 /// * *access_token* (query-string) - OAuth access token.
1251 /// * *alt* (query-string) - Data format for response.
1252 /// * *callback* (query-string) - JSONP
1253 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1254 /// * *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.
1255 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1256 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1257 /// * *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.
1258 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1259 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1260 pub fn param<T>(mut self, name: T, value: T) -> DocumentAnalyzeSentimentCall<'a, C>
1261 where
1262 T: AsRef<str>,
1263 {
1264 self._additional_params
1265 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1266 self
1267 }
1268
1269 /// Identifies the authorization scope for the method you are building.
1270 ///
1271 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1272 /// [`Scope::CloudLanguage`].
1273 ///
1274 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1275 /// tokens for more than one scope.
1276 ///
1277 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1278 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1279 /// sufficient, a read-write scope will do as well.
1280 pub fn add_scope<St>(mut self, scope: St) -> DocumentAnalyzeSentimentCall<'a, C>
1281 where
1282 St: AsRef<str>,
1283 {
1284 self._scopes.insert(String::from(scope.as_ref()));
1285 self
1286 }
1287 /// Identifies the authorization scope(s) for the method you are building.
1288 ///
1289 /// See [`Self::add_scope()`] for details.
1290 pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentAnalyzeSentimentCall<'a, C>
1291 where
1292 I: IntoIterator<Item = St>,
1293 St: AsRef<str>,
1294 {
1295 self._scopes
1296 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1297 self
1298 }
1299
1300 /// Removes all scopes, and no default scope will be used either.
1301 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1302 /// for details).
1303 pub fn clear_scopes(mut self) -> DocumentAnalyzeSentimentCall<'a, C> {
1304 self._scopes.clear();
1305 self
1306 }
1307}
1308
1309/// Analyzes the syntax of the text and provides sentence boundaries and tokenization along with part of speech tags, dependency trees, and other properties.
1310///
1311/// A builder for the *analyzeSyntax* method supported by a *document* resource.
1312/// It is not used directly, but through a [`DocumentMethods`] instance.
1313///
1314/// # Example
1315///
1316/// Instantiate a resource method builder
1317///
1318/// ```test_harness,no_run
1319/// # extern crate hyper;
1320/// # extern crate hyper_rustls;
1321/// # extern crate google_language1_beta1 as language1_beta1;
1322/// use language1_beta1::api::AnalyzeSyntaxRequest;
1323/// # async fn dox() {
1324/// # use language1_beta1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1325///
1326/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1327/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1328/// # secret,
1329/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1330/// # ).build().await.unwrap();
1331///
1332/// # let client = hyper_util::client::legacy::Client::builder(
1333/// # hyper_util::rt::TokioExecutor::new()
1334/// # )
1335/// # .build(
1336/// # hyper_rustls::HttpsConnectorBuilder::new()
1337/// # .with_native_roots()
1338/// # .unwrap()
1339/// # .https_or_http()
1340/// # .enable_http1()
1341/// # .build()
1342/// # );
1343/// # let mut hub = CloudNaturalLanguage::new(client, auth);
1344/// // As the method needs a request, you would usually fill it with the desired information
1345/// // into the respective structure. Some of the parts shown here might not be applicable !
1346/// // Values shown here are possibly random and not representative !
1347/// let mut req = AnalyzeSyntaxRequest::default();
1348///
1349/// // You can configure optional parameters by calling the respective setters at will, and
1350/// // execute the final call using `doit()`.
1351/// // Values shown here are possibly random and not representative !
1352/// let result = hub.documents().analyze_syntax(req)
1353/// .doit().await;
1354/// # }
1355/// ```
1356pub struct DocumentAnalyzeSyntaxCall<'a, C>
1357where
1358 C: 'a,
1359{
1360 hub: &'a CloudNaturalLanguage<C>,
1361 _request: AnalyzeSyntaxRequest,
1362 _delegate: Option<&'a mut dyn common::Delegate>,
1363 _additional_params: HashMap<String, String>,
1364 _scopes: BTreeSet<String>,
1365}
1366
1367impl<'a, C> common::CallBuilder for DocumentAnalyzeSyntaxCall<'a, C> {}
1368
1369impl<'a, C> DocumentAnalyzeSyntaxCall<'a, C>
1370where
1371 C: common::Connector,
1372{
1373 /// Perform the operation you have build so far.
1374 pub async fn doit(mut self) -> common::Result<(common::Response, AnalyzeSyntaxResponse)> {
1375 use std::borrow::Cow;
1376 use std::io::{Read, Seek};
1377
1378 use common::{url::Params, ToParts};
1379 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1380
1381 let mut dd = common::DefaultDelegate;
1382 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1383 dlg.begin(common::MethodInfo {
1384 id: "language.documents.analyzeSyntax",
1385 http_method: hyper::Method::POST,
1386 });
1387
1388 for &field in ["alt"].iter() {
1389 if self._additional_params.contains_key(field) {
1390 dlg.finished(false);
1391 return Err(common::Error::FieldClash(field));
1392 }
1393 }
1394
1395 let mut params = Params::with_capacity(3 + self._additional_params.len());
1396
1397 params.extend(self._additional_params.iter());
1398
1399 params.push("alt", "json");
1400 let mut url = self.hub._base_url.clone() + "v1beta1/documents:analyzeSyntax";
1401 if self._scopes.is_empty() {
1402 self._scopes
1403 .insert(Scope::CloudLanguage.as_ref().to_string());
1404 }
1405
1406 let url = params.parse_with_url(&url);
1407
1408 let mut json_mime_type = mime::APPLICATION_JSON;
1409 let mut request_value_reader = {
1410 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1411 common::remove_json_null_values(&mut value);
1412 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1413 serde_json::to_writer(&mut dst, &value).unwrap();
1414 dst
1415 };
1416 let request_size = request_value_reader
1417 .seek(std::io::SeekFrom::End(0))
1418 .unwrap();
1419 request_value_reader
1420 .seek(std::io::SeekFrom::Start(0))
1421 .unwrap();
1422
1423 loop {
1424 let token = match self
1425 .hub
1426 .auth
1427 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1428 .await
1429 {
1430 Ok(token) => token,
1431 Err(e) => match dlg.token(e) {
1432 Ok(token) => token,
1433 Err(e) => {
1434 dlg.finished(false);
1435 return Err(common::Error::MissingToken(e));
1436 }
1437 },
1438 };
1439 request_value_reader
1440 .seek(std::io::SeekFrom::Start(0))
1441 .unwrap();
1442 let mut req_result = {
1443 let client = &self.hub.client;
1444 dlg.pre_request();
1445 let mut req_builder = hyper::Request::builder()
1446 .method(hyper::Method::POST)
1447 .uri(url.as_str())
1448 .header(USER_AGENT, self.hub._user_agent.clone());
1449
1450 if let Some(token) = token.as_ref() {
1451 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1452 }
1453
1454 let request = req_builder
1455 .header(CONTENT_TYPE, json_mime_type.to_string())
1456 .header(CONTENT_LENGTH, request_size as u64)
1457 .body(common::to_body(
1458 request_value_reader.get_ref().clone().into(),
1459 ));
1460
1461 client.request(request.unwrap()).await
1462 };
1463
1464 match req_result {
1465 Err(err) => {
1466 if let common::Retry::After(d) = dlg.http_error(&err) {
1467 sleep(d).await;
1468 continue;
1469 }
1470 dlg.finished(false);
1471 return Err(common::Error::HttpError(err));
1472 }
1473 Ok(res) => {
1474 let (mut parts, body) = res.into_parts();
1475 let mut body = common::Body::new(body);
1476 if !parts.status.is_success() {
1477 let bytes = common::to_bytes(body).await.unwrap_or_default();
1478 let error = serde_json::from_str(&common::to_string(&bytes));
1479 let response = common::to_response(parts, bytes.into());
1480
1481 if let common::Retry::After(d) =
1482 dlg.http_failure(&response, error.as_ref().ok())
1483 {
1484 sleep(d).await;
1485 continue;
1486 }
1487
1488 dlg.finished(false);
1489
1490 return Err(match error {
1491 Ok(value) => common::Error::BadRequest(value),
1492 _ => common::Error::Failure(response),
1493 });
1494 }
1495 let response = {
1496 let bytes = common::to_bytes(body).await.unwrap_or_default();
1497 let encoded = common::to_string(&bytes);
1498 match serde_json::from_str(&encoded) {
1499 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1500 Err(error) => {
1501 dlg.response_json_decode_error(&encoded, &error);
1502 return Err(common::Error::JsonDecodeError(
1503 encoded.to_string(),
1504 error,
1505 ));
1506 }
1507 }
1508 };
1509
1510 dlg.finished(true);
1511 return Ok(response);
1512 }
1513 }
1514 }
1515 }
1516
1517 ///
1518 /// Sets the *request* property to the given value.
1519 ///
1520 /// Even though the property as already been set when instantiating this call,
1521 /// we provide this method for API completeness.
1522 pub fn request(mut self, new_value: AnalyzeSyntaxRequest) -> DocumentAnalyzeSyntaxCall<'a, C> {
1523 self._request = new_value;
1524 self
1525 }
1526 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1527 /// while executing the actual API request.
1528 ///
1529 /// ````text
1530 /// It should be used to handle progress information, and to implement a certain level of resilience.
1531 /// ````
1532 ///
1533 /// Sets the *delegate* property to the given value.
1534 pub fn delegate(
1535 mut self,
1536 new_value: &'a mut dyn common::Delegate,
1537 ) -> DocumentAnalyzeSyntaxCall<'a, C> {
1538 self._delegate = Some(new_value);
1539 self
1540 }
1541
1542 /// Set any additional parameter of the query string used in the request.
1543 /// It should be used to set parameters which are not yet available through their own
1544 /// setters.
1545 ///
1546 /// Please note that this method must not be used to set any of the known parameters
1547 /// which have their own setter method. If done anyway, the request will fail.
1548 ///
1549 /// # Additional Parameters
1550 ///
1551 /// * *$.xgafv* (query-string) - V1 error format.
1552 /// * *access_token* (query-string) - OAuth access token.
1553 /// * *alt* (query-string) - Data format for response.
1554 /// * *callback* (query-string) - JSONP
1555 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1556 /// * *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.
1557 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1558 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1559 /// * *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.
1560 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1561 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1562 pub fn param<T>(mut self, name: T, value: T) -> DocumentAnalyzeSyntaxCall<'a, C>
1563 where
1564 T: AsRef<str>,
1565 {
1566 self._additional_params
1567 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1568 self
1569 }
1570
1571 /// Identifies the authorization scope for the method you are building.
1572 ///
1573 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1574 /// [`Scope::CloudLanguage`].
1575 ///
1576 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1577 /// tokens for more than one scope.
1578 ///
1579 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1580 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1581 /// sufficient, a read-write scope will do as well.
1582 pub fn add_scope<St>(mut self, scope: St) -> DocumentAnalyzeSyntaxCall<'a, C>
1583 where
1584 St: AsRef<str>,
1585 {
1586 self._scopes.insert(String::from(scope.as_ref()));
1587 self
1588 }
1589 /// Identifies the authorization scope(s) for the method you are building.
1590 ///
1591 /// See [`Self::add_scope()`] for details.
1592 pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentAnalyzeSyntaxCall<'a, C>
1593 where
1594 I: IntoIterator<Item = St>,
1595 St: AsRef<str>,
1596 {
1597 self._scopes
1598 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1599 self
1600 }
1601
1602 /// Removes all scopes, and no default scope will be used either.
1603 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1604 /// for details).
1605 pub fn clear_scopes(mut self) -> DocumentAnalyzeSyntaxCall<'a, C> {
1606 self._scopes.clear();
1607 self
1608 }
1609}
1610
1611/// A convenience method that provides all the features that analyzeSentiment, analyzeEntities, and analyzeSyntax provide in one call.
1612///
1613/// A builder for the *annotateText* method supported by a *document* resource.
1614/// It is not used directly, but through a [`DocumentMethods`] instance.
1615///
1616/// # Example
1617///
1618/// Instantiate a resource method builder
1619///
1620/// ```test_harness,no_run
1621/// # extern crate hyper;
1622/// # extern crate hyper_rustls;
1623/// # extern crate google_language1_beta1 as language1_beta1;
1624/// use language1_beta1::api::AnnotateTextRequest;
1625/// # async fn dox() {
1626/// # use language1_beta1::{CloudNaturalLanguage, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1627///
1628/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1629/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
1630/// # secret,
1631/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1632/// # ).build().await.unwrap();
1633///
1634/// # let client = hyper_util::client::legacy::Client::builder(
1635/// # hyper_util::rt::TokioExecutor::new()
1636/// # )
1637/// # .build(
1638/// # hyper_rustls::HttpsConnectorBuilder::new()
1639/// # .with_native_roots()
1640/// # .unwrap()
1641/// # .https_or_http()
1642/// # .enable_http1()
1643/// # .build()
1644/// # );
1645/// # let mut hub = CloudNaturalLanguage::new(client, auth);
1646/// // As the method needs a request, you would usually fill it with the desired information
1647/// // into the respective structure. Some of the parts shown here might not be applicable !
1648/// // Values shown here are possibly random and not representative !
1649/// let mut req = AnnotateTextRequest::default();
1650///
1651/// // You can configure optional parameters by calling the respective setters at will, and
1652/// // execute the final call using `doit()`.
1653/// // Values shown here are possibly random and not representative !
1654/// let result = hub.documents().annotate_text(req)
1655/// .doit().await;
1656/// # }
1657/// ```
1658pub struct DocumentAnnotateTextCall<'a, C>
1659where
1660 C: 'a,
1661{
1662 hub: &'a CloudNaturalLanguage<C>,
1663 _request: AnnotateTextRequest,
1664 _delegate: Option<&'a mut dyn common::Delegate>,
1665 _additional_params: HashMap<String, String>,
1666 _scopes: BTreeSet<String>,
1667}
1668
1669impl<'a, C> common::CallBuilder for DocumentAnnotateTextCall<'a, C> {}
1670
1671impl<'a, C> DocumentAnnotateTextCall<'a, C>
1672where
1673 C: common::Connector,
1674{
1675 /// Perform the operation you have build so far.
1676 pub async fn doit(mut self) -> common::Result<(common::Response, AnnotateTextResponse)> {
1677 use std::borrow::Cow;
1678 use std::io::{Read, Seek};
1679
1680 use common::{url::Params, ToParts};
1681 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1682
1683 let mut dd = common::DefaultDelegate;
1684 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1685 dlg.begin(common::MethodInfo {
1686 id: "language.documents.annotateText",
1687 http_method: hyper::Method::POST,
1688 });
1689
1690 for &field in ["alt"].iter() {
1691 if self._additional_params.contains_key(field) {
1692 dlg.finished(false);
1693 return Err(common::Error::FieldClash(field));
1694 }
1695 }
1696
1697 let mut params = Params::with_capacity(3 + self._additional_params.len());
1698
1699 params.extend(self._additional_params.iter());
1700
1701 params.push("alt", "json");
1702 let mut url = self.hub._base_url.clone() + "v1beta1/documents:annotateText";
1703 if self._scopes.is_empty() {
1704 self._scopes
1705 .insert(Scope::CloudLanguage.as_ref().to_string());
1706 }
1707
1708 let url = params.parse_with_url(&url);
1709
1710 let mut json_mime_type = mime::APPLICATION_JSON;
1711 let mut request_value_reader = {
1712 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1713 common::remove_json_null_values(&mut value);
1714 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1715 serde_json::to_writer(&mut dst, &value).unwrap();
1716 dst
1717 };
1718 let request_size = request_value_reader
1719 .seek(std::io::SeekFrom::End(0))
1720 .unwrap();
1721 request_value_reader
1722 .seek(std::io::SeekFrom::Start(0))
1723 .unwrap();
1724
1725 loop {
1726 let token = match self
1727 .hub
1728 .auth
1729 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1730 .await
1731 {
1732 Ok(token) => token,
1733 Err(e) => match dlg.token(e) {
1734 Ok(token) => token,
1735 Err(e) => {
1736 dlg.finished(false);
1737 return Err(common::Error::MissingToken(e));
1738 }
1739 },
1740 };
1741 request_value_reader
1742 .seek(std::io::SeekFrom::Start(0))
1743 .unwrap();
1744 let mut req_result = {
1745 let client = &self.hub.client;
1746 dlg.pre_request();
1747 let mut req_builder = hyper::Request::builder()
1748 .method(hyper::Method::POST)
1749 .uri(url.as_str())
1750 .header(USER_AGENT, self.hub._user_agent.clone());
1751
1752 if let Some(token) = token.as_ref() {
1753 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1754 }
1755
1756 let request = req_builder
1757 .header(CONTENT_TYPE, json_mime_type.to_string())
1758 .header(CONTENT_LENGTH, request_size as u64)
1759 .body(common::to_body(
1760 request_value_reader.get_ref().clone().into(),
1761 ));
1762
1763 client.request(request.unwrap()).await
1764 };
1765
1766 match req_result {
1767 Err(err) => {
1768 if let common::Retry::After(d) = dlg.http_error(&err) {
1769 sleep(d).await;
1770 continue;
1771 }
1772 dlg.finished(false);
1773 return Err(common::Error::HttpError(err));
1774 }
1775 Ok(res) => {
1776 let (mut parts, body) = res.into_parts();
1777 let mut body = common::Body::new(body);
1778 if !parts.status.is_success() {
1779 let bytes = common::to_bytes(body).await.unwrap_or_default();
1780 let error = serde_json::from_str(&common::to_string(&bytes));
1781 let response = common::to_response(parts, bytes.into());
1782
1783 if let common::Retry::After(d) =
1784 dlg.http_failure(&response, error.as_ref().ok())
1785 {
1786 sleep(d).await;
1787 continue;
1788 }
1789
1790 dlg.finished(false);
1791
1792 return Err(match error {
1793 Ok(value) => common::Error::BadRequest(value),
1794 _ => common::Error::Failure(response),
1795 });
1796 }
1797 let response = {
1798 let bytes = common::to_bytes(body).await.unwrap_or_default();
1799 let encoded = common::to_string(&bytes);
1800 match serde_json::from_str(&encoded) {
1801 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1802 Err(error) => {
1803 dlg.response_json_decode_error(&encoded, &error);
1804 return Err(common::Error::JsonDecodeError(
1805 encoded.to_string(),
1806 error,
1807 ));
1808 }
1809 }
1810 };
1811
1812 dlg.finished(true);
1813 return Ok(response);
1814 }
1815 }
1816 }
1817 }
1818
1819 ///
1820 /// Sets the *request* property to the given value.
1821 ///
1822 /// Even though the property as already been set when instantiating this call,
1823 /// we provide this method for API completeness.
1824 pub fn request(mut self, new_value: AnnotateTextRequest) -> DocumentAnnotateTextCall<'a, C> {
1825 self._request = new_value;
1826 self
1827 }
1828 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1829 /// while executing the actual API request.
1830 ///
1831 /// ````text
1832 /// It should be used to handle progress information, and to implement a certain level of resilience.
1833 /// ````
1834 ///
1835 /// Sets the *delegate* property to the given value.
1836 pub fn delegate(
1837 mut self,
1838 new_value: &'a mut dyn common::Delegate,
1839 ) -> DocumentAnnotateTextCall<'a, C> {
1840 self._delegate = Some(new_value);
1841 self
1842 }
1843
1844 /// Set any additional parameter of the query string used in the request.
1845 /// It should be used to set parameters which are not yet available through their own
1846 /// setters.
1847 ///
1848 /// Please note that this method must not be used to set any of the known parameters
1849 /// which have their own setter method. If done anyway, the request will fail.
1850 ///
1851 /// # Additional Parameters
1852 ///
1853 /// * *$.xgafv* (query-string) - V1 error format.
1854 /// * *access_token* (query-string) - OAuth access token.
1855 /// * *alt* (query-string) - Data format for response.
1856 /// * *callback* (query-string) - JSONP
1857 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1858 /// * *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.
1859 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1860 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1861 /// * *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.
1862 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1863 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1864 pub fn param<T>(mut self, name: T, value: T) -> DocumentAnnotateTextCall<'a, C>
1865 where
1866 T: AsRef<str>,
1867 {
1868 self._additional_params
1869 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1870 self
1871 }
1872
1873 /// Identifies the authorization scope for the method you are building.
1874 ///
1875 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1876 /// [`Scope::CloudLanguage`].
1877 ///
1878 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1879 /// tokens for more than one scope.
1880 ///
1881 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1882 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1883 /// sufficient, a read-write scope will do as well.
1884 pub fn add_scope<St>(mut self, scope: St) -> DocumentAnnotateTextCall<'a, C>
1885 where
1886 St: AsRef<str>,
1887 {
1888 self._scopes.insert(String::from(scope.as_ref()));
1889 self
1890 }
1891 /// Identifies the authorization scope(s) for the method you are building.
1892 ///
1893 /// See [`Self::add_scope()`] for details.
1894 pub fn add_scopes<I, St>(mut self, scopes: I) -> DocumentAnnotateTextCall<'a, C>
1895 where
1896 I: IntoIterator<Item = St>,
1897 St: AsRef<str>,
1898 {
1899 self._scopes
1900 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1901 self
1902 }
1903
1904 /// Removes all scopes, and no default scope will be used either.
1905 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1906 /// for details).
1907 pub fn clear_scopes(mut self) -> DocumentAnnotateTextCall<'a, C> {
1908 self._scopes.clear();
1909 self
1910 }
1911}