Coverage for trimesh/resources/__init__.py: 100%
29 statements
« prev ^ index » next coverage.py v7.14.1, created at 2026-06-24 04:40 +0000
« prev ^ index » next coverage.py v7.14.1, created at 2026-06-24 04:40 +0000
1import gzip
2import json
3import os
4from io import BytesIO
6# find the current absolute path to this directory
7_pwd = os.path.expanduser(os.path.abspath(os.path.dirname(__file__)))
8# once resources are loaded cache them
9_cache = {}
12def get_schema(name: str) -> dict:
13 """
14 Load a schema and evaluate the referenced files.
16 Parameters
17 ------------
18 name : str
19 Filename of schema.
21 Returns
22 ----------
23 schema
24 Loaded and resolved schema.
25 """
26 from ..resolvers import FilePathResolver
27 from ..schemas import resolve
29 # get a resolver for our base path
30 resolver = FilePathResolver(os.path.join(_pwd, "schema", name))
31 # recursively load `$ref` keys
32 return resolve(json.loads(resolver.get(name).decode("utf-8")), resolver=resolver)
35def get_json(name: str) -> dict:
36 """
37 Get a resource from the `trimesh/resources` folder as a decoded string.
39 Parameters
40 -------------
41 name : str
42 File path relative to `trimesh/resources/{name}`
44 Returns
45 -------------
46 resource
47 File data decoded from JSON.
48 """
49 raw = get_bytes(name)
50 if name.endswith(".gzip"):
51 raw = gzip.decompress(raw)
52 else:
53 raw = raw.decode("utf-8")
54 return json.loads(raw)
57def get_string(name: str) -> str:
58 """
59 Get a resource from the `trimesh/resources` folder as a decoded string.
61 Parameters
62 -------------
63 name
64 File path relative to `trimesh/resources`
66 Returns
67 -------------
68 resource
69 File data as a string.
70 """
71 return get_bytes(name).decode("utf-8")
74def get_bytes(name: str) -> bytes:
75 """
76 Get a resource from the `trimesh/resources` folder as binary data.
78 Parameters
79 -------------
80 name
81 File path relative to `trimesh/resources`
83 Returns
84 -------------
85 resource
86 File data as raw bytes.
87 """
88 cached = _cache.get(name, None)
89 if cached is not None:
90 return cached
92 # get the resource using relative names
93 # all templates are using POSIX relative paths
94 # so fix them to be platform-specific
95 with open(os.path.join(_pwd, *name.split("/")), "rb") as f:
96 resource = f.read()
98 _cache[name] = resource
99 return resource
102def get_stream(name: str) -> BytesIO:
103 """
104 Get a resource from the `trimesh/resources` folder as a binary stream.
106 Parameters
107 -------------
108 name : str
109 File path relative to `trimesh/resources`
111 Returns
112 -------------
113 resource
114 File data as a binary stream.
115 """
117 return BytesIO(get_bytes(name))