Spaces:
Runtime error
Runtime error
Update load_book.py
Browse files- load_book.py +36 -32
load_book.py
CHANGED
|
@@ -6,34 +6,39 @@ from langchain_text_splitters import RecursiveCharacterTextSplitter
|
|
| 6 |
from langchain_community.vectorstores import SupabaseVectorStore
|
| 7 |
from supabase.client import create_client
|
| 8 |
|
| 9 |
-
|
| 10 |
-
def
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
content=texts,
|
| 18 |
task_type="retrieval_document"
|
| 19 |
)
|
| 20 |
-
return result['embedding']
|
| 21 |
-
except Exception as e:
|
| 22 |
-
print(f"КРИТИЧЕСКАЯ ОШИБКА GOOGLE API: {e}")
|
| 23 |
-
sys.exit(1)
|
| 24 |
-
|
| 25 |
-
# Класс-обертка, чтобы SupabaseVectorStore принял наши данные
|
| 26 |
-
class ManualEmbeddings:
|
| 27 |
-
def __init__(self, api_key):
|
| 28 |
-
self.api_key = api_key
|
| 29 |
-
def embed_documents(self, texts):
|
| 30 |
-
genai.configure(api_key=self.api_key)
|
| 31 |
-
# Отправляем батчем через официальный SDK
|
| 32 |
-
res = genai.embed_content(model="models/text-embedding-004", content=texts, task_type="retrieval_document")
|
| 33 |
return res['embedding']
|
|
|
|
| 34 |
def embed_query(self, text):
|
| 35 |
-
genai.
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
| 37 |
return res['embedding']
|
| 38 |
|
| 39 |
def load_book_to_supabase():
|
|
@@ -42,7 +47,7 @@ def load_book_to_supabase():
|
|
| 42 |
gemini_api_key = os.environ.get("GEMINI_API_KEY")
|
| 43 |
|
| 44 |
if not all([supabase_url, supabase_key, gemini_api_key]):
|
| 45 |
-
print("ОШИБКА: Проверьте секреты!")
|
| 46 |
sys.exit(1)
|
| 47 |
|
| 48 |
print("--- Шаг 1: Подключение к Supabase ---")
|
|
@@ -53,19 +58,18 @@ def load_book_to_supabase():
|
|
| 53 |
loader = TextLoader("book.txt", encoding="utf-8")
|
| 54 |
documents = loader.load()
|
| 55 |
except Exception as e:
|
| 56 |
-
print(f"ОШИБКА: {e}")
|
| 57 |
sys.exit(1)
|
| 58 |
|
| 59 |
print("--- Шаг 3: Нарезка текста ---")
|
| 60 |
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
|
| 61 |
docs = text_splitter.split_documents(documents)
|
| 62 |
-
print(f"Нарезано на {len(docs)}
|
| 63 |
|
| 64 |
-
print("--- Шаг 4:
|
| 65 |
-
|
| 66 |
-
custom_embeddings = ManualEmbeddings(gemini_api_key)
|
| 67 |
|
| 68 |
-
print("--- Шаг 5: Загрузка в
|
| 69 |
try:
|
| 70 |
SupabaseVectorStore.from_documents(
|
| 71 |
docs,
|
|
@@ -74,9 +78,9 @@ def load_book_to_supabase():
|
|
| 74 |
table_name="documents",
|
| 75 |
query_name="match_documents",
|
| 76 |
)
|
| 77 |
-
print("--- УСПЕХ:
|
| 78 |
except Exception as e:
|
| 79 |
-
print(f"ОШИБКА
|
| 80 |
sys.exit(1)
|
| 81 |
|
| 82 |
if __name__ == "__main__":
|
|
|
|
| 6 |
from langchain_community.vectorstores import SupabaseVectorStore
|
| 7 |
from supabase.client import create_client
|
| 8 |
|
| 9 |
+
class DynamicEmbeddings:
|
| 10 |
+
def __init__(self, api_key):
|
| 11 |
+
genai.configure(api_key=api_key)
|
| 12 |
+
self.model_name = self._find_best_model()
|
| 13 |
+
print(f"--- Выбрана рабочая модель: {self.model_name} ---")
|
| 14 |
+
|
| 15 |
+
def _find_best_model(self):
|
| 16 |
+
# Автоматический поиск доступной модели эмбеддингов
|
| 17 |
+
try:
|
| 18 |
+
for m in genai.list_models():
|
| 19 |
+
if 'embedContent' in m.supported_generation_methods:
|
| 20 |
+
return m.name
|
| 21 |
+
except Exception as e:
|
| 22 |
+
print(f"Ошибка при поиске моделей: {e}")
|
| 23 |
+
|
| 24 |
+
# Если поиск не удался, пробуем стандартную заглушку
|
| 25 |
+
return "models/embedding-001"
|
| 26 |
+
|
| 27 |
+
def embed_documents(self, texts):
|
| 28 |
+
# Отправляем тексты пачками (батчами), чтобы не превысить лимиты
|
| 29 |
+
res = genai.embed_content(
|
| 30 |
+
model=self.model_name,
|
| 31 |
content=texts,
|
| 32 |
task_type="retrieval_document"
|
| 33 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
return res['embedding']
|
| 35 |
+
|
| 36 |
def embed_query(self, text):
|
| 37 |
+
res = genai.embed_content(
|
| 38 |
+
model=self.model_name,
|
| 39 |
+
content=text,
|
| 40 |
+
task_type="retrieval_query"
|
| 41 |
+
)
|
| 42 |
return res['embedding']
|
| 43 |
|
| 44 |
def load_book_to_supabase():
|
|
|
|
| 47 |
gemini_api_key = os.environ.get("GEMINI_API_KEY")
|
| 48 |
|
| 49 |
if not all([supabase_url, supabase_key, gemini_api_key]):
|
| 50 |
+
print("ОШИБКА: Проверьте секреты GitHub!")
|
| 51 |
sys.exit(1)
|
| 52 |
|
| 53 |
print("--- Шаг 1: Подключение к Supabase ---")
|
|
|
|
| 58 |
loader = TextLoader("book.txt", encoding="utf-8")
|
| 59 |
documents = loader.load()
|
| 60 |
except Exception as e:
|
| 61 |
+
print(f"ОШИБКА чтении файла: {e}")
|
| 62 |
sys.exit(1)
|
| 63 |
|
| 64 |
print("--- Шаг 3: Нарезка текста ---")
|
| 65 |
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
|
| 66 |
docs = text_splitter.split_documents(documents)
|
| 67 |
+
print(f"Нарезано на {len(docs)} фрагментов.")
|
| 68 |
|
| 69 |
+
print("--- Шаг 4: Поиск доступной модели Google ---")
|
| 70 |
+
custom_embeddings = DynamicEmbeddings(gemini_api_key)
|
|
|
|
| 71 |
|
| 72 |
+
print("--- Шаг 5: Загрузка векторов в Supabase ---")
|
| 73 |
try:
|
| 74 |
SupabaseVectorStore.from_documents(
|
| 75 |
docs,
|
|
|
|
| 78 |
table_name="documents",
|
| 79 |
query_name="match_documents",
|
| 80 |
)
|
| 81 |
+
print("--- УСПЕХ: Данные загружены! ---")
|
| 82 |
except Exception as e:
|
| 83 |
+
print(f"КРИТИЧЕСКАЯ ОШИБКА: {e}")
|
| 84 |
sys.exit(1)
|
| 85 |
|
| 86 |
if __name__ == "__main__":
|