This repository has been archived by the owner on Feb 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
visdom.nim
61 lines (50 loc) · 1.55 KB
/
visdom.nim
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
import httpclient, json, base64
proc webEncodeData(data, mimeType: string): string =
return "data:image/" & mimeType & ";base64," & base64.encode(data, newLine="")
proc postJson(url: string, params: JsonNode) =
let body = $params
let client = newHttpClient()
client.headers = newHttpHeaders({
"content-type": "application/json",
"content-length": $body.len
})
let response = client.request(url, httpMethod = HttpPost, body = body)
if response.code != Http200:
raise newException(IOError, "Failed to post json data")
type
VisdomClient = object
host: string
port: int
proc newVisdomClient*(host: string = "localhost", port: int = 8097): VisdomClient =
## Prepare a visdom client for visualization
result.host = host
result.port = port
proc sendEvent(self: VisdomClient, opts: JsonNode, data: JsonNode, window: string) =
let params = %*{
"eid": "main",
"opts": opts,
"data": data
}
if window.len > 0:
params["win"] = % window
let url = "http://" & self.host & ":" & $self.port & "/events"
postJson(url, params)
proc image*(vis: VisdomClient,
img: Tensor[uint8],
window: string = "",
caption: string = "",
title: string = "") =
## Show image into visdom with the given title and specified window
let opts = %*{
"title": if title.len > 0: title else: window,
"height": img.height,
"width": img.width
}
let data = %*[{
"content": {
"src": img.toJPG().webEncodeData("image/jpg"),
"caption": caption
},
"type": "image"
}]
vis.sendEvent(opts, data, window)