Spaces:
Running
Running
File size: 26,769 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 |
import os
import logging
import json
import shutil
from pathlib import Path
import pandas as pd
from datetime import datetime, timedelta
# Імпорт LlamaIndex компонентів
from llama_index.core import (
VectorStoreIndex,
Document,
StorageContext,
load_index_from_storage,
Settings
)
from llama_index.core.node_parser import TokenTextSplitter
from llama_index.retrievers.bm25 import BM25Retriever
from llama_index.vector_stores.faiss import FaissVectorStore
from llama_index.core.schema import TextNode
from llama_index.core.storage.docstore import SimpleDocumentStore
import faiss
from modules.config.paths import INDICES_DIR
from modules.data_management.hash_utils import generate_data_hash
from modules.data_management.index_utils import (
check_indexing_availability,
initialize_embedding_model,
check_index_integrity
)
from modules.config.ai_settings import (
get_metadata_csv,
)
# Встановлюємо формат збереження на бінарний (не JSON)
Settings.persist_json_format = False
logger = logging.getLogger(__name__)
class UnifiedIndexManager:
"""
Уніфікований менеджер для створення та управління індексами даних.
"""
def __init__(self, base_indices_dir=None):
"""
Ініціалізація менеджера індексів.
Args:
base_indices_dir (str, optional): Базова директорія для зберігання індексів
"""
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 = check_indexing_availability("temp/indices")
if not self.indexing_available:
logger.warning("Функціональність індексування недоступна. Встановіть необхідні пакети.")
def get_or_create_indices(self, df, session_id=None):
"""
Отримання або створення індексів для даних.
Args:
df (pandas.DataFrame): DataFrame з даними
session_id (str, optional): Ідентифікатор сесії
Returns:
dict: Інформація про індекси
"""
if not self.indexing_available:
return {"error": "Функціональність індексування недоступна. Встановіть необхідні пакети."}
try:
# Генеруємо хеш для даних
data_hash = generate_data_hash(df, key_columns=['Issue key', 'Summary', 'Status', 'Issue Type', 'Created', 'Updated'])
if not data_hash:
return {"error": "Не вдалося згенерувати хеш для даних"}
# Перевіряємо, чи існують індекси для цих даних
existing_indices = self._find_indices_by_hash(data_hash)
if existing_indices:
# Перевіряємо цілісність індексів
is_valid, message = check_index_integrity(existing_indices)
if is_valid:
logger.info(f"Знайдено існуючі індекси для даних з хешем {data_hash}")
return {
"success": True,
"indices_dir": str(existing_indices),
"data_hash": data_hash,
"reused_existing": True
}
else:
logger.warning(f"Знайдено індекси з відповідним хешем, але вони не пройшли перевірку цілісності: {message}")
# Створюємо нові індекси
# Визначаємо директорію для індексів
if session_id:
indices_path = self.base_indices_dir / session_id
else:
# Якщо не вказано session_id, використовуємо поточну дату і час
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
indices_path = self.base_indices_dir / timestamp
indices_path.mkdir(exist_ok=True, parents=True)
# Створюємо нові індекси
result = self._create_new_indices(indices_path, session_id, data_hash, df)
# Форматуємо результат
if isinstance(result, dict):
return result
else:
return {
"success": True,
"indices_dir": str(indices_path),
"data_hash": data_hash
}
except Exception as e:
logger.error(f"Помилка при отриманні або створенні індексів: {e}")
import traceback
logger.error(traceback.format_exc())
return {"error": f"Помилка при отриманні або створенні індексів: {str(e)}"}
def _find_indices_by_hash(self, data_hash):
"""
Пошук існуючих індексів за хешем даних.
Args:
data_hash (str): Хеш даних
Returns:
Path: Шлях до директорії з індексами або 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:
return index_dir
except Exception as e:
logger.error(f"Помилка при перевірці метаданих {metadata_file}: {e}")
return None
except Exception as e:
logger.error(f"Помилка при пошуку індексів за хешем: {e}")
return None
def _create_new_indices(self, indices_path, session_id, data_hash, df):
"""
Створення нових індексів.
Args:
indices_path (Path): Шлях для збереження індексів
session_id (str): Ідентифікатор сесії
data_hash (str): Хеш даних
df (pandas.DataFrame): DataFrame з даними
Returns:
dict: Інформація про створені індекси
"""
try:
# Ініціалізуємо модель ембедингів
embed_model = initialize_embedding_model()
if not embed_model:
return {"error": "Не вдалося ініціалізувати модель ембедингів"}
# Отримуємо розмірність ембедингів
sample_embedding = embed_model.get_text_embedding("Test")
embedding_dim = len(sample_embedding)
logger.info(f"Розмірність ембедингів: {embedding_dim}")
# Конвертуємо DataFrame в документи
documents = self._convert_dataframe_to_documents(df)
if not documents:
return {"error": "Не вдалося конвертувати дані в документи"}
# Створюємо ноди з документів
nodes = [TextNode(text=doc.text, metadata=doc.metadata) for doc in documents]
# Створюємо FAISS індекс
faiss_index = faiss.IndexFlatL2(embedding_dim)
vector_store = FaissVectorStore(faiss_index=faiss_index)
# Створюємо документне сховище
docstore = SimpleDocumentStore()
docstore.add_documents(nodes)
# Створюємо контекст зберігання
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
)
# Зберігаємо індекс у файл (бінарний формат)
index.storage_context.persist(str(indices_path))
# Створюємо BM25 retriever і зберігаємо його параметри
bm25_retriever = BM25Retriever.from_defaults(
docstore=docstore,
similarity_top_k=10
)
self._save_bm25_data(indices_path, bm25_retriever)
# Зберігаємо метадані
self._save_indices_metadata(indices_path, {
"session_id": session_id,
"created_at": datetime.now().isoformat(),
"data_hash": data_hash,
"documents_count": len(documents),
"nodes_count": len(nodes),
"rows_count": len(df),
"columns_count": len(df.columns),
"embedding_model": str(embed_model),
"embedding_dim": embedding_dim,
"storage_format": "binary"
})
# Створюємо маркерний файл для перевірки валідності індексів
with open(indices_path / "indices.valid", "w") as f:
f.write(f"Indices created at {datetime.now().isoformat()}")
logger.info(f"Індекси успішно створено в {indices_path}")
# Зберігаємо шлях глобально, якщо доступно
self._save_indices_path_globally(str(indices_path))
return {
"success": True,
"indices_dir": str(indices_path),
"data_hash": data_hash,
"documents_count": len(documents),
"nodes_count": len(nodes),
"rows_count": len(df),
"reused_existing": False
}
except Exception as e:
logger.error(f"Помилка при створенні нових індексів: {e}")
import traceback
logger.error(traceback.format_exc())
return {"error": f"Помилка при створенні нових індексів: {str(e)}"}
def _save_indices_metadata(self, indices_path, metadata):
"""Зберігає метадані індексів у файл."""
try:
with open(indices_path / "metadata.json", "w", encoding="utf-8") as f:
json.dump(metadata, f, ensure_ascii=False, indent=2)
return True
except Exception as e:
logger.error(f"Помилка при збереженні метаданих: {e}")
return False
def _save_indices_path_globally(self, indices_path):
"""Зберігає шлях до індексів у глобальних об'єктах (app, index_manager)."""
try:
import builtins
if hasattr(builtins, 'app'):
builtins.app.indices_path = indices_path
logger.info(f"Шлях до індексів збережено глобально: {indices_path}")
# Якщо також є глобальний index_manager, зберігаємо в ньому
if hasattr(builtins, 'index_manager'):
builtins.index_manager.last_indices_path = indices_path
return True
except Exception as e:
logger.warning(f"Не вдалося зберегти шлях до індексів глобально: {e}")
return False
def _convert_dataframe_to_documents(self, df):
"""
Конвертує DataFrame у документи для індексування.
Кожен документ представляє один рядок CSV з усіма його полями.
"""
try:
# Перевірка типу даних
if not hasattr(df, 'iterrows'):
logger.error(f"Отримано не DataFrame: {type(df)}")
return None
# Конвертація в документи
documents = []
for idx, row in df.iterrows():
# Формуємо текст документа, включаючи всі основні поля
text_parts = []
# Додаємо основні поля
key_fields = [
('Issue key', 'Ключ задачі'),
('Summary', 'Заголовок'),
('Issue Type', 'Тип задачі'),
('Status', 'Статус'),
('Priority', 'Пріоритет'),
('Assignee', 'Виконавець'),
('Reporter', 'Автор'),
('Created', 'Створено'),
('Updated', 'Оновлено'),
('Project name', 'Проект')
]
for field, title in key_fields:
if field in row and pd.notna(row[field]):
text_parts.append(f"{title}: {str(row[field])}")
# Додаємо опис, якщо він є
if 'Description' in row and pd.notna(row['Description']):
text_parts.append(f"Опис: {str(row['Description'])}")
# Додаємо коментарі, якщо вони є
comments = []
for col in df.columns:
if col.startswith('Comment') and pd.notna(row[col]):
comments.append(str(row[col]))
if comments:
text_parts.append("Коментарі:")
for i, comment in enumerate(comments, 1):
text_parts.append(f"Коментар {i}: {comment}")
# Додаємо інформацію про зв'язки, якщо вона є
links = []
for col in df.columns:
if col.startswith('Outward issue link') and pd.notna(row[col]):
link_type = col.replace('Outward issue link (', '').replace(')', '')
links.append(f"{link_type}: {str(row[col])}")
if links:
text_parts.append("Зв'язки:")
for link in links:
text_parts.append(link)
# Додаємо користувацькі поля
custom_fields = []
for col in df.columns:
if (col.startswith('Custom field') or col.startswith('Sprint')) and pd.notna(row[col]):
field_name = col.replace('Custom field (', '').replace(')', '')
custom_fields.append(f"{field_name}: {str(row[col])}")
if custom_fields:
text_parts.append("Додаткові поля:")
for field in custom_fields:
text_parts.append(field)
# Об'єднуємо все в один текст
text = "\n".join(text_parts)
# Якщо текст порожній, використовуємо хоча б заголовок
if not text and 'Summary' in row and pd.notna(row['Summary']):
text = f"Заголовок: {str(row['Summary'])}"
elif not text:
text = f"Задача {idx}"
# Створюємо метадані - включаємо всі основні поля
metadata = get_metadata_csv(row, idx)
# Додаємо інформацію про зв'язки в метадані
if 'Outward issue link (Relates)' in row and pd.notna(row['Outward issue link (Relates)']):
metadata["related_issues"] = row['Outward issue link (Relates)']
# Створення документа
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}")
import traceback
logger.error(traceback.format_exc())
return []
def _save_bm25_data(self, indices_path, bm25_retriever):
"""
Збереження даних для BM25 retriever.
"""
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 load_indices(self, indices_dir):
"""Завантаження індексів з директорії."""
try:
# Перевірка наявності директорії
indices_path = Path(indices_dir)
if not indices_path.exists():
logger.error(f"Директорія індексів не існує: {indices_dir}")
return None, None
# Перевірка наявності маркерного файлу
marker_path = indices_path / "indices.valid"
if not marker_path.exists():
logger.warning(f"Файл маркера не знайдено в {indices_dir}. Індекси не завантажено.")
return None, None
try:
# Спробуємо завантажити vector_store
vector_store = FaissVectorStore.from_persist_dir(indices_dir)
# Створюємо контекст зберігання
storage_context = StorageContext.from_defaults(
vector_store=vector_store,
persist_dir=indices_dir
)
# Завантажуємо індекс
index = load_index_from_storage(
storage_context=storage_context,
index_cls=VectorStoreIndex
)
# Створюємо BM25 retriever
bm25_retriever = BM25Retriever.from_defaults(
docstore=storage_context.docstore,
similarity_top_k=10
)
# Перевіряємо наявність параметрів BM25
bm25_params_path = indices_path / "bm25" / "params.json"
if bm25_params_path.exists():
try:
with open(bm25_params_path, "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}")
import traceback
logger.error(traceback.format_exc())
# Діагностичні повідомлення
logger.info(f"Файли у директорії {indices_dir}: {[f.name for f in indices_path.iterdir() if f.is_file()]}")
return None, None
except Exception as e:
logger.error(f"Помилка при завантаженні індексів: {e}")
return None, None
def cleanup_old_indices(self, max_age_days=7, max_indices=20):
"""
Очищення застарілих індексів.
Args:
max_age_days (int): Максимальний вік індексів у днях
max_indices (int): Максимальна кількість індексів для зберігання
Returns:
int: Кількість видалених директорій
"""
try:
# Збираємо інформацію про всі директорії індексів
index_dirs = []
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)
# Отримуємо час створення
created_at = metadata.get("created_at", "")
index_dirs.append({
"path": str(index_dir),
"created_at": created_at
})
except Exception as e:
logger.error(f"Помилка при перевірці метаданих {metadata_file}: {e}")
# Якщо немає директорій, виходимо
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 |