Spaces:
Running

hub-wrapped / src /api.js
enzostvs's picture
enzostvs HF Staff
Hub Wrapped: your year on Hugging Face
868affd verified
Raw History Blame Contribute Delete
1.87 kB
// Everything here is public Hub data, fetched straight from the browser.
const HUB = 'https://huggingface.co'
const API = `${HUB}/api`
export class HubError extends Error {
constructor(status) {
super(`Hub request failed (${status})`)
this.status = status
}
}
async function get(url) {
let res
try {
res = await fetch(url)
} catch {
throw new HubError(0)
}
if (!res.ok) throw new HubError(res.status)
return res
}
// Follows the Hub's `Link: <...>; rel="next"` cursor pagination.
async function listAll(path, max = 5000) {
let url = `${API}/${path}`
const out = []
while (url && out.length < max) {
const res = await get(url)
out.push(...(await res.json()))
const next = /<([^>]+)>;\s*rel="next"/.exec(res.headers.get('link') || '')
url = next ? next[1] : null
}
return out
}
const optional = (p, fallback) => p.catch(() => fallback)
export const absUrl = (u) => (u && u.startsWith('/') ? HUB + u : u)
export async function fetchHubData(username) {
const u = encodeURIComponent(username)
// The overview call goes first: it tells us whether the user exists.
const overview = await (await get(`${API}/users/${u}/overview`)).json()
const repos = (type) =>
optional(listAll(`${type}?author=${u}&limit=1000&sort=createdAt&direction=-1`), [])
const [models, datasets, spaces, likes] = await Promise.all([
repos('models'),
repos('datasets'),
repos('spaces'),
optional(listAll(`users/${u}/likes`), []),
])
return { overview, models, datasets, spaces, likes }
}
export async function toDataUrl(url) {
try {
const blob = await (await fetch(url)).blob()
return await new Promise((resolve, reject) => {
const r = new FileReader()
r.onload = () => resolve(r.result)
r.onerror = reject
r.readAsDataURL(blob)
})
} catch {
return null
}
}