Skip to content

Instantly share code, notes, and snippets.

@toolittlecakes
Created December 15, 2024 07:13
Show Gist options
  • Save toolittlecakes/28114495689ead0fc823ff65da3e1e0f to your computer and use it in GitHub Desktop.
Save toolittlecakes/28114495689ead0fc823ff65da3e1e0f to your computer and use it in GitHub Desktop.
google.generativeai file upload
import requests
from pathlib import Path
from google.generativeai.types import File
from google.ai.generativelanguage_v1beta.types import File as ProtoFile
# use url without /v1beta
def upload_file(filepath: str, base_url: str = "https://generativelanguage.googleapis.com") -> File:
upload_url = base_url + "/upload/v1beta/files"
file_path = Path(filepath)
file_size = file_path.stat().st_size
file_content = file_path.read_bytes()
headers = {
"X-Goog-Upload-Command": "start, upload, finalize",
"X-Goog-Upload-Header-Content-Length": str(file_size),
"X-Goog-Upload-Header-Content-Type": "audio/mpeg",
"Content-Type": "audio/mpeg",
"x-goog-api-key": api_key,
}
# cert_path = "nginx-selfsigned.crt"
response = requests.post(
upload_url,
headers=headers,
data=file_content,
# verify=cert_path,
)
if response.status_code != 200:
raise Exception(
f"Upload failed with status {response.status_code}: {response.text}"
)
response_info = response.json()["file"]
return File(
ProtoFile(
name=response_info["name"],
display_name=file_path.name,
mime_type=response_info["mimeType"],
size_bytes=response_info["sizeBytes"],
create_time=response_info["createTime"],
update_time=response_info["updateTime"],
expiration_time=response_info["expirationTime"],
sha256_hash=response_info["sha256Hash"],
uri=response_info["uri"],
state=response_info["state"],
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment