File size: 9,927 Bytes
86c402d
744a170
86c402d
 
 
 
 
 
744a170
86c402d
 
744a170
 
 
 
 
 
 
 
 
86c402d
fd3c8b9
86c402d
 
 
 
 
fd3c8b9
744a170
86c402d
 
 
744a170
86c402d
 
 
744a170
86c402d
 
 
 
744a170
86c402d
 
 
744a170
86c402d
 
 
 
 
744a170
86c402d
 
 
 
 
 
 
 
 
 
 
744a170
86c402d
 
 
 
 
 
744a170
86c402d
 
 
 
 
 
fd3c8b9
744a170
86c402d
 
 
744a170
86c402d
 
 
744a170
86c402d
 
 
 
 
744a170
0341212
86c402d
744a170
86c402d
 
 
 
 
744a170
86c402d
 
 
 
 
 
744a170
 
86c402d
744a170
 
86c402d
 
 
744a170
 
 
 
 
 
 
86c402d
 
 
 
 
744a170
86c402d
 
744a170
86c402d
 
 
 
 
 
fd3c8b9
744a170
86c402d
 
 
744a170
86c402d
 
 
744a170
86c402d
 
 
 
744a170
86c402d
744a170
86c402d
744a170
86c402d
 
744a170
86c402d
 
 
 
 
744a170
86c402d
 
744a170
86c402d
 
 
 
 
 
 
744a170
86c402d
 
 
 
 
 
 
 
 
 
 
 
744a170
86c402d
744a170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86c402d
 
744a170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86c402d
744a170
 
 
86c402d
744a170
 
86c402d
 
744a170
86c402d
 
744a170
 
 
 
 
 
86c402d
744a170
86c402d
744a170
 
86c402d
744a170
 
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
from typing import Annotated
from uuid import UUID

import numpy as np
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

import common.dependencies as DI
from common import auth
from components.dbo.chunk_repository import ChunkRepository
from components.services.entity import EntityService
from schemas.entity import (
    ChunkInfo,
    EntitySearchRequest,
    EntitySearchResponse,
    EntitySearchWithTextRequest,
    EntitySearchWithTextResponse,
    EntityTextRequest,
    EntityTextResponse,
)

router = APIRouter(prefix="/entity", tags=["Entity"])


@router.post("/search", response_model=EntitySearchResponse)
async def search_entities(
    request: EntitySearchRequest,
    entity_service: Annotated[EntityService, Depends(DI.get_entity_service)],
    current_user: Annotated[any, Depends(auth.get_current_user)],
) -> EntitySearchResponse:
    """
    Поиск похожих сущностей по векторному сходству (только ID).

    Args:
        request: Параметры поиска
        entity_service: Сервис для работы с сущностями

    Returns:
        Результаты поиска (ID и оценки), отсортированные по убыванию сходства
    """
    try:
        _, scores, ids = entity_service.search_similar_old(
            request.query,
            request.dataset_id,
        )

        # Проверяем, что scores и ids - корректные numpy массивы
        if not isinstance(scores, np.ndarray):
            scores = np.array(scores)
        if not isinstance(ids, np.ndarray):
            ids = np.array(ids)

        # Сортируем результаты по убыванию оценок
        # Проверим, что массивы не пустые
        if len(scores) > 0:
            # Преобразуем индексы в список, чтобы избежать проблем с индексацией
            sorted_indices = scores.argsort()[::-1].tolist()
            sorted_scores = [float(scores[i]) for i in sorted_indices]
            # Преобразуем все ID в строки
            sorted_ids = [str(ids[i]) for i in sorted_indices]
        else:
            sorted_scores = []
            sorted_ids = []

        return EntitySearchResponse(
            scores=sorted_scores,
            entity_ids=sorted_ids,
        )
    except Exception as e:
        raise HTTPException(
            status_code=500, detail=f"Error during entity search: {str(e)}"
        )


