openai/openai-python

Public

mirrored from https://github.com/openai/openai-pythonAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.10.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

openai/upload_progress.py

52lines · modecode

1import io
2
3
4class CancelledError(Exception):
5 def __init__(self, msg):
6 self.msg = msg
7 Exception.__init__(self, msg)
8
9 def __str__(self):
10 return self.msg
11
12 __repr__ = __str__
13
14
15class BufferReader(io.BytesIO):
16 def __init__(self, buf=b"", desc=None):
17 self._len = len(buf)
18 io.BytesIO.__init__(self, buf)
19 self._progress = 0
20 self._callback = progress(len(buf), desc=desc)
21
22 def __len__(self):
23 return self._len
24
25 def read(self, n=-1):
26 chunk = io.BytesIO.read(self, n)
27 self._progress += len(chunk)
28 if self._callback:
29 try:
30 self._callback(self._progress)
31 except Exception as e: # catches exception from the callback
32 raise CancelledError("The upload was cancelled: {}".format(e))
33 return chunk
34
35
36def progress(total, desc):
37 import tqdm # type: ignore
38
39 meter = tqdm.tqdm(total=total, unit_scale=True, desc=desc)
40
41 def incr(progress):
42 meter.n = progress
43 if progress == total:
44 meter.close()
45 else:
46 meter.refresh()
47
48 return incr
49
50
51def MB(i):
52 return int(i // 1024 ** 2)
53