Shroominic commited on
Commit
bbd909e
·
1 Parent(s): 8f62e66

file methods

Browse files
Files changed (1) hide show
  1. codeinterpreterapi/schema/file.py +57 -0
codeinterpreterapi/schema/file.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from pydantic import BaseModel
3
+
4
+
5
+ class File(BaseModel):
6
+ name: str
7
+ content: bytes
8
+
9
+ @classmethod
10
+ def from_path(cls, path: str):
11
+ with open(path, "rb") as f:
12
+ path = path.split("/")[-1]
13
+ return cls(name=path, content=f.read())
14
+
15
+ @classmethod
16
+ async def afrom_path(cls, path: str):
17
+ await asyncio.to_thread(cls.from_path, path)
18
+
19
+ @classmethod
20
+ def from_url(cls, url: str):
21
+ import requests # type: ignore
22
+ r = requests.get(url)
23
+ return cls(name=url.split("/")[-1], content=r.content)
24
+
25
+ @classmethod
26
+ async def afrom_url(cls, url: str):
27
+ import aiohttp
28
+ async with aiohttp.ClientSession() as session:
29
+ async with session.get(url) as r:
30
+ return cls(name=url.split("/")[-1], content=await r.read())
31
+
32
+ def save(self, path: str):
33
+ with open(path, "wb") as f:
34
+ f.write(self.content)
35
+
36
+ async def asave(self, path: str):
37
+ await asyncio.to_thread(self.save, path)
38
+
39
+ def show_image(self):
40
+ try:
41
+ from PIL import Image # type: ignore
42
+ except ImportError:
43
+ print("Please install it with `pip install codeinterpreterapi[image_support]` to display images.")
44
+ exit(1)
45
+
46
+ from io import BytesIO
47
+ img_io = BytesIO(self.content)
48
+ img = Image.open(img_io)
49
+
50
+ # Display the image
51
+ img.show()
52
+
53
+ def __str__(self):
54
+ return self.name
55
+
56
+ def __repr__(self):
57
+ return f"File(name={self.name})"