I'm using rust_bert
for summarising text. I need to set a model with rust_bert::pipelines::summarization::SummarizationModel::new
, which fetches the model from the internet. It does this asynchronously using tokio
and the issue that (I think) I'm running into is that I am running the Tokio runtime within another Tokio runtime, as indicated by the error message:
Downloading https://cdn.huggingface.co/facebook/bart-large-cnn/config.json to "/home/(censored)/.cache/.rustbert/bart-cnn/config.json"
thread 'main' panicked at 'Cannot start a runtime from within a runtime. This happens because a function (like `block_on`) attempted to block the current thread while the thread is being used to drive asynchronous tasks.', /home/(censored)/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-0.2.21/src/runtime/enter.rs:38:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
I've tried running the model fetching synchronously with
tokio::task::spawn_blocking
and tokio::task::block_in_place
but neither of them are working for me. block_in_place
gives the same error as if weren't there, and spawn_blocking
doesn't really seem to be of use to me.
I've also tried making summarize_text
async, but that didn't help much. Github Issue
tokio-rs/tokio#2194
and Reddit post
"'Cannot start a runtime from within a runtime.' with Actix-Web And Postgresql"
seem similar (same-ish error message), but they weren't of much help in finding a solution.
The code I've got issues with is as follows:
use egg_mode::tweet;
use rust_bert::pipelines::summarization::SummarizationModel;
fn summarize_text(model: SummarizationModel, text: &str) -> String {
let output = model.summarize(&[text]);
// @TODO: output summarization
match output.is_empty() {
false => "FALSE".to_string(),
true => "TRUE".to_string(),
}
}
#[tokio::main]
async fn main() {
let model = SummarizationModel::new(Default::default()).unwrap();
let token = egg_mode::auth::Token::Bearer("obviously not my token".to_string());
let tweet_id = 1221552460768202756; // example tweet
println!("Loading tweet [{id}]", id = tweet_id);
let status = tweet::show(tweet_id, &token).await;
match status {
Err(err) => println!("Failed to fetch tweet: {}", err),
Ok(tweet) => {
println!(
"Original tweet:\n{orig}\n\nSummarized tweet:\n{sum}",
orig = tweet.text,
sum = summarize_text(model, &tweet.text)
);
}
}
}