-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathhuggingface_ws.js
80 lines (69 loc) · 1.84 KB
/
huggingface_ws.js
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import WebSocket from 'ws';
function generateHash() {
const chars = "qwertyuopasdfghjklizxcvbnm0123456789"
let hash = ""
for (let i = 0; i < 11; i++) {
hash += chars[Math.floor(Math.random() * chars.length)]
}
return {
session_hash: hash,
fn_index: 2
}
}
function request(API_URL,userData, callback,opts={}, tryCount=5) {
const client = new WebSocket(API_URL);
const hash = generateHash()
let tmr = setTimeout(() => {
client.close()
callback({
error: true
})
}, 10 * 60 * 1000);
client.on("open", () => {
})
client.on("error",(err)=>{
console.log(err)
callback({
error:true,
})
})
client.on("message", (message) => {
let msg = JSON.parse("" + message)
if (msg.msg == "send_hash") {
client.send(JSON.stringify(hash))
} else if (msg.msg == "send_data") {
let data = {
data: userData,
...hash,
...opts
}
client.send(JSON.stringify(data))
} else if (msg.msg == "process_completed") {
clearTimeout(tmr)
try{
const results = msg.output.data
callback({
error:false,
results
})
}catch(e){
callback({
error:true,
})
}
}else if(msg.msg == "queue_full"){
if(tryCount <= 0){
callback({
error:true,
})
}else{
setTimeout(()=>{
request(API_URL,userData,callback,opts,tryCount-1)
},5000)
}
}
})
}
export default {
request
}