Skip to content

Commit

Permalink
adding scripts and outputs to litterbox (#161)
Browse files Browse the repository at this point in the history
* adding scripts and outputs to litterbox

* Updating script outputs

* rename some stuff for tests

Signed-off-by: Jess Frazelle <[email protected]>

* fix tests

Signed-off-by: Jess Frazelle <[email protected]>

* Updating script outputs

* format

Signed-off-by: Jess Frazelle <[email protected]>

* Updating script outputs

---------

Signed-off-by: Jess Frazelle <[email protected]>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Jess Frazelle <[email protected]>
  • Loading branch information
3 people authored Jan 8, 2024
1 parent 7a18fe8 commit c2ed6af
Show file tree
Hide file tree
Showing 8 changed files with 305 additions and 1 deletion.
7 changes: 7 additions & 0 deletions .github/workflows/build-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ on:
paths:
- '**.py'
- '**.go'
- '**.js'
- '**.ts'
- 'ORIGINALVOXEL-3.obj'
- .github/workflows/build-test.yml
- requirements.txt
Expand All @@ -13,6 +15,8 @@ on:
paths:
- '**.py'
- '**.go'
- '**.js'
- '**.ts'
- 'ORIGINALVOXEL-3.obj'
- .github/workflows/build-test.yml
- requirements.txt
Expand Down Expand Up @@ -65,6 +69,8 @@ jobs:
- ./tutorials/conversion_obj_stl
- ./tutorials/get_mass_volume
- ./tutorials/getting_started
- ./tutorials/modeling_websocket
- ./tutorials/beginner_tutorial
- ./samples/convert_file
- ./samples/file_density
- ./samples/file_mass
Expand Down Expand Up @@ -100,6 +106,7 @@ jobs:
matrix:
node: [16, 18]
test-path:
- ./tutorials/beginner_tutorial
- ./samples/convert_file
- ./samples/file_density
- ./samples/file_mass
Expand Down
3 changes: 3 additions & 0 deletions dodecahedron.obj
Git LFS file not shown
3 changes: 3 additions & 0 deletions gear.obj
Git LFS file not shown
26 changes: 26 additions & 0 deletions tutorials/beginner_tutorial/convert.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { file } from '@kittycad/lib'
import fsp from 'fs/promises'

async function convertOBJtoSTEP() {
// Use KittyCAD client library to output base64 string from OBJ to STEP
const response = await file.create_file_conversion({
output_format: 'step',
src_format: 'obj',
body: await fsp.readFile('./gear.obj', 'base64'),
})


for (const key in response.outputs) {
if (response.outputs.hasOwnProperty(key)) {
const output = response.outputs[key];
const outputFilePath = "./output.step";

console.log(`Saving output to ${outputFilePath}`);

const decodedData = Buffer.from(output, "base64").toString("utf-8");
fsp.writeFile(outputFilePath, decodedData);
}
}
}

convertOBJtoSTEP()
51 changes: 51 additions & 0 deletions tutorials/beginner_tutorial/convert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from typing import Dict, Optional, Union

from kittycad.api.file import create_file_conversion
from kittycad.client import ClientFromEnv
from kittycad.models import Error, FileConversion
from kittycad.models.base64data import Base64Data
from kittycad.models.file_export_format import FileExportFormat
from kittycad.models.file_import_format import FileImportFormat
from kittycad.types import Unset

# Create a new client with your token parsed from the environment variable:
# KITTYCAD_API_TOKEN.


def convertOBJtoSTL():
client = ClientFromEnv(timeout=500, verify_ssl=True)

# Convert a file from OBJ to STL.
# Read in the contents of the file.
file = open("./dodecahedron.obj", "rb")
content = file.read()
file.close()

result: Optional[Union[Error, FileConversion]] = create_file_conversion.sync(
client=client,
body=content,
src_format=FileImportFormat.OBJ,
output_format=FileExportFormat.STL,
)

if isinstance(result, Error) or result is None:
raise Exception("There was a problem")

body: FileConversion = result

if isinstance(body.outputs, Unset):
raise Exception("Expected outputs to be set")

outputs: Dict[str, Base64Data] = body.outputs

for _, output in outputs.items():
output_file_path = "./output.stl"
print(f"Saving output to {output_file_path}")
output_file = open(output_file_path, "wb")
output_file.write(output.get_decoded())
output_file.close()

return body


convertOBJtoSTL()
2 changes: 1 addition & 1 deletion tutorials/conversion_obj_step/output.step
Git LFS file not shown
214 changes: 214 additions & 0 deletions tutorials/modeling_websocket/modeling_websocket.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
import json
import os
import uuid

from kittycad.api.modeling import modeling_commands_ws
from kittycad.client import ClientFromEnv
from kittycad.models import ImageFormat, ModelingCmd, ModelingCmdId, WebSocketRequest
from kittycad.models.modeling_cmd import (
close_path,
default_camera_look_at,
extend_path,
extrude,
move_path_pen,
start_path,
take_snapshot,
)
from kittycad.models.path_segment import line
from kittycad.models.web_socket_request import modeling_cmd_req


def make_cube():
# Create our client.
client = ClientFromEnv()

# Create a unique id for the sketch path.
sketch_path_id = uuid.uuid4()

# Connect to the websocket.
with modeling_commands_ws.WebSocket(
client=client,
fps=30,
unlocked_framerate=False,
video_res_height=360,
video_res_width=480,
webrtc=False,
) as websocket:
# Draw a sqaure

# Start the Path
websocket.send(
WebSocketRequest(
modeling_cmd_req(
cmd=ModelingCmd(start_path()), cmd_id=ModelingCmdId(sketch_path_id)
),
)
)

websocket.send(
WebSocketRequest(
modeling_cmd_req(
cmd=ModelingCmd(
move_path_pen(
path=str(sketch_path_id),
to={
"x": -5,
"y": -5,
"z": 0,
},
)
),
cmd_id=ModelingCmdId(uuid.uuid4()),
)
)
)

websocket.send(
WebSocketRequest(
modeling_cmd_req(
cmd=ModelingCmd(
extend_path(
path=str(sketch_path_id),
segment=line(
end={
"x": 10,
"y": 0,
"z": 0,
},
relative=True,
),
)
),
cmd_id=ModelingCmdId(uuid.uuid4()),
)
)
)

websocket.send(
WebSocketRequest(
modeling_cmd_req(
cmd=ModelingCmd(
extend_path(
path=str(sketch_path_id),
segment=line(
end={
"x": 0,
"y": 10,
"z": 0,
},
relative=True,
),
)
),
cmd_id=ModelingCmdId(uuid.uuid4()),
)
)
)

websocket.send(
WebSocketRequest(
modeling_cmd_req(
cmd=ModelingCmd(
extend_path(
path=str(sketch_path_id),
segment=line(
end={
"x": -10,
"y": 0,
"z": 0,
},
relative=True,
),
)
),
cmd_id=ModelingCmdId(uuid.uuid4()),
)
)
)

# Close the sketch
websocket.send(
WebSocketRequest(
modeling_cmd_req(
cmd=ModelingCmd(close_path(path_id=ModelingCmdId(sketch_path_id))),
cmd_id=ModelingCmdId(uuid.uuid4()),
)
)
)

# Extrude the square into a cube
websocket.send(
WebSocketRequest(
modeling_cmd_req(
cmd=ModelingCmd(
extrude(
cap=True,
distance=10,
target=ModelingCmdId(sketch_path_id),
)
),
cmd_id=ModelingCmdId(uuid.uuid4()),
)
)
)

# Get the messages.
while True:
message = websocket.recv()
print(json.dumps(message.model_dump_json(), indent=4, sort_keys=True))
break

# Orient the camera.
websocket.send(
WebSocketRequest(
modeling_cmd_req(
cmd=ModelingCmd(
default_camera_look_at(
center={"x": 0, "y": 0, "z": 0},
up={"x": 0, "y": 0, "z": 1},
vantage={"x": 20, "y": 20, "z": 20},
)
),
cmd_id=ModelingCmdId(uuid.uuid4()),
)
)
)

# Take a snapshot.
websocket.send(
WebSocketRequest(
modeling_cmd_req(
cmd=ModelingCmd(take_snapshot(format=ImageFormat.PNG)),
cmd_id=ModelingCmdId(uuid.uuid4()),
)
)
)

png_contents = b""
for message in websocket:
message_dict = message.model_dump()
print(message_dict)
if (
message_dict["resp"]["data"]["modeling_response"]["type"]
== "take_snapshot"
):
png_contents = message_dict["resp"]["data"]["modeling_response"][
"data"
]["contents"].get_decoded()
break

# Save the contents to a file.
dir_path = os.path.dirname(os.path.realpath(__file__))
png_path = os.path.join(dir_path, "snapshot.png")
print(png_path)
with open(png_path, "wb") as f:
f.write(png_contents)

# Ensure the file is not empty.
assert len(png_contents) > 0

# Ensure the file exists.
assert os.path.exists(png_path)


make_cube()
Binary file added tutorials/modeling_websocket/snapshot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit c2ed6af

Please sign in to comment.