@router.post("/search/with_text", response_model=EntitySearchWithTextResponse)
async def search_entities_with_text(
    request: EntitySearchWithTextRequest,
    entity_service: Annotated[EntityService, Depends(DI.get_entity_service)],
    current_user: Annotated[any, Depends(auth.get_current_user)],
) -> EntitySearchWithTextResponse:
    """
    Поиск похожих сущностей по векторному сходству с возвратом текстов.

    Args:
        request: Параметры поиска
        entity_service: Сервис для работы с сущностями

    Returns:
        Результаты поиска с текстами чанков, отсортированные по убыванию сходства
    """
    try:
        # Получаем результаты поиска
        _, scores, entity_ids = entity_service.search_similar_old(
            request.query, request.dataset_id, 100
        )

        # Проверяем, что scores и entity_ids - корректные numpy массивы
        if not isinstance(scores, np.ndarray):
            scores = np.array(scores)
        if not isinstance(entity_ids, np.ndarray):
            entity_ids = np.array(entity_ids)

        # Сортируем результаты по убыванию оценок
        # Проверим, что массивы не пустые
        if len(scores) > 0:
            # Преобразуем индексы в список, чтобы избежать проблем с индексацией
            sorted_indices = scores.argsort()[::-1].tolist()
            sorted_scores = [float(scores[i]) for i in sorted_indices]
            sorted_ids = [UUID(entity_ids[i]) for i in sorted_indices]

            # Получаем тексты чанков
            chunks = entity_service.chunk_repository.get_entities_by_ids(sorted_ids)

            # Формируем ответ
            return EntitySearchWithTextResponse(
                chunks=[
                    ChunkInfo(
                        id=str(chunk.id),  # Преобразуем UUID в строку
                        text=chunk.text,
                        score=score,
                        type=chunk.type,
                        in_search_text=chunk.in_search_text,
                    )
                    for chunk, score in zip(chunks, sorted_scores)
                ]
            )
        else:
            return EntitySearchWithTextResponse(chunks=[])

    except Exception as e:
        raise HTTPException(
            status_code=500, detail=f"Error during entity search with text: {str(e)}"
        )


@router.post("/text", response_model=EntityTextResponse)
async def build_entity_text(
    request: EntityTextRequest,
    entity_service: Annotated[EntityService, Depends(DI.get_entity_service)],
    current_user: Annotated[any, Depends(auth.get_current_user)],
) -> EntityTextResponse:
    """
    Сборка текста из сущностей.

    Args:
        request: Параметры сборки текста
        entity_service: Сервис для работы с сущностями

    Returns:
        Собранный текст
    """
    try:
        if not request.entities:
            raise HTTPException(
                status_code=404, detail="No entities found with provided IDs"
            )

        # Собираем текст
        text = entity_service.build_text(
            entities=request.entities,
            chunk_scores=request.chunk_scores,
            include_tables=request.include_tables,
            max_documents=request.max_documents,
        )

        return EntityTextResponse(text=text)
    except Exception as e:
        raise HTTPException(
            status_code=500, detail=f"Error building entity text: {str(e)}"
        )


@router.get("/info/{dataset_id}")
async def get_entity_info(
    dataset_id: int,
    db: Annotated[Session, Depends(DI.get_db)],
    current_user: Annotated[any, Depends(auth.get_current_user)],
) -> dict:
    """
    Получить информацию о сущностях в датасете.

    Args:
        dataset_id: ID датасета
        db: Сессия базы данных
        config: Конфигурация приложения

    Returns:
        dict: Информация о сущностях
    """
    # Создаем репозиторий, передавая sessionmaker
    chunk_repository = ChunkRepository(db)

    # Получаем общее количество сущностей
    total_entities_count = chunk_repository.count_entities_by_dataset_id(dataset_id)

    # Получаем сущности, готовые к поиску (с текстом и эмбеддингом)
    searchable_entities, searchable_embeddings = (
        chunk_repository.get_searching_entities(dataset_id)
    )

    # Проверка, найдены ли сущности, готовые к поиску
    # Можно оставить проверку, чтобы не возвращать пустые примеры, если таких нет,
    # но основная ошибка 404 должна базироваться на total_entities_count
    if total_entities_count == 0:
        raise HTTPException(
            status_code=404, detail=f"No entities found for dataset {dataset_id}"
        )

    # Собираем статистику
    stats = {
        "total_entities": total_entities_count,  # Реальное общее число
        "searchable_entities": len(
            searchable_entities
        ),  # Число сущностей с текстом и эмбеддингом
        "entities_with_embeddings": len(
            [e for e in searchable_embeddings if e is not None]
        ),
        "embedding_shapes": [
            e.shape if e is not None else None for e in searchable_embeddings
        ],
        "unique_embedding_shapes": set(
            str(e.shape) if e is not None else None for e in searchable_embeddings
        ),
        # Статистику по типам лучше считать на основе searchable_entities, т.к. для них есть объекты
        "entity_types": set(e.type for e in searchable_entities),
        "entities_per_type": {
            t: len([e for e in searchable_entities if e.type == t])
            for t in set(e.type for e in searchable_entities)
        },
    }

    # Примеры сущностей берем из searchable_entities
    examples = [
        {
            "id": str(e.id),
            "name": e.name,
            "type": e.type,
            "has_embedding": searchable_embeddings[i] is not None,
            "embedding_shape": (
                str(searchable_embeddings[i].shape)
                if searchable_embeddings[i] is not None
                else None
            ),
            "text_length": len(e.text),
            "in_search_text_length": len(e.in_search_text) if e.in_search_text else 0,
        }
        # Берем примеры из сущностей, готовых к поиску
        for i, e in enumerate(searchable_entities[:5])
    ]

    return {"stats": stats, "examples": examples}