File size: 2,474 Bytes
9324a72
7cf7ce2
 
b527adb
6f058fb
7cf7ce2
 
6f058fb
9324a72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cc9e49
e284d85
 
 
 
9324a72
e284d85
 
 
9324a72
 
e284d85
 
9324a72
 
 
e284d85
 
 
 
 
 
 
 
 
 
 
 
 
 
e7f5f1e
b527adb
 
 
 
 
 
9cc9e49
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
<input type="file" id="fileInput" webkitdirectory multiple>
<input type="text" id="repoInput" placeholder="Enter repo">
<input type="password" id="accessTokenInput" placeholder="Enter access token">
<button id="uploadButton">Upload</button>

<script type="module">
    import { createRepo, uploadFiles } from "https://cdn.jsdelivr.net/npm/@huggingface/[email protected]/+esm";

    function traverseFileTree(item, path) {
        path = path || "";
        return new Promise(resolve => {
            if (item.isFile) {
                // Get file
                item.file(file => {
                    file.webkitRelativePath = path + file.name;
                    resolve(file);
                });
            } else if (item.isDirectory) {
                // Get folder contents
                item.createReader().readEntries(entries => {
                    Promise.all(entries.map(entry => traverseFileTree(entry, path + item.name + "/")))
                        .then(files => resolve([].concat(...files)));
                });
            }
        });
    }

    async function upload() {
        try {
            const fileInput = document.getElementById('fileInput');
            const repoInput = document.getElementById('repoInput');
            const accessTokenInput = document.getElementById('accessTokenInput');

            const repo = repoInput.value;
            const accessToken = accessTokenInput.value;

            const entries = Array.from(fileInput.files).map(file => file.webkitGetAsEntry());
            const files = [].concat(...await Promise.all(entries.map(entry => traverseFileTree(entry))));
            console.log(`Uploading ${files.length} file(s) to ${repo} with access token ${accessToken.substr(0, 4)}...`);

            const filesToUpload = files.map(file => ({
                path: file.webkitRelativePath,
                content: file,
            }));

            const result = await uploadFiles({
                repo,
                credentials: {
                    accessToken,
                },
                files: filesToUpload,
            });

            console.log('Upload successful:', result);
        } catch (error) {
            console.error('An error occurred:', error);
        }
    }

    // Attach the function to the window object
    window.upload = upload;

    // Attach the event listener to the button
    document.getElementById('uploadButton').addEventListener('click', upload);
</script>