Skip to content

Commit

Permalink
Implement preview worker
Browse files Browse the repository at this point in the history
  • Loading branch information
YayunHuang committed Aug 16, 2024
1 parent 0c15bbb commit 96c7a4c
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions public/scripts/preview_worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
importScripts("https://cdn.jsdelivr.net/pyodide/v0.23.4/full/pyodide.js");

async function initianPyodide() {
console.log("start startup");
const pyodide = await loadPyodide();
await pyodide.loadPackage(["numpy", "opencv-python", "pillow", "micropip"]);
let zipResponse = await fetch("/mockup.zip");
let zipBinary = await zipResponse.arrayBuffer();
pyodide.unpackArchive(zipBinary, "zip");
await pyodide.runPythonAsync(
`
from pyodide.http import pyfetch
response = await pyfetch("/image_process.py")
with open("./image_process.py", "wb") as f:
f.write(await response.bytes())
`,
(output) => console.log(output),
(output) => console.log(output),
);
console.log("end up");
return pyodide;
}

async function runPreviewMockup(pyodide) {
let pythonNamespace = pyodide.globals.get("dict")();
await pyodide.runPythonAsync(
`
import mockup
import image_process
from js import locationKey, imageUploadList, deviceInfo, deviceId
origin_image_List = await image_process.upload_files()
print("start preview")
output_img_path_list = await mockup.previewMockup(locationKey, deviceId, origin_image_List, deviceInfo)
`,
{ globals: pythonNamespace },
);
pyodide.runPython(
`
temp = image_process.save_image(output_img_path_list)
`,
{ globals: pythonNamespace },
);
return pythonNamespace.get("temp").toJs();
}

async function main() {
let pyodideObject = initianPyodide();
self.onmessage = async (event) => {
pyodideObject = await pyodideObject;

self["imageUploadList"] = event.data.imageUploadList;
self["locationKey"] = event.data.location;
self["deviceId"] = event.data.deviceId;
self["deviceInfo"] = event.data.deviceInfo;

try {
let results = await runPreviewMockup(pyodideObject);
console.log("preview results", results);
self.postMessage(results);
} catch (error) {
self.postMessage({ error: error.message });
}
};
}

main();

0 comments on commit 96c7a4c

Please sign in to comment.