Skip to content

Commit b951559

Browse files
committed
create better examples
1 parent a74a88a commit b951559

File tree

4 files changed

+78
-82
lines changed

4 files changed

+78
-82
lines changed

example_jobs/add.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# this code adds two numbers
2+
3+
import time
4+
5+
a = 123
6+
b = 123
7+
8+
time.sleep(60)
9+
10+
print(a * 2 if a == b else a + b)
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# this is an absolute overkill for just adding two numbers but we will still do it
2+
3+
from nbox import Instance
4+
from pprint import pprint as peepee
5+
6+
instance = Instance("GPT4NBX", url = "https://test-2.nimblebox.ai")
7+
# instance = Instance.create("GPT4NBX", url = "https://test-2.nimblebox.ai")
8+
9+
instance.compute_server.test("get")
10+
instance.compute_server.get_files(
11+
"post", {"dir_path": "/"}, verbose = True
12+
)
13+
out = instance.compute_server.run_script("post", {"script": "add.py"}, verbose = True)
14+
print("RUN:")
15+
peepee(out)
16+
uid = out["uid"]
17+
18+
out = instance.compute_server.get_script_status("post", {"uid": out["uid"]}, verbose = True)
19+
print("STATUS:")
20+
peepee(out)
21+
22+
out = instance.compute_server.clear_jobs_db("get", verbose = True)
23+
print("CLEAR:")
24+
peepee(out)
25+
26+
out = instance.compute_server.get_script_status("post", {"uid": uid}, verbose = True)
27+
print("STATUS:")
28+
peepee(out)

example_jobs/simple_addition.py

Lines changed: 5 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,11 @@
1-
# # this is an absolute overkill for just adding two numbers but we will
2-
# # still do it
3-
4-
import time
5-
6-
from pprint import pprint as peepee
1+
# this is an absolute overkill for just adding two numbers but we will still do it
72

83
from nbox import Instance
9-
from nbox.utils import nbox_session
104

115
instance = Instance("GPT4NBX", url = "https://test-2.nimblebox.ai")
126
# instance = Instance.create("GPT4NBX", url = "https://test-2.nimblebox.ai")
13-
instance.start(True)
14-
# instance("add.py")
15-
# instance.stop()
16-
17-
instance.compute_server.test("get").json()
18-
instance.compute_server.get_files(
19-
"post", {"dir_path": "/"}, verbose = True
20-
).json()
21-
out = instance.compute_server.run_script("post", {"script": "add.py"}, verbose = True).json()
22-
print("RUN:")
23-
peepee(out)
24-
uid = out["uid"]
25-
26-
out = instance.compute_server.get_script_status("post", {"uid": out["uid"]}, verbose = True).json()
27-
print("STATUS:")
28-
peepee(out)
297

30-
out = instance.compute_server.clear_jobs_db("get", verbose = True).json()
31-
print("CLEAR:")
32-
peepee(out)
33-
34-
out = instance.compute_server.get_script_status("post", {"uid": uid}, verbose = True).json()
35-
print("STATUS:")
36-
peepee(out)
37-
38-
# class Sample():
39-
# def __init__(self):
40-
# pass
41-
# def __getattribute__(self, __name: str):
42-
# print(__name)
43-
# def __func(a, b):
44-
# return a + b
45-
# return __func
46-
47-
# s = Sample()
48-
# print(s.add)
49-
# print(s.add(123, 123))
50-
# print(s.multiply(123, 123))
8+
instance.start(True)
9+
my_uid = instance("add.py")
10+
print("My UID:", my_uid)
11+
instance(my_uid)

nbox/jobs.py

Lines changed: 35 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,17 @@ def __repr__(self):
2727
return f"<Subway ({self.url})>"
2828

2929
def __getattr__(self, attr):
30+
# https://stackoverflow.com/questions/3278077/difference-between-getattr-vs-getattribute
3031
def wrapper(method = "get", data = None, verbose = False):
3132
fn = getattr(nbox_session, method)
3233
url = f"{self.url}/{attr}"
3334
if verbose:
3435
logger.info(f"Calling {url}")
35-
return fn(url, json = data)
36+
r = fn(url, json = data)
37+
if verbose:
38+
logger.info(r.content.decode())
39+
r.raise_for_status() # good when server is good
40+
return r.json()
3641
return wrapper
3742

3843

@@ -133,8 +138,8 @@ def start(self, cpu_only = False, gpu_count = 1):
133138

134139
if not self.state == "RUNNING":
135140
logger.info(f"Starting instance {self.instance_id}")
136-
r = self.web_server.start_instance(
137-
method = "post",
141+
message = self.web_server.start_instance(
142+
"post",
138143
data = {
139144
"instance_id": self.instance_id,
140145
"hw":"cpu" if cpu_only else "gpu",
@@ -144,8 +149,7 @@ def start(self, cpu_only = False, gpu_count = 1):
144149
"gpuCount": gpu_count,
145150
}
146151
}
147-
)
148-
message = r.json()["msg"]
152+
)["msg"]
149153
if not message == "success":
150154
raise ValueError(message)
151155

