Spaces:
Running
Running
| import { fetchEventSource } from '@microsoft/fetch-event-source'; | |
| // On loaded, add event listeners | |
| window.document.addEventListener("DOMContentLoaded", () => { | |
| const form = window.document.querySelector("form"); | |
| form.addEventListener("submit", async (event) => { | |
| const spaceName = window.document.querySelector("#space-name"); | |
| const buildCommand = window.document.querySelector("#build-command"); | |
| const hfToken = window.document.querySelector("#hf-token"); | |
| const outputPath = window.document.querySelector("#output-path"); | |
| const output = window.document.querySelector("#output"); | |
| const logOuput = window.document.querySelector("#log-output"); | |
| const eventOutput = window.document.querySelector("#event-output"); | |
| event.preventDefault(); | |
| output.textContent = ""; | |
| logOuput.textContent = ""; | |
| eventOutput.textContent = ""; | |
| const data = { | |
| environment: { | |
| HF_SPACE_NAME: spaceName.value, | |
| BUILD_COMMAND: buildCommand.value, | |
| // Remove filename | |
| OUTPUT_PATH: outputPath.value.replace(/\/[^/]*$/, ""), | |
| }, | |
| secrets: { | |
| HF_TOKEN: hfToken.value, | |
| }, | |
| arguments: [], | |
| command: ["/app/build.sh"], | |
| flavor: "cpu-basic", | |
| spaceId: "huggingface/space-build", | |
| }; | |
| const tokenOwnerResp = await fetch("https://huggingface.co/api/whoami-v2", { | |
| method: "GET", | |
| headers: { | |
| Authorization: `Bearer ${hfToken.value}`, | |
| }, | |
| }); | |
| if (!tokenOwnerResp.ok) { | |
| output.textContent = "Invalid token"; | |
| return; | |
| } | |
| const tokenOwer = (await tokenOwnerResp.json())["name"]; | |
| if (!tokenOwer) { | |
| output.textContent = "Invalid token"; | |
| return; | |
| } | |
| output.textContent += `Token owner: ${tokenOwer}\n`; | |
| const jobResponse = await fetch(`https://huggingface.co/api/jobs/${tokenOwer}`, { | |
| method: "POST", | |
| headers: { | |
| "Content-Type": "application/json", | |
| Authorization: `Bearer ${hfToken.value}`, | |
| }, | |
| body: JSON.stringify(data), | |
| }); | |
| const result = await jobResponse.json(); | |
| if (!jobResponse.ok) { | |
| output.textContent += `Error: ${result.error}`; | |
| return; | |
| } | |
| output.textContent += JSON.stringify(result, null, 2); | |
| const jobId = result["metadata"]["jobId"]; | |
| fetchEventSource(`https://huggingface.co/api/jobs/${tokenOwer}/${jobId}/sse`, { | |
| onmessage: (event) => { | |
| eventOutput.textContent += `${event.data}\n`; | |
| }, | |
| headers: { | |
| Authorization: `Bearer ${hfToken.value}`, | |
| }, | |
| }); | |
| fetchEventSource(`https://huggingface.co/api/jobs/${tokenOwer}/${jobId}/logs-stream`, { | |
| onmessage: (event) => { | |
| logOuput.textContent += `${event.data}\n`; | |
| }, | |
| headers: { | |
| Authorization: `Bearer ${hfToken.value}`, | |
| }, | |
| }); | |
| }); | |
| }); | |