pub struct StudentModel { /* private fields */ }Expand description
A local student checkpoint for English prose. Load once and reuse across documents.
Implementations§
Source§impl StudentModel
impl StudentModel
Sourcepub fn load(directory: impl AsRef<Path>) -> Result<Self>
pub fn load(directory: impl AsRef<Path>) -> Result<Self>
Load student.json, spm.model and the ONNX graph exported by the training script.
Examples found in repository?
examples/student_corpus.rs (line 62)
29fn main() -> Result<()> {
30 let args: Vec<_> = std::env::args().skip(1).collect();
31 let [command, path] = args.as_slice() else {
32 anyhow::bail!(
33 "expected `inputs TOKENIZER`, `predict CHECKPOINT` or `predict-with-rules CHECKPOINT`"
34 );
35 };
36 let books: Vec<Book> = serde_json::from_reader(io::stdin().lock())?;
37 let mut out = BufWriter::new(io::stdout().lock());
38 let opts = Options::default();
39 match command.as_str() {
40 "inputs" => {
41 let tokenizer = InputTokenizer::load(Path::new(path))?;
42 for book in books {
43 let text = read_book(&book.path)?;
44 let spans: Vec<_> = book.items.iter().map(|item| item.span).collect();
45 for (item, input) in book
46 .items
47 .into_iter()
48 .zip(tokenizer.prepare(&text, &spans, &opts)?)
49 {
50 serde_json::to_writer(
51 &mut out,
52 &TrainingInput {
53 number: item.number,
54 input,
55 },
56 )?;
57 writeln!(out)?;
58 }
59 }
60 }
61 "predict" | "predict-with-rules" => {
62 let model = StudentModel::load(path)?;
63 for book in books {
64 let text = read_book(&book.path)?;
65 let numbers: BTreeMap<_, _> = book
66 .items
67 .iter()
68 .map(|item| (item.span, item.number))
69 .collect();
70 ensure!(numbers.len() == book.items.len(), "duplicate sentence span");
71 let spans: Vec<_> = numbers.keys().copied().collect();
72 let mut facts = model.predict_spans(&text, &spans, &opts)?;
73 if command == "predict-with-rules" {
74 facts.extend(extract_aggregates(&text, &opts)?);
75 }
76 let mut predictions = BTreeSet::new();
77 for fact in &facts {
78 for &[offset, _] in &fact.spans {
79 let target = numbers.range(..=[offset, usize::MAX]).next_back();
80 if let Some((_, number)) = target.filter(|(span, _)| offset < span[1]) {
81 predictions.insert((
82 number,
83 &fact.subject,
84 &fact.relation,
85 &fact.object,
86 fact.polarity,
87 ));
88 }
89 }
90 }
91 for (number, subject, relation, object, polarity) in predictions {
92 let prefix = if polarity == Polarity::Denied {
93 "not "
94 } else {
95 ""
96 };
97 writeln!(out, "{number} | {prefix}{subject} | {relation} | {object}")?;
98 }
99 }
100 }
101 _ => anyhow::bail!("unknown student corpus command {command}"),
102 }
103 out.flush()?;
104 Ok(())
105}Sourcepub fn extract_candidate_triples(
&self,
text: &str,
opts: &Options,
) -> Result<Vec<TripleCandidate>>
pub fn extract_candidate_triples( &self, text: &str, opts: &Options, ) -> Result<Vec<TripleCandidate>>
Extract asserted candidates from the rules and the student.
Sourcepub fn extract_aggregates(
&self,
text: &str,
opts: &Options,
) -> Result<Vec<AggregateTriple>>
pub fn extract_aggregates( &self, text: &str, opts: &Options, ) -> Result<Vec<AggregateTriple>>
Extract asserted and denied aggregates from the rules and the student.
Sourcepub fn predict_spans(
&self,
text: &str,
spans: &[[usize; 2]],
opts: &Options,
) -> Result<Vec<AggregateTriple>>
pub fn predict_spans( &self, text: &str, spans: &[[usize; 2]], opts: &Options, ) -> Result<Vec<AggregateTriple>>
Score only the requested sentence byte ranges, with document context.
Examples found in repository?
examples/student_corpus.rs (line 72)
29fn main() -> Result<()> {
30 let args: Vec<_> = std::env::args().skip(1).collect();
31 let [command, path] = args.as_slice() else {
32 anyhow::bail!(
33 "expected `inputs TOKENIZER`, `predict CHECKPOINT` or `predict-with-rules CHECKPOINT`"
34 );
35 };
36 let books: Vec<Book> = serde_json::from_reader(io::stdin().lock())?;
37 let mut out = BufWriter::new(io::stdout().lock());
38 let opts = Options::default();
39 match command.as_str() {
40 "inputs" => {
41 let tokenizer = InputTokenizer::load(Path::new(path))?;
42 for book in books {
43 let text = read_book(&book.path)?;
44 let spans: Vec<_> = book.items.iter().map(|item| item.span).collect();
45 for (item, input) in book
46 .items
47 .into_iter()
48 .zip(tokenizer.prepare(&text, &spans, &opts)?)
49 {
50 serde_json::to_writer(
51 &mut out,
52 &TrainingInput {
53 number: item.number,
54 input,
55 },
56 )?;
57 writeln!(out)?;
58 }
59 }
60 }
61 "predict" | "predict-with-rules" => {
62 let model = StudentModel::load(path)?;
63 for book in books {
64 let text = read_book(&book.path)?;
65 let numbers: BTreeMap<_, _> = book
66 .items
67 .iter()
68 .map(|item| (item.span, item.number))
69 .collect();
70 ensure!(numbers.len() == book.items.len(), "duplicate sentence span");
71 let spans: Vec<_> = numbers.keys().copied().collect();
72 let mut facts = model.predict_spans(&text, &spans, &opts)?;
73 if command == "predict-with-rules" {
74 facts.extend(extract_aggregates(&text, &opts)?);
75 }
76 let mut predictions = BTreeSet::new();
77 for fact in &facts {
78 for &[offset, _] in &fact.spans {
79 let target = numbers.range(..=[offset, usize::MAX]).next_back();
80 if let Some((_, number)) = target.filter(|(span, _)| offset < span[1]) {
81 predictions.insert((
82 number,
83 &fact.subject,
84 &fact.relation,
85 &fact.object,
86 fact.polarity,
87 ));
88 }
89 }
90 }
91 for (number, subject, relation, object, polarity) in predictions {
92 let prefix = if polarity == Polarity::Denied {
93 "not "
94 } else {
95 ""
96 };
97 writeln!(out, "{number} | {prefix}{subject} | {relation} | {object}")?;
98 }
99 }
100 }
101 _ => anyhow::bail!("unknown student corpus command {command}"),
102 }
103 out.flush()?;
104 Ok(())
105}Auto Trait Implementations§
impl !RefUnwindSafe for StudentModel
impl !UnwindSafe for StudentModel
impl Forget for StudentModel
impl Freeze for StudentModel
impl Move for StudentModel
impl Send for StudentModel
impl Sync for StudentModel
impl Unpin for StudentModel
impl UnsafeUnpin for StudentModel
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Converts
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be
downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Converts
Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further
downcast into Rc<ConcreteType> where ConcreteType implements Trait.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
Converts
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
Converts
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.Source§impl<T> DowncastSend for T
impl<T> DowncastSend for T
Source§impl<T> DowncastSync for T
impl<T> DowncastSync for T
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
Converts
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
Converts
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more