opendal/services/huggingface/
backend.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::sync::Arc;
19
20use bytes::Buf;
21use http::Response;
22use http::StatusCode;
23use log::debug;
24
25use super::HUGGINGFACE_SCHEME;
26use super::config::HuggingfaceConfig;
27use super::core::HuggingfaceCore;
28use super::core::HuggingfaceStatus;
29use super::error::parse_error;
30use super::lister::HuggingfaceLister;
31use crate::raw::*;
32use crate::*;
33
34/// [Huggingface](https://huggingface.co/docs/huggingface_hub/package_reference/hf_api)'s API support.
35#[doc = include_str!("docs.md")]
36#[derive(Debug, Default)]
37pub struct HuggingfaceBuilder {
38    pub(super) config: HuggingfaceConfig,
39}
40
41impl HuggingfaceBuilder {
42    /// Set repo type of this backend. Default is model.
43    ///
44    /// Available values:
45    /// - model
46    /// - dataset
47    /// - datasets (alias for dataset)
48    ///
49    /// Currently, only models and datasets are supported.
50    /// [Reference](https://huggingface.co/docs/hub/repositories)
51    pub fn repo_type(mut self, repo_type: &str) -> Self {
52        if !repo_type.is_empty() {
53            self.config.repo_type = Some(repo_type.to_string());
54        }
55        self
56    }
57
58    /// Set repo id of this backend. This is required.
59    ///
60    /// Repo id consists of the account name and the repository name.
61    ///
62    /// For example, model's repo id looks like:
63    /// - meta-llama/Llama-2-7b
64    ///
65    /// Dataset's repo id looks like:
66    /// - databricks/databricks-dolly-15k
67    pub fn repo_id(mut self, repo_id: &str) -> Self {
68        if !repo_id.is_empty() {
69            self.config.repo_id = Some(repo_id.to_string());
70        }
71        self
72    }
73
74    /// Set revision of this backend. Default is main.
75    ///
76    /// Revision can be a branch name or a commit hash.
77    ///
78    /// For example, revision can be:
79    /// - main
80    /// - 1d0c4eb
81    pub fn revision(mut self, revision: &str) -> Self {
82        if !revision.is_empty() {
83            self.config.revision = Some(revision.to_string());
84        }
85        self
86    }
87
88    /// Set root of this backend.
89    ///
90    /// All operations will happen under this root.
91    pub fn root(mut self, root: &str) -> Self {
92        self.config.root = if root.is_empty() {
93            None
94        } else {
95            Some(root.to_string())
96        };
97
98        self
99    }
100
101    /// Set the token of this backend.
102    ///
103    /// This is optional.
104    pub fn token(mut self, token: &str) -> Self {
105        if !token.is_empty() {
106            self.config.token = Some(token.to_string());
107        }
108        self
109    }
110
111    /// configure the Hub base url. You might want to set this variable if your
112    /// organization is using a Private Hub https://huggingface.co/enterprise
113    ///
114    /// Default is "https://huggingface.co"
115    pub fn endpoint(mut self, endpoint: &str) -> Self {
116        if !endpoint.is_empty() {
117            self.config.endpoint = Some(endpoint.to_string());
118        }
119        self
120    }
121}
122
123impl Builder for HuggingfaceBuilder {
124    type Config = HuggingfaceConfig;
125
126    /// Build a HuggingfaceBackend.
127    fn build(self) -> Result<impl Access> {
128        debug!("backend build started: {:?}", &self);
129
130        let repo_type = match self.config.repo_type.as_deref() {
131            Some("model") => Ok(RepoType::Model),
132            Some("dataset") | Some("datasets") => Ok(RepoType::Dataset),
133            Some("space") => Err(Error::new(
134                ErrorKind::ConfigInvalid,
135                "repo type \"space\" is unsupported",
136            )),
137            Some(repo_type) => Err(Error::new(
138                ErrorKind::ConfigInvalid,
139                format!("unknown repo_type: {repo_type}").as_str(),
140            )
141            .with_operation("Builder::build")
142            .with_context("service", HUGGINGFACE_SCHEME)),
143            None => Ok(RepoType::Model),
144        }?;
145        debug!("backend use repo_type: {:?}", &repo_type);
146
147        let repo_id = match &self.config.repo_id {
148            Some(repo_id) => Ok(repo_id.clone()),
149            None => Err(Error::new(ErrorKind::ConfigInvalid, "repo_id is empty")
150                .with_operation("Builder::build")
151                .with_context("service", HUGGINGFACE_SCHEME)),
152        }?;
153        debug!("backend use repo_id: {}", &repo_id);
154
155        let revision = match &self.config.revision {
156            Some(revision) => revision.clone(),
157            None => "main".to_string(),
158        };
159        debug!("backend use revision: {}", &revision);
160
161        let root = normalize_root(&self.config.root.unwrap_or_default());
162        debug!("backend use root: {}", &root);
163
164        let token = self.config.token.as_ref().cloned();
165
166        let endpoint = match &self.config.endpoint {
167            Some(endpoint) => endpoint.clone(),
168            None => {
169                // Try to read from HF_ENDPOINT env var which is used
170                // by the official huggingface clients.
171                if let Ok(env_endpoint) = std::env::var("HF_ENDPOINT") {
172                    env_endpoint
173                } else {
174                    "https://huggingface.co".to_string()
175                }
176            }
177        };
178        debug!("backend use endpoint: {}", &endpoint);
179
180        Ok(HuggingfaceBackend {
181            core: Arc::new(HuggingfaceCore {
182                info: {
183                    let am = AccessorInfo::default();
184                    am.set_scheme(HUGGINGFACE_SCHEME)
185                        .set_native_capability(Capability {
186                            stat: true,
187                            read: true,
188                            list: true,
189                            list_with_recursive: true,
190                            shared: true,
191                            ..Default::default()
192                        });
193                    am.into()
194                },
195                repo_type,
196                repo_id,
197                revision,
198                root,
199                token,
200                endpoint,
201            }),
202        })
203    }
204}
205
206/// Backend for Huggingface service
207#[derive(Debug, Clone)]
208pub struct HuggingfaceBackend {
209    core: Arc<HuggingfaceCore>,
210}
211
212impl Access for HuggingfaceBackend {
213    type Reader = HttpBody;
214    type Writer = ();
215    type Lister = oio::PageLister<HuggingfaceLister>;
216    type Deleter = ();
217
218    fn info(&self) -> Arc<AccessorInfo> {
219        self.core.info.clone()
220    }
221
222    async fn stat(&self, path: &str, _: OpStat) -> Result<RpStat> {
223        // Stat root always returns a DIR.
224        if path == "/" {
225            return Ok(RpStat::new(Metadata::new(EntryMode::DIR)));
226        }
227
228        let resp = self.core.hf_path_info(path).await?;
229
230        let status = resp.status();
231
232        match status {
233            StatusCode::OK => {
234                let mut meta = parse_into_metadata(path, resp.headers())?;
235                let bs = resp.into_body();
236
237                let decoded_response: Vec<HuggingfaceStatus> =
238                    serde_json::from_reader(bs.reader()).map_err(new_json_deserialize_error)?;
239
240                // NOTE: if the file is not found, the server will return 200 with an empty array
241                if let Some(status) = decoded_response.first() {
242                    if let Some(commit_info) = status.last_commit.as_ref() {
243                        meta.set_last_modified(commit_info.date.parse::<Timestamp>()?);
244                    }
245
246                    meta.set_content_length(status.size);
247
248                    match status.type_.as_str() {
249                        "directory" => meta.set_mode(EntryMode::DIR),
250                        "file" => meta.set_mode(EntryMode::FILE),
251                        _ => return Err(Error::new(ErrorKind::Unexpected, "unknown status type")),
252                    };
253                } else {
254                    return Err(Error::new(ErrorKind::NotFound, "path not found"));
255                }
256
257                Ok(RpStat::new(meta))
258            }
259            _ => Err(parse_error(resp)),
260        }
261    }
262
263    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
264        let resp = self.core.hf_resolve(path, args.range(), &args).await?;
265
266        let status = resp.status();
267
268        match status {
269            StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
270                Ok((RpRead::default(), resp.into_body()))
271            }
272            _ => {
273                let (part, mut body) = resp.into_parts();
274                let buf = body.to_buffer().await?;
275                Err(parse_error(Response::from_parts(part, buf)))
276            }
277        }
278    }
279
280    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
281        let l = HuggingfaceLister::new(self.core.clone(), path.to_string(), args.recursive());
282
283        Ok((RpList::default(), oio::PageLister::new(l)))
284    }
285}
286
287/// Repository type of Huggingface. Currently, we only support `model` and `dataset`.
288/// [Reference](https://huggingface.co/docs/hub/repositories)
289#[derive(Debug, Clone, Copy)]
290pub enum RepoType {
291    Model,
292    Dataset,
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    #[test]
300    fn build_accepts_datasets_alias() {
301        HuggingfaceBuilder::default()
302            .repo_id("org/repo")
303            .repo_type("datasets")
304            .build()
305            .expect("builder should accept datasets alias");
306    }
307}