Apply code formatting and linting fixes
Co-authored-by: ArtemFilin1990 <221041513+ArtemFilin1990@users.noreply.github.com>
This commit is contained in:
1 parent
371899a509
commit
cd42e6750c
2 files changed
+194
-229
No files matched your search
+82
-116
@@ -8,33 +8,33 @@ API endpoints для работы с подшипниками.
|
||||
- Доступа к справочным данным
|
||||
"""
|
||||
|
||||
from fastapi import FastAPI, Query, HTTPException
|
||||
from fastapi.responses import StreamingResponse, JSONResponse
|
||||
from typing import Optional, List
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Query
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
|
||||
from .export_utils import AnalogsExporter, SearchResultsExporter
|
||||
from .logic import AutocompleteEngine, DocumentSearchEngine, SearchHistory
|
||||
from .export_utils import SearchResultsExporter, AnalogsExporter
|
||||
|
||||
|
||||
def _sanitize_filename(text: str, max_length: int = 50) -> str:
|
||||
"""Sanitize text for safe use in filenames"""
|
||||
# Remove or replace filesystem-sensitive characters
|
||||
sanitized = re.sub(r'[<>:"/\\|?*]', '_', text)
|
||||
sanitized = re.sub(r'[<>:"/\\|?*]', "_", text)
|
||||
# Remove leading/trailing whitespace and dots
|
||||
sanitized = sanitized.strip('. ')
|
||||
sanitized = sanitized.strip(". ")
|
||||
# Limit length
|
||||
return sanitized[:max_length] if sanitized else 'export'
|
||||
return sanitized[:max_length] if sanitized else "export"
|
||||
|
||||
|
||||
# Инициализация приложения
|
||||
app = FastAPI(
|
||||
title="Справочник подшипников - API поиска",
|
||||
description="API для поиска подшипников с автодополнением, похожими документами, историей и экспортом",
|
||||
version="1.0.0"
|
||||
version="1.0.0",
|
||||
)
|
||||
|
||||
# Инициализация движков
|
||||
@@ -54,8 +54,8 @@ async def root():
|
||||
"search": "/search",
|
||||
"similar": "/similar/{document_id}",
|
||||
"history": "/history",
|
||||
"export": "/search/export"
|
||||
}
|
||||
"export": "/search/export",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -63,16 +63,16 @@ async def root():
|
||||
async def autocomplete(
|
||||
q: str = Query(..., min_length=1, description="Префикс для поиска (минимум 1 символ)"),
|
||||
limit: int = Query(10, ge=1, le=50, description="Количество предложений"),
|
||||
types: Optional[List[str]] = Query(None, description="Типы: term, bearing_code, brand, series")
|
||||
types: list[str] | None = Query(None, description="Типы: term, bearing_code, brand, series"),
|
||||
):
|
||||
"""
|
||||
Автодополнение поисковых запросов
|
||||
|
||||
|
||||
Примеры:
|
||||
- /autocomplete?q=под → ["подшипник", "подшипники качения", "подшипниковые узлы"]
|
||||
- /autocomplete?q=620 → ["6205", "6206", "6207", "6208"]
|
||||
- /autocomplete?q=SK → ["SKF", "SKF Y-типа"]
|
||||
|
||||
|
||||
Возвращает:
|
||||
{
|
||||
"query": "под",
|
||||
@@ -87,25 +87,16 @@ async def autocomplete(
|
||||
}
|
||||
"""
|
||||
suggestions = autocomplete_engine.suggest(q, limit=limit, types=types)
|
||||
|
||||
return {
|
||||
"query": q,
|
||||
"suggestions": suggestions,
|
||||
"count": len(suggestions)
|
||||
}
|
||||
|
||||
return {"query": q, "suggestions": suggestions, "count": len(suggestions)}
|
||||
|
||||
|
||||
@app.get("/autocomplete/popular")
|
||||
async def get_popular_autocomplete(
|
||||
limit: int = Query(10, ge=1, le=50, description="Количество результатов")
|
||||
):
|
||||
async def get_popular_autocomplete(limit: int = Query(10, ge=1, le=50, description="Количество результатов")):
|
||||
"""Получить самые популярные термины для автодополнения"""
|
||||
popular = autocomplete_engine.get_popular_searches(limit=limit)
|
||||
|
||||
return {
|
||||
"popular": popular,
|
||||
"count": len(popular)
|
||||
}
|
||||
|
||||
return {"popular": popular, "count": len(popular)}
|
||||
|
||||
|
||||
@app.get("/search")
|
||||
@@ -113,12 +104,12 @@ async def search(
|
||||
q: str = Query(..., min_length=1, description="Поисковый запрос"),
|
||||
include_similar: bool = Query(True, description="Добавить похожие документы"),
|
||||
limit: int = Query(20, ge=1, le=100, description="Количество результатов"),
|
||||
user_id: Optional[str] = Query(None, description="Токен пользователя (опционально)"),
|
||||
session_id: Optional[str] = Query(None, description="ID сессии")
|
||||
user_id: str | None = Query(None, description="Токен пользователя (опционально)"),
|
||||
session_id: str | None = Query(None, description="ID сессии"),
|
||||
):
|
||||
"""
|
||||
Поиск документов
|
||||
|
||||
|
||||
Возвращает:
|
||||
{
|
||||
"total": 45,
|
||||
@@ -142,56 +133,47 @@ async def search(
|
||||
"""
|
||||
# Выполнить поиск
|
||||
results = search_engine.search(q, limit=limit)
|
||||
|
||||
|
||||
# Добавить похожие документы
|
||||
if include_similar:
|
||||
for result in results:
|
||||
similar_docs = search_engine.get_similar_documents(result['id'], limit=3)
|
||||
result['similar_documents'] = similar_docs
|
||||
|
||||
similar_docs = search_engine.get_similar_documents(result["id"], limit=3)
|
||||
result["similar_documents"] = similar_docs
|
||||
|
||||
# Сохранить в историю
|
||||
if user_id:
|
||||
search_history.add_search(user_id, q, len(results), session_id)
|
||||
|
||||
return {
|
||||
"query": q,
|
||||
"total": len(results),
|
||||
"results": results
|
||||
}
|
||||
|
||||
return {"query": q, "total": len(results), "results": results}
|
||||
|
||||
|
||||
@app.get("/similar/{document_id}")
|
||||
async def get_similar_documents(
|
||||
document_id: str,
|
||||
limit: int = Query(5, ge=1, le=20, description="Количество похожих документов")
|
||||
document_id: str, limit: int = Query(5, ge=1, le=20, description="Количество похожих документов")
|
||||
):
|
||||
"""
|
||||
Получить похожие документы для конкретного документа
|
||||
|
||||
|
||||
Пример: /similar/doc_123
|
||||
|
||||
|
||||
Возвращает список документов отсортированных по схожести
|
||||
"""
|
||||
similar = search_engine.get_similar_documents(document_id, limit=limit)
|
||||
|
||||
|
||||
if not similar:
|
||||
raise HTTPException(status_code=404, detail="Документ не найден или нет похожих документов")
|
||||
|
||||
return {
|
||||
"document_id": document_id,
|
||||
"similar": similar,
|
||||
"count": len(similar)
|
||||
}
|
||||
|
||||
return {"document_id": document_id, "similar": similar, "count": len(similar)}
|
||||
|
||||
|
||||
@app.get("/history")
|
||||
async def get_search_history(
|
||||
user_id: str = Query(..., description="ID пользователя"),
|
||||
limit: int = Query(50, ge=1, le=200, description="Количество записей")
|
||||
limit: int = Query(50, ge=1, le=200, description="Количество записей"),
|
||||
):
|
||||
"""
|
||||
Получить историю поиска пользователя
|
||||
|
||||
|
||||
Возвращает:
|
||||
{
|
||||
"history": [
|
||||
@@ -204,54 +186,38 @@ async def get_search_history(
|
||||
}
|
||||
"""
|
||||
history = search_history.get_user_history(user_id, limit=limit)
|
||||
|
||||
return {
|
||||
"user_id": user_id,
|
||||
"history": history,
|
||||
"count": len(history)
|
||||
}
|
||||
|
||||
return {"user_id": user_id, "history": history, "count": len(history)}
|
||||
|
||||
|
||||
@app.delete("/history")
|
||||
async def clear_search_history(
|
||||
user_id: str = Query(..., description="ID пользователя")
|
||||
):
|
||||
async def clear_search_history(user_id: str = Query(..., description="ID пользователя")):
|
||||
"""Очистить историю поиска"""
|
||||
search_history.clear_user_history(user_id)
|
||||
|
||||
return {
|
||||
"message": f"История пользователя {user_id} очищена",
|
||||
"status": "success"
|
||||
}
|
||||
|
||||
return {"message": f"История пользователя {user_id} очищена", "status": "success"}
|
||||
|
||||
|
||||
@app.get("/history/popular")
|
||||
async def get_popular_queries(
|
||||
limit: int = Query(10, ge=1, le=50, description="Количество запросов")
|
||||
):
|
||||
async def get_popular_queries(limit: int = Query(10, ge=1, le=50, description="Количество запросов")):
|
||||
"""
|
||||
Получить самые популярные поисковые запросы (без привязки к пользователю)
|
||||
|
||||
|
||||
Используется для:
|
||||
- Показа популярных запросов на главной странице
|
||||
- Улучшения автодополнения
|
||||
- Аналитики
|
||||
"""
|
||||
popular = search_history.get_popular_queries(limit=limit)
|
||||
|
||||
return {
|
||||
"popular": popular,
|
||||
"count": len(popular)
|
||||
}
|
||||
|
||||
return {"popular": popular, "count": len(popular)}
|
||||
|
||||
|
||||
@app.get("/analytics/search")
|
||||
async def get_search_analytics(
|
||||
period: str = Query("7d", regex="^(1d|7d|30d)$", description="Период: 1d, 7d, 30d")
|
||||
):
|
||||
async def get_search_analytics(period: str = Query("7d", regex="^(1d|7d|30d)$", description="Период: 1d, 7d, 30d")):
|
||||
"""
|
||||
Аналитика поисковых запросов
|
||||
|
||||
|
||||
Возвращает:
|
||||
{
|
||||
"total_searches": 1240,
|
||||
@@ -263,14 +229,14 @@ async def get_search_analytics(
|
||||
"""
|
||||
# Заглушка для аналитики
|
||||
# В реальной системе здесь должна быть работа с БД
|
||||
|
||||
|
||||
return {
|
||||
"period": period,
|
||||
"total_searches": len(search_history.history),
|
||||
"unique_queries": len(set(h['query'] for h in search_history.history)),
|
||||
"unique_queries": len(set(h["query"] for h in search_history.history)),
|
||||
"top_queries": search_history.get_popular_queries(limit=10),
|
||||
"zero_results_queries": [],
|
||||
"avg_results_per_query": 0
|
||||
"avg_results_per_query": 0,
|
||||
}
|
||||
|
||||
|
||||
@@ -278,56 +244,56 @@ async def get_search_analytics(
|
||||
async def export_search_results(
|
||||
q: str = Query(..., description="Поисковый запрос"),
|
||||
export_format: str = Query("json", regex="^(json|csv|xlsx)$", description="Формат: json, csv, xlsx"),
|
||||
limit: int = Query(100, ge=1, le=1000, description="Количество результатов")
|
||||
limit: int = Query(100, ge=1, le=1000, description="Количество результатов"),
|
||||
):
|
||||
"""
|
||||
Экспорт результатов поиска
|
||||
|
||||
|
||||
Примеры:
|
||||
- /search/export?q=подшипник&export_format=json
|
||||
- /search/export?q=6205&export_format=csv
|
||||
- /search/export?q=SKF&export_format=xlsx
|
||||
|
||||
|
||||
Возвращает файл для скачивания
|
||||
"""
|
||||
# Выполняем поиск
|
||||
results = search_engine.search(q, limit=limit)
|
||||
|
||||
|
||||
# Sanitize query for filename
|
||||
safe_query = _sanitize_filename(q, max_length=20)
|
||||
|
||||
|
||||
if export_format == "json":
|
||||
json_data = SearchResultsExporter.to_json(results, pretty=True)
|
||||
return JSONResponse(content=json.loads(json_data))
|
||||
|
||||
|
||||
elif export_format == "csv":
|
||||
csv_data = SearchResultsExporter.to_csv(results)
|
||||
return StreamingResponse(
|
||||
io.BytesIO(csv_data.encode('utf-8-sig')), # BOM для корректного отображения в Excel
|
||||
io.BytesIO(csv_data.encode("utf-8-sig")), # BOM для корректного отображения в Excel
|
||||
media_type="text/csv; charset=utf-8",
|
||||
headers={"Content-Disposition": f"attachment; filename=search_results_{safe_query}.csv"}
|
||||
headers={"Content-Disposition": f"attachment; filename=search_results_{safe_query}.csv"},
|
||||
)
|
||||
|
||||
|
||||
elif export_format == "xlsx":
|
||||
excel_data = SearchResultsExporter.to_excel(results)
|
||||
if excel_data is None:
|
||||
raise HTTPException(status_code=500, detail="Ошибка при создании Excel файла")
|
||||
|
||||
|
||||
return StreamingResponse(
|
||||
excel_data,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": f"attachment; filename=search_results_{safe_query}.xlsx"}
|
||||
headers={"Content-Disposition": f"attachment; filename=search_results_{safe_query}.xlsx"},
|
||||
)
|
||||
|
||||
|
||||
@app.get("/analogs/{bearing_code}/export")
|
||||
async def export_analogs(
|
||||
bearing_code: str,
|
||||
export_format: str = Query("json", regex="^(json|csv|xlsx)$", description="Формат: json, csv, xlsx")
|
||||
export_format: str = Query("json", regex="^(json|csv|xlsx)$", description="Формат: json, csv, xlsx"),
|
||||
):
|
||||
"""
|
||||
Экспорт списка аналогов
|
||||
|
||||
|
||||
Форматы:
|
||||
- JSON: структурированный объект
|
||||
- CSV: таблица с колонками [code, standard, manufacturer, compatibility]
|
||||
@@ -341,66 +307,67 @@ async def export_analogs(
|
||||
"standard": "ГОСТ",
|
||||
"manufacturer": "SKF",
|
||||
"compatibility": "100%",
|
||||
"notes": "Прямой аналог"
|
||||
"notes": "Прямой аналог",
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
# Sanitize bearing_code for filename
|
||||
safe_code = _sanitize_filename(bearing_code)
|
||||
|
||||
|
||||
if export_format == "json":
|
||||
return JSONResponse(content=analogs)
|
||||
|
||||
|
||||
elif export_format == "csv":
|
||||
csv_data = AnalogsExporter.to_csv(analogs)
|
||||
return StreamingResponse(
|
||||
io.BytesIO(csv_data.encode('utf-8-sig')),
|
||||
io.BytesIO(csv_data.encode("utf-8-sig")),
|
||||
media_type="text/csv; charset=utf-8",
|
||||
headers={"Content-Disposition": f"attachment; filename=analogs_{safe_code}.csv"}
|
||||
headers={"Content-Disposition": f"attachment; filename=analogs_{safe_code}.csv"},
|
||||
)
|
||||
|
||||
|
||||
elif export_format == "xlsx":
|
||||
excel_data = AnalogsExporter.to_excel(analogs)
|
||||
return StreamingResponse(
|
||||
excel_data,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": f"attachment; filename=analogs_{safe_code}.xlsx"}
|
||||
headers={"Content-Disposition": f"attachment; filename=analogs_{safe_code}.xlsx"},
|
||||
)
|
||||
|
||||
|
||||
@app.post("/export/batch")
|
||||
async def export_batch(
|
||||
queries: List[str],
|
||||
export_format: str = Query("xlsx", regex="^(json|xlsx)$", description="Формат: json, xlsx")
|
||||
queries: list[str], export_format: str = Query("xlsx", regex="^(json|xlsx)$", description="Формат: json, xlsx")
|
||||
):
|
||||
"""
|
||||
Массовый экспорт результатов для списка запросов
|
||||
|
||||
|
||||
Body:
|
||||
{
|
||||
"queries": ["6205", "6305", "6405"]
|
||||
}
|
||||
|
||||
|
||||
Создает Excel файл с отдельным листом для каждого запроса
|
||||
"""
|
||||
if not queries:
|
||||
raise HTTPException(status_code=400, detail="Список запросов не может быть пустым")
|
||||
|
||||
|
||||
# Выполняем поиск для каждого запроса
|
||||
batch_results = {}
|
||||
for query in queries:
|
||||
results = search_engine.search(query, limit=50)
|
||||
batch_results[query] = results
|
||||
|
||||
|
||||
if export_format == "json":
|
||||
return JSONResponse(content=batch_results)
|
||||
|
||||
|
||||
elif export_format == "xlsx":
|
||||
excel_data = SearchResultsExporter.create_batch_excel(batch_results)
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
filename = f"batch_export_{timestamp}.xlsx"
|
||||
return StreamingResponse(
|
||||
excel_data,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": f"attachment; filename=batch_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"}
|
||||
headers={"Content-Disposition": f"attachment; filename={filename}"},
|
||||
)
|
||||
|
||||
|
||||
@@ -414,12 +381,11 @@ async def global_exception_handler(request, exc):
|
||||
# In production, log the full exception details server-side
|
||||
# import logging
|
||||
# logging.error(f"Unhandled exception: {exc}", exc_info=True)
|
||||
|
||||
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={
|
||||
"error": "Internal server error",
|
||||
"message": "An unexpected error occurred. Please contact support if the problem persists."
|
||||
}
|
||||
"message": "An unexpected error occurred. Please contact support if the problem persists.",
|
||||
},
|
||||
)
|
||||
|
||||
+112
-113
@@ -10,38 +10,37 @@
|
||||
|
||||
import json
|
||||
import os
|
||||
from typing import List, Dict
|
||||
|
||||
|
||||
class AutocompleteEngine:
|
||||
"""Движок автодополнения поисковых запросов"""
|
||||
|
||||
|
||||
def __init__(self, dict_path: str = "data/autocomplete_dict.json"):
|
||||
self.dict_path = dict_path
|
||||
self.terms = []
|
||||
self.index = {}
|
||||
self.metadata = {}
|
||||
self.load_dictionary(dict_path)
|
||||
|
||||
|
||||
def load_dictionary(self, dict_path: str):
|
||||
"""Загрузить словарь автодополнения"""
|
||||
if not os.path.exists(dict_path):
|
||||
print(f"Словарь автодополнения не найден: {dict_path}")
|
||||
return
|
||||
|
||||
|
||||
try:
|
||||
with open(dict_path, 'r', encoding='utf-8') as f:
|
||||
with open(dict_path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
self.terms = data.get('terms', [])
|
||||
self.index = data.get('index', {})
|
||||
self.metadata = data.get('metadata', {})
|
||||
self.terms = data.get("terms", [])
|
||||
self.index = data.get("index", {})
|
||||
self.metadata = data.get("metadata", {})
|
||||
except Exception as e:
|
||||
print(f"Ошибка при загрузке словаря: {e}")
|
||||
|
||||
def suggest(self, prefix: str, limit: int = 10, types: List[str] = None) -> List[Dict]:
|
||||
|
||||
def suggest(self, prefix: str, limit: int = 10, types: list[str] = None) -> list[dict]:
|
||||
"""
|
||||
Генерировать предложения по префиксу
|
||||
|
||||
|
||||
Алгоритм:
|
||||
1. Нормализовать запрос (lowercase, удалить спецсимволы)
|
||||
2. Найти в префиксном дереве
|
||||
@@ -51,204 +50,204 @@ class AutocompleteEngine:
|
||||
"""
|
||||
if not prefix or len(prefix) < 1:
|
||||
return []
|
||||
|
||||
|
||||
# Нормализация запроса
|
||||
normalized_prefix = prefix.lower().strip()
|
||||
|
||||
|
||||
# Поиск в индексе
|
||||
candidates = self.index.get(normalized_prefix, [])
|
||||
|
||||
|
||||
# Если не найдено в индексе, ищем в полном списке терминов
|
||||
if not candidates:
|
||||
candidates = []
|
||||
for term in self.terms:
|
||||
if term['value'].lower().startswith(normalized_prefix):
|
||||
candidates.append(term['value'])
|
||||
|
||||
if term["value"].lower().startswith(normalized_prefix):
|
||||
candidates.append(term["value"])
|
||||
|
||||
# Получаем полную информацию о кандидатах
|
||||
suggestions = []
|
||||
for candidate in candidates[:limit * 2]: # Берем больше для фильтрации
|
||||
for candidate in candidates[: limit * 2]: # Берем больше для фильтрации
|
||||
# Ищем в списке терминов
|
||||
term_info = next((t for t in self.terms if t['value'] == candidate), None)
|
||||
term_info = next((t for t in self.terms if t["value"] == candidate), None)
|
||||
if term_info:
|
||||
# Фильтр по типу
|
||||
if types and term_info['type'] not in types:
|
||||
if types and term_info["type"] not in types:
|
||||
continue
|
||||
|
||||
|
||||
# Подсветка совпадения
|
||||
highlighted = self._highlight_match(term_info['value'], prefix)
|
||||
|
||||
suggestions.append({
|
||||
'value': term_info['value'],
|
||||
'type': term_info['type'],
|
||||
'frequency': term_info['frequency'],
|
||||
'highlight': highlighted
|
||||
})
|
||||
|
||||
highlighted = self._highlight_match(term_info["value"], prefix)
|
||||
|
||||
suggestions.append(
|
||||
{
|
||||
"value": term_info["value"],
|
||||
"type": term_info["type"],
|
||||
"frequency": term_info["frequency"],
|
||||
"highlight": highlighted,
|
||||
}
|
||||
)
|
||||
|
||||
# Сортировка по частотности
|
||||
suggestions.sort(key=lambda x: x['frequency'], reverse=True)
|
||||
|
||||
suggestions.sort(key=lambda x: x["frequency"], reverse=True)
|
||||
|
||||
return suggestions[:limit]
|
||||
|
||||
|
||||
def _highlight_match(self, value: str, prefix: str) -> str:
|
||||
"""Подсветка совпадающей части"""
|
||||
if not prefix:
|
||||
return value
|
||||
|
||||
|
||||
# Находим позицию совпадения (регистронезависимо)
|
||||
value_lower = value.lower()
|
||||
prefix_lower = prefix.lower()
|
||||
|
||||
|
||||
pos = value_lower.find(prefix_lower)
|
||||
if pos == -1:
|
||||
return value
|
||||
|
||||
|
||||
# Создаем подсвеченную версию
|
||||
highlighted = (
|
||||
value[:pos] +
|
||||
'<b>' + value[pos:pos+len(prefix)] + '</b>' +
|
||||
value[pos+len(prefix):]
|
||||
)
|
||||
|
||||
highlighted = value[:pos] + "<b>" + value[pos : pos + len(prefix)] + "</b>" + value[pos + len(prefix) :]
|
||||
|
||||
return highlighted
|
||||
|
||||
def get_popular_searches(self, limit: int = 10) -> List[Dict]:
|
||||
|
||||
def get_popular_searches(self, limit: int = 10) -> list[dict]:
|
||||
"""Получить самые популярные поисковые запросы"""
|
||||
# Сортируем по частотности
|
||||
sorted_terms = sorted(self.terms, key=lambda x: x['frequency'], reverse=True)
|
||||
|
||||
sorted_terms = sorted(self.terms, key=lambda x: x["frequency"], reverse=True)
|
||||
|
||||
# Возвращаем топ-N
|
||||
return sorted_terms[:limit]
|
||||
|
||||
|
||||
class DocumentSearchEngine:
|
||||
"""Движок поиска документов"""
|
||||
|
||||
def __init__(self,
|
||||
index_path: str = "data/document_index.json",
|
||||
similarity_path: str = "data/similarity_matrix.json"):
|
||||
|
||||
def __init__(
|
||||
self, index_path: str = "data/document_index.json", similarity_path: str = "data/similarity_matrix.json"
|
||||
):
|
||||
self.index_path = index_path
|
||||
self.similarity_path = similarity_path
|
||||
self.documents = {}
|
||||
self.similarity_matrix = {}
|
||||
self.load_data()
|
||||
|
||||
|
||||
def load_data(self):
|
||||
"""Загрузить индекс документов и матрицу схожести"""
|
||||
# Загрузка индекса документов
|
||||
if os.path.exists(self.index_path):
|
||||
try:
|
||||
with open(self.index_path, 'r', encoding='utf-8') as f:
|
||||
with open(self.index_path, encoding="utf-8") as f:
|
||||
self.documents = json.load(f)
|
||||
except Exception as e:
|
||||
print(f"Ошибка при загрузке индекса документов: {e}")
|
||||
|
||||
|
||||
# Загрузка матрицы схожести
|
||||
if os.path.exists(self.similarity_path):
|
||||
try:
|
||||
with open(self.similarity_path, 'r', encoding='utf-8') as f:
|
||||
with open(self.similarity_path, encoding="utf-8") as f:
|
||||
self.similarity_matrix = json.load(f)
|
||||
except Exception as e:
|
||||
print(f"Ошибка при загрузке матрицы схожести: {e}")
|
||||
|
||||
def search(self, query: str, limit: int = 20) -> List[Dict]:
|
||||
|
||||
def search(self, query: str, limit: int = 20) -> list[dict]:
|
||||
"""
|
||||
Простой поиск по документам
|
||||
|
||||
|
||||
В реальной системе здесь должен быть полнотекстовый поиск
|
||||
(Elasticsearch, PostgreSQL Full-Text Search, etc.)
|
||||
"""
|
||||
if not query:
|
||||
return []
|
||||
|
||||
|
||||
query_lower = query.lower()
|
||||
results = []
|
||||
|
||||
|
||||
for doc_id, doc in self.documents.items():
|
||||
# Простой поиск по названию и описанию
|
||||
if (query_lower in doc['title'].lower() or
|
||||
query_lower in doc.get('excerpt', '').lower()):
|
||||
|
||||
if query_lower in doc["title"].lower() or query_lower in doc.get("excerpt", "").lower():
|
||||
|
||||
# Вычисление релевантности (упрощенно)
|
||||
relevance = 0.5
|
||||
if query_lower in doc['title'].lower():
|
||||
if query_lower in doc["title"].lower():
|
||||
relevance += 0.5
|
||||
|
||||
results.append({
|
||||
'id': doc_id,
|
||||
'title': doc['title'],
|
||||
'path': doc['path'],
|
||||
'excerpt': doc.get('excerpt', ''),
|
||||
'relevance': relevance
|
||||
})
|
||||
|
||||
|
||||
results.append(
|
||||
{
|
||||
"id": doc_id,
|
||||
"title": doc["title"],
|
||||
"path": doc["path"],
|
||||
"excerpt": doc.get("excerpt", ""),
|
||||
"relevance": relevance,
|
||||
}
|
||||
)
|
||||
|
||||
# Сортировка по релевантности
|
||||
results.sort(key=lambda x: x['relevance'], reverse=True)
|
||||
|
||||
results.sort(key=lambda x: x["relevance"], reverse=True)
|
||||
|
||||
return results[:limit]
|
||||
|
||||
def get_similar_documents(self, document_id: str, limit: int = 5) -> List[Dict]:
|
||||
|
||||
def get_similar_documents(self, document_id: str, limit: int = 5) -> list[dict]:
|
||||
"""Получить похожие документы для конкретного документа"""
|
||||
if document_id not in self.similarity_matrix:
|
||||
return []
|
||||
|
||||
similar = self.similarity_matrix[document_id].get('similar', [])
|
||||
|
||||
|
||||
similar = self.similarity_matrix[document_id].get("similar", [])
|
||||
|
||||
# Дополняем информацией из индекса
|
||||
result = []
|
||||
for sim_doc in similar[:limit]:
|
||||
doc_id = sim_doc['doc_id']
|
||||
doc_id = sim_doc["doc_id"]
|
||||
if doc_id in self.documents:
|
||||
result.append({
|
||||
'id': doc_id,
|
||||
'title': sim_doc.get('title', self.documents[doc_id]['title']),
|
||||
'path': self.documents[doc_id]['path'],
|
||||
'similarity': sim_doc['score']
|
||||
})
|
||||
|
||||
result.append(
|
||||
{
|
||||
"id": doc_id,
|
||||
"title": sim_doc.get("title", self.documents[doc_id]["title"]),
|
||||
"path": self.documents[doc_id]["path"],
|
||||
"similarity": sim_doc["score"],
|
||||
}
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class SearchHistory:
|
||||
"""Управление историей поиска (заглушка для работы без БД)"""
|
||||
|
||||
|
||||
def __init__(self):
|
||||
self.history = []
|
||||
|
||||
|
||||
def add_search(self, user_id: str, query: str, results_count: int, session_id: str = None):
|
||||
"""Добавить запись в историю поиска"""
|
||||
from datetime import datetime
|
||||
|
||||
self.history.append({
|
||||
'user_id': user_id,
|
||||
'query': query,
|
||||
'results_count': results_count,
|
||||
'session_id': session_id,
|
||||
'timestamp': datetime.now().isoformat()
|
||||
})
|
||||
|
||||
def get_user_history(self, user_id: str, limit: int = 50) -> List[Dict]:
|
||||
|
||||
self.history.append(
|
||||
{
|
||||
"user_id": user_id,
|
||||
"query": query,
|
||||
"results_count": results_count,
|
||||
"session_id": session_id,
|
||||
"timestamp": datetime.now().isoformat(),
|
||||
}
|
||||
)
|
||||
|
||||
def get_user_history(self, user_id: str, limit: int = 50) -> list[dict]:
|
||||
"""Получить историю поиска пользователя"""
|
||||
user_searches = [h for h in self.history if h['user_id'] == user_id]
|
||||
user_searches.sort(key=lambda x: x['timestamp'], reverse=True)
|
||||
user_searches = [h for h in self.history if h["user_id"] == user_id]
|
||||
user_searches.sort(key=lambda x: x["timestamp"], reverse=True)
|
||||
return user_searches[:limit]
|
||||
|
||||
|
||||
def clear_user_history(self, user_id: str):
|
||||
"""Очистить историю поиска пользователя"""
|
||||
self.history = [h for h in self.history if h['user_id'] != user_id]
|
||||
|
||||
def get_popular_queries(self, limit: int = 10) -> List[Dict]:
|
||||
self.history = [h for h in self.history if h["user_id"] != user_id]
|
||||
|
||||
def get_popular_queries(self, limit: int = 10) -> list[dict]:
|
||||
"""Получить популярные поисковые запросы"""
|
||||
from collections import Counter
|
||||
|
||||
queries = [h['query'] for h in self.history]
|
||||
|
||||
queries = [h["query"] for h in self.history]
|
||||
counter = Counter(queries)
|
||||
|
||||
|
||||
popular = []
|
||||
for query, count in counter.most_common(limit):
|
||||
popular.append({
|
||||
'query': query,
|
||||
'count': count
|
||||
})
|
||||
|
||||
popular.append({"query": query, "count": count})
|
||||
|
||||
return popular
|
||||
Reference in new issue
Block a user