|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | | -import hashlib |
4 | 3 | import time |
5 | 4 | from functools import lru_cache |
6 | 5 | from pathlib import Path |
7 | 6 |
|
| 7 | +import magic |
8 | 8 | from google import genai |
| 9 | +from google.genai import types |
9 | 10 | from google.genai.types import ( |
10 | 11 | CountTokensConfig, |
11 | 12 | File, |
12 | 13 | GenerateContentConfig, |
13 | 14 | GenerateContentResponse, |
14 | 15 | Model, |
| 16 | + Part, |
15 | 17 | ) |
16 | 18 | from openai.types import CompletionUsage |
17 | 19 | from openai.types.chat import ( |
@@ -59,20 +61,28 @@ def get_models(self) -> set[str]: |
59 | 61 | def is_model_supported(self, model: str) -> bool: |
60 | 62 | return model in self.get_models() |
61 | 63 |
|
62 | | - def __upload(self, file: Path | NotGiven) -> File | None: |
| 64 | + def __upload(self, file: Path | NotGiven) -> Part | File | None: |
63 | 65 | if file is NotGiven: |
64 | 66 | return None |
65 | 67 |
|
66 | | - md5_name = hashlib.md5(file.read_bytes()).hexdigest() |
| 68 | + file_bytes = file.read_bytes() |
| 69 | + |
| 70 | + try: |
| 71 | + mime_type = magic.Magic(mime=True, uncompress=True).from_buffer(file_bytes) |
| 72 | + return types.Part.from_bytes(data=file_bytes, mime_type=mime_type) |
| 73 | + except Exception as e: |
| 74 | + pass |
| 75 | + |
| 76 | + cleaned_name = "".join([char for char in file.name.lower() if char.isalnum()]) |
67 | 77 | try: |
68 | | - file_ref = self.client.files.get(name=md5_name) |
| 78 | + file_ref = self.client.files.get(name=cleaned_name) |
69 | 79 | if file_ref.error is None: |
70 | 80 | return file_ref |
71 | 81 | except Exception as e: |
72 | 82 | pass |
73 | 83 |
|
74 | 84 | try: |
75 | | - file_ref = self.client.files.upload(file=file, config=dict(name=md5_name)) |
| 85 | + file_ref = self.client.files.upload(file=file, config=dict(name=cleaned_name)) |
76 | 86 | if file_ref.error is None: |
77 | 87 | return file_ref |
78 | 88 | except Exception as e: |
|
0 commit comments