Spaces:
Running
Running
File size: 27,979 Bytes
4ad5efa |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 |
import os
import logging
import json
import shutil
from pathlib import Path
import pandas as pd
from datetime import datetime, timedelta
import hashlib
import uuid
import faiss
from modules.data_management.index_utils import validate_index_directory
from modules.data_management.index_utils import check_indexing_availability, initialize_embedding_model
from modules.data_management.hash_utils import generate_data_hash
from modules.data_management.index_utils import check_index_integrity
from modules.config.paths import INDICES_DIR
from modules.config.ai_settings import (
CHUNK_SIZE,
CHUNK_OVERLAP,
EXCLUDED_EMBED_METADATA_KEYS,
EXCLUDED_LLM_METADATA_KEYS
)
logger = logging.getLogger(__name__)
# Перевірка доступності модулів для індексування
INDEXING_AVAILABLE = check_indexing_availability()
INDEXING_MODULES = {
"VectorStoreIndex": None,
"StorageContext": None,
"SimpleDocumentStore": None,
"TokenTextSplitter": None,
"BM25Retriever": None,
"FaissVectorStore": None,
"Settings": None
}
def _generate_data_hash(self, df):
"""
Генерація хешу для DataFrame для ідентифікації унікальних даних.
Args:
df (pandas.DataFrame): DataFrame для хешування
Returns:
str: Хеш даних
"""
# Використовуємо основні колонки для хешування
key_columns = ['Issue key', 'Summary', 'Status', 'Issue Type', 'Created', 'Updated']
return generate_data_hash(df, key_columns)
class IndexManager:
"""
Менеджер для створення та управління індексами даних (FAISS, BM25).
"""
def __init__(self, base_indices_dir="temp/indices"):
"""
Ініціалізація менеджера індексів.
Args:
base_indices_dir (str): Базова директорія для зберігання індексів
"""
self.base_indices_dir = Path(base_indices_dir) if base_indices_dir else INDICES_DIR
self.base_indices_dir.mkdir(exist_ok=True, parents=True)
# Перевірка доступності модулів для індексування
self.indexing_available = INDEXING_AVAILABLE
if not self.indexing_available:
logger.warning("Функціональність індексування недоступна. Встановіть необхідні пакети.")
def create_indices_for_session(self, session_id, merged_df, indices_dir=None):
"""
Створення індексів для даних сесії.
Args:
session_id (str): Ідентифікатор сесії
merged_df (pandas.DataFrame): DataFrame з об'єднаними даними
indices_dir (str, optional): Директорія для збереження індексів.
Якщо None, використовується директорія сесії.
Returns:
dict: Інформація про створені індекси
"""
if not self.indexing_available:
return {"error": "Функціональність індексування недоступна. Встановіть необхідні пакети."}
try:
# Визначаємо директорію для індексів
indices_path = Path(indices_dir) if indices_dir else self.base_indices_dir / session_id
indices_path.mkdir(exist_ok=True, parents=True)
# Генеруємо хеш для даних
data_hash = self._generate_data_hash(merged_df)
# Перевіряємо, чи існують індекси для цих даних
existing_indices = self._find_indices_by_hash(data_hash)
if existing_indices:
return self._reuse_existing_indices(existing_indices, indices_path, session_id, data_hash, merged_df)
# Створюємо нові індекси
return self._create_new_indices(indices_path, session_id, data_hash, merged_df)
except Exception as e:
logger.error(f"Помилка при створенні індексів: {e}")
return {"error": f"Помилка при створенні індексів: {str(e)}"}
def _reuse_existing_indices(self, existing_indices, indices_path, session_id, data_hash, merged_df):
"""
Повторне використання існуючих індексів.
Args:
existing_indices (str): Шлях до існуючих індексів
indices_path (Path): Шлях для нових індексів
session_id (str): Ідентифікатор сесії
data_hash (str): Хеш даних
merged_df (pandas.DataFrame): DataFrame з даними
Returns:
dict: Інформація про скопійовані індекси
"""
logger.info(f"Знайдено існуючі індекси для даних з хешем {data_hash}")
try:
# Спочатку очищаємо цільову директорію
if indices_path.exists():
for item in indices_path.iterdir():
if item.is_file():
item.unlink()
elif item.is_dir():
shutil.rmtree(item)
# Копіюємо індекси
for item in Path(existing_indices).iterdir():
if item.is_file():
shutil.copy2(item, indices_path)
elif item.is_dir():
shutil.copytree(item, indices_path / item.name)
logger.info(f"Індекси успішно скопійовано в {indices_path}")
# Оновлюємо метадані
metadata = {
"session_id": session_id,
"created_at": datetime.now().isoformat(),
"data_hash": data_hash,
"rows_count": len(merged_df),
"columns_count": len(merged_df.columns),
"copied_from": str(existing_indices)
}
with open(indices_path / "metadata.json", "w", encoding="utf-8") as f:
json.dump(metadata, f, ensure_ascii=False, indent=2)
return {
"success": True,
"indices_dir": str(indices_path),
"data_hash": data_hash,
"reused_existing": True,
"source": str(existing_indices)
}
except Exception as copy_err:
logger.error(f"Помилка при копіюванні індексів: {copy_err}")
# Продовжуємо створення нових індексів
return self._create_new_indices(indices_path, session_id, data_hash, merged_df)
def _create_new_indices(self, indices_path, session_id, data_hash, merged_df):
"""
Створення нових індексів.
Зберігає індекси у форматі, сумісному з jira_hybrid_chat.py.
"""
if not INDEXING_AVAILABLE:
return {"error": "Функціональність індексування недоступна"}
try:
logger.info(f"Створення нових індексів для сесії {session_id}")
# Імпортуємо необхідні модулі напряму
from llama_index.core import VectorStoreIndex, StorageContext, Settings
from llama_index.core.storage.docstore import SimpleDocumentStore
from llama_index.core.node_parser import TokenTextSplitter
from llama_index.retrievers.bm25 import BM25Retriever
from llama_index.vector_stores.faiss import FaissVectorStore
import faiss
# Ініціалізуємо модель ембедингів
from modules.data_management.index_utils import initialize_embedding_model
embed_model = initialize_embedding_model()
# Отримуємо розмірність ембедингів динамічно
import numpy as np
test_embedding = embed_model.get_text_embedding("Тестовий текст")
embed_dim = len(test_embedding)
logger.info(f"Розмірність ембедингів: {embed_dim}")
# Конвертуємо DataFrame в документи
documents = self._convert_dataframe_to_documents(merged_df)
# Створюємо розділювач тексту
text_splitter = TokenTextSplitter(
chunk_size=CHUNK_SIZE,
chunk_overlap=CHUNK_OVERLAP
)
# Встановлюємо формат збереження на JSON через глобальні налаштування
# Це важливо для сумісності з jira_hybrid_chat.py
Settings.persist_json_format = True
# Створюємо FAISS індекс
faiss_index = faiss.IndexFlatL2(embed_dim)
# Створюємо контекст зберігання
docstore = SimpleDocumentStore()
vector_store = FaissVectorStore(faiss_index=faiss_index)
storage_context = StorageContext.from_defaults(
docstore=docstore,
vector_store=vector_store
)
# Встановлюємо модель ембедингів у налаштуваннях
Settings.embed_model = embed_model
# Створюємо індекс
index = VectorStoreIndex.from_documents(
documents,
storage_context=storage_context,
transformations=[text_splitter]
)
# Зберігаємо індекс у форматі JSON (через глобальні налаштування)
# НЕ передаємо json_format як аргумент
index.storage_context.persist(persist_dir=str(indices_path))
# Створюємо BM25 retriever
bm25_retriever = BM25Retriever.from_defaults(
docstore=docstore,
similarity_top_k=10
)
# Зберігаємо параметри BM25
bm25_dir = indices_path / "bm25"
bm25_dir.mkdir(exist_ok=True)
with open(bm25_dir / "params.json", "w", encoding="utf-8") as f:
json.dump({"similarity_top_k": 10}, f)
# Зберігаємо метадані
metadata = {
"session_id": session_id,
"created_at": datetime.now().isoformat(),
"data_hash": data_hash,
"rows_count": len(merged_df),
"columns_count": len(merged_df.columns),
"embedding_model": embed_model.__class__.__name__,
"embedding_dim": embed_dim,
"format": "json" # Вказуємо використаний формат збереження
}
with open(indices_path / "metadata.json", "w", encoding="utf-8") as f:
json.dump(metadata, f, ensure_ascii=False, indent=2)
with open(indices_path / "indices.valid", "w", encoding="utf-8") as f:
f.write(f"Indices created at {datetime.now().isoformat()}")
logger.info(f"Створено файл-маркер indices.valid")
return {
"success": True,
"indices_dir": str(indices_path),
"data_hash": data_hash
}
except Exception as e:
logger.error(f"Помилка при створенні нових індексів: {e}")
return {"error": f"Помилка при створенні нових індексів: {str(e)}"}
def _save_bm25_data(self, indices_path, bm25_retriever):
"""
Збереження даних для BM25 retriever.
Args:
indices_path (Path): Шлях до директорії індексів
bm25_retriever (BM25Retriever): Об'єкт BM25Retriever
Returns:
bool: True, якщо дані успішно збережені, False у випадку помилки
"""
try:
# Створюємо директорію для BM25
bm25_dir = indices_path / "bm25"
bm25_dir.mkdir(exist_ok=True)
# Зберігаємо параметри BM25
bm25_params = {
"similarity_top_k": bm25_retriever.similarity_top_k,
"alpha": getattr(bm25_retriever, "alpha", 0.75),
"beta": getattr(bm25_retriever, "beta", 0.75),
"index_creation_time": datetime.now().isoformat()
}
with open(bm25_dir / "params.json", "w", encoding="utf-8") as f:
json.dump(bm25_params, f, ensure_ascii=False, indent=2)
logger.info(f"Дані BM25 збережено в {bm25_dir}")
return True
except Exception as e:
logger.error(f"Помилка при збереженні даних BM25: {e}")
return False
def _convert_dataframe_to_documents(self, df):
"""
Конвертує DataFrame в документи для індексування.
Args:
df (pandas.DataFrame): DataFrame для конвертації
Returns:
list: Список документів
"""
try:
# Імпортуємо Document напряму
from llama_index.core import Document
documents = []
# Перебираємо рядки DataFrame
for idx, row in df.iterrows():
# Створюємо текст документа
text = f"Issue Key: {row.get('Issue key', '')}\n"
text += f"Summary: {row.get('Summary', '')}\n"
text += f"Status: {row.get('Status', '')}\n"
text += f"Issue Type: {row.get('Issue Type', '')}\n"
# Додаємо опис, якщо він є
if 'Description' in row and pd.notna(row['Description']):
text += f"Description: {row['Description']}\n"
# Додаємо коментарі, якщо вони є
if 'Comments' in row and pd.notna(row['Comments']):
text += f"Comments: {row['Comments']}\n"
# Створюємо метадані
metadata = {
"issue_key": row.get('Issue key', ''),
"summary": row.get('Summary', ''),
"status": row.get('Status', ''),
"issue_type": row.get('Issue Type', ''),
"created": str(row.get('Created', '')),
"updated": str(row.get('Updated', ''))
}
# Створюємо документ
doc = Document(
text=text,
metadata=metadata
)
documents.append(doc)
logger.info(f"Створено {len(documents)} документів з DataFrame")
return documents
except Exception as e:
logger.error(f"Помилка при конвертації DataFrame в документи: {e}")
raise
def _generate_data_hash(self, df):
"""
Генерація хешу для DataFrame для ідентифікації унікальних даних.
Args:
df (pandas.DataFrame): DataFrame для хешування
Returns:
str: Хеш даних
"""
try:
# Використовуємо основні колонки для хешування
key_columns = ['Issue key', 'Summary', 'Status', 'Issue Type', 'Created', 'Updated']
# Фільтруємо тільки наявні колонки
available_columns = [col for col in key_columns if col in df.columns]
if not available_columns:
# Якщо немає жодної ключової колонки, використовуємо всі дані
data_str = df.to_json()
else:
# Інакше використовуємо тільки ключові колонки
data_str = df[available_columns].to_json()
# Створюємо хеш
hash_object = hashlib.sha256(data_str.encode())
data_hash = hash_object.hexdigest()
return data_hash
except Exception as e:
logger.error(f"Помилка при генерації хешу даних: {e}")
# У випадку помилки повертаємо випадковий хеш
return str(uuid.uuid4())
def _find_indices_by_hash(self, data_hash):
"""
Пошук існуючих індексів за хешем даних.
Args:
data_hash (str): Хеш даних
Returns:
str: Шлях до директорії з індексами або None, якщо не знайдено
"""
try:
# Перебираємо всі піддиректорії в базовій директорії індексів
for index_dir in self.base_indices_dir.iterdir():
if not index_dir.is_dir():
continue
# Перевіряємо метадані
metadata_file = index_dir / "metadata.json"
if not metadata_file.exists():
continue
try:
with open(metadata_file, "r", encoding="utf-8") as f:
metadata = json.load(f)
# Перевіряємо хеш
if metadata.get("data_hash") == data_hash:
# Перевіряємо наявність необхідних файлів
if validate_index_directory(index_dir):
logger.info(f"Знайдено існуючі індекси з відповідним хешем: {index_dir}")
return str(index_dir)
else:
logger.warning(f"Знайдено індекси з відповідним хешем, але вони неповні: {index_dir}")
except Exception as e:
logger.error(f"Помилка при перевірці метаданих {metadata_file}: {e}")
logger.info(f"Не знайдено існуючих індексів з хешем {data_hash}")
return None
except Exception as e:
logger.error(f"Помилка при пошуку індексів за хешем: {e}")
return None
def cleanup_old_indices(self, max_age_days=7, max_indices=20):
"""
Очищення застарілих індексів.
Args:
max_age_days (int): Максимальний вік індексів у днях
max_indices (int): Максимальна кількість індексів для зберігання
Returns:
int: Кількість видалених директорій індексів
"""
try:
# Перевіряємо, чи існує базова директорія
if not self.base_indices_dir.exists():
return 0
# Отримуємо список директорій індексів
index_dirs = []
for index_dir in self.base_indices_dir.iterdir():
if not index_dir.is_dir():
continue
# Перевіряємо метадані для отримання часу створення
metadata_file = index_dir / "metadata.json"
created_at = None
if metadata_file.exists():
try:
with open(metadata_file, "r", encoding="utf-8") as f:
metadata = json.load(f)
created_at = metadata.get("created_at")
except Exception:
pass
# Якщо немає метаданих, використовуємо час створення директорії
if not created_at:
created_at = datetime.fromtimestamp(index_dir.stat().st_mtime).isoformat()
# Додаємо інформацію про директорію
index_dirs.append({
"path": str(index_dir),
"created_at": created_at
})
# Якщо немає директорій для обробки, повертаємо 0
if not index_dirs:
return 0
# Сортуємо директорії за часом створення (від найновіших до найстаріших)
index_dirs.sort(key=lambda x: x["created_at"], reverse=True)
# Визначаємо директорії для видалення
dirs_to_delete = []
# 1. Залишаємо max_indices найновіших директорій
if len(index_dirs) > max_indices:
dirs_to_delete.extend(index_dirs[max_indices:])
# 2. Перевіряємо, чи є серед залишених застарілі директорії
cutoff_date = (datetime.now() - timedelta(days=max_age_days)).isoformat()
for index_info in index_dirs[:max_indices]:
if index_info["created_at"] < cutoff_date:
dirs_to_delete.append(index_info)
# Видаляємо директорії
deleted_count = 0
for dir_info in dirs_to_delete:
try:
dir_path = Path(dir_info["path"])
if dir_path.exists():
shutil.rmtree(dir_path)
logger.info(f"Видалено застарілу директорію індексів: {dir_path}")
deleted_count += 1
except Exception as e:
logger.error(f"Помилка при видаленні директорії {dir_info['path']}: {e}")
return deleted_count
except Exception as e:
logger.error(f"Помилка при очищенні застарілих індексів: {e}")
return 0
def load_indices(self, indices_dir):
"""
Завантаження індексів з директорії.
Args:
indices_dir (str): Шлях до директорії з індексами
Returns:
tuple: (VectorStoreIndex, BM25Retriever) або (None, None) у випадку помилки
"""
if not self.indexing_available:
logger.warning("Функціональність індексування недоступна. Встановіть необхідні пакети.")
return None, None
try:
# Перевіряємо цілісність індексів
is_valid, message = check_index_integrity(indices_dir)
if not is_valid:
logger.error(f"Індекси не пройшли перевірку цілісності: {message}")
return None, None
indices_path = Path(indices_dir)
if not indices_path.exists():
logger.error(f"Директорія індексів не існує: {indices_dir}")
return None, None
# Перевіряємо наявність необхідних файлів
if not (indices_path / "docstore.json").exists():
logger.error(f"Директорія індексів не містить необхідних файлів: {indices_dir}")
return None, None
# Імпортуємо необхідні модулі
StorageContext = INDEXING_MODULES.get("StorageContext")
VectorStoreIndex = INDEXING_MODULES.get("VectorStoreIndex")
BM25Retriever = INDEXING_MODULES.get("BM25Retriever")
# Завантажуємо контекст зберігання
storage_context = StorageContext.from_defaults(persist_dir=str(indices_path))
# Завантажуємо індекс
index = VectorStoreIndex.from_storage_context(storage_context)
# Створюємо BM25 retriever
bm25_retriever = BM25Retriever.from_defaults(
docstore=storage_context.docstore,
similarity_top_k=10
)
# Завантажуємо параметри BM25, якщо вони є
bm25_params_file = indices_path / "bm25" / "params.json"
if bm25_params_file.exists():
try:
with open(bm25_params_file, "r", encoding="utf-8") as f:
bm25_params = json.load(f)
# Встановлюємо параметри
if "similarity_top_k" in bm25_params:
bm25_retriever.similarity_top_k = bm25_params["similarity_top_k"]
except Exception as e:
logger.warning(f"Помилка при завантаженні параметрів BM25: {e}")
logger.info(f"Індекси успішно завантажено з {indices_dir}")
return index, bm25_retriever
except Exception as e:
logger.error(f"Помилка при завантаженні індексів: {e}")
return None, None |