Spaces:
Sleeping
Sleeping
Update src/components/ai_core_identityscan.py
Browse files- src/components/ai_core_identityscan.py +110 -110
src/components/ai_core_identityscan.py
CHANGED
|
@@ -1,111 +1,111 @@
|
|
| 1 |
-
"""Lightweight AI core for identity scanning and analysis.
|
| 2 |
-
|
| 3 |
-
This module provides a compact, dependency-safe `AICore` class used by
|
| 4 |
-
other components. The original file contained merge markers and
|
| 5 |
-
incomplete code; this replacement focuses on providing functioning
|
| 6 |
-
interfaces (async `generate_response`, `shutdown`) and uses existing
|
| 7 |
-
local components where available.
|
| 8 |
-
"""
|
| 9 |
-
from typing import Any, Dict, List, Optional
|
| 10 |
-
import asyncio
|
| 11 |
-
import json
|
| 12 |
-
import logging
|
| 13 |
-
import os
|
| 14 |
-
|
| 15 |
-
from
|
| 16 |
-
from
|
| 17 |
-
from
|
| 18 |
-
|
| 19 |
-
try:
|
| 20 |
-
from utils.logger import logger
|
| 21 |
-
except Exception:
|
| 22 |
-
logger = logging.getLogger(__name__)
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
class AICore:
|
| 26 |
-
"""Minimal, safe AICore replacement for identity scanning workflows."""
|
| 27 |
-
|
| 28 |
-
def __init__(self, config_path: str = "config.json"):
|
| 29 |
-
self.config = self._load_config(config_path)
|
| 30 |
-
self.multimodal = MultimodalAnalyzer()
|
| 31 |
-
self.learner = DynamicLearner()
|
| 32 |
-
self.health = HealthMonitor()
|
| 33 |
-
self._initialized = False
|
| 34 |
-
|
| 35 |
-
def _load_config(self, path: str) -> Dict[str, Any]:
|
| 36 |
-
if not path or not os.path.exists(path):
|
| 37 |
-
return {}
|
| 38 |
-
try:
|
| 39 |
-
with open(path, "r", encoding="utf-8") as f:
|
| 40 |
-
return json.load(f)
|
| 41 |
-
except Exception:
|
| 42 |
-
return {}
|
| 43 |
-
|
| 44 |
-
async def initialize(self) -> bool:
|
| 45 |
-
"""Initialize async subsystems (e.g., health monitor)."""
|
| 46 |
-
try:
|
| 47 |
-
ok = await self.health.initialize()
|
| 48 |
-
self._initialized = ok
|
| 49 |
-
return ok
|
| 50 |
-
except Exception as e:
|
| 51 |
-
logger.exception("Failed to initialize AICore: %s", e)
|
| 52 |
-
return False
|
| 53 |
-
|
| 54 |
-
async def generate_response(self, user_id: int, query: str, multimodal_input: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
| 55 |
-
"""Produce a safe, explainable response using local subsystems.
|
| 56 |
-
|
| 57 |
-
- Runs a lightweight analysis of any multimodal input
|
| 58 |
-
- Updates the dynamic learner with a summary of the interaction
|
| 59 |
-
- Returns a dict containing analysis and a text response
|
| 60 |
-
"""
|
| 61 |
-
try:
|
| 62 |
-
analyses = {}
|
| 63 |
-
if multimodal_input:
|
| 64 |
-
analyses = self.multimodal.analyze_content(multimodal_input)
|
| 65 |
-
|
| 66 |
-
# Simple content-based reply
|
| 67 |
-
text_summary = ""
|
| 68 |
-
if "text" in analyses:
|
| 69 |
-
t = analyses["text"]
|
| 70 |
-
text_summary = f"Received text: length={t.get('length')} words={t.get('word_count')}"
|
| 71 |
-
else:
|
| 72 |
-
text_summary = f"Query received: {query[:200]}"
|
| 73 |
-
|
| 74 |
-
# Update learner with a compact interaction record
|
| 75 |
-
adaptation_score = self.learner.update({
|
| 76 |
-
"user_id": user_id,
|
| 77 |
-
"query_summary": text_summary,
|
| 78 |
-
"multimodal_modalities": list(analyses.keys())
|
| 79 |
-
})
|
| 80 |
-
|
| 81 |
-
# Health snapshot
|
| 82 |
-
health_status = self.health.get_health_summary()
|
| 83 |
-
|
| 84 |
-
response_text = f"Acknowledged. Adaptation score={adaptation_score:.2f}."
|
| 85 |
-
|
| 86 |
-
return {
|
| 87 |
-
"response": response_text,
|
| 88 |
-
"analysis": analyses,
|
| 89 |
-
"adaptation_score": adaptation_score,
|
| 90 |
-
"health": health_status,
|
| 91 |
-
}
|
| 92 |
-
except Exception as e:
|
| 93 |
-
logger.exception("generate_response failed: %s", e)
|
| 94 |
-
return {"error": "internal_error", "detail": str(e)}
|
| 95 |
-
|
| 96 |
-
async def shutdown(self):
|
| 97 |
-
"""Clean up resources if necessary."""
|
| 98 |
-
# HealthMonitor has no async shutdown but we keep the method for parity.
|
| 99 |
-
await asyncio.sleep(0)
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
# Module quick test when run directly
|
| 103 |
-
if __name__ == "__main__":
|
| 104 |
-
async def _test():
|
| 105 |
-
core = AICore()
|
| 106 |
-
await core.initialize()
|
| 107 |
-
out = await core.generate_response(1, "Hello world", {"text": "Hello world from test"})
|
| 108 |
-
print(out)
|
| 109 |
-
await core.shutdown()
|
| 110 |
-
|
| 111 |
asyncio.run(_test())
|
|
|
|
| 1 |
+
"""Lightweight AI core for identity scanning and analysis.
|
| 2 |
+
|
| 3 |
+
This module provides a compact, dependency-safe `AICore` class used by
|
| 4 |
+
other components. The original file contained merge markers and
|
| 5 |
+
incomplete code; this replacement focuses on providing functioning
|
| 6 |
+
interfaces (async `generate_response`, `shutdown`) and uses existing
|
| 7 |
+
local components where available.
|
| 8 |
+
"""
|
| 9 |
+
from typing import Any, Dict, List, Optional
|
| 10 |
+
import asyncio
|
| 11 |
+
import json
|
| 12 |
+
import logging
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
from .multimodal_analyzer import MultimodalAnalyzer
|
| 16 |
+
from .dynamic_learning import DynamicLearner
|
| 17 |
+
from .health_monitor import HealthMonitor
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
from utils.logger import logger
|
| 21 |
+
except Exception:
|
| 22 |
+
logger = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class AICore:
|
| 26 |
+
"""Minimal, safe AICore replacement for identity scanning workflows."""
|
| 27 |
+
|
| 28 |
+
def __init__(self, config_path: str = "config.json"):
|
| 29 |
+
self.config = self._load_config(config_path)
|
| 30 |
+
self.multimodal = MultimodalAnalyzer()
|
| 31 |
+
self.learner = DynamicLearner()
|
| 32 |
+
self.health = HealthMonitor()
|
| 33 |
+
self._initialized = False
|
| 34 |
+
|
| 35 |
+
def _load_config(self, path: str) -> Dict[str, Any]:
|
| 36 |
+
if not path or not os.path.exists(path):
|
| 37 |
+
return {}
|
| 38 |
+
try:
|
| 39 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 40 |
+
return json.load(f)
|
| 41 |
+
except Exception:
|
| 42 |
+
return {}
|
| 43 |
+
|
| 44 |
+
async def initialize(self) -> bool:
|
| 45 |
+
"""Initialize async subsystems (e.g., health monitor)."""
|
| 46 |
+
try:
|
| 47 |
+
ok = await self.health.initialize()
|
| 48 |
+
self._initialized = ok
|
| 49 |
+
return ok
|
| 50 |
+
except Exception as e:
|
| 51 |
+
logger.exception("Failed to initialize AICore: %s", e)
|
| 52 |
+
return False
|
| 53 |
+
|
| 54 |
+
async def generate_response(self, user_id: int, query: str, multimodal_input: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
| 55 |
+
"""Produce a safe, explainable response using local subsystems.
|
| 56 |
+
|
| 57 |
+
- Runs a lightweight analysis of any multimodal input
|
| 58 |
+
- Updates the dynamic learner with a summary of the interaction
|
| 59 |
+
- Returns a dict containing analysis and a text response
|
| 60 |
+
"""
|
| 61 |
+
try:
|
| 62 |
+
analyses = {}
|
| 63 |
+
if multimodal_input:
|
| 64 |
+
analyses = self.multimodal.analyze_content(multimodal_input)
|
| 65 |
+
|
| 66 |
+
# Simple content-based reply
|
| 67 |
+
text_summary = ""
|
| 68 |
+
if "text" in analyses:
|
| 69 |
+
t = analyses["text"]
|
| 70 |
+
text_summary = f"Received text: length={t.get('length')} words={t.get('word_count')}"
|
| 71 |
+
else:
|
| 72 |
+
text_summary = f"Query received: {query[:200]}"
|
| 73 |
+
|
| 74 |
+
# Update learner with a compact interaction record
|
| 75 |
+
adaptation_score = self.learner.update({
|
| 76 |
+
"user_id": user_id,
|
| 77 |
+
"query_summary": text_summary,
|
| 78 |
+
"multimodal_modalities": list(analyses.keys())
|
| 79 |
+
})
|
| 80 |
+
|
| 81 |
+
# Health snapshot
|
| 82 |
+
health_status = self.health.get_health_summary()
|
| 83 |
+
|
| 84 |
+
response_text = f"Acknowledged. Adaptation score={adaptation_score:.2f}."
|
| 85 |
+
|
| 86 |
+
return {
|
| 87 |
+
"response": response_text,
|
| 88 |
+
"analysis": analyses,
|
| 89 |
+
"adaptation_score": adaptation_score,
|
| 90 |
+
"health": health_status,
|
| 91 |
+
}
|
| 92 |
+
except Exception as e:
|
| 93 |
+
logger.exception("generate_response failed: %s", e)
|
| 94 |
+
return {"error": "internal_error", "detail": str(e)}
|
| 95 |
+
|
| 96 |
+
async def shutdown(self):
|
| 97 |
+
"""Clean up resources if necessary."""
|
| 98 |
+
# HealthMonitor has no async shutdown but we keep the method for parity.
|
| 99 |
+
await asyncio.sleep(0)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# Module quick test when run directly
|
| 103 |
+
if __name__ == "__main__":
|
| 104 |
+
async def _test():
|
| 105 |
+
core = AICore()
|
| 106 |
+
await core.initialize()
|
| 107 |
+
out = await core.generate_response(1, "Hello world", {"text": "Hello world from test"})
|
| 108 |
+
print(out)
|
| 109 |
+
await core.shutdown()
|
| 110 |
+
|
| 111 |
asyncio.run(_test())
|