File size: 1,691 Bytes
e9674a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { v4 as uuidv4 } from "uuid"
import { createRepo, uploadFiles, whoAmI } from "@huggingface/hub"
import type { RepoDesignation, Credentials } from "@huggingface/hub"
import slugify from "slugify"

import { RepoFile } from "./types.mts"

export const createSpace = async (files: RepoFile[], token: string) => {

  const credentials: Credentials = { accessToken: token }

  const { name: username } = await whoAmI({ credentials })

  let slug = ``
  let title = ``
  const readme = files.find(p => p.path === "README.md")
  try {
    const matches = readme.content.match(/title: ([^\n]+)\n/)
    title = matches?.[1] || ""
    slug = (slugify as any)(title) as string
    if (!slug.length) {
      throw new Error("sluggification failed")
    }
  } catch (err) {
    slug = `sf-${uuidv4().slice(0, 3)}`
  }

  const repoName = `${username}/${slug}`

  const repo: RepoDesignation = { type: "space", name: repoName }
  console.log(`Creating space at ${repoName}${title ? ` (${title})` : ''}`)

  await createRepo({
    repo,
    credentials,
    license: "mit",
    sdk:
      files.some(file => file.path.includes("Dockerfile"))
        ? "docker"
      : files.some(file => file.path.includes("app.py"))
        ? "streamlit"
        : "static" // "streamlit" | "gradio" | "docker" | "static";
  });

  console.log("uploading files..")
  await uploadFiles({
    repo,
    credentials,
    files: files.map(file => ({
      path: file.path,
      content: new Blob([ file.content ])
    })),
  });

  console.log("upload done!")

  // TODO we should keep track of the repo and delete it after 30 min
  // or delete it if we reached 20 repos
  // await deleteRepo({ repo, credentials })
}