File size: 69,766 Bytes
f440f03 | 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 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 | """Vision endpoints attēlu un kadru analīzei."""
from __future__ import annotations
import base64
import binascii
import io
import logging
import os
from collections import Counter
from datetime import UTC, datetime
from typing import Any
from uuid import uuid4
import httpx
import numpy as np
from fastapi import APIRouter, HTTPException
from PIL import Image, ImageDraw, ImageStat
from pydantic import BaseModel, Field, field_validator, model_validator
from maris_core.memory_context import memory_store
logger = logging.getLogger(__name__)
router = APIRouter()
_DETECTOR: Any | None = None
_DETECTOR_FAILED = False
_SEGMENTER: Any | None = None
_SEGMENTER_FAILED = False
_OCR_ENGINE: Any | None = None
_OCR_ENGINE_KIND: str | None = None
_OCR_FAILED = False
_LIVE_CAMERAS: dict[str, dict[str, Any]] = {}
_LIVE_REID_INDEX: dict[str, list[dict[str, Any]]] = {}
SCENE_BRIGHTNESS_DELTA = 30.0
TRACKING_DISTANCE_RATIO = 0.18
POSE_CONNECTIONS = [
("nose", "left_shoulder"),
("nose", "right_shoulder"),
("left_shoulder", "right_shoulder"),
("left_shoulder", "left_elbow"),
("left_elbow", "left_wrist"),
("right_shoulder", "right_elbow"),
("right_elbow", "right_wrist"),
("left_shoulder", "left_hip"),
("right_shoulder", "right_hip"),
("left_hip", "right_hip"),
("left_hip", "left_knee"),
("left_knee", "left_ankle"),
("right_hip", "right_knee"),
("right_knee", "right_ankle"),
]
class BoundingBox(BaseModel):
x: float
y: float
width: float
height: float
class VisionDetection(BaseModel):
label: str
confidence: float
bbox: BoundingBox
class ImageSourceRequest(BaseModel):
image_url: str | None = None
image_base64: str | None = None
session_id: str | None = Field(default=None, max_length=120)
camera_id: str | None = Field(default=None, max_length=120)
max_detections: int = Field(default=10, ge=1, le=50)
confidence_threshold: float = Field(default=0.25, ge=0.0, le=1.0)
@model_validator(mode="after")
def validate_source(self) -> ImageSourceRequest:
has_url = bool((self.image_url or "").strip())
has_base64 = bool((self.image_base64 or "").strip())
if has_url == has_base64:
raise ValueError("Norādi tieši vienu no image_url vai image_base64.")
return self
@field_validator("session_id", "camera_id")
@classmethod
def normalize_optional_text(cls, value: str | None) -> str | None:
normalized = (value or "").strip()
return normalized or None
class FrameSequenceRequest(BaseModel):
frames_base64: list[str] = Field(min_length=1, max_length=24)
max_detections: int = Field(default=10, ge=1, le=50)
confidence_threshold: float = Field(default=0.25, ge=0.0, le=1.0)
@field_validator("frames_base64")
@classmethod
def validate_frames(cls, value: list[str]) -> list[str]:
cleaned = [item.strip() for item in value if item.strip()]
if not cleaned:
raise ValueError("frames_base64 nedrīkst būt tukšs.")
return cleaned
class VisionAnalyzeResponse(BaseModel):
summary: str
detections: list[VisionDetection]
width: int
height: int
model: str
fallback_used: bool = False
class OCRTextBlock(BaseModel):
text: str
confidence: float
bbox: BoundingBox
language: str
class VisionOCRResponse(BaseModel):
summary: str
results: list[OCRTextBlock]
width: int
height: int
model: str
fallback_used: bool = False
class PoseKeypoint(BaseModel):
name: str
x: float
y: float
confidence: float
class PoseConnection(BaseModel):
start: str
end: str
class PoseDetection(BaseModel):
person_id: int
confidence: float
bbox: BoundingBox
keypoints: list[PoseKeypoint]
connections: list[PoseConnection]
class VisionPoseResponse(BaseModel):
summary: str
poses: list[PoseDetection]
width: int
height: int
model: str
fallback_used: bool = False
class SegmentationMask(BaseModel):
label: str
confidence: float
mask_data_url: str
bbox: BoundingBox
area_pixels: int
class VisionSegmentationResponse(BaseModel):
summary: str
masks: list[SegmentationMask]
width: int
height: int
model: str
fallback_used: bool = False
class ActionPrediction(BaseModel):
action: str
confidence: float
subject_label: str
rationale: str
class VisionActionResponse(BaseModel):
summary: str
actions: list[ActionPrediction]
width: int
height: int
model: str
fallback_used: bool = False
class TrackObservation(BaseModel):
frame_index: int
confidence: float
bbox: BoundingBox
class TrackedObject(BaseModel):
track_id: int
label: str
average_confidence: float
observations: list[TrackObservation]
class VisionTrackingResponse(BaseModel):
summary: str
tracks: list[TrackedObject]
frame_count: int
model: str
fallback_used: bool = False
class FrameAnalysis(BaseModel):
frame_index: int
summary: str
detections: list[VisionDetection]
dominant_labels: list[str]
brightness: float
class VisionFrameAnalysisResponse(BaseModel):
summary: str
frames: list[FrameAnalysis]
frame_count: int
model: str
fallback_used: bool = False
class SceneSegment(BaseModel):
scene_index: int
start_frame: int
end_frame: int
summary: str
dominant_labels: list[str]
average_brightness: float
class VisionSceneTimelineResponse(BaseModel):
summary: str
scenes: list[SceneSegment]
frame_count: int
model: str
fallback_used: bool = False
class CameraResolution(BaseModel):
width: int = Field(default=1280, ge=1, le=8192)
height: int = Field(default=720, ge=1, le=8192)
class CameraHealth(BaseModel):
connected: bool = True
analysis_active: bool = False
reconnect_attempts: int = Field(default=0, ge=0)
dropped_frames: int = Field(default=0, ge=0)
events_emitted: int = Field(default=0, ge=0)
last_frame_at: str | None = None
last_event_at: str | None = None
last_error: str | None = None
ingest_mode: str = "client_push"
class LiveCameraConnectRequest(BaseModel):
camera_id: str | None = Field(default=None, min_length=1, max_length=120)
source_type: str = Field(min_length=2, max_length=40)
transport: str = Field(min_length=2, max_length=40)
url: str | None = None
device_id: str | None = None
auth: dict[str, str] = Field(default_factory=dict)
resolution: CameraResolution = Field(default_factory=CameraResolution)
fps: float = Field(default=10.0, ge=0.1, le=120.0)
enabled_pipelines: list[str] = Field(default_factory=list)
detection_stride: int = Field(default=3, ge=1, le=10)
ocr_interval: int = Field(default=12, ge=1, le=120)
fps_budget: float = Field(default=6.0, ge=0.5, le=60.0)
roi_zones: list[dict[str, Any]] = Field(default_factory=list)
alert_rules: list[str] = Field(default_factory=list)
@model_validator(mode="after")
def validate_source(self) -> LiveCameraConnectRequest:
if not (self.url or self.device_id):
raise ValueError("Norādi url vai device_id kamerai.")
return self
class LiveSessionCommandRequest(BaseModel):
camera_id: str = Field(min_length=1, max_length=120)
enabled_pipelines: list[str] | None = None
detection_stride: int | None = Field(default=None, ge=1, le=10)
ocr_interval: int | None = Field(default=None, ge=1, le=120)
fps_budget: float | None = Field(default=None, ge=0.5, le=60.0)
class LiveCameraConfigRequest(BaseModel):
camera_id: str = Field(min_length=1, max_length=120)
roi_zones: list[dict[str, Any]] = Field(default_factory=list)
alert_rules: list[str] = Field(default_factory=list)
enabled_pipelines: list[str] | None = None
fps_budget: float | None = Field(default=None, ge=0.5, le=60.0)
class LiveFrameRequest(BaseModel):
camera_id: str = Field(min_length=1, max_length=120)
image_base64: str = Field(min_length=8)
frame_index: int | None = Field(default=None, ge=0)
timestamp_ms: int | None = Field(default=None, ge=0)
class LiveEvent(BaseModel):
event_id: str
camera_id: str
type: str
severity: str
timestamp: str
summary: str
payload: dict[str, Any] = Field(default_factory=dict)
class LiveCameraSession(BaseModel):
camera_id: str
source_type: str
transport: str
url: str | None = None
device_id: str | None = None
auth: dict[str, Any] = Field(default_factory=dict)
resolution: CameraResolution
fps: float
status: str
health: CameraHealth
enabled_pipelines: list[str]
detection_stride: int
ocr_interval: int
fps_budget: float
roi_zones: list[dict[str, Any]] = Field(default_factory=list)
alert_rules: list[str] = Field(default_factory=list)
latest_snapshot: str | None = None
latest_result: dict[str, Any] = Field(default_factory=dict)
recent_events: list[LiveEvent] = Field(default_factory=list)
timeline: list[SceneSegment] = Field(default_factory=list)
tracks: list[TrackedObject] = Field(default_factory=list)
class LiveCameraCatalogResponse(BaseModel):
summary: str
cameras: list[LiveCameraSession]
class LiveCameraResponse(BaseModel):
summary: str
camera: LiveCameraSession
class LiveEventsResponse(BaseModel):
summary: str
camera_id: str
events: list[LiveEvent]
class LiveSnapshotResponse(BaseModel):
summary: str
camera_id: str
snapshot_data_url: str | None = None
class LiveFrameResponse(BaseModel):
summary: str
camera: LiveCameraSession
events: list[LiveEvent] = Field(default_factory=list)
def _decode_base64_payload(value: str) -> bytes:
payload = value.strip()
if payload.startswith("data:"):
_, _, payload = payload.partition(",")
try:
return base64.b64decode(payload, validate=True)
except (ValueError, binascii.Error) as exc:
raise HTTPException(status_code=400, detail="Nederīgs base64 saturs.") from exc
async def _load_image_from_source(image_url: str | None, image_base64: str | None) -> Image.Image:
if image_base64:
image_bytes = _decode_base64_payload(image_base64)
elif image_url and image_url.startswith("data:"):
image_bytes = _decode_base64_payload(image_url)
elif image_url and image_url.startswith(("http://", "https://")):
async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:
response = await client.get(image_url)
response.raise_for_status()
image_bytes = response.content
else:
raise HTTPException(
status_code=400,
detail="Atbalstīts ir tikai http(s) URL vai base64 attēls.",
)
try:
return Image.open(io.BytesIO(image_bytes)).convert("RGB")
except Exception as exc: # noqa: BLE001
raise HTTPException(status_code=400, detail="Neizdevās nolasīt attēlu.") from exc
async def _load_image(req: ImageSourceRequest) -> Image.Image:
return await _load_image_from_source(req.image_url, req.image_base64)
async def _load_frames(req: FrameSequenceRequest) -> list[Image.Image]:
return [await _load_image_from_source(None, frame) for frame in req.frames_base64]
def _image_to_data_url(image: Image.Image) -> str:
buffer = io.BytesIO()
image.save(buffer, format="PNG")
encoded = base64.b64encode(buffer.getvalue()).decode()
return f"data:image/png;base64,{encoded}"
def _color_tone_name(rgb: tuple[int, int, int]) -> str:
red, green, blue = rgb
if max(rgb) - min(rgb) < 20:
return "neitrāli"
if red >= green and red >= blue:
return "silti"
if blue >= red and blue >= green:
return "vēsi"
return "zaļgani"
def _fallback_summary(image: Image.Image, reason: str) -> str:
width, height = image.size
orientation = "horizontāls" if width >= height else "vertikāls"
brightness = ImageStat.Stat(image.convert("L")).mean[0]
light = "gaišu" if brightness >= 150 else "tumšu" if brightness <= 85 else "vidēji apgaismotu"
dominant_rgb = image.resize((1, 1)).getpixel((0, 0))
tone = _color_tone_name(dominant_rgb)
return (
f"Fallback vision summary: {orientation} {width}x{height} attēls ar {light} ekspozīciju "
f"un {tone} krāsu toni. {reason}"
)
def _detection_center(detection: VisionDetection) -> tuple[float, float]:
return (
detection.bbox.x + detection.bbox.width / 2.0,
detection.bbox.y + detection.bbox.height / 2.0,
)
def _build_detection_summary(detections: list[VisionDetection], width: int, height: int) -> str:
if not detections:
return (
f"Vision model neredzēja objektus virs sliekšņa šajā attēlā ({width}x{height}). "
"Pamēģini zemāku confidence_threshold vai citu kadru."
)
counts = Counter(detection.label for detection in detections)
ordered = ", ".join(
f"{label}×{count}" if count > 1 else label for label, count in counts.most_common(5)
)
return f"Analīze pabeigta: attēlā ({width}x{height}) atrasti {len(detections)} objekti — {ordered}."
def _dominant_labels(detections: list[VisionDetection], limit: int = 4) -> list[str]:
counts = Counter(item.label for item in detections)
return [label for label, _ in counts.most_common(limit)]
def _frame_brightness(image: Image.Image) -> float:
return float(ImageStat.Stat(image.convert("L")).mean[0])
def _get_detector() -> tuple[Any | None, str]:
global _DETECTOR, _DETECTOR_FAILED
model_name = os.getenv("VISION_DETECTION_MODEL", "facebook/detr-resnet-50")
if _DETECTOR is not None:
return _DETECTOR, model_name
if _DETECTOR_FAILED:
return None, model_name
try:
import torch # type: ignore
from transformers import pipeline # type: ignore
device = 0 if torch.cuda.is_available() else -1
_DETECTOR = pipeline("object-detection", model=model_name, device=device)
except Exception as exc: # noqa: BLE001
logger.warning("Vision detector unavailable, using fallback summary: %s", exc)
_DETECTOR_FAILED = True
return None, model_name
return _DETECTOR, model_name
def _run_detection(
detector: Any,
image: Image.Image,
*,
threshold: float,
max_detections: int,
) -> list[VisionDetection]:
raw_detections = detector(image)
detections: list[VisionDetection] = []
for item in raw_detections:
score = float(item.get("score", 0.0))
if score < threshold:
continue
box = item.get("box") or {}
xmin = float(box.get("xmin", 0.0))
ymin = float(box.get("ymin", 0.0))
xmax = float(box.get("xmax", xmin))
ymax = float(box.get("ymax", ymin))
width = max(0.0, xmax - xmin)
height = max(0.0, ymax - ymin)
if width <= 0.0 or height <= 0.0:
continue
detections.append(
VisionDetection(
label=str(item.get("label", "unknown")).strip() or "unknown",
confidence=score,
bbox=BoundingBox(x=xmin, y=ymin, width=width, height=height),
)
)
if len(detections) >= max_detections:
break
return detections
def _detect_image_payload(
image: Image.Image,
*,
threshold: float,
max_detections: int,
) -> tuple[list[VisionDetection], str, bool]:
detector, model_name = _get_detector()
if detector is None:
return [], "fallback/basic-image-summary", True
try:
return (
_run_detection(
detector,
image,
threshold=threshold,
max_detections=max_detections,
),
model_name,
False,
)
except Exception as exc: # noqa: BLE001
logger.warning("Vision detection failed, using fallback: %s", exc)
return [], f"{model_name} (fallback)", True
def _get_segmenter() -> tuple[Any | None, str]:
global _SEGMENTER, _SEGMENTER_FAILED
model_name = os.getenv(
"VISION_SEGMENTATION_MODEL",
"facebook/mask2former-swin-small-coco-instance",
)
if _SEGMENTER is not None:
return _SEGMENTER, model_name
if _SEGMENTER_FAILED:
return None, model_name
try:
import torch # type: ignore
from transformers import pipeline # type: ignore
device = 0 if torch.cuda.is_available() else -1
_SEGMENTER = pipeline("image-segmentation", model=model_name, device=device)
except Exception as exc: # noqa: BLE001
logger.warning("Vision segmenter unavailable, using bbox masks: %s", exc)
_SEGMENTER_FAILED = True
return None, model_name
return _SEGMENTER, model_name
def _bbox_from_mask(mask_array: np.ndarray) -> BoundingBox | None:
ys, xs = np.where(mask_array > 0)
if len(xs) == 0 or len(ys) == 0:
return None
xmin = float(xs.min())
xmax = float(xs.max())
ymin = float(ys.min())
ymax = float(ys.max())
return BoundingBox(
x=xmin, y=ymin, width=max(1.0, xmax - xmin + 1.0), height=max(1.0, ymax - ymin + 1.0)
)
def _mask_to_data_url(mask_array: np.ndarray) -> str:
mask_image = Image.fromarray(np.where(mask_array > 0, 255, 0).astype(np.uint8), mode="L")
return _image_to_data_url(mask_image)
def _bbox_mask(width: int, height: int, bbox: BoundingBox) -> np.ndarray:
mask = Image.new("L", (width, height), 0)
draw = ImageDraw.Draw(mask)
draw.rectangle(
[bbox.x, bbox.y, bbox.x + bbox.width, bbox.y + bbox.height],
fill=255,
)
return np.array(mask, dtype=np.uint8)
def _coerce_mask_array(mask: Any) -> np.ndarray | None:
if isinstance(mask, Image.Image):
return np.array(mask.convert("L"), dtype=np.uint8)
if isinstance(mask, np.ndarray):
return mask.astype(np.uint8)
try:
array = np.asarray(mask, dtype=np.uint8)
except Exception: # noqa: BLE001
return None
if array.ndim < 2:
return None
return array
def _segment_from_detections(
image: Image.Image, detections: list[VisionDetection]
) -> list[SegmentationMask]:
width, height = image.size
masks: list[SegmentationMask] = []
for detection in detections:
mask_array = _bbox_mask(width, height, detection.bbox)
masks.append(
SegmentationMask(
label=detection.label,
confidence=detection.confidence,
mask_data_url=_mask_to_data_url(mask_array),
bbox=detection.bbox,
area_pixels=int((mask_array > 0).sum()),
)
)
return masks
def _extract_segmentation_masks(
image: Image.Image,
detections: list[VisionDetection],
) -> tuple[list[SegmentationMask], str, bool]:
segmenter, model_name = _get_segmenter()
if segmenter is None:
return _segment_from_detections(image, detections), "bbox-mask-fallback", True
try:
raw_masks = segmenter(image)
masks: list[SegmentationMask] = []
for item in raw_masks:
mask_array = _coerce_mask_array(item.get("mask"))
if mask_array is None:
continue
bbox = _bbox_from_mask(mask_array)
if bbox is None:
continue
masks.append(
SegmentationMask(
label=str(item.get("label", "segment")).strip() or "segment",
confidence=float(item.get("score", 0.0)),
mask_data_url=_mask_to_data_url(mask_array),
bbox=bbox,
area_pixels=int((mask_array > 0).sum()),
)
)
if masks:
return masks, model_name, False
except Exception as exc: # noqa: BLE001
logger.warning("Vision segmentation failed, using bbox masks: %s", exc)
return _segment_from_detections(image, detections), f"{model_name} (fallback)", True
def _get_ocr_engine() -> tuple[tuple[str, Any] | None, str]:
global _OCR_ENGINE, _OCR_ENGINE_KIND, _OCR_FAILED
trocr_model = os.getenv("VISION_OCR_MODEL", "microsoft/trocr-base-printed")
if _OCR_ENGINE is not None and _OCR_ENGINE_KIND is not None:
return (_OCR_ENGINE_KIND, _OCR_ENGINE), trocr_model
if _OCR_FAILED:
return None, trocr_model
try:
import pytesseract # type: ignore
_OCR_ENGINE = pytesseract
_OCR_ENGINE_KIND = "pytesseract"
return (_OCR_ENGINE_KIND, _OCR_ENGINE), "pytesseract"
except Exception: # noqa: BLE001
pass
try:
import torch # type: ignore
from transformers import TrOCRProcessor, VisionEncoderDecoderModel # type: ignore
processor = TrOCRProcessor.from_pretrained(trocr_model)
model = VisionEncoderDecoderModel.from_pretrained(trocr_model)
if torch.cuda.is_available():
model = model.to("cuda")
_OCR_ENGINE = {"processor": processor, "model": model, "torch": torch}
_OCR_ENGINE_KIND = "trocr"
return (_OCR_ENGINE_KIND, _OCR_ENGINE), trocr_model
except Exception as exc: # noqa: BLE001
logger.warning("Vision OCR engine unavailable, using fallback summary: %s", exc)
_OCR_FAILED = True
return None, trocr_model
def _extract_ocr_blocks(image: Image.Image) -> tuple[list[OCRTextBlock], str, bool]:
engine, model_name = _get_ocr_engine()
width, height = image.size
if engine is None:
return [], "fallback/ocr-unavailable", True
engine_kind, payload = engine
if engine_kind == "pytesseract":
try:
data = payload.image_to_data(image, output_type=payload.Output.DICT)
blocks: list[OCRTextBlock] = []
total = len(data.get("text", []))
for index in range(total):
text = str(data["text"][index]).strip()
if not text:
continue
confidence_raw = str(data.get("conf", ["0"])[index]).strip()
try:
confidence = max(0.0, min(1.0, float(confidence_raw) / 100.0))
except ValueError:
confidence = 0.0
blocks.append(
OCRTextBlock(
text=text,
confidence=confidence,
bbox=BoundingBox(
x=float(data["left"][index]),
y=float(data["top"][index]),
width=float(data["width"][index]),
height=float(data["height"][index]),
),
language="unknown",
)
)
return blocks, model_name, False
except Exception as exc: # noqa: BLE001
logger.warning("pytesseract OCR failed, falling back: %s", exc)
if engine_kind == "trocr":
try:
processor = payload["processor"]
model = payload["model"]
torch = payload["torch"]
pixel_values = processor(images=image, return_tensors="pt").pixel_values
if torch.cuda.is_available():
pixel_values = pixel_values.to("cuda")
generated_ids = model.generate(pixel_values)
text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
if text:
return (
[
OCRTextBlock(
text=text,
confidence=0.65,
bbox=BoundingBox(
x=0.0, y=0.0, width=float(width), height=float(height)
),
language="auto",
)
],
model_name,
False,
)
except Exception as exc: # noqa: BLE001
logger.warning("TrOCR inference failed, falling back: %s", exc)
return [], f"{model_name} (fallback)", True
def _keypoint(x: float, y: float, confidence: float, name: str) -> PoseKeypoint:
return PoseKeypoint(name=name, x=x, y=y, confidence=confidence)
def _estimate_pose_from_detections(detections: list[VisionDetection]) -> list[PoseDetection]:
people = [item for item in detections if item.label.lower() == "person"]
poses: list[PoseDetection] = []
for index, person in enumerate(people, start=1):
x = person.bbox.x
y = person.bbox.y
width = person.bbox.width
height = person.bbox.height
confidence = max(0.2, min(1.0, person.confidence * 0.92))
points = [
_keypoint(x + width * 0.50, y + height * 0.12, confidence, "nose"),
_keypoint(x + width * 0.32, y + height * 0.26, confidence, "left_shoulder"),
_keypoint(x + width * 0.68, y + height * 0.26, confidence, "right_shoulder"),
_keypoint(x + width * 0.24, y + height * 0.44, confidence * 0.95, "left_elbow"),
_keypoint(x + width * 0.76, y + height * 0.44, confidence * 0.95, "right_elbow"),
_keypoint(x + width * 0.18, y + height * 0.62, confidence * 0.88, "left_wrist"),
_keypoint(x + width * 0.82, y + height * 0.62, confidence * 0.88, "right_wrist"),
_keypoint(x + width * 0.38, y + height * 0.56, confidence, "left_hip"),
_keypoint(x + width * 0.62, y + height * 0.56, confidence, "right_hip"),
_keypoint(x + width * 0.36, y + height * 0.77, confidence * 0.9, "left_knee"),
_keypoint(x + width * 0.64, y + height * 0.77, confidence * 0.9, "right_knee"),
_keypoint(x + width * 0.34, y + height * 0.97, confidence * 0.82, "left_ankle"),
_keypoint(x + width * 0.66, y + height * 0.97, confidence * 0.82, "right_ankle"),
]
poses.append(
PoseDetection(
person_id=index,
confidence=confidence,
bbox=person.bbox,
keypoints=points,
connections=[
PoseConnection(start=start, end=end) for start, end in POSE_CONNECTIONS
],
)
)
return poses
def _predict_actions(detections: list[VisionDetection]) -> list[ActionPrediction]:
labels = {item.label.lower() for item in detections}
actions: list[ActionPrediction] = []
people = [item for item in detections if item.label.lower() == "person"]
for person in people:
ratio = person.bbox.height / max(person.bbox.width, 1.0)
if "cell phone" in labels:
action = "using_phone"
confidence = min(0.97, 0.55 + person.confidence * 0.35)
rationale = "Persona ir kopā ar phone tipa objektu vienā kadrā."
elif "sports ball" in labels:
action = "playing_ball"
confidence = min(0.94, 0.5 + person.confidence * 0.3)
rationale = "Kadrā redzams cilvēks un sporta bumba."
elif ratio > 2.3:
action = "standing"
confidence = min(0.9, 0.45 + person.confidence * 0.4)
rationale = "Cilvēka bbox ir izteikti vertikāls, kas atbilst stāvēšanai."
elif ratio > 1.6:
action = "walking"
confidence = min(0.84, 0.4 + person.confidence * 0.32)
rationale = "Cilvēka siluets izskatās kustībā vai solī."
else:
action = "sitting_or_crouching"
confidence = min(0.78, 0.38 + person.confidence * 0.28)
rationale = "Cilvēka bbox proporcijas norāda uz sēdošu vai pietupušos pozu."
actions.append(
ActionPrediction(
action=action,
confidence=confidence,
subject_label=person.label,
rationale=rationale,
)
)
return actions
def _frame_detections(
image: Image.Image,
*,
threshold: float,
max_detections: int,
) -> tuple[list[VisionDetection], str, bool]:
return _detect_image_payload(image, threshold=threshold, max_detections=max_detections)
def _build_frame_analysis(
frames: list[Image.Image],
*,
threshold: float,
max_detections: int,
) -> tuple[list[FrameAnalysis], str, bool]:
analyses: list[FrameAnalysis] = []
model_names: list[str] = []
fallback_used = False
for index, frame in enumerate(frames):
detections, model_name, frame_fallback = _frame_detections(
frame,
threshold=threshold,
max_detections=max_detections,
)
model_names.append(model_name)
fallback_used = fallback_used or frame_fallback
analyses.append(
FrameAnalysis(
frame_index=index,
summary=_build_detection_summary(detections, frame.size[0], frame.size[1])
if detections
else _fallback_summary(
frame, "Objektu noteikšanas modelis šim kadrām nav pieejams."
),
detections=detections,
dominant_labels=_dominant_labels(detections),
brightness=_frame_brightness(frame),
)
)
model_name = (
Counter(model_names).most_common(1)[0][0] if model_names else "fallback/basic-image-summary"
)
return analyses, model_name, fallback_used
def _build_tracks(
frames: list[FrameAnalysis],
frame_size: tuple[int, int],
) -> list[TrackedObject]:
width, height = frame_size
max_distance = ((width**2 + height**2) ** 0.5) * TRACKING_DISTANCE_RATIO
active_tracks: dict[int, tuple[str, tuple[float, float]]] = {}
observations: dict[int, list[tuple[str, TrackObservation, float]]] = {}
next_track_id = 1
for frame in frames:
frame_active: dict[int, tuple[str, tuple[float, float]]] = {}
for detection in frame.detections:
center = _detection_center(detection)
track_id: int | None = None
best_distance = float("inf")
for candidate_id, (candidate_label, candidate_center) in active_tracks.items():
if candidate_label != detection.label:
continue
distance = (
(candidate_center[0] - center[0]) ** 2 + (candidate_center[1] - center[1]) ** 2
) ** 0.5
if distance <= max_distance and distance < best_distance:
best_distance = distance
track_id = candidate_id
if track_id is None:
track_id = next_track_id
next_track_id += 1
frame_active[track_id] = (detection.label, center)
observations.setdefault(track_id, []).append(
(
detection.label,
TrackObservation(
frame_index=frame.frame_index,
confidence=detection.confidence,
bbox=detection.bbox,
),
detection.confidence,
)
)
active_tracks = frame_active
tracks: list[TrackedObject] = []
for track_id, items in observations.items():
label = items[0][0]
confs = [item[2] for item in items]
tracks.append(
TrackedObject(
track_id=track_id,
label=label,
average_confidence=sum(confs) / len(confs),
observations=[item[1] for item in items],
)
)
return tracks
def _build_scenes(frame_analyses: list[FrameAnalysis]) -> list[SceneSegment]:
if not frame_analyses:
return []
scenes: list[list[FrameAnalysis]] = [[frame_analyses[0]]]
for frame in frame_analyses[1:]:
previous = scenes[-1][-1]
previous_labels = set(previous.dominant_labels)
current_labels = set(frame.dominant_labels)
if previous_labels or current_labels:
overlap = len(previous_labels & current_labels) / max(
len(previous_labels | current_labels), 1
)
else:
overlap = 1.0
brightness_delta = abs(frame.brightness - previous.brightness)
if overlap < 0.4 or brightness_delta >= SCENE_BRIGHTNESS_DELTA:
scenes.append([frame])
else:
scenes[-1].append(frame)
response: list[SceneSegment] = []
for scene_index, scene_frames in enumerate(scenes):
labels = Counter(label for frame in scene_frames for label in frame.dominant_labels)
dominant_labels = [label for label, _ in labels.most_common(4)]
avg_brightness = sum(frame.brightness for frame in scene_frames) / len(scene_frames)
response.append(
SceneSegment(
scene_index=scene_index,
start_frame=scene_frames[0].frame_index,
end_frame=scene_frames[-1].frame_index,
summary=(
f"Scene {scene_index + 1}: kadri {scene_frames[0].frame_index}-{scene_frames[-1].frame_index} "
f"ar dominējošiem elementiem {', '.join(dominant_labels) if dominant_labels else 'nav noteikts'}."
),
dominant_labels=dominant_labels,
average_brightness=avg_brightness,
)
)
return response
def _utc_now_iso() -> str:
return datetime.now(UTC).isoformat().replace("+00:00", "Z")
def _default_live_pipelines() -> list[str]:
return [
"object_detection",
"tracking",
"action_recognition",
"scene_timeline",
"ocr",
"pose_estimation",
"segmentation",
"anomaly_detection",
]
def _public_auth(auth: dict[str, str]) -> dict[str, Any]:
username = (auth.get("username") or "").strip()
return {
"username_hint": f"{username[:2]}***" if username else None,
"token_present": bool(auth.get("token")),
"password_present": bool(auth.get("password")),
}
def _create_live_event(
camera_id: str,
event_type: str,
summary: str,
*,
severity: str = "info",
payload: dict[str, Any] | None = None,
) -> dict[str, Any]:
return {
"event_id": f"evt_{uuid4().hex}",
"camera_id": camera_id,
"type": event_type,
"severity": severity,
"timestamp": _utc_now_iso(),
"summary": summary,
"payload": payload or {},
}
def _camera_health(session: dict[str, Any]) -> CameraHealth:
return CameraHealth(**session["health"])
def _camera_resolution(session: dict[str, Any]) -> CameraResolution:
return CameraResolution(**session["resolution"])
def _camera_events(session: dict[str, Any]) -> list[LiveEvent]:
return [LiveEvent(**item) for item in session.get("recent_events", [])]
def _session_to_response(session: dict[str, Any]) -> LiveCameraSession:
return LiveCameraSession(
camera_id=session["camera_id"],
source_type=session["source_type"],
transport=session["transport"],
url=session.get("url"),
device_id=session.get("device_id"),
auth=_public_auth(session.get("auth", {})),
resolution=_camera_resolution(session),
fps=float(session["fps"]),
status=session["status"],
health=_camera_health(session),
enabled_pipelines=list(session.get("enabled_pipelines", [])),
detection_stride=int(session.get("detection_stride", 3)),
ocr_interval=int(session.get("ocr_interval", 12)),
fps_budget=float(session.get("fps_budget", 6.0)),
roi_zones=list(session.get("roi_zones", [])),
alert_rules=list(session.get("alert_rules", [])),
latest_snapshot=session.get("latest_snapshot"),
latest_result=dict(session.get("latest_result", {})),
recent_events=_camera_events(session),
timeline=list(session.get("timeline", [])),
tracks=list(session.get("tracks", [])),
)
def _append_session_event(session: dict[str, Any], event: dict[str, Any]) -> LiveEvent:
session.setdefault("recent_events", []).append(event)
session["recent_events"] = session["recent_events"][-40:]
health = session["health"]
health["events_emitted"] = int(health.get("events_emitted", 0)) + 1
health["last_event_at"] = event["timestamp"]
return LiveEvent(**event)
def _scene_changed(
previous: FrameAnalysis | None,
current: FrameAnalysis,
threshold: float,
) -> bool:
if previous is None:
return True
previous_labels = set(previous.dominant_labels)
current_labels = set(current.dominant_labels)
overlap = (
len(previous_labels & current_labels) / max(len(previous_labels | current_labels), 1)
if previous_labels or current_labels
else 1.0
)
brightness_delta = abs(current.brightness - previous.brightness)
return overlap < 0.4 or brightness_delta >= threshold
def _live_alerts(frame: FrameAnalysis, scene_changed_flag: bool) -> list[dict[str, Any]]:
alerts: list[dict[str, Any]] = []
detection_count = len(frame.detections)
person_count = sum(1 for item in frame.detections if item.label.lower() == "person")
if frame.brightness < 45:
alerts.append(
{
"rule": "low_light",
"severity": "warning",
"summary": "Kamera redz ļoti tumšu ainu; kvalitāte var kristies.",
}
)
if person_count >= 4 or detection_count >= 8:
alerts.append(
{
"rule": "crowded_scene",
"severity": "warning",
"summary": "Ainā ir liela objektu koncentrācija; var būt vajadzīga prioritizācija.",
}
)
if scene_changed_flag:
alerts.append(
{
"rule": "scene_change",
"severity": "info",
"summary": "Atklāta būtiska ainas maiņa; timeline un OCR tiek atsvaidzināti.",
}
)
return alerts
def _bbox_intersects_roi(bbox: BoundingBox, roi: dict[str, Any]) -> bool:
roi_x = float(roi.get("x", 0.0))
roi_y = float(roi.get("y", 0.0))
roi_width = float(roi.get("width", 0.0))
roi_height = float(roi.get("height", 0.0))
if roi_width <= 0 or roi_height <= 0:
return True
return not (
bbox.x + bbox.width < roi_x
or roi_x + roi_width < bbox.x
or bbox.y + bbox.height < roi_y
or roi_y + roi_height < bbox.y
)
def _apply_roi_zones(
detections: list[VisionDetection],
roi_zones: list[dict[str, Any]],
) -> list[VisionDetection]:
if not roi_zones:
return detections
filtered: list[VisionDetection] = []
for detection in detections:
if any(_bbox_intersects_roi(detection.bbox, roi) for roi in roi_zones):
filtered.append(detection)
return filtered
def _evaluate_alert_rules(
detections: list[VisionDetection],
alert_rules: list[str],
camera_id: str,
) -> list[dict[str, Any]]:
if not alert_rules:
return []
alerts: list[dict[str, Any]] = []
for raw_rule in alert_rules:
parts = [part.strip() for part in raw_rule.split(":") if part.strip()]
if len(parts) < 2:
continue
rule_name = parts[0]
target_label = parts[1].lower()
min_count = int(parts[2]) if len(parts) > 2 and parts[2].isdigit() else 1
confidence_floor = float(parts[3]) if len(parts) > 3 else 0.0
matched = [
detection
for detection in detections
if detection.label.lower() == target_label and detection.confidence >= confidence_floor
]
if len(matched) >= min_count:
alerts.append(
{
"rule": rule_name,
"severity": "warning",
"summary": (
f"Alert rule `{rule_name}` aktivizējās kamerai {camera_id}: "
f"{len(matched)}× {target_label} virs sliekšņa."
),
"target_label": target_label,
"count": len(matched),
"confidence_floor": confidence_floor,
}
)
return alerts
def _reid_signature(
camera_id: str,
track: TrackedObject,
frame_analysis: FrameAnalysis,
) -> dict[str, Any] | None:
if not track.observations:
return None
latest = track.observations[-1]
bbox = latest.bbox
width_norm = bbox.width / max(
frame_analysis.detections[0].bbox.width if frame_analysis.detections else 1.0, 1.0
)
height_norm = bbox.height / max(frame_analysis.brightness, 1.0)
center_x = bbox.x + bbox.width / 2.0
center_y = bbox.y + bbox.height / 2.0
return {
"camera_id": camera_id,
"track_id": track.track_id,
"label": track.label,
"vector": [
round(track.average_confidence, 4),
round(width_norm, 4),
round(height_norm, 4),
round(center_x / max(bbox.x + bbox.width, 1.0), 4),
round(center_y / max(bbox.y + bbox.height, 1.0), 4),
round(frame_analysis.brightness / 255.0, 4),
],
}
def _vector_similarity(left: list[float], right: list[float]) -> float:
left_norm = sum(value * value for value in left) ** 0.5
right_norm = sum(value * value for value in right) ** 0.5
if left_norm == 0 or right_norm == 0:
return 0.0
dot = sum(a * b for a, b in zip(left, right, strict=False))
return dot / (left_norm * right_norm)
def _update_reid_index(
session: dict[str, Any],
tracks: list[TrackedObject],
frame_analysis: FrameAnalysis,
) -> list[dict[str, Any]]:
camera_id = session["camera_id"]
matches: list[dict[str, Any]] = []
camera_signatures = [
signature
for track in tracks
if (signature := _reid_signature(camera_id, track, frame_analysis)) is not None
]
for signature in camera_signatures:
for other_camera_id, items in _LIVE_REID_INDEX.items():
if other_camera_id == camera_id:
continue
for candidate in items:
if candidate["label"].lower() != signature["label"].lower():
continue
similarity = _vector_similarity(signature["vector"], candidate["vector"])
if similarity >= 0.94:
matches.append(
{
"target_camera_id": other_camera_id,
"source_track_id": signature["track_id"],
"target_track_id": candidate["track_id"],
"source_label": signature["label"],
"target_label": candidate["label"],
"similarity_score": round(similarity, 4),
"summary": (
f"Iespējams cross-camera match starp {camera_id} track {signature['track_id']} "
f"un {other_camera_id} track {candidate['track_id']}."
),
}
)
_LIVE_REID_INDEX[camera_id] = camera_signatures[-12:]
return matches
def _build_live_frame_payload(
session: dict[str, Any],
frame: Image.Image,
frame_index: int,
detections: list[VisionDetection],
model_name: str,
fallback_used: bool,
) -> tuple[dict[str, Any], list[LiveEvent]]:
detections = _apply_roi_zones(detections, list(session.get("roi_zones", [])))
analyses: list[FrameAnalysis] = session.setdefault("frame_analyses", [])
frame_analysis = FrameAnalysis(
frame_index=frame_index,
summary=_build_detection_summary(detections, frame.size[0], frame.size[1])
if detections
else _fallback_summary(frame, "Live stream šajā kadrā nedeva stabilus objektus."),
detections=detections,
dominant_labels=_dominant_labels(detections),
brightness=_frame_brightness(frame),
)
previous = analyses[-1] if analyses else None
analyses.append(frame_analysis)
session["frame_analyses"] = analyses[-24:]
scene_changed_flag = _scene_changed(
previous,
frame_analysis,
float(session.get("scene_change_threshold", SCENE_BRIGHTNESS_DELTA)),
)
tracks = (
_build_tracks(session["frame_analyses"], frame.size)
if "tracking" in session["enabled_pipelines"]
else session.get("tracks", [])
)
timeline = (
_build_scenes(session["frame_analyses"])
if "scene_timeline" in session["enabled_pipelines"]
else session.get("timeline", [])
)
session["tracks"] = tracks
session["timeline"] = timeline
should_run_ocr = "ocr" in session["enabled_pipelines"] and (
scene_changed_flag or frame_index % max(int(session.get("ocr_interval", 12)), 1) == 0
)
ocr_results: list[OCRTextBlock] = []
ocr_model = "disabled"
ocr_fallback = False
if should_run_ocr:
ocr_results, ocr_model, ocr_fallback = _extract_ocr_blocks(frame)
poses = (
_estimate_pose_from_detections(detections)
if "pose_estimation" in session["enabled_pipelines"]
else []
)
masks = (
_segment_from_detections(frame, detections)
if "segmentation" in session["enabled_pipelines"]
else []
)
actions = (
_predict_actions(detections) if "action_recognition" in session["enabled_pipelines"] else []
)
alerts = (
_live_alerts(frame_analysis, scene_changed_flag)
if "anomaly_detection" in session["enabled_pipelines"]
else []
)
alerts.extend(
_evaluate_alert_rules(
detections, list(session.get("alert_rules", [])), session["camera_id"]
)
)
reid_matches = _update_reid_index(session, tracks, frame_analysis) if tracks else []
session["latest_snapshot"] = _image_to_data_url(frame)
session["latest_result"] = {
"summary": frame_analysis.summary,
"frame_index": frame_index,
"model": model_name,
"fallback_used": fallback_used,
"width": frame.size[0],
"height": frame.size[1],
"detections": [item.model_dump() for item in detections],
"results": [item.model_dump() for item in ocr_results],
"poses": [item.model_dump() for item in poses],
"masks": [item.model_dump() for item in masks],
"actions": [item.model_dump() for item in actions],
"tracks": [item.model_dump() for item in tracks],
"scenes": [item.model_dump() for item in timeline],
"alerts": alerts,
"reid_matches": reid_matches,
"ocr_model": ocr_model,
"ocr_fallback_used": ocr_fallback,
}
events: list[LiveEvent] = [
_append_session_event(
session,
_create_live_event(
session["camera_id"],
"analysis_result",
f"Live frame {frame_index} analizēts ar {len(detections)} detekcijām.",
payload={
"frame_index": frame_index,
"detection_count": len(detections),
"scene_changed": scene_changed_flag,
},
),
)
]
if tracks:
events.append(
_append_session_event(
session,
_create_live_event(
session["camera_id"],
"track_update",
f"Track layer atjaunināts ar {len(tracks)} aktīvām trajektorijām.",
payload={"track_count": len(tracks)},
),
)
)
if timeline:
latest_scene = timeline[-1]
events.append(
_append_session_event(
session,
_create_live_event(
session["camera_id"],
"timeline_update",
latest_scene.summary,
payload=latest_scene.model_dump(),
),
)
)
for alert in alerts:
events.append(
_append_session_event(
session,
_create_live_event(
session["camera_id"],
"alert",
alert["summary"],
severity=alert["severity"],
payload=alert,
),
)
)
for match in reid_matches:
events.append(
_append_session_event(
session,
_create_live_event(
session["camera_id"],
"reid_match",
match["summary"],
severity="info",
payload=match,
),
)
)
return session["latest_result"], events
async def _save_generation(event: str, metadata: dict[str, Any]) -> None:
from maris_core.utils.hf_integration import HFIntegration
hf = HFIntegration()
await hf.save_generation("vision", event, metadata)
@router.post("/analyze", response_model=VisionAnalyzeResponse)
async def analyze_image(req: ImageSourceRequest) -> VisionAnalyzeResponse:
"""Analizē attēlu ar objektu noteikšanu."""
image = await _load_image(req)
detections, model_name, fallback_used = _detect_image_payload(
image,
threshold=req.confidence_threshold,
max_detections=req.max_detections,
)
width, height = image.size
summary = (
_fallback_summary(image, "Objekta noteikšanas modelis šobrīd nav pieejams.")
if fallback_used and not detections
else _build_detection_summary(detections, width, height)
)
await _save_generation(
"vision/analyze",
{
"model": model_name,
"width": width,
"height": height,
"detections": len(detections),
"fallback_used": fallback_used,
"session_id": req.session_id,
"camera_id": req.camera_id,
},
)
if req.session_id:
memory_store.remember_message(
req.session_id,
"assistant",
summary,
source="vision_camera" if req.camera_id else "vision_analyze",
)
return VisionAnalyzeResponse(
summary=summary,
detections=detections,
width=width,
height=height,
model=model_name,
fallback_used=fallback_used,
)
@router.post("/ocr", response_model=VisionOCRResponse)
async def ocr_image(req: ImageSourceRequest) -> VisionOCRResponse:
"""Izlasa tekstu no attēla."""
image = await _load_image(req)
width, height = image.size
results, model_name, fallback_used = _extract_ocr_blocks(image)
summary = (
f"OCR pabeigts: atrasti {len(results)} teksta bloki attēlā ({width}x{height})."
if results
else _fallback_summary(image, "OCR modelis šobrīd nav pieejams vai teksts nav atrasts.")
)
await _save_generation(
"vision/ocr",
{
"model": model_name,
"width": width,
"height": height,
"blocks": len(results),
"fallback_used": fallback_used,
},
)
return VisionOCRResponse(
summary=summary,
results=results,
width=width,
height=height,
model=model_name,
fallback_used=fallback_used,
)
@router.post("/pose-estimate", response_model=VisionPoseResponse)
async def estimate_pose(req: ImageSourceRequest) -> VisionPoseResponse:
"""Aprēķina aptuvenus ķermeņa punktus no noteiktām personām."""
image = await _load_image(req)
detections, _, detection_fallback = _detect_image_payload(
image,
threshold=req.confidence_threshold,
max_detections=req.max_detections,
)
poses = _estimate_pose_from_detections(detections)
width, height = image.size
fallback_used = detection_fallback or not poses
model_name = "bbox-derived-pose-v1"
summary = (
f"Pose estimation pabeigta: atrasti {len(poses)} cilvēku skeleti attēlā ({width}x{height})."
if poses
else _fallback_summary(
image, "Pose estimation nevarēja atrast personu bbox, no kā atvasināt skeletu."
)
)
await _save_generation(
"vision/pose-estimate",
{
"model": model_name,
"width": width,
"height": height,
"poses": len(poses),
"fallback_used": fallback_used,
},
)
return VisionPoseResponse(
summary=summary,
poses=poses,
width=width,
height=height,
model=model_name,
fallback_used=fallback_used,
)
@router.post("/segment", response_model=VisionSegmentationResponse)
async def segment_image(req: ImageSourceRequest) -> VisionSegmentationResponse:
"""Atgriež objektu segmentācijas maskas."""
image = await _load_image(req)
detections, _, detection_fallback = _detect_image_payload(
image,
threshold=req.confidence_threshold,
max_detections=req.max_detections,
)
masks, model_name, segmentation_fallback = _extract_segmentation_masks(image, detections)
width, height = image.size
fallback_used = segmentation_fallback or detection_fallback
summary = (
f"Segmentation pabeigta: ģenerētas {len(masks)} maskas attēlā ({width}x{height})."
if masks
else _fallback_summary(image, "Segmentācijas modelis nevarēja izveidot maskas.")
)
await _save_generation(
"vision/segment",
{
"model": model_name,
"width": width,
"height": height,
"masks": len(masks),
"fallback_used": fallback_used,
},
)
return VisionSegmentationResponse(
summary=summary,
masks=masks,
width=width,
height=height,
model=model_name,
fallback_used=fallback_used,
)
@router.post("/action-recognize", response_model=VisionActionResponse)
async def recognize_action(req: ImageSourceRequest) -> VisionActionResponse:
"""Atgriež darbību prognozes no viena kadra."""
image = await _load_image(req)
detections, _, detection_fallback = _detect_image_payload(
image,
threshold=req.confidence_threshold,
max_detections=req.max_detections,
)
actions = _predict_actions(detections)
width, height = image.size
fallback_used = detection_fallback or not actions
model_name = "vision-action-heuristics-v1"
summary = (
f"Action recognition pabeigta: atrastas {len(actions)} darbību hipotēzes attēlā ({width}x{height})."
if actions
else _fallback_summary(
image, "Darbību noteikšanai vajadzīgs vismaz viens person objekts kadrā."
)
)
await _save_generation(
"vision/action-recognize",
{
"model": model_name,
"width": width,
"height": height,
"actions": len(actions),
"fallback_used": fallback_used,
},
)
return VisionActionResponse(
summary=summary,
actions=actions,
width=width,
height=height,
model=model_name,
fallback_used=fallback_used,
)
@router.post("/tracking", response_model=VisionTrackingResponse)
async def track_objects(req: FrameSequenceRequest) -> VisionTrackingResponse:
"""Seko objektiem kadru secībā."""
frames = await _load_frames(req)
analyses, model_name, fallback_used = _build_frame_analysis(
frames,
threshold=req.confidence_threshold,
max_detections=req.max_detections,
)
tracks = _build_tracks(analyses, frames[0].size)
summary = (
f"Tracking pabeigts: {len(tracks)} trajektorijas pāri {len(frames)} kadriem."
if tracks
else "Tracking pabeigts bez stabilām trajektorijām — pārbaudi ievades kadrus vai modeļa pieejamību."
)
await _save_generation(
"vision/tracking",
{
"model": model_name,
"frame_count": len(frames),
"tracks": len(tracks),
"fallback_used": fallback_used,
},
)
return VisionTrackingResponse(
summary=summary,
tracks=tracks,
frame_count=len(frames),
model=model_name,
fallback_used=fallback_used,
)
@router.post("/frame-analysis", response_model=VisionFrameAnalysisResponse)
async def analyze_frames(req: FrameSequenceRequest) -> VisionFrameAnalysisResponse:
"""Analizē katru video kadru atsevišķi."""
frames = await _load_frames(req)
analyses, model_name, fallback_used = _build_frame_analysis(
frames,
threshold=req.confidence_threshold,
max_detections=req.max_detections,
)
summary = f"Frame-by-frame analīze pabeigta {len(analyses)} kadriem."
await _save_generation(
"vision/frame-analysis",
{
"model": model_name,
"frame_count": len(frames),
"fallback_used": fallback_used,
},
)
return VisionFrameAnalysisResponse(
summary=summary,
frames=analyses,
frame_count=len(analyses),
model=model_name,
fallback_used=fallback_used,
)
@router.post("/scene-timeline", response_model=VisionSceneTimelineResponse)
async def scene_timeline(req: FrameSequenceRequest) -> VisionSceneTimelineResponse:
"""Saspiež kadru analīzi ainu laika skalā."""
frames = await _load_frames(req)
analyses, model_name, fallback_used = _build_frame_analysis(
frames,
threshold=req.confidence_threshold,
max_detections=req.max_detections,
)
scenes = _build_scenes(analyses)
summary = (
f"Scene timeline pabeigta: {len(scenes)} ainas pāri {len(frames)} kadriem."
if scenes
else "Scene timeline nevarēja atrast ainu robežas dotajos kadros."
)
await _save_generation(
"vision/scene-timeline",
{
"model": model_name,
"frame_count": len(frames),
"scenes": len(scenes),
"fallback_used": fallback_used,
},
)
return VisionSceneTimelineResponse(
summary=summary,
scenes=scenes,
frame_count=len(analyses),
model=model_name,
fallback_used=fallback_used,
)
@router.get("/live/cameras", response_model=LiveCameraCatalogResponse)
async def list_live_cameras() -> LiveCameraCatalogResponse:
cameras = [_session_to_response(session) for session in _LIVE_CAMERAS.values()]
return LiveCameraCatalogResponse(
summary=f"Live camera registry satur {len(cameras)} kameras.",
cameras=cameras,
)
@router.post("/live/connect", response_model=LiveCameraResponse)
async def connect_live_camera(req: LiveCameraConnectRequest) -> LiveCameraResponse:
camera_id = (req.camera_id or f"cam_{uuid4().hex[:10]}").strip()
session = {
"camera_id": camera_id,
"source_type": req.source_type,
"transport": req.transport,
"url": req.url,
"device_id": req.device_id,
"auth": dict(req.auth),
"resolution": req.resolution.model_dump(),
"fps": req.fps,
"status": "connected",
"health": CameraHealth().model_dump(),
"enabled_pipelines": req.enabled_pipelines or _default_live_pipelines(),
"detection_stride": req.detection_stride,
"ocr_interval": req.ocr_interval,
"fps_budget": req.fps_budget,
"scene_change_threshold": SCENE_BRIGHTNESS_DELTA,
"roi_zones": req.roi_zones,
"alert_rules": req.alert_rules,
"latest_snapshot": None,
"latest_result": {},
"recent_events": [],
"frame_analyses": [],
"timeline": [],
"tracks": [],
"frame_counter": 0,
}
session["health"]["connected"] = True
session["health"]["analysis_active"] = False
_append_session_event(
session,
_create_live_event(
camera_id,
"camera_connected",
f"Kamera {camera_id} piereģistrēta ar transportu {req.transport}.",
payload={
"source_type": req.source_type,
"transport": req.transport,
"device_id": req.device_id,
"url": req.url,
},
),
)
_LIVE_CAMERAS[camera_id] = session
await _save_generation(
"vision/live-connect",
{
"camera_id": camera_id,
"source_type": req.source_type,
"transport": req.transport,
},
)
return LiveCameraResponse(
summary=f"Live kamera {camera_id} ir savienota.",
camera=_session_to_response(session),
)
def _require_live_camera(camera_id: str) -> dict[str, Any]:
session = _LIVE_CAMERAS.get(camera_id)
if session is None:
raise HTTPException(status_code=404, detail="Live kamera nav atrasta.")
return session
@router.post("/live/start", response_model=LiveCameraResponse)
async def start_live_camera(req: LiveSessionCommandRequest) -> LiveCameraResponse:
session = _require_live_camera(req.camera_id)
if req.enabled_pipelines is not None:
session["enabled_pipelines"] = req.enabled_pipelines or _default_live_pipelines()
if req.detection_stride is not None:
session["detection_stride"] = req.detection_stride
if req.ocr_interval is not None:
session["ocr_interval"] = req.ocr_interval
if req.fps_budget is not None:
session["fps_budget"] = req.fps_budget
session["status"] = "streaming"
session["health"]["analysis_active"] = True
_append_session_event(
session,
_create_live_event(
req.camera_id,
"analysis_started",
"Live analīzes sesija ir startēta.",
payload={"enabled_pipelines": session["enabled_pipelines"]},
),
)
await _save_generation(
"vision/live-start",
{"camera_id": req.camera_id, "pipelines": session["enabled_pipelines"]},
)
return LiveCameraResponse(
summary=f"Live analīze kamerai {req.camera_id} ir palaista.",
camera=_session_to_response(session),
)
@router.post("/live/config", response_model=LiveCameraResponse)
async def configure_live_camera(req: LiveCameraConfigRequest) -> LiveCameraResponse:
session = _require_live_camera(req.camera_id)
session["roi_zones"] = req.roi_zones
session["alert_rules"] = req.alert_rules
if req.enabled_pipelines is not None:
session["enabled_pipelines"] = req.enabled_pipelines or _default_live_pipelines()
if req.fps_budget is not None:
session["fps_budget"] = req.fps_budget
_append_session_event(
session,
_create_live_event(
req.camera_id,
"config_updated",
"Kameras ROI, rules vai pipeline konfigurācija tika atjaunināta.",
payload={
"roi_zone_count": len(req.roi_zones),
"alert_rule_count": len(req.alert_rules),
"enabled_pipelines": session["enabled_pipelines"],
"fps_budget": session["fps_budget"],
},
),
)
await _save_generation(
"vision/live-config",
{
"camera_id": req.camera_id,
"roi_zone_count": len(req.roi_zones),
"alert_rule_count": len(req.alert_rules),
},
)
return LiveCameraResponse(
summary=f"Kameras {req.camera_id} konfigurācija ir atjaunināta.",
camera=_session_to_response(session),
)
@router.post("/live/pause", response_model=LiveCameraResponse)
async def pause_live_camera(req: LiveSessionCommandRequest) -> LiveCameraResponse:
session = _require_live_camera(req.camera_id)
session["status"] = "paused"
session["health"]["analysis_active"] = False
_append_session_event(
session,
_create_live_event(req.camera_id, "analysis_paused", "Live analīze ir pauzēta."),
)
return LiveCameraResponse(
summary=f"Live analīze kamerai {req.camera_id} ir pauzēta.",
camera=_session_to_response(session),
)
@router.post("/live/stop", response_model=LiveCameraResponse)
async def stop_live_camera(req: LiveSessionCommandRequest) -> LiveCameraResponse:
session = _require_live_camera(req.camera_id)
session["status"] = "stopped"
session["health"]["analysis_active"] = False
_append_session_event(
session,
_create_live_event(req.camera_id, "analysis_stopped", "Live analīze ir apturēta."),
)
await _save_generation("vision/live-stop", {"camera_id": req.camera_id})
return LiveCameraResponse(
summary=f"Live analīze kamerai {req.camera_id} ir apturēta.",
camera=_session_to_response(session),
)
@router.get("/live/{camera_id}/state", response_model=LiveCameraResponse)
async def live_camera_state(camera_id: str) -> LiveCameraResponse:
session = _require_live_camera(camera_id)
return LiveCameraResponse(
summary=f"Stāvoklis kamerai {camera_id} ir atjaunots.",
camera=_session_to_response(session),
)
@router.get("/live/{camera_id}/snapshot", response_model=LiveSnapshotResponse)
async def live_camera_snapshot(camera_id: str) -> LiveSnapshotResponse:
session = _require_live_camera(camera_id)
return LiveSnapshotResponse(
summary=f"Atgriezts pēdējais snapshot kamerai {camera_id}.",
camera_id=camera_id,
snapshot_data_url=session.get("latest_snapshot"),
)
@router.get("/live/{camera_id}/events", response_model=LiveEventsResponse)
async def live_camera_events(camera_id: str) -> LiveEventsResponse:
session = _require_live_camera(camera_id)
return LiveEventsResponse(
summary=f"Atgriezti {len(session.get('recent_events', []))} live notikumi kamerai {camera_id}.",
camera_id=camera_id,
events=_camera_events(session),
)
@router.post("/live/frame", response_model=LiveFrameResponse)
async def process_live_frame(req: LiveFrameRequest) -> LiveFrameResponse:
session = _require_live_camera(req.camera_id)
if not session["health"]["analysis_active"]:
raise HTTPException(status_code=409, detail="Live sesija nav palaista.")
frame_index = req.frame_index if req.frame_index is not None else int(session["frame_counter"])
session["frame_counter"] = frame_index + 1
if req.timestamp_ms is not None:
last_timestamp_ms = session.get("last_timestamp_ms")
min_interval_ms = 1000.0 / max(float(session.get("fps_budget", 6.0)), 0.5)
if (
isinstance(last_timestamp_ms, int)
and req.timestamp_ms >= last_timestamp_ms
and req.timestamp_ms - last_timestamp_ms < min_interval_ms
):
session["health"]["dropped_frames"] = (
int(session["health"].get("dropped_frames", 0)) + 1
)
event = _append_session_event(
session,
_create_live_event(
req.camera_id,
"frame_dropped",
"Kadrs tika atmests, lai ievērotu FPS budget un backpressure politiku.",
severity="warning",
payload={
"frame_index": frame_index,
"fps_budget": session.get("fps_budget", 6.0),
},
),
)
return LiveFrameResponse(
summary=f"Live frame {frame_index} tika atmests backpressure dēļ.",
camera=_session_to_response(session),
events=[event],
)
session["last_timestamp_ms"] = int(req.timestamp_ms)
image = await _load_image_from_source(None, req.image_base64)
session["health"]["last_frame_at"] = _utc_now_iso()
run_detection = (
frame_index % max(int(session.get("detection_stride", 3)), 1) == 0
or not session.get("latest_detections")
or "tracking" in session["enabled_pipelines"]
)
if run_detection:
detections, model_name, fallback_used = _frame_detections(
image,
threshold=0.25,
max_detections=10,
)
session["latest_detections"] = [item.model_dump() for item in detections]
session["latest_model_name"] = model_name
session["latest_fallback_used"] = fallback_used
else:
detections = [
VisionDetection.model_validate(item) for item in session.get("latest_detections", [])
]
model_name = str(session.get("latest_model_name", "scheduled-cache"))
fallback_used = bool(session.get("latest_fallback_used", False))
_, events = _build_live_frame_payload(
session,
image,
frame_index,
detections,
model_name,
fallback_used,
)
return LiveFrameResponse(
summary=f"Live frame {frame_index} apstrādāts kamerai {req.camera_id}.",
camera=_session_to_response(session),
events=events,
)
|