21
21
import logging
22
22
from google .generativeai import protos
23
23
from itertools import islice
24
+ from io import IOBase
24
25
25
26
from google .generativeai .types import file_types
26
27
32
33
33
34
34
35
def upload_file (
35
- path : str | pathlib .Path | os .PathLike ,
36
+ path : str | pathlib .Path | os .PathLike | IOBase ,
36
37
* ,
37
38
mime_type : str | None = None ,
38
39
name : str | None = None ,
@@ -42,7 +43,7 @@ def upload_file(
42
43
"""Calls the API to upload a file using a supported file service.
43
44
44
45
Args:
45
- path: The path to the file to be uploaded.
46
+ path: The path to the file or a file-like object (e.g., BytesIO) to be uploaded.
46
47
mime_type: The MIME type of the file. If not provided, it will be
47
48
inferred from the file extension.
48
49
name: The name of the file in the destination (e.g., 'files/sample-image').
@@ -57,17 +58,22 @@ def upload_file(
57
58
"""
58
59
client = get_default_file_client ()
59
60
60
- path = pathlib .Path (os .fspath (path ))
61
+ if not isinstance (path , IOBase ):
62
+ path = pathlib .Path (os .fspath (path ))
63
+
64
+ if display_name is None :
65
+ display_name = path .name
66
+
67
+ if mime_type is None :
68
+ mime_type , _ = mimetypes .guess_type (path )
61
69
62
70
if mime_type is None :
63
- mime_type , _ = mimetypes .guess_type (path )
71
+ # Guess failed or IOBase, use octet-stream.
72
+ mime_type = 'application/octet-stream'
64
73
65
74
if name is not None and "/" not in name :
66
75
name = f"files/{ name } "
67
76
68
- if display_name is None :
69
- display_name = path .name
70
-
71
77
response = client .create_file (
72
78
path = path , mime_type = mime_type , name = name , display_name = display_name , resumable = resumable
73
79
)
0 commit comments