168 lines
5.4 KiB
Python
168 lines
5.4 KiB
Python
import heapq
|
||
from difflib import SequenceMatcher
|
||
from typing import Literal
|
||
from uuid import UUID
|
||
|
||
from django.db.models import Q
|
||
from ninja import NinjaAPI, Query, Schema
|
||
from ninja.errors import HttpError
|
||
|
||
from .models import AddressObject, House
|
||
|
||
api = NinjaAPI(title="FIAS Address API", version="1.0.0", docs_url="docs/")
|
||
|
||
|
||
class AddressOut(Schema):
|
||
fias_id: UUID
|
||
object_id: int | None
|
||
parent_id: int | None
|
||
name: str
|
||
type_name: str
|
||
level: int
|
||
region_code: str
|
||
postal_code: str
|
||
|
||
|
||
class SearchParams(Schema):
|
||
query: str = ""
|
||
region_code: str | None = None
|
||
parent_id: int | None = None
|
||
limit: int = 20
|
||
offset: int = 0
|
||
fuzzy: bool = True
|
||
|
||
|
||
class SearchResponse(Schema):
|
||
count: int
|
||
items: list[AddressOut]
|
||
|
||
|
||
class HouseOut(Schema):
|
||
fias_id: UUID
|
||
object_id: int
|
||
parent_id: int | None
|
||
region_code: str
|
||
house_number: str
|
||
house_type: int | None
|
||
additional_number_1: str
|
||
additional_type_1: int | None
|
||
additional_number_2: str
|
||
additional_type_2: int | None
|
||
display_number: str
|
||
|
||
|
||
class HouseSearchResponse(Schema):
|
||
count: int
|
||
items: list[HouseOut]
|
||
|
||
|
||
def normalize(value: str) -> str:
|
||
return " ".join(value.casefold().replace("ё", "е").split())
|
||
|
||
|
||
def similarity(query: str, name: str, type_name: str) -> float:
|
||
normalized_name = normalize(name)
|
||
normalized_full_name = normalize(f"{type_name} {name}")
|
||
if query in normalized_name or query in normalized_full_name:
|
||
return 1.0
|
||
return max(
|
||
SequenceMatcher(None, query, normalized_name).ratio(),
|
||
SequenceMatcher(None, query, normalized_full_name).ratio(),
|
||
)
|
||
|
||
|
||
def fuzzy_search(queryset, query: str, limit: int, offset: int) -> SearchResponse:
|
||
normalized_query = normalize(query)
|
||
wanted = offset + limit
|
||
matches = 0
|
||
candidates = []
|
||
for item in queryset.only("id", "name", "type_name").iterator(chunk_size=2000):
|
||
score = similarity(normalized_query, item.name, item.type_name)
|
||
if score < 0.55:
|
||
continue
|
||
matches += 1
|
||
candidate = (score, -item.id, item.id)
|
||
if len(candidates) < wanted:
|
||
heapq.heappush(candidates, candidate)
|
||
elif candidate > candidates[0]:
|
||
heapq.heapreplace(candidates, candidate)
|
||
|
||
ranked_ids = [item_id for _, _, item_id in sorted(candidates, reverse=True)][offset:wanted]
|
||
by_id = AddressObject.objects.in_bulk(ranked_ids)
|
||
return SearchResponse(count=matches, items=[by_id[item_id] for item_id in ranked_ids])
|
||
|
||
|
||
def search(levels: tuple[int, ...], params: SearchParams) -> SearchResponse:
|
||
limit = min(max(params.limit, 1), 100)
|
||
offset = max(params.offset, 0)
|
||
queryset = AddressObject.objects.filter(level__in=levels, is_active=True)
|
||
if params.query.strip() and not params.fuzzy:
|
||
terms = params.query.split()
|
||
for term in terms:
|
||
queryset = queryset.filter(Q(name__icontains=term) | Q(type_name__icontains=term))
|
||
if params.region_code:
|
||
queryset = queryset.filter(region_code=params.region_code.zfill(2))
|
||
if params.parent_id:
|
||
queryset = queryset.filter(parent_id=params.parent_id)
|
||
if params.query.strip() and params.fuzzy:
|
||
return fuzzy_search(queryset, params.query, limit, offset)
|
||
count = queryset.count()
|
||
return SearchResponse(count=count, items=list(queryset[offset : offset + limit]))
|
||
|
||
|
||
@api.get("health", tags=["service"])
|
||
def health(request):
|
||
return {"status": "ok"}
|
||
|
||
|
||
@api.get("regions", response=SearchResponse, tags=["addresses"])
|
||
def regions(request, params: Query[SearchParams]):
|
||
return search((AddressObject.Level.REGION,), params)
|
||
|
||
|
||
@api.get("cities", response=SearchResponse, tags=["addresses"])
|
||
def cities(request, params: Query[SearchParams]):
|
||
return search((AddressObject.Level.CITY, AddressObject.Level.SETTLEMENT), params)
|
||
|
||
|
||
@api.get("streets", response=SearchResponse, tags=["addresses"])
|
||
def streets(request, params: Query[SearchParams]):
|
||
return search((AddressObject.Level.STREET,), params)
|
||
|
||
|
||
@api.get("houses", response=HouseSearchResponse, tags=["addresses"])
|
||
def houses(request, params: Query[SearchParams]):
|
||
limit = min(max(params.limit, 1), 100)
|
||
offset = max(params.offset, 0)
|
||
queryset = House.objects.filter(is_actual=True, is_active=True)
|
||
if params.region_code:
|
||
queryset = queryset.filter(region_code=params.region_code.zfill(2))
|
||
if params.parent_id:
|
||
queryset = queryset.filter(parent_id=params.parent_id)
|
||
for term in params.query.split():
|
||
queryset = queryset.filter(
|
||
Q(house_number__icontains=term)
|
||
| Q(additional_number_1__icontains=term)
|
||
| Q(additional_number_2__icontains=term)
|
||
)
|
||
return HouseSearchResponse(
|
||
count=queryset.count(), items=list(queryset[offset : offset + limit])
|
||
)
|
||
|
||
|
||
@api.get("search", response=SearchResponse, tags=["addresses"])
|
||
def universal_search(
|
||
request,
|
||
params: Query[SearchParams],
|
||
kind: Literal["region", "city", "street"] | None = None,
|
||
):
|
||
if not params.region_code:
|
||
raise HttpError(422, "Для поиска необходимо указать region_code")
|
||
levels = {
|
||
"region": (AddressObject.Level.REGION,),
|
||
"city": (AddressObject.Level.CITY, AddressObject.Level.SETTLEMENT),
|
||
"street": (AddressObject.Level.STREET,),
|
||
None: tuple(level.value for level in AddressObject.Level),
|
||
}
|
||
return search(levels[kind], params)
|