Skip to content

Commit fb29861

Browse files
authored
Add samples for Files API (#395)
* Add samples for Files API Change-Id: Ied2df1633e132bda8c144e59107ae11e02b36b2f * Move sample media to third_party/ directory. Change-Id: Iee3a0e3d30b7754907c48c11822eac6cadd1082b * Format. Change-Id: Ie62a1314ca44074fa1f8904a1d5e3ada2c52fcba
1 parent 419a7ce commit fb29861

File tree

5 files changed

+127
-1
lines changed

5 files changed

+127
-1
lines changed

google/generativeai/types/file_types.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,16 @@
1515
from __future__ import annotations
1616

1717
import datetime
18-
from typing import Union
18+
from typing import Any, Union
1919
from typing_extensions import TypedDict
2020

2121
from google.rpc.status_pb2 import Status
2222
from google.generativeai.client import get_default_file_client
2323

2424
from google.generativeai import protos
2525

26+
import pprint
27+
2628

2729
class File:
2830
def __init__(self, proto: protos.File | File | dict):
@@ -33,6 +35,27 @@ def __init__(self, proto: protos.File | File | dict):
3335
def to_proto(self) -> protos.File:
3436
return self._proto
3537

38+
def to_dict(self) -> dict[str, Any]:
39+
return type(self._proto).to_dict(self._proto, use_integers_for_enums=False)
40+
41+
def __str__(self):
42+
def sort_key(pair):
43+
name, value = pair
44+
if name == "name":
45+
return ""
46+
elif "time" in name:
47+
return "zz_" + name
48+
else:
49+
return name
50+
51+
dict_format = dict(sorted(self.to_dict().items(), key=sort_key))
52+
dict_format = pprint.pformat(dict_format, sort_dicts=False)
53+
dict_format = "{\n " + dict_format[1:]
54+
dict_format = "\n ".join(dict_format.splitlines())
55+
return dict_format.join(["genai.File(", ")"])
56+
57+
__repr__ = __str__
58+
3659
@property
3760
def name(self) -> str:
3861
return self._proto.name

samples/files.py

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# -*- coding: utf-8 -*-
2+
# Copyright 2023 Google LLC
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
from absl.testing import absltest
16+
17+
import google
18+
import google.generativeai as genai
19+
import pathlib
20+
21+
media = pathlib.Path(__file__).parents[1] / "third_party"
22+
23+
24+
class UnitTests(absltest.TestCase):
25+
def test_files_create(self):
26+
# [START files_create]
27+
myfile = genai.upload_file(media / "poem.txt")
28+
print(f"{myfile=}")
29+
print()
30+
31+
model = genai.GenerativeModel("gemini-1.5-flash")
32+
result = model.generate_content(
33+
[myfile, "\n\n", "Can you add a few more lines to this poem?"]
34+
)
35+
print(f"{result.text=}")
36+
print()
37+
# [END files_create]
38+
39+
def test_files_create_video(self):
40+
# [START files_create_video]
41+
import time
42+
43+
# Video clip from https://peach.blender.org/download/
44+
myfile = genai.upload_file(media / "Big_Buck_Bunny.mp4")
45+
print(f"{myfile=}")
46+
print()
47+
48+
while myfile.state.name == "PROCESSING":
49+
print("processing video...")
50+
time.sleep(5)
51+
myfile = genai.get_file(myfile.name)
52+
53+
model = genai.GenerativeModel("gemini-1.5-flash")
54+
result = model.generate_content([myfile, "Describe this video clip"])
55+
print()
56+
print(f"{result.text=}")
57+
print()
58+
# [END files_create_video]
59+
60+
def test_files_list(self):
61+
# [START files_list]
62+
print("My files:")
63+
for f in genai.list_files():
64+
print(" ", f.name)
65+
# [END files_list]
66+
67+
def test_files_delete(self):
68+
# [START files_delete]
69+
myfile = genai.upload_file(media / "poem.txt")
70+
71+
myfile.delete()
72+
73+
try:
74+
# Error.
75+
model = genai.GenerativeModel("gemini-1.5-flash")
76+
result = model.generate_content([myfile, "Describe this file."])
77+
except google.api_core.exceptions.PermissionDenied:
78+
pass
79+
# [END files_delete]
80+
81+
def test_files_get(self):
82+
# [START files_get]
83+
myfile = genai.upload_file(media / "poem.txt")
84+
file_name = myfile.name
85+
print(file_name) # "files/*"
86+
87+
myfile = genai.get_file(file_name)
88+
print(myfile)
89+
# [END files_get]
90+
91+
92+
if __name__ == "__main__":
93+
absltest.main()

third_party/Big_Buck_Bunny.mp4

104 KB
Binary file not shown.

third_party/LICENSE.txt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
* poem.txt:
2+
* This is the first paragraph from shakespear's spring, no copyright.
3+
* Big_Buck_Bunny.mp4:
4+
* This is a clip from https://peach.blender.org/download/
5+
* License CC-BY 3.0 (Attribution)
6+

third_party/poem.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
When daisies pied, and violets blue,
2+
And lady-smocks all silver-white,
3+
And cuckoo-buds of yellow hue
4+
Do paint the meadows with delight

0 commit comments

Comments
 (0)