opendal/services/huggingface/
backend.rs1use 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#[doc = include_str!("docs.md")]
36#[derive(Debug, Default)]
37pub struct HuggingfaceBuilder {
38 pub(super) config: HuggingfaceConfig,
39}
40
41impl HuggingfaceBuilder {
42 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 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 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 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 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 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 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 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#[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 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 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#[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}