@@ -164,9 +168,9 @@ def start(self, cpu_only = False, gpu_count = 1):
164168
# now the instance is running, we can open it, opening will assign a bunch of cookies and
165169
# then get us the exact location of the instance
166170
logger.info(f"Opening instance {self.instance_id}")
167-
r = self.web_server.open_instance(method = "post", data = {"instance_id":self.instance_id})
168-
r.raise_for_status()
169-
instance_url = r.json()["base_url"].lstrip("/").rstrip("/")
171+
instance_url = self.web_server.open_instance(
172+
"post", data = {"instance_id":self.instance_id}
173+
)["base_url"].lstrip("/").rstrip("/")
170174
self.cs_url = f"{self.url}/{instance_url}/server"
171175

172176
# create a subway
@@ -175,51 +179,47 @@ def start(self, cpu_only = False, gpu_count = 1):
175179

176180
# run a simple test and see if everything is working or not
177181
logger.info(f"Testing instance {self.instance_id}")
178-
r = self.compute_server.test()
179-
r.raise_for_status()
180-
182+
self.compute_server.test()
181183
self.__opened = True
182184

183-
def __call__(self, path_or_func):
185+
def __call__(self, path_or_func_or_uid):
184186
if not self.__opened:
185187
raise ValueError("Instance is not opened, please call .start() first")
186188

187-
if isinstance(path_or_func, str):
188-
if path_or_func not in self.running_scripts:
189+
if isinstance(path_or_func_or_uid, str):
190+
if path_or_func_or_uid not in self.running_scripts:
189191
# this script is not running, so we will start it
190-
logger.info(f"Running script {path_or_func} on instance {self.instance_id}")
191-
r = self.compute_server.run_script(method = "post", data = {"script_path": path_or_func})
192-
r.raise_for_status()
193-
message = r.json()["msg"]
192+
logger.info(f"Running script {path_or_func_or_uid} on instance {self.instance_id}")
193+
data = self.compute_server.run_script("post", data = {"script": path_or_func_or_uid})
194+
message = data["msg"]
195+
self.running_scripts.append(data["uid"])
194196
if not message == "success":
195197
raise ValueError(message)
196-
self.running_scripts.append(path_or_func)
198+
logger.info(f"Script {path_or_func_or_uid} started on instance {self.instance_id} with UID: {data['uid']}")
199+
return data["uid"]
197200
else:
198201
# we already have this script running, so get the status of this script
199-
logger.info(f"Getting status of script {path_or_func} on instance {self.instance_id}")
200-
r = self.compute_server.get_script_status(method = "post", data = {"script": path_or_func})
201-
message = r.json()["msg"]
202-
if not message == "script running":
203-
raise ValueError(message)
204-
elif "script not running" in message:
205-
logger.info(f"Script {path_or_func} on instance {self.instance_id} is either completed or errored out.")
202+
logger.info(f"Getting status of script {path_or_func_or_uid} on instance {self.instance_id}")
203+
data = self.compute_server.get_script_status("post", data = {"uid": path_or_func_or_uid})
204+
if not data["msg"] == "success":
205+
raise ValueError(data["msg"])
206206
else:
207-
raise ValueError(message)
207+
status = "RUNNING" if data["status"] else "STOPPED" # /ERRORED
208+
logger.info(f"Script {path_or_func_or_uid} on instance {self.instance_id} is {status}")
208209

209-
elif callable(path_or_func):
210+
elif callable(path_or_func_or_uid):
210211
# this is the next generation power of nbox, we can pass a function to run on the instance (CasH step1)
211212
raise ValueError("callable methods are not supported yet, will be included in the next release")
212213
else:
213-
raise ValueError("path_or_func must be a string or a function")
214+
raise ValueError("path_or_func_or_uid must be a string or a function")
214215

215216
def stop(self):
216217
if self.state == "STOPPED":
217218
logger.info(f"Instance {self.instance_id} is already stopped")
218219
return
219220

220221
logger.info(f"Stopping instance {self.instance_id}")
221-
r = self.web_server.stop_instance(method="post", data = {"instance_id":self.instance_id})
222-
message = r.json()["msg"]
222+
message = self.web_server.stop_instance("post", data = {"instance_id":self.instance_id})["msg"]
223223
if not message == "success":
224224
raise ValueError(message)
225225

@@ -239,16 +239,13 @@ def delete(self, force = False):
239239
if self.__opened and not force:
240240
raise ValueError("Instance is still opened, please call .stop() first")
241241

242-
r = self.web_server.delete_instance(method = "post", data = {"instance_id":self.instance_id})
243-
r.raise_for_status()
244-
message = r.json()["msg"]
242+
message = self.web_server.delete_instance("post", data = {"instance_id":self.instance_id})["msg"]
245243
if not message == "success":
246244
raise ValueError(message)
247245

248246
def update(self):
249-
r = self.web_server.get_user_instances(method = "post", data = {"instance_id": self.instance_id})
250-
r.raise_for_status()
251-
for k,v in r.json().items():
247+
out = self.web_server.get_user_instances("post", data = {"instance_id": self.instance_id})
248+
for k,v in out.items():
252249
if k in self.useful_keys:
253250
setattr(self, k, v)
254-
self.data = r.json()
251+
self.data = out

0 commit comments

Comments
 (0)