rust_bert/common/
config.rs

1// Copyright 2019 Guillaume Becquin
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//     http://www.apache.org/licenses/LICENSE-2.0
6// Unless required by applicable law or agreed to in writing, software
7// distributed under the License is distributed on an "AS IS" BASIS,
8// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9// See the License for the specific language governing permissions and
10// limitations under the License.
11
12use serde::Deserialize;
13use std::fs::File;
14use std::io::BufReader;
15use std::path::Path;
16
17/// # Utility to deserialize JSON config files
18pub trait Config
19where
20    for<'de> Self: Deserialize<'de>,
21{
22    /// Loads a `Config` object from a JSON file. The format is expected to be aligned with the [Transformers library](https://github.com/huggingface/transformers) configuration files for each model.
23    /// The parsing will fail if non-optional keys expected by the model are missing.
24    ///
25    /// # Arguments
26    ///
27    /// * `path` - `Path` to the configuration JSON file.
28    ///
29    /// # Example
30    ///
31    /// ```no_run
32    /// use rust_bert::gpt2::Gpt2Config;
33    /// use rust_bert::Config;
34    /// use std::path::Path;
35    ///
36    /// let config_path = Path::new("path/to/config.json");
37    /// let config = Gpt2Config::from_file(config_path);
38    /// ```
39    fn from_file<P: AsRef<Path>>(path: P) -> Self {
40        let f = File::open(path).expect("Could not open configuration file.");
41        let br = BufReader::new(f);
42        let config: Self = serde_json::from_reader(br).expect("could not parse configuration");
43        config
44    }
45}