Spaces:
Running
Running
<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/hub@0.8.3/+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> | |