rust_bert/pipelines/
mod.rs

1//! # Ready-to-use NLP pipelines and models
2//!
3//! Based on Huggingface's pipelines, ready to use end-to-end NLP pipelines are available as part of this crate. The following capabilities are currently available:
4//!
5//! **Disclaimer**
6//! The contributors of this repository are not responsible for any generation from the 3rd party utilization of the pretrained systems proposed herein.
7//!
8//! #### 1. Question Answering
9//! Extractive question answering from a given question and context. DistilBERT model finetuned on SQuAD (Stanford Question Answering Dataset)
10//!
11//! ```ignore
12//! use rust_bert::pipelines::question_answering::{QaInput, QuestionAnsweringModel};
13//! # fn main() -> anyhow::Result<()> {
14//! let qa_model = QuestionAnsweringModel::new(Default::default())?;
15//!
16//! let question = String::from("Where does Amy live ?");
17//! let context = String::from("Amy lives in Amsterdam");
18//!
19//! let answers = qa_model.predict(&[QaInput { question, context }], 1, 32);
20//! # Ok(())
21//! # }
22//! ```
23//!
24//! Output: \
25//! ```ignore
26//! # use rust_bert::pipelines::question_answering::Answer;
27//! # let output =
28//! [Answer {
29//!     score: 0.9976,
30//!     start: 13,
31//!     end: 21,
32//!     answer: String::from("Amsterdam"),
33//! }]
34//! # ;
35//! ```
36//!
37//! #### 2. Translation
38//! Translation using the MarianMT architecture and pre-trained models from the Opus-MT team from Language Technology at the University of Helsinki.
39//! Currently supported languages are :
40//! - English <-> French
41//! - English <-> Spanish
42//! - English <-> Portuguese
43//! - English <-> Italian
44//! - English <-> Catalan
45//! - English <-> German
46//! - English <-> Russian
47//! - English <-> Chinese (Simplified)
48//! - English <-> Chinese (Traditional)
49//! - English <-> Dutch
50//! - English <-> Swedish
51//! - English <-> Arabic
52//! - English <-> Hebrew
53//! - English <-> Hindi
54//! - French <-> German
55//!
56//! ```ignore
57//! # fn main() -> anyhow::Result<()> {
58//! # use rust_bert::pipelines::generation_utils::LanguageGenerator;
59//! use rust_bert::pipelines::common::ModelType;
60//! use rust_bert::pipelines::translation::{
61//!     Language, TranslationConfig, TranslationModel, TranslationModelBuilder,
62//! };
63//! use tch::Device;
64//! let model = TranslationModelBuilder::new()
65//!     .with_device(Device::cuda_if_available())
66//!     .with_model_type(ModelType::Marian)
67//!     .with_source_languages(vec![Language::English])
68//!     .with_target_languages(vec![Language::French])
69//!     .create_model()?;
70//!
71//! let input = ["This is a sentence to be translated"];
72//!
73//! let output = model.translate(&input, None, Language::French);
74//! # Ok(())
75//! # }
76//! ```
77//! Output: \
78//! ```ignore
79//! # let output =
80//! " Il s'agit d'une phrase à traduire"
81//! # ;
82//! ```
83//!
84//! Output: \
85//! ```ignore
86//! # let output =
87//! "Il s'agit d'une phrase à traduire"
88//! # ;
89//! ```
90//!
91//! #### 3. Summarization
92//! Abstractive summarization of texts based on the BART encoder-decoder architecture
93//! Include techniques such as beam search, top-k and nucleus sampling, temperature setting and repetition penalty.
94//!
95//! ```ignore
96//! # fn main() -> anyhow::Result<()> {
97//! # use rust_bert::pipelines::generation_utils::LanguageGenerator;
98//! use rust_bert::pipelines::summarization::SummarizationModel;
99//!
100//! let mut model = SummarizationModel::new(Default::default())?;
101//!
102//! let input = ["In findings published Tuesday in Cornell University's arXiv by a team of scientists
103//! from the University of Montreal and a separate report published Wednesday in Nature Astronomy by a team
104//! from University College London (UCL), the presence of water vapour was confirmed in the atmosphere of K2-18b,
105//! a planet circling a star in the constellation Leo. This is the first such discovery in a planet in its star's
106//! habitable zone — not too hot and not too cold for liquid water to exist. The Montreal team, led by Björn Benneke,
107//! used data from the NASA's Hubble telescope to assess changes in the light coming from K2-18b's star as the planet
108//! passed between it and Earth. They found that certain wavelengths of light, which are usually absorbed by water,
109//! weakened when the planet was in the way, indicating not only does K2-18b have an atmosphere, but the atmosphere
110//! contains water in vapour form. The team from UCL then analyzed the Montreal team's data using their own software
111//! and confirmed their conclusion. This was not the first time scientists have found signs of water on an exoplanet,
112//! but previous discoveries were made on planets with high temperatures or other pronounced differences from Earth.
113//! \"This is the first potentially habitable planet where the temperature is right and where we now know there is water,\"
114//! said UCL astronomer Angelos Tsiaras. \"It's the best candidate for habitability right now.\" \"It's a good sign\",
115//! said Ryan Cloutier of the Harvard–Smithsonian Center for Astrophysics, who was not one of either study's authors.
116//! \"Overall,\" he continued, \"the presence of water in its atmosphere certainly improves the prospect of K2-18b being
117//! a potentially habitable planet, but further observations will be required to say for sure. \"
118//! K2-18b was first identified in 2015 by the Kepler space telescope. It is about 110 light-years from Earth and larger
119//! but less dense. Its star, a red dwarf, is cooler than the Sun, but the planet's orbit is much closer, such that a year
120//! on K2-18b lasts 33 Earth days. According to The Guardian, astronomers were optimistic that NASA's James Webb space
121//! telescope — scheduled for launch in 2021 — and the European Space Agency's 2028 ARIEL program, could reveal more
122//! about exoplanets like K2-18b."];
123//!
124//! let output = model.summarize(&input);
125//! # Ok(())
126//! # }
127//! ```
128//! (example from: [WikiNews](https://en.wikinews.org/wiki/Astronomers_find_water_vapour_in_atmosphere_of_exoplanet_K2-18b))
129//!
130//! Example output: \
131//! ```ignore
132//! # let output =
133//! "Scientists have found water vapour on K2-18b, a planet 110 light-years from Earth.
134//!  This is the first such discovery in a planet in its star's habitable zone.
135//!  The planet is not too hot and not too cold for liquid water to exist."
136//! # ;
137//! ```
138//!
139//!
140//! #### 4. Dialogue Model
141//! Conversation model based on Microsoft's [DialoGPT](https://github.com/microsoft/DialoGPT).
142//! This pipeline allows the generation of single or multi-turn conversations between a human and a model.
143//! The DialoGPT's page states that
144//! > The human evaluation results indicate that the response generated from DialoGPT is comparable to human response quality
145//! > under a single-turn conversation Turing test. ([DialoGPT repository](https://github.com/microsoft/DialoGPT))
146//!
147//! The model uses a `ConversationManager` to keep track of active conversations and generate responses to them.
148//!
149//! ```ignore
150//! # fn main() -> anyhow::Result<()> {
151//! use rust_bert::pipelines::conversation::{ConversationManager, ConversationModel};
152//! let conversation_model = ConversationModel::new(Default::default())?;
153//! let mut conversation_manager = ConversationManager::new();
154//!
155//! let conversation_id =
156//!     conversation_manager.create("Going to the movies tonight - any suggestions?");
157//! let output = conversation_model.generate_responses(&mut conversation_manager);
158//! # Ok(())
159//! # }
160//! ```
161//! Example output: \
162//! ```ignore
163//! # let output =
164//! "The Big Lebowski."
165//! # ;
166//! ```
167//!
168//! #### 5. Natural Language Generation
169//! Generate language based on a prompt. GPT2 and GPT available as base models.
170//! Include techniques such as beam search, top-k and nucleus sampling, temperature setting and repetition penalty.
171//! Supports batch generation of sentences from several prompts. Sequences will be left-padded with the model's padding token if present, the unknown token otherwise.
172//! This may impact the results and it is recommended to submit prompts of similar length for best results. Additional information on the input parameters for generation is provided in this module's documentation.
173//!
174//! ```ignore
175//! # fn main() -> anyhow::Result<()> {
176//! use rust_bert::pipelines::text_generation::TextGenerationModel;
177//! use rust_bert::pipelines::common::ModelType;
178//! let mut model = TextGenerationModel::new(Default::default())?;
179//! let input_context_1 = "The dog";
180//! let input_context_2 = "The cat was";
181//!
182//! let prefix = None; // Optional prefix to append prompts with, will be excluded from the generated output
183//!
184//! let output = model.generate(&[input_context_1, input_context_2], prefix);
185//! # Ok(())
186//! # }
187//! ```
188//! Example output: \
189//! ```ignore
190//! # let output =
191//! [
192//!     "The dog's owners, however, did not want to be named. According to the lawsuit, the animal's owner, a 29-year",
193//!     "The dog has always been part of the family. \"He was always going to be my dog and he was always looking out for me",
194//!     "The dog has been able to stay in the home for more than three months now. \"It's a very good dog. She's",
195//!     "The cat was discovered earlier this month in the home of a relative of the deceased. The cat\'s owner, who wished to remain anonymous,",
196//!     "The cat was pulled from the street by two-year-old Jazmine.\"I didn't know what to do,\" she said",
197//!     "The cat was attacked by two stray dogs and was taken to a hospital. Two other cats were also injured in the attack and are being treated."
198//! ]
199//! # ;
200//! ```
201//!
202//! #### 6. Zero-shot classification
203//! Performs zero-shot classification on input sentences with provided labels using a model fine-tuned for Natural Language Inference.
204//! ```ignore
205//! # use rust_bert::pipelines::zero_shot_classification::ZeroShotClassificationModel;
206//! # fn main() -> anyhow::Result<()> {
207//! let sequence_classification_model = ZeroShotClassificationModel::new(Default::default())?;
208//! let input_sentence = "Who are you voting for in 2020?";
209//! let input_sequence_2 = "The prime minister has announced a stimulus package which was widely criticized by the opposition.";
210//! let candidate_labels = &["politics", "public health", "economics", "sports"];
211//! let output = sequence_classification_model.predict_multilabel(
212//!     &[input_sentence, input_sequence_2],
213//!     candidate_labels,
214//!     None,
215//!     128,
216//! );
217//! # Ok(())
218//! # }
219//! ```
220//!
221//! outputs:
222//! ```ignore
223//! # use rust_bert::pipelines::sequence_classification::Label;
224//! let output = [
225//!     [
226//!         Label {
227//!             text: "politics".to_string(),
228//!             score: 0.972,
229//!             id: 0,
230//!             sentence: 0,
231//!         },
232//!         Label {
233//!             text: "public health".to_string(),
234//!             score: 0.032,
235//!             id: 1,
236//!             sentence: 0,
237//!         },
238//!         Label {
239//!             text: "economics".to_string(),
240//!             score: 0.006,
241//!             id: 2,
242//!             sentence: 0,
243//!         },
244//!         Label {
245//!             text: "sports".to_string(),
246//!             score: 0.004,
247//!             id: 3,
248//!             sentence: 0,
249//!         },
250//!     ],
251//!     [
252//!         Label {
253//!             text: "politics".to_string(),
254//!             score: 0.975,
255//!             id: 0,
256//!             sentence: 1,
257//!         },
258//!         Label {
259//!             text: "economics".to_string(),
260//!             score: 0.852,
261//!             id: 2,
262//!             sentence: 1,
263//!         },
264//!         Label {
265//!             text: "public health".to_string(),
266//!             score: 0.0818,
267//!             id: 1,
268//!             sentence: 1,
269//!         },
270//!         Label {
271//!             text: "sports".to_string(),
272//!             score: 0.001,
273//!             id: 3,
274//!             sentence: 1,
275//!         },
276//!     ],
277//! ]
278//! .to_vec();
279//! ```
280//!
281//! #### 7. Sentiment analysis
282//! Predicts the binary sentiment for a sentence. DistilBERT model finetuned on SST-2.
283//! ```ignore
284//! use rust_bert::pipelines::sentiment::SentimentModel;
285//! # fn main() -> anyhow::Result<()> {
286//! let sentiment_model = SentimentModel::new(Default::default())?;
287//! let input = [
288//!     "Probably my all-time favorite movie, a story of selflessness, sacrifice and dedication to a noble cause, but it's not preachy or boring.",
289//!     "This film tried to be too many things all at once: stinging political satire, Hollywood blockbuster, sappy romantic comedy, family values promo...",
290//!     "If you like original gut wrenching laughter you will like this movie. If you are young or old then you will love this movie, hell even my mom liked it.",
291//! ];
292//! let output = sentiment_model.predict(&input);
293//! # Ok(())
294//! # }
295//! ```
296//! (Example courtesy of [IMDb](http://www.imdb.com))
297//!
298//! Output: \
299//! ```ignore
300//! # use rust_bert::pipelines::sentiment::Sentiment;
301//! # use rust_bert::pipelines::sentiment::SentimentPolarity::{Positive, Negative};
302//! # let output =
303//! [
304//!     Sentiment {
305//!         polarity: Positive,
306//!         score: 0.998,
307//!     },
308//!     Sentiment {
309//!         polarity: Negative,
310//!         score: 0.992,
311//!     },
312//!     Sentiment {
313//!         polarity: Positive,
314//!         score: 0.999,
315//!     },
316//! ]
317//! # ;
318//! ```
319//!
320//! #### 8. Named Entity Recognition
321//! Extracts entities (Person, Location, Organization, Miscellaneous) from text. The default NER mode is an English BERT cased large model finetuned on CoNNL03, contributed by the [MDZ Digital Library team at the Bavarian State Library](https://github.com/dbmdz)
322//! Additional pre-trained models are available for English, German, Spanish and Dutch.
323//! ```ignore
324//! use rust_bert::pipelines::ner::NERModel;
325//! # fn main() -> anyhow::Result<()> {
326//! let ner_model = NERModel::new(Default::default())?;
327//! let input = [
328//!     "My name is Amy. I live in Paris.",
329//!     "Paris is a city in France.",
330//! ];
331//! let output = ner_model.predict(&input);
332//! # Ok(())
333//! # }
334//! ```
335//! Output: \
336//! ```ignore
337//! # use rust_bert::pipelines::ner::Entity;
338//! # use rust_tokenizers::Offset;
339//! # let output =
340//! [
341//!     [
342//!         Entity {
343//!             word: String::from("Amy"),
344//!             score: 0.9986,
345//!             label: String::from("I-PER"),
346//!             offset: Offset { begin: 11, end: 14 },
347//!         },
348//!         Entity {
349//!             word: String::from("Paris"),
350//!             score: 0.9985,
351//!             label: String::from("I-LOC"),
352//!             offset: Offset { begin: 26, end: 31 },
353//!         },
354//!     ],
355//!     [
356//!         Entity {
357//!             word: String::from("Paris"),
358//!             score: 0.9988,
359//!             label: String::from("I-LOC"),
360//!             offset: Offset { begin: 0, end: 5 },
361//!         },
362//!         Entity {
363//!             word: String::from("France"),
364//!             score: 0.9993,
365//!             label: String::from("I-LOC"),
366//!             offset: Offset { begin: 19, end: 25 },
367//!         },
368//!     ],
369//! ]
370//! # ;
371//! ```
372//!
373//! #### 9. Keywords/Keyphrases extraction
374//!
375//! Extract keywords and keyphrases extractions from input documents. Based on a sentence embedding model
376//! to compute the semantic similarity between the full text and word n-grams composing it.
377//!
378//!```no_run
379//! # fn main() -> anyhow::Result<()> {
380//!     use rust_bert::pipelines::keywords_extraction::KeywordExtractionModel;
381//!     let keyword_extraction_model = KeywordExtractionModel::new(Default::default())?;
382//!
383//!     let input = "Rust is a multi-paradigm, general-purpose programming language. \
384//!         Rust emphasizes performance, type safety, and concurrency. Rust enforces memory safety—that is, \
385//!         that all references point to valid memory—without requiring the use of a garbage collector or \
386//!         reference counting present in other memory-safe languages. To simultaneously enforce \
387//!         memory safety and prevent concurrent data races, Rust's borrow checker tracks the object lifetime \
388//!         and variable scope of all references in a program during compilation. Rust is popular for \
389//!         systems programming but also offers high-level features including functional programming constructs.";
390//!     // Credits: Wikimedia https://en.wikipedia.org/wiki/Rust_(programming_language)
391//!     let output = keyword_extraction_model.predict(&[input])?;
392//!     Ok(())
393//! }
394//! ```
395//! Output:
396//! ```no_run
397//! # let output =
398//! [
399//!     ("rust", 0.50910604),
400//!     ("concurrency", 0.33825397),
401//!     ("languages", 0.28515345),
402//!     ("compilation", 0.2801403),
403//!     ("safety", 0.2657791),
404//! ]
405//! # ;
406//! ```
407//!
408//! #### 10. Part of Speech tagging
409//! Extracts Part of Speech tags (Noun, Verb, Adjective...) from text.
410//! ```ignore
411//! use rust_bert::pipelines::pos_tagging::POSModel;
412//! # fn main() -> anyhow::Result<()> {
413//! let pos_model = POSModel::new(Default::default())?;
414//! let input = ["My name is Bob"];
415//! let output = pos_model.encode_as_tensor(&input);
416//! # Ok(())
417//! # }
418//! ```
419//! Output: \
420//! ```ignore
421//! # use rust_bert::pipelines::pos_tagging::POSTag;
422//! # let output =
423//! [
424//!     POSTag {
425//!         word: String::from("My"),
426//!         score: 0.1560,
427//!         label: String::from("PRP"),
428//!     },
429//!     POSTag {
430//!         word: String::from("name"),
431//!         score: 0.6565,
432//!         label: String::from("NN"),
433//!     },
434//!     POSTag {
435//!         word: String::from("is"),
436//!         score: 0.3697,
437//!         label: String::from("VBZ"),
438//!     },
439//!     POSTag {
440//!         word: String::from("Bob"),
441//!         score: 0.7460,
442//!         label: String::from("NNP"),
443//!     },
444//! ]
445//! # ;
446//! ```
447//!
448//! #### 11. Sentence embeddings
449//!
450//! Generate sentence embeddings (vector representation). These can be used for applications including dense information retrieval.
451//!```ignore
452//! # use rust_bert::pipelines::sentence_embeddings::{SentenceEmbeddingsBuilder, SentenceEmbeddingsModelType};
453//! # fn main() -> anyhow::Result<()> {
454//!    let model = SentenceEmbeddingsBuilder::remote(
455//!             SentenceEmbeddingsModelType::AllMiniLmL12V2
456//!         ).create_model()?;
457//!
458//!     let sentences = [
459//!         "this is an example sentence",
460//!         "each sentence is converted"
461//!     ];
462//!     
463//!     let output = model.encode(&sentences);
464//! #   Ok(())
465//! # }
466//! ```
467//! Output:
468//! ```ignore
469//! # let output =
470//! [
471//!     [-0.000202666, 0.08148022, 0.03136178, 0.002920636],
472//!     [0.064757116, 0.048519745, -0.01786038, -0.0479775],
473//! ]
474//! # ;
475//! ```
476//!
477//! # [Tokenizers](https://github.com/huggingface/tokenizers) support
478//!
479//! The pipelines support both the default [rust-tokenizers](https://github.com/guillaume-be/rust-tokenizers) and
480//! Hugging Face's [Tokenizers](https://github.com/huggingface/tokenizers) library. In order to use the latter,
481//! the tokenizer needs to be created manually and passed as an argument to the pipeline's `new_with_tokenizer` method.
482//!
483//! Note that the `special_token_maps` is required to create a `TokenizerOption` from a HFTokenizer. This file is sometimes not provided
484//! (the Python Transformers library provides the special token map information as part of the actual tokenizer loaded wrapping the rust-based
485//! tokenizer). If that is the case a temporary file with the special token map information can be created as illustrated below:
486//! ```no_run
487//! fn main() -> anyhow::Result<()> {
488//!   use std::fs::File;
489//!   use std::io::Write;
490//!   use tempfile::TempDir;
491//!   use rust_bert::pipelines::common::{ModelType, TokenizerOption};
492//!   use rust_bert::pipelines::text_generation::{TextGenerationConfig, TextGenerationModel};
493//!   use rust_bert::resources::{RemoteResource, ResourceProvider};
494//!  
495//!   let generate_config = TextGenerationConfig {
496//!           model_type: ModelType::GPT2,
497//!           ..Default::default()
498//!   };
499//!  
500//!    // Create tokenizer
501//!    let tmp_dir = TempDir::new()?;
502//!    let special_token_map_path = tmp_dir.path().join("special_token_map.json");
503//!    let mut tmp_file = File::create(&special_token_map_path)?;
504//!    writeln!(
505//!        tmp_file,
506//!        r#"{{"bos_token": "<|endoftext|>", "eos_token": "<|endoftext|>", "unk_token": "<|endoftext|>"}}"#
507//!    )?;
508//!    let tokenizer_path = RemoteResource::from_pretrained((
509//!        "gpt2/tokenizer",
510//!        "https://huggingface.co/gpt2/resolve/main/tokenizer.json",
511//!    )).get_local_path()?;
512//!   let tokenizer =
513//!        TokenizerOption::from_hf_tokenizer_file(tokenizer_path, special_token_map_path)?;
514//!  
515//!    // Create model
516//!    let model = TextGenerationModel::new_with_tokenizer(generate_config, tokenizer)?;
517//!  
518//!    let input_context = "The dog";
519//!    let output = model.generate(&[input_context], None);
520//!    for sentence in output {
521//!        println!("{sentence:?}");
522//!    }
523//!    Ok(())
524//! }
525//! ```
526
527pub mod common;
528pub mod conversation;
529pub mod generation_utils;
530pub mod keywords_extraction;
531pub mod masked_language;
532pub mod ner;
533pub mod pos_tagging;
534pub mod question_answering;
535pub mod sentence_embeddings;
536pub mod sentiment;
537pub mod sequence_classification;
538pub mod summarization;
539pub mod text_generation;
540pub mod token_classification;
541pub mod translation;
542pub mod zero_shot_classification;
543
544#[cfg(feature = "onnx")]
545pub mod onnx;
546
547#[cfg(feature = "hf-tokenizers")]
548pub mod hf_tokenizers;