-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
353 lines (295 loc) · 10.1 KB
/
client.py
File metadata and controls
353 lines (295 loc) · 10.1 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "httpx==0.28.1",
# "marimo",
# "requests==2.32.5",
# ]
# ///
import marimo
__generated_with = "0.17.7"
app = marimo.App(width="medium")
@app.cell
def _():
import marimo as mo
import requests
import json
import httpx
from collections import deque
import asyncio
return asyncio, deque, httpx, json, mo, requests
@app.cell
def _(mo):
mo.md(r"""
# CTController Client
""")
return
@app.cell
def _(mo):
user_controller_ip = mo.ui.text(value=f'http://127.0.0.1:8080', label='CTController IP: ', full_width=True)
user_controller_ip
return (user_controller_ip,)
@app.cell
def _(user_controller_ip):
controller_ip = user_controller_ip.value
return (controller_ip,)
@app.cell
def _(controller_ip, requests):
def get_request(endpoint):
try:
response = requests.get(f"{controller_ip}/{endpoint}")
response.raise_for_status()
return response.json()
except requests.RequestException as e:
return(f"Error fetching data from {endpoint}: {e}")
return (get_request,)
@app.cell
def _(controller_ip, requests):
def post_request(endpoint, payload={}, files={}):
try:
response = requests.post(f"{controller_ip}/{endpoint}", json=payload, files=files)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
return(f"Error posting data to {endpoint}: {e}")
return (post_request,)
@app.cell
def _(controller_ip, requests):
def file_get_request(endpoint):
try:
response = requests.get(f"{controller_ip}/{endpoint}")
response.raise_for_status()
return response.content.decode('utf-8')
except requests.RequestException as e:
return(f"Error fetching file from {endpoint}: {e}")
return (file_get_request,)
@app.cell
def _(get_request):
def check_health():
return get_request('health')
return
@app.cell
def _():
default_config_payload = {
"gpu": "false",
"ckn_mqtt_broker": "10.169.143.160",
"ct_version": "latest",
"model": "yolov5nu_ep120_bs32_lr0.001_0cfb1c03.pt",
"inference_server": "false",
"detection_thresholds": "{\"animal\": \"0.7\"}",
"image_store_save_threshold": "0",
"image_store_reduce_save_threshold": "0"
}
return (default_config_payload,)
@app.cell
def _(config_payload_box, json):
config_payload = json.loads(config_payload_box.value)
return (config_payload,)
@app.cell
def _(mo):
startup_button = mo.ui.run_button(label='Startup', kind='success')
configure_button = mo.ui.run_button(label='Configure', kind='warn')
run_button = mo.ui.run_button(label='Run', kind='success')
stop_button = mo.ui.run_button(label='Stop', kind='danger')
shutdown_button = mo.ui.run_button(label='Shutdown', kind='danger')
health_button = mo.ui.run_button(label='Check Health')
container_health_button = mo.ui.run_button(label='Container Health')
dl_logs_button = mo.ui.run_button(label='Controller Logs')
dl_config_button = mo.ui.run_button(label='Config')
dl_app_out_button = mo.ui.run_button(label='App Stdout')
dl_app_err_button = mo.ui.run_button(label='App Stderr')
stream_app_button = mo.ui.switch(label='Stream App Logs')
show_hide_stream_button = mo.ui.switch(label='Show Camera Stream')
return (
configure_button,
container_health_button,
dl_app_err_button,
dl_app_out_button,
dl_config_button,
dl_logs_button,
health_button,
run_button,
show_hide_stream_button,
shutdown_button,
startup_button,
stop_button,
stream_app_button,
)
@app.cell
def _(
configure_button,
container_health_button,
dl_app_err_button,
dl_app_out_button,
dl_config_button,
dl_logs_button,
health_button,
mo,
run_button,
shutdown_button,
startup_button,
stop_button,
):
mo.vstack(
[
mo.hstack([startup_button, configure_button, run_button, stop_button, shutdown_button], justify='center', gap=1.5),
mo.hstack([health_button, container_health_button, dl_logs_button, dl_config_button, dl_app_out_button, dl_app_err_button], justify='center', gap=1.5),
],
gap=2
)
return
@app.cell
def _(list_models_button, mo, model_input, upload_button):
mo.hstack([model_input, upload_button, list_models_button], justify='center', gap=1.5)
return
@app.cell
def _(default_config_payload, json, mo):
config_payload_box = mo.ui.text_area(value=json.dumps(default_config_payload, indent=2), label='Configuration: ', full_width=True, rows=10)
config_payload_box
return (config_payload_box,)
@app.cell
def _():
#stream_task = None
state = {'stream_task': None, 'show_stream': False, 'stream_frame': None}
return (state,)
@app.cell
def _(
config_payload,
configure_button,
container_health_button,
dl_app_err_button,
dl_app_out_button,
dl_config_button,
dl_logs_button,
file_get_request,
get_request,
health_button,
json,
list_models_button,
model_input,
post_request,
run_button,
shutdown_button,
startup_button,
state,
stop_button,
upload_button,
):
mapping = [
(startup_button, (lambda: post_request('startup'), False)),
(configure_button, (lambda: post_request('configure', config_payload), False)),
(run_button, (lambda: post_request('run'), False)),
(stop_button, (lambda: post_request('stop'), False)),
(shutdown_button, (lambda: post_request('shutdown'), False)),
(dl_logs_button, (lambda: file_get_request('controller_logs/download'), False)),
(dl_config_button, (lambda: file_get_request('dl_config'), False)),
(health_button, (lambda: get_request('health'), False)),
(dl_app_out_button, (lambda: file_get_request('app_logs/download/stdout'), False)),
(dl_app_err_button, (lambda: file_get_request('app_logs/download/stderr'), False)),
(container_health_button, (lambda: get_request('health/containers'), False)),
(list_models_button, (lambda: get_request('list_models'), False)),
]
response_output = ''
counter = 0
for button, (fhandle, is_stream) in mapping:
if button.value:
if state["stream_task"] and not state["stream_task"].done():
state["stream_task"].cancel()
if is_stream:
state["stream_task"] = fhandle()
else:
result = fhandle()
if isinstance(result, dict):
if 'message' in result.keys():
response_output=result['message']
else:
response_output = json.dumps(result, indent=2)
elif result is None:
pass
else:
response_output = str(result)
state['response_output'] = response_output
response_output = state['response_output']
counter = (counter + 1) % 2
if upload_button.value and model_input.value is not None:
response = post_request('upload_model', files={'file': (model_input.value[0].name, model_input.value[0].contents)})
response_output = response['message'] if 'message' in response else ''
return counter, response_output
@app.cell
def _(counter, state):
header = counter
if state.get('response_output'):
header = state['response_output'].split('\n')[0]
else:
header = ''
print(header)
return
@app.cell
def _(mo, response_output):
mo.ui.text_area(
value=response_output,
label="API Response",
full_width=True,
disabled=True,
rows=10
)
return
@app.cell
def _(asyncio, deque, httpx):
async def tail_stream(url, n=100):
buffer = deque(maxlen=n)
async with httpx.AsyncClient(timeout=None) as client:
async with client.stream("GET", url) as response:
response.raise_for_status()
async for chunk in response.aiter_text():
for line in chunk.splitlines():
buffer.append(line)
yield "\n".join(buffer)
await asyncio.sleep(0)
return (tail_stream,)
@app.cell
def _(asyncio, controller_ip, tail_stream):
def launch_stream(state, endpoint, response_output):
if state.get('stream_task') is None or state.get('stream_task').done():
async def stream_runner():
async for text in tail_stream(f'{controller_ip}/{endpoint}', n=10):
state['response_output'] = text
state['stream_task'] = asyncio.create_task(stream_runner())
return state['stream_task']
#stream_task = asyncio.create_task(tail_stream(f'{controller_ip}/{endpoint}', n=10))
return
@app.cell
def _(mo, show_hide_stream_button):
mo.hstack([show_hide_stream_button], justify='center')
return
@app.cell
def _(mo, show_hide_stream_button, user_controller_ip):
video_port = 8081
host_ip = ':'.join(user_controller_ip.value.split(':')[:-1])
video_ip = f'{host_ip}:{video_port}'
if show_hide_stream_button.value:
stream_frame = mo.Html(f'<div style="display: flex; justify-content: center"><img src={video_ip} /></div>')
else:
stream_frame = None
stream_frame
return
@app.cell
def _(mo, stream_app_button):
mo.hstack([stream_app_button], justify='center')
return
@app.cell
def _(controller_ip, mo, stream_app_button):
if stream_app_button.value:
app_stream = mo.iframe(f'{controller_ip}/app_logs/stream')
else:
app_stream = None
app_stream
return
@app.cell
def _(mo):
model_input = mo.ui.file()
upload_button = mo.ui.run_button(label="Upload")
list_models_button = mo.ui.run_button(label="List Models")
return list_models_button, model_input, upload_button
if __name__ == "__main__":
app.run()