relation_extraction/
relation_extraction.rs

1use composable::*;
2use orp::model::Model;
3use orp::pipeline::*;
4use orp::params::RuntimeParameters;
5use gliner::util::result::Result;
6use gliner::model::params::Parameters;
7use gliner::model::pipeline::{token::TokenPipeline, relation::RelationPipeline};
8use gliner::model::input::{text::TextInput, relation::schema::RelationSchema};
9
10
11/// Sample usage of the public API for Relation Extraction
12/// 
13/// Also provides an example of direct use of `Model` and `Pipeline`.
14/// 
15/// Expected output:
16/// 
17/// ```text
18/// Entities:
19/// 0 | Bill Gates      | person     | 99.9%
20/// 0 | Microsoft       | company    | 99.6%
21/// Relations:
22/// 0 | Bill Gates      | founded    | Microsoft       | 99.7%
23/// ```
24fn main() -> Result<()> {
25    // Set model and tokenizer paths    
26    const MODEL_PATH: &str = "models/gliner-multitask-large-v0.5/onnx/model.onnx";
27    const TOKENIZER_PATH: &str = "models/gliner-multitask-large-v0.5/tokenizer.json";
28    
29    // Use default parameters
30    let params: Parameters = Parameters::default();
31    let runtime_params = RuntimeParameters::default();
32
33    // Define a relation schema.
34    // We declare a "founded" relation which subject has to be a "person" and object has to be a "company"
35    let mut relation_schema = RelationSchema::new();
36    relation_schema.push_with_allowed_labels("founded", &["person"], &["company"]);
37
38    // Sample input text and entity labels
39    let input = TextInput::from_str(
40        &["Bill Gates is an American businessman who co-founded Microsoft."],
41        &["person", "company"],
42    )?;
43    
44    // Load the model that will be leveraged for the pipeline below
45    println!("Loading model...");      
46    let model = Model::new(MODEL_PATH, runtime_params)?;
47    
48    // Relation Extraction needs Named Entity Recognition to be applied first.
49    // Here we combine the two pipelines: one for NER, and one for RE.
50    // For testing purposes we also insert printing functions.
51    let pipeline = composed![
52        TokenPipeline::new(TOKENIZER_PATH)?.to_composable(&model, &params),
53        Print::new(Some("Entities:\n"), None),
54        RelationPipeline::default(TOKENIZER_PATH, &relation_schema)?.to_composable(&model, &params),
55        Print::new(Some("Relations:\n"), None)
56    ];
57
58    // Actually perform inferences using the pipeline defined above
59    pipeline.apply(input)?;
60    
61    Ok(())
62}