inferencesh 0.1.5__tar.gz → 0.1.14__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of inferencesh might be problematic. Click here for more details.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: inferencesh
3
- Version: 0.1.5
3
+ Version: 0.1.14
4
4
  Summary: inference.sh Python SDK
5
5
  Author: Inference Shell Inc.
6
6
  Author-email: "Inference Shell Inc." <hello@inference.sh>
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "inferencesh"
7
- version = "0.1.5"
7
+ version = "0.1.14"
8
8
  description = "inference.sh Python SDK"
9
9
  authors = [
10
10
  {name = "Inference Shell Inc.", email = "hello@inference.sh"},
@@ -0,0 +1,210 @@
1
+ from typing import Optional, Union, ClassVar
2
+ from pydantic import BaseModel, ConfigDict
3
+ import mimetypes
4
+ import os
5
+ import urllib.request
6
+ import urllib.parse
7
+ import tempfile
8
+
9
+ from typing import Any, Dict, List
10
+ import inspect
11
+ import ast
12
+ import textwrap
13
+ from collections import OrderedDict
14
+
15
+
16
+ # inspired by https://github.com/pydantic/pydantic/issues/7580
17
+ class OrderedSchemaModel(BaseModel):
18
+ """A base model that ensures the JSON schema properties and required fields are in the order of field definition."""
19
+
20
+ @classmethod
21
+ def model_json_schema(cls, by_alias: bool = True, **kwargs: Any) -> Dict[str, Any]:
22
+ schema = super().model_json_schema(by_alias=by_alias, **kwargs)
23
+
24
+ field_order = cls._get_field_order()
25
+
26
+ if field_order:
27
+ # Order properties
28
+ ordered_properties = OrderedDict()
29
+ for field_name in field_order:
30
+ if field_name in schema['properties']:
31
+ ordered_properties[field_name] = schema['properties'][field_name]
32
+
33
+ # Add any remaining properties that weren't in field_order
34
+ for field_name, field_schema in schema['properties'].items():
35
+ if field_name not in ordered_properties:
36
+ ordered_properties[field_name] = field_schema
37
+
38
+ schema['properties'] = ordered_properties
39
+
40
+ # Order required fields
41
+ if 'required' in schema:
42
+ ordered_required = [field for field in field_order if field in schema['required']]
43
+ # Add any remaining required fields that weren't in field_order
44
+ ordered_required.extend([field for field in schema['required'] if field not in ordered_required])
45
+ schema['required'] = ordered_required
46
+
47
+ return schema
48
+
49
+ @classmethod
50
+ def _get_field_order(cls) -> List[str]:
51
+ """Get the order of fields as they were defined in the class."""
52
+ source = inspect.getsource(cls)
53
+
54
+ # Unindent the entire source code
55
+ source = textwrap.dedent(source)
56
+
57
+ try:
58
+ module = ast.parse(source)
59
+ except IndentationError:
60
+ # If we still get an IndentationError, wrap the class in a dummy module
61
+ source = f"class DummyModule:\n{textwrap.indent(source, ' ')}"
62
+ module = ast.parse(source)
63
+ # Adjust to look at the first class def inside DummyModule
64
+ # noinspection PyUnresolvedReferences
65
+ class_def = module.body[0].body[0]
66
+ else:
67
+ # Find the class definition
68
+ class_def = next(
69
+ node for node in module.body if isinstance(node, ast.ClassDef) and node.name == cls.__name__
70
+ )
71
+
72
+ # Extract field names in the order they were defined
73
+ field_order = []
74
+ for node in class_def.body:
75
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
76
+ field_order.append(node.target.id)
77
+
78
+ return field_order
79
+
80
+ class BaseAppInput(OrderedSchemaModel):
81
+ pass
82
+
83
+ class BaseAppOutput(OrderedSchemaModel):
84
+ pass
85
+
86
+ class BaseApp(BaseModel):
87
+ model_config = ConfigDict(
88
+ arbitrary_types_allowed=True,
89
+ extra='allow'
90
+ )
91
+
92
+ async def setup(self):
93
+ pass
94
+
95
+ async def run(self, app_input: BaseAppInput) -> BaseAppOutput:
96
+ raise NotImplementedError("run method must be implemented")
97
+
98
+ async def unload(self):
99
+ pass
100
+
101
+
102
+ class File(BaseModel):
103
+ """A class representing a file in the inference.sh ecosystem."""
104
+ uri: str # Original location (URL or file path)
105
+ path: Optional[str] = None # Resolved local file path
106
+ mime_type: Optional[str] = None # MIME type of the file
107
+ size: Optional[int] = None # File size in bytes
108
+ filename: Optional[str] = None # Original filename if available
109
+ _tmp_path: Optional[str] = PrivateAttr(default=None) # Internal storage for temporary file path
110
+
111
+ def __init__(self, **data):
112
+ super().__init__(**data)
113
+ if self._is_url(self.uri):
114
+ self._download_url()
115
+ elif not os.path.isabs(self.uri):
116
+ self.path = os.path.abspath(self.uri)
117
+ else:
118
+ self.path = self.uri
119
+ self._populate_metadata()
120
+
121
+ def _is_url(self, path: str) -> bool:
122
+ """Check if the path is a URL."""
123
+ parsed = urllib.parse.urlparse(path)
124
+ return parsed.scheme in ('http', 'https')
125
+
126
+ def _download_url(self) -> None:
127
+ """Download the URL to a temporary file and update the path."""
128
+ original_url = self.uri
129
+ tmp_file = None
130
+ try:
131
+ # Create a temporary file with a suffix based on the URL path
132
+ suffix = os.path.splitext(urllib.parse.urlparse(original_url).path)[1]
133
+ tmp_file = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
134
+ self._tmp_path = tmp_file.name
135
+
136
+ # Set up request with user agent
137
+ headers = {
138
+ 'User-Agent': (
139
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
140
+ 'AppleWebKit/537.36 (KHTML, like Gecko) '
141
+ 'Chrome/91.0.4472.124 Safari/537.36'
142
+ )
143
+ }
144
+ req = urllib.request.Request(original_url, headers=headers)
145
+
146
+ # Download the file
147
+ print(f"Downloading URL: {original_url} to {self._tmp_path}")
148
+ try:
149
+ with urllib.request.urlopen(req) as response, open(self._tmp_path, 'wb') as out_file:
150
+ out_file.write(response.read())
151
+ self.path = self._tmp_path
152
+ except (urllib.error.URLError, urllib.error.HTTPError) as e:
153
+ raise RuntimeError(f"Failed to download URL {original_url}: {str(e)}")
154
+ except IOError as e:
155
+ raise RuntimeError(f"Failed to write downloaded file to {self._tmp_path}: {str(e)}")
156
+ except Exception as e:
157
+ # Clean up temp file if something went wrong
158
+ if tmp_file is not None and hasattr(self, '_tmp_path'):
159
+ try:
160
+ os.unlink(self._tmp_path)
161
+ except:
162
+ pass
163
+ raise RuntimeError(f"Error downloading URL {original_url}: {str(e)}")
164
+
165
+ def __del__(self):
166
+ """Cleanup temporary file if it exists."""
167
+ if hasattr(self, '_tmp_path') and self._tmp_path:
168
+ try:
169
+ os.unlink(self._tmp_path)
170
+ except:
171
+ pass
172
+
173
+ def _populate_metadata(self) -> None:
174
+ """Populate file metadata from the path if it exists."""
175
+ if os.path.exists(self.path):
176
+ if not self.mime_type:
177
+ self.mime_type = self._guess_mime_type()
178
+ if not self.size:
179
+ self.size = self._get_file_size()
180
+ if not self.filename:
181
+ self.filename = self._get_filename()
182
+
183
+ @classmethod
184
+ def from_path(cls, path: Union[str, os.PathLike]) -> 'File':
185
+ """Create a File instance from a file path."""
186
+ return cls(uri=str(path))
187
+
188
+ def _guess_mime_type(self) -> Optional[str]:
189
+ """Guess the MIME type of the file."""
190
+ return mimetypes.guess_type(self.path)[0]
191
+
192
+ def _get_file_size(self) -> int:
193
+ """Get the size of the file in bytes."""
194
+ return os.path.getsize(self.path)
195
+
196
+ def _get_filename(self) -> str:
197
+ """Get the base filename from the path."""
198
+ return os.path.basename(self.path)
199
+
200
+ def exists(self) -> bool:
201
+ """Check if the file exists."""
202
+ return os.path.exists(self.path)
203
+
204
+ def refresh_metadata(self) -> None:
205
+ """Refresh all metadata from the file."""
206
+ self._populate_metadata()
207
+
208
+ class Config:
209
+ """Pydantic config"""
210
+ arbitrary_types_allowed = True
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: inferencesh
3
- Version: 0.1.5
3
+ Version: 0.1.14
4
4
  Summary: inference.sh Python SDK
5
5
  Author: Inference Shell Inc.
6
6
  Author-email: "Inference Shell Inc." <hello@inference.sh>
@@ -1,74 +0,0 @@
1
- from typing import Optional, Union
2
- from pydantic import BaseModel, ConfigDict
3
- import mimetypes
4
- import os
5
-
6
- class BaseAppInput(BaseModel):
7
- pass
8
-
9
- class BaseAppOutput(BaseModel):
10
- pass
11
-
12
- class BaseApp(BaseModel):
13
- model_config = ConfigDict(arbitrary_types_allowed=True, extra='allow')
14
- async def setup(self):
15
- pass
16
-
17
- async def run(self, app_input: BaseAppInput) -> BaseAppOutput:
18
- raise NotImplementedError("run method must be implemented")
19
-
20
- async def unload(self):
21
- pass
22
-
23
-
24
- class File(BaseModel):
25
- """A class representing a file in the inference.sh ecosystem."""
26
- path: str # Absolute path to the file
27
- mime_type: Optional[str] = None # MIME type of the file
28
- size: Optional[int] = None # File size in bytes
29
- filename: Optional[str] = None # Original filename if available
30
-
31
- def __init__(self, **data):
32
- super().__init__(**data)
33
- if not os.path.isabs(self.path):
34
- self.path = os.path.abspath(self.path)
35
- self._populate_metadata()
36
-
37
- def _populate_metadata(self) -> None:
38
- """Populate file metadata from the path if it exists."""
39
- if os.path.exists(self.path):
40
- if not self.mime_type:
41
- self.mime_type = self._guess_mime_type()
42
- if not self.size:
43
- self.size = self._get_file_size()
44
- if not self.filename:
45
- self.filename = self._get_filename()
46
-
47
- @classmethod
48
- def from_path(cls, path: Union[str, os.PathLike]) -> 'File':
49
- """Create a File instance from a file path."""
50
- return cls(path=str(path))
51
-
52
- def _guess_mime_type(self) -> Optional[str]:
53
- """Guess the MIME type of the file."""
54
- return mimetypes.guess_type(self.path)[0]
55
-
56
- def _get_file_size(self) -> int:
57
- """Get the size of the file in bytes."""
58
- return os.path.getsize(self.path)
59
-
60
- def _get_filename(self) -> str:
61
- """Get the base filename from the path."""
62
- return os.path.basename(self.path)
63
-
64
- def exists(self) -> bool:
65
- """Check if the file exists."""
66
- return os.path.exists(self.path)
67
-
68
- def refresh_metadata(self) -> None:
69
- """Refresh all metadata from the file."""
70
- self._populate_metadata()
71
-
72
- class Config:
73
- """Pydantic config"""
74
- arbitrary_types_allowed = True
File without changes
File without changes
File without changes
File without changes