Skip to content

Commit 1e024cd

Browse files
committed
add js example
Signed-off-by: Praneeth Bedapudi <[email protected]>
1 parent cfa5350 commit 1e024cd

File tree

1 file changed

+176
-0
lines changed

1 file changed

+176
-0
lines changed

clients/browser_side_js/client.html

+176
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6+
<title>FDClient Test with Multiple File Upload and Download</title>
7+
<script src="https://unpkg.com/@msgpack/[email protected]/dist.es5+umd/msgpack.min.js"></script>
8+
<style>
9+
main {
10+
width: 80%;
11+
margin: 20px auto;
12+
}
13+
#fileList, #downloadList {
14+
margin-top: 10px;
15+
}
16+
#result {
17+
white-space: pre-wrap;
18+
word-break: break-all;
19+
}
20+
</style>
21+
<script>
22+
// FDClient class implementation
23+
class FDClient {
24+
constructor(serverUrl, compression = true, requestTimeout = null) {
25+
if (!serverUrl.startsWith("http://") && !serverUrl.startsWith("https://")) {
26+
throw new Error("Server URL must start with http:// or https://");
27+
}
28+
if ((serverUrl.match(/\//g) || []).length !== 2) {
29+
throw new Error("Server URL must be in the format http(s)://<ip>:<port>");
30+
}
31+
this.serverUrl = serverUrl;
32+
this.compression = compression;
33+
this.requestTimeout = requestTimeout;
34+
this.inputType = 'msgpack';
35+
}
36+
37+
async infer(data, uniqueId = null, isAsync = false) {
38+
if (!Array.isArray(data)) {
39+
throw new Error("Data must be of type array");
40+
}
41+
42+
uniqueId = uniqueId || crypto.randomUUID();
43+
44+
let packedData = MessagePack.encode(data);
45+
46+
const params = new URLSearchParams({
47+
unique_id: uniqueId,
48+
async: isAsync,
49+
input_type: this.inputType,
50+
compressed: false,
51+
});
52+
53+
const response = await fetch(`${this.serverUrl}/infer?${params}`, {
54+
method: 'POST',
55+
headers: {
56+
'Content-Type': 'application/octet-stream',
57+
},
58+
body: packedData,
59+
signal: this.requestTimeout ? AbortSignal.timeout(this.requestTimeout) : undefined,
60+
});
61+
62+
return await MessagePack.decodeAsync(response.body);
63+
}
64+
}
65+
66+
let client;
67+
68+
function initClient() {
69+
const serverUrl = document.getElementById('serverUrl').value;
70+
client = new FDClient(serverUrl);
71+
console.log("Client initialized with server URL:", serverUrl);
72+
}
73+
74+
function updateFileList() {
75+
const fileInput = document.getElementById('fileInput');
76+
const fileList = document.getElementById('fileList');
77+
fileList.innerHTML = '';
78+
for (let file of fileInput.files) {
79+
const li = document.createElement('li');
80+
li.textContent = `${file.name} (${file.type || 'unknown'}) - ${file.size} bytes`;
81+
fileList.appendChild(li);
82+
}
83+
}
84+
85+
function byteArrayToHexString(byteArray) {
86+
return Array.from(byteArray, function(byte) {
87+
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
88+
}).join(' ');
89+
}
90+
91+
function createDownloadLink(filename, content) {
92+
const blob = new Blob([content], { type: 'application/octet-stream' });
93+
const url = URL.createObjectURL(blob);
94+
const a = document.createElement('a');
95+
a.href = url;
96+
a.download = filename;
97+
a.textContent = `Download ${filename}`;
98+
return a;
99+
}
100+
101+
async function testInfer() {
102+
if (!client) {
103+
alert("Please initialize the client first!");
104+
return;
105+
}
106+
107+
const fileInput = document.getElementById('fileInput');
108+
if (fileInput.files.length === 0) {
109+
alert("Please select at least one file!");
110+
return;
111+
}
112+
113+
try {
114+
const fileContents = await Promise.all(
115+
Array.from(fileInput.files).map(file =>
116+
new Promise((resolve, reject) => {
117+
const reader = new FileReader();
118+
reader.onload = e => resolve(new Uint8Array(e.target.result));
119+
reader.onerror = reject;
120+
reader.readAsArrayBuffer(file);
121+
})
122+
)
123+
);
124+
125+
console.time('infer');
126+
const result = await client.infer(fileContents);
127+
console.timeEnd('infer');
128+
129+
if (result && result.prediction && Array.isArray(result.prediction)) {
130+
const downloadList = document.getElementById('downloadList');
131+
downloadList.innerHTML = '';
132+
result.prediction.forEach((fileContent, index) => {
133+
const filename = `output_file_${index + 1}`;
134+
const li = document.createElement('li');
135+
const downloadLink = createDownloadLink(filename, fileContent);
136+
li.appendChild(downloadLink);
137+
downloadList.appendChild(li);
138+
});
139+
document.getElementById('result').textContent = `Received ${result.prediction.length} file(s). You can download them using the links above.`;
140+
} else {
141+
document.getElementById('result').textContent = "Unexpected response format. Raw response:\n" + JSON.stringify(result, null, 2);
142+
}
143+
} catch (error) {
144+
console.error("Error during inference:", error);
145+
document.getElementById('result').textContent = "Error: " + error.message;
146+
}
147+
}
148+
</script>
149+
</head>
150+
<body>
151+
<main>
152+
<h1>FDClient Test with Multiple File Upload and Download</h1>
153+
<div>
154+
<label for="serverUrl">Server URL:</label>
155+
<input type="text" id="serverUrl" value="http://localhost:8080">
156+
<button onclick="initClient()">Initialize Client</button>
157+
</div>
158+
<div>
159+
<label for="fileInput">Select Files:</label>
160+
<input type="file" id="fileInput" multiple onchange="updateFileList()">
161+
<ul id="fileList"></ul>
162+
</div>
163+
<div>
164+
<button onclick="testInfer()">Test Infer</button>
165+
</div>
166+
<div>
167+
<h3>Download Processed Files:</h3>
168+
<ul id="downloadList"></ul>
169+
</div>
170+
<div>
171+
<h3>Result:</h3>
172+
<pre id="result"></pre>
173+
</div>
174+
</main>
175+
</body>
176+
</html>

0 commit comments

Comments
 (0)