Spaces:
Running
Running
File size: 1,870 Bytes
868affd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | // 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
}
}
|