Datasets:
Download Version4/render-main/smart_context.py from ysn-rfd/text-dataset-tiny-code-script-py-format: direct link, hf CLI and curl.
- Browser
- Download file 49.9 kB
-
https://huggingface.co/datasets/ysn-rfd/text-dataset-tiny-code-script-py-format/resolve/main/Version4/render-main/smart_context.py
- Command line
-
hf download hf://datasets/ysn-rfd/text-dataset-tiny-code-script-py-format/Version4/render-main/smart_context.py
-
curl -L -o smart_context.py https://huggingface.co/datasets/ysn-rfd/text-dataset-tiny-code-script-py-format/resolve/main/Version4/render-main/smart_context.py
49.9 kB
| # smart_context.py | |
| import os | |
| import json | |
| import logging | |
| import asyncio | |
| import hashlib | |
| import numpy as np | |
| from datetime import datetime, timedelta | |
| from typing import List, Dict, Any, Optional, Tuple, Set | |
| from collections import defaultdict, deque | |
| import pickle | |
| from dataclasses import dataclass, field | |
| from enum import Enum | |
| import re | |
| import heapq | |
| # برای embeddings (در صورت نبود کتابخانه، از روش جایگزین استفاده میشود) | |
| try: | |
| from sentence_transformers import SentenceTransformer | |
| HAS_SBERT = True | |
| except ImportError: | |
| HAS_SBERT = False | |
| from sklearn.feature_extraction.text import TfidfVectorizer | |
| import warnings | |
| warnings.filterwarnings("ignore") | |
| # وارد کردن مدیر دادهها | |
| import data_manager | |
| logger = logging.getLogger(__name__) | |
| # ==================== ENUMS و DataClasses ==================== | |
| class MemoryPriority(Enum): | |
| """اولویت حافظه""" | |
| LOW = 1 | |
| MEDIUM = 2 | |
| HIGH = 3 | |
| CRITICAL = 4 | |
| class MessageType(Enum): | |
| """نوع پیام""" | |
| FACT = "fact" | |
| PREFERENCE = "preference" | |
| EMOTION = "emotion" | |
| QUESTION = "question" | |
| ANSWER = "answer" | |
| DECISION = "decision" | |
| ACTION = "action" | |
| CHITCHAT = "chitchat" | |
| class EmotionType(Enum): | |
| """نوع احساس""" | |
| POSITIVE = "positive" | |
| NEUTRAL = "neutral" | |
| NEGATIVE = "negative" | |
| EXCITED = "excited" | |
| ANGRY = "angry" | |
| CONFUSED = "confused" | |
| class MessageNode: | |
| """گره پیام در گراف حافظه""" | |
| id: str | |
| content: str | |
| role: str | |
| timestamp: datetime | |
| message_type: MessageType | |
| importance_score: float = 0.5 | |
| emotion_score: Dict[EmotionType, float] = field(default_factory=dict) | |
| tokens: int = 0 | |
| embeddings: Optional[np.ndarray] = None | |
| metadata: Dict[str, Any] = field(default_factory=dict) | |
| def __hash__(self): | |
| return hash(self.id) | |
| def __eq__(self, other): | |
| return self.id == other.id | |
| class MemoryConnection: | |
| """اتصال بین پیامها در گراف حافظه""" | |
| source_id: str | |
| target_id: str | |
| connection_type: str # 'semantic', 'temporal', 'causal', 'contextual' | |
| strength: float = 1.0 | |
| metadata: Dict[str, Any] = field(default_factory=dict) | |
| class UserProfile: | |
| """پروفایل کاربر""" | |
| user_id: int | |
| personality_traits: Dict[str, float] = field(default_factory=dict) | |
| interests: Set[str] = field(default_factory=set) | |
| preferences: Dict[str, Any] = field(default_factory=dict) | |
| conversation_style: str = "balanced" | |
| knowledge_level: Dict[str, float] = field(default_factory=dict) | |
| emotional_patterns: Dict[str, List[float]] = field(default_factory=dict) | |
| learning_style: Optional[str] = None | |
| def update_from_message(self, message: str, analysis: Dict[str, Any]): | |
| """بهروزرسانی پروفایل بر اساس پیام جدید""" | |
| if 'personality_clues' in analysis: | |
| for trait, score in analysis['personality_clues'].items(): | |
| current = self.personality_traits.get(trait, 0.5) | |
| self.personality_traits[trait] = 0.7 * current + 0.3 * score | |
| if 'interests' in analysis: | |
| self.interests.update(analysis['interests']) | |
| if 'preferences' in analysis: | |
| self.preferences.update(analysis['preferences']) | |
| # ==================== کلاس Embedding Manager ==================== | |
| class EmbeddingManager: | |
| """مدیریت embeddings برای جستجوی معنایی""" | |
| def __init__(self, model_name: str = None): | |
| self.model = None | |
| self.vectorizer = None | |
| self.use_sbert = HAS_SBERT | |
| if self.use_sbert: | |
| try: | |
| self.model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2') | |
| logger.info("Loaded multilingual sentence transformer") | |
| except Exception as e: | |
| logger.warning(f"Failed to load sentence transformer: {e}") | |
| self.use_sbert = False | |
| if not self.use_sbert: | |
| try: | |
| from sklearn.feature_extraction.text import TfidfVectorizer | |
| self.vectorizer = TfidfVectorizer(max_features=1000) | |
| logger.info("Using TF-IDF for embeddings") | |
| except ImportError: | |
| logger.warning("scikit-learn not available, using simple word vectors") | |
| self.vectorizer = None | |
| def get_embedding(self, text: str) -> np.ndarray: | |
| """دریافت embedding برای متن""" | |
| if self.use_sbert and self.model: | |
| return self.model.encode([text])[0] | |
| elif self.vectorizer: | |
| # برای TF-IDF نیاز به fit داریم، فقط بردار ساده برمیگردانیم | |
| words = text.lower().split() | |
| unique_words = list(set(words)) | |
| embedding = np.zeros(100) | |
| for i, word in enumerate(unique_words[:100]): | |
| embedding[i] = hash(word) % 100 / 100.0 | |
| return embedding | |
| else: | |
| # روش سادهتر | |
| text_lower = text.lower() | |
| embedding = np.zeros(50) | |
| # وزن بر اساس طول و محتوا | |
| embedding[0] = len(text) / 1000.0 | |
| embedding[1] = text.count('؟') / 5.0 | |
| embedding[2] = text.count('!') / 5.0 | |
| # ویژگیهای ساده | |
| embedding[3] = 1.0 if 'چه' in text_lower else 0.0 | |
| embedding[4] = 1.0 if 'چرا' in text_lower else 0.0 | |
| embedding[5] = 1.0 if 'چگونه' in text_lower else 0.0 | |
| return embedding | |
| def cosine_similarity(self, vec1: np.ndarray, vec2: np.ndarray) -> float: | |
| """محاسبه cosine similarity""" | |
| norm1 = np.linalg.norm(vec1) | |
| norm2 = np.linalg.norm(vec2) | |
| if norm1 == 0 or norm2 == 0: | |
| return 0.0 | |
| return np.dot(vec1, vec2) / (norm1 * norm2) | |
| # ==================== کلاس Memory Graph ==================== | |
| class MemoryGraph: | |
| """گراف حافظه برای ذخیره و بازیابی ارتباطات""" | |
| def __init__(self): | |
| self.nodes: Dict[str, MessageNode] = {} | |
| self.connections: List[MemoryConnection] = [] | |
| self.adjacency: Dict[str, List[MemoryConnection]] = defaultdict(list) | |
| self.topic_clusters: Dict[str, Set[str]] = defaultdict(set) | |
| self.time_index: List[Tuple[datetime, str]] = [] | |
| def add_node(self, node: MessageNode): | |
| """افزودن گره جدید""" | |
| self.nodes[node.id] = node | |
| self.time_index.append((node.timestamp, node.id)) | |
| self.time_index.sort(key=lambda x: x[0]) | |
| def add_connection(self, connection: MemoryConnection): | |
| """افزودن اتصال جدید""" | |
| self.connections.append(connection) | |
| self.adjacency[connection.source_id].append(connection) | |
| def find_similar_nodes(self, query_embedding: np.ndarray, | |
| threshold: float = 0.7, | |
| max_results: int = 5) -> List[Tuple[str, float]]: | |
| """یافتن گرههای مشابه""" | |
| similarities = [] | |
| for node_id, node in self.nodes.items(): | |
| if node.embeddings is not None: | |
| similarity = self._cosine_similarity(query_embedding, node.embeddings) | |
| if similarity > threshold: | |
| similarities.append((node_id, similarity)) | |
| similarities.sort(key=lambda x: x[1], reverse=True) | |
| return similarities[:max_results] | |
| def get_temporal_neighbors(self, node_id: str, | |
| time_window: timedelta = timedelta(hours=24)) -> List[str]: | |
| """یافتن همسایههای زمانی""" | |
| if node_id not in self.nodes: | |
| return [] | |
| node_time = self.nodes[node_id].timestamp | |
| neighbors = [] | |
| for timestamp, nid in self.time_index: | |
| if nid != node_id and abs(timestamp - node_time) <= time_window: | |
| neighbors.append(nid) | |
| return neighbors | |
| def get_semantic_cluster(self, node_id: str, min_similarity: float = 0.6) -> Set[str]: | |
| """دریافت خوشه معنایی یک گره""" | |
| cluster = {node_id} | |
| if node_id not in self.nodes or self.nodes[node_id].embeddings is None: | |
| return cluster | |
| query_embedding = self.nodes[node_id].embeddings | |
| for other_id, other_node in self.nodes.items(): | |
| if other_id != node_id and other_node.embeddings is not None: | |
| similarity = self._cosine_similarity(query_embedding, other_node.embeddings) | |
| if similarity > min_similarity: | |
| cluster.add(other_id) | |
| return cluster | |
| def _cosine_similarity(self, vec1: np.ndarray, vec2: np.ndarray) -> float: | |
| """محاسبه cosine similarity""" | |
| norm1 = np.linalg.norm(vec1) | |
| norm2 = np.linalg.norm(vec2) | |
| if norm1 == 0 or norm2 == 0: | |
| return 0.0 | |
| return np.dot(vec1, vec2) / (norm1 * norm2) | |
| # ==================== کلاس Context Analyzer ==================== | |
| class ContextAnalyzer: | |
| """آنالیزور هوشمند context""" | |
| def __init__(self): | |
| self.keyword_patterns = { | |
| 'name': [r'نام\s+من\s+(.*?)(?:است|میباشد)', r'اسم\s+من\s+(.*?)'], | |
| 'age': [r'سن\s+من\s+(\d+)', r'(\d+)\s+سالمه'], | |
| 'location': [r'اهل\s+(.*?)\s+هستم', r'در\s+(.*?)\s+زندگی میکنم'], | |
| 'preference': [r'دوست\s+دارم\s+(.*?)', r'علاقه\s+دارم\s+(.*?)', r'ترجیح\s+میدهم\s+(.*?)'], | |
| 'dislike': [r'دوست\s+ندارم\s+(.*?)', r'مخالف\s+(.*?)\s+هستم'], | |
| 'goal': [r'میخواهم\s+(.*?)', r'هدف\s+من\s+(.*?)\s+است'], | |
| 'question': [r'(چرا|چگونه|چه|کجا|کی|آیا)\s+.*?\?'], | |
| 'decision': [r'تصمیم\s+گرفتم\s+(.*?)', r'قصد\s+دارم\s+(.*?)'], | |
| 'emotion': [r'احساس\s+(.*?)\s+دارم', r'(خوشحالم|ناراحتم|عصبانیام|خستهام)'] | |
| } | |
| self.emotion_keywords = { | |
| EmotionType.POSITIVE: ['خوب', 'عالی', 'خوشحال', 'عالی', 'ممنون', 'مرسی', 'دوست دارم', 'عالیه'], | |
| EmotionType.NEGATIVE: ['بد', 'بدی', 'ناراحت', 'غمگین', 'عصبانی', 'مشکل', 'خطا', 'اشتباه'], | |
| EmotionType.EXCITED: ['هیجانزده', 'هیجان', 'جالب', 'شگفتانگیز', 'عالی', 'وای'], | |
| EmotionType.ANGRY: ['عصبانی', 'خشمگین', 'ناراحت', 'اعصاب', 'دیوانه'], | |
| EmotionType.CONFUSED: ['سردرگم', 'گیج', 'نمیفهمم', 'مشکل دارم', 'کمک'] | |
| } | |
| def analyze_message(self, text: str, role: str) -> Dict[str, Any]: | |
| """آنالیز پیام و استخراج اطلاعات""" | |
| analysis = { | |
| 'type': self._detect_message_type(text, role), | |
| 'entities': self._extract_entities(text), | |
| 'keywords': self._extract_keywords(text), | |
| 'emotion': self._analyze_emotion(text), | |
| 'importance': self._calculate_importance(text, role), | |
| 'topics': self._extract_topics(text), | |
| 'intent': self._detect_intent(text), | |
| 'complexity': self._calculate_complexity(text), | |
| 'has_personal_info': False, | |
| 'personal_info': {} | |
| } | |
| # استخراج اطلاعات شخصی | |
| personal_info = self._extract_personal_info(text) | |
| if personal_info: | |
| analysis['has_personal_info'] = True | |
| analysis['personal_info'] = personal_info | |
| # استخراج ترجیحات | |
| preferences = self._extract_preferences(text) | |
| if preferences: | |
| analysis['preferences'] = preferences | |
| return analysis | |
| def _detect_message_type(self, text: str, role: str) -> MessageType: | |
| """تشخیص نوع پیام""" | |
| text_lower = text.lower() | |
| if role == 'user': | |
| if any(q in text_lower for q in ['؟', '?', 'چرا', 'چگونه', 'چه', 'کجا']): | |
| return MessageType.QUESTION | |
| elif any(e in text_lower for e in ['احساس', 'حالم', 'خوشحالم', 'ناراحتم']): | |
| return MessageType.EMOTION | |
| elif any(d in text_lower for d in ['تصمیم', 'قصد', 'میخواهم']): | |
| return MessageType.DECISION | |
| elif any(p in text_lower for p in ['دوست دارم', 'علاقه', 'ترجیح']): | |
| return MessageType.PREFERENCE | |
| else: | |
| return MessageType.FACT | |
| else: | |
| if '؟' in text_lower: | |
| return MessageType.QUESTION | |
| elif any(a in text_lower for a in ['پاسخ', 'جواب', 'راه حل']): | |
| return MessageType.ANSWER | |
| else: | |
| return MessageType.FACT | |
| def _extract_entities(self, text: str) -> List[str]: | |
| """استخراج موجودیتها""" | |
| entities = [] | |
| # الگوهای ساده برای اسامی | |
| name_patterns = [ | |
| r'نام\s+(?:من|او)\s+(.*?)(?:\s|$|\.|،)', | |
| r'اسم\s+(?:من|او)\s+(.*?)(?:\s|$|\.|،)', | |
| ] | |
| for pattern in name_patterns: | |
| matches = re.findall(pattern, text) | |
| entities.extend(matches) | |
| return entities | |
| def _extract_keywords(self, text: str) -> List[str]: | |
| """استخراج کلمات کلیدی""" | |
| # حذف کلمات توقف فارسی | |
| stopwords = {'و', 'در', 'با', 'به', 'از', 'که', 'این', 'آن', 'را', 'برای', 'اما', 'یا'} | |
| words = re.findall(r'\b[\wآ-ی]+\b', text.lower()) | |
| keywords = [w for w in words if w not in stopwords and len(w) > 2] | |
| return list(set(keywords))[:10] | |
| def _analyze_emotion(self, text: str) -> Dict[EmotionType, float]: | |
| """تحلیل احساسات متن""" | |
| emotion_scores = {e: 0.0 for e in EmotionType} | |
| text_lower = text.lower() | |
| for emotion_type, keywords in self.emotion_keywords.items(): | |
| score = 0.0 | |
| for keyword in keywords: | |
| if keyword in text_lower: | |
| score += 1.0 | |
| emotion_scores[emotion_type] = min(score / 3.0, 1.0) | |
| # تشخیص احساس کلی | |
| if sum(emotion_scores.values()) == 0: | |
| emotion_scores[EmotionType.NEUTRAL] = 1.0 | |
| return emotion_scores | |
| def _calculate_importance(self, text: str, role: str) -> float: | |
| """محاسبه اهمیت پیام""" | |
| score = 0.0 | |
| # امتیاز بر اساس نقش | |
| if role == 'user': | |
| score += 0.3 | |
| # امتیاز بر اساس طول | |
| length = len(text) | |
| if length > 200: | |
| score += 0.3 | |
| elif length > 100: | |
| score += 0.2 | |
| elif length > 50: | |
| score += 0.1 | |
| # امتیاز بر اساس سوال بودن | |
| if '؟' in text or '?' in text: | |
| score += 0.2 | |
| # امتیاز بر اساس کلمات کلیدی مهم | |
| important_words = ['مهم', 'لطفا', 'فوری', 'ضروری', 'لازم', 'حتما'] | |
| for word in important_words: | |
| if word in text.lower(): | |
| score += 0.2 | |
| break | |
| # امتیاز بر اساس اطلاعات شخصی | |
| if any(pattern in text for pattern in ['نام من', 'سن من', 'اهل']): | |
| score += 0.3 | |
| return min(score, 1.0) | |
| def _extract_topics(self, text: str) -> List[str]: | |
| """استخراج موضوعات""" | |
| topics = [] | |
| # دستهبندی موضوعات بر اساس کلمات کلیدی | |
| topic_categories = { | |
| 'ورزش': ['فوتبال', 'ورزش', 'تمرین', 'مسابقه', 'تیم'], | |
| 'تکنولوژی': ['کامپیوتر', 'برنامه', 'کد', 'پایتون', 'هوش مصنوعی'], | |
| 'هنر': ['فیلم', 'موسیقی', 'نقاشی', 'کتاب', 'خواننده'], | |
| 'علم': ['تحقیق', 'دانش', 'کشف', 'آزمایش', 'نظریه'], | |
| 'غذا': ['غذا', 'رستوران', 'پخت', 'خوراک', 'ناهار'], | |
| 'سفر': ['سفر', 'مسافرت', 'کشور', 'شهر', 'هتل'], | |
| 'سلامتی': ['سلامت', 'بیماری', 'درمان', 'دکتر', 'بیمارستان'], | |
| 'کاری': ['کار', 'شغل', 'شرکت', 'مصاحبه', 'پروژه'], | |
| 'تحصیل': ['درس', 'دانشگاه', 'مدرسه', 'آموزش', 'یادگیری'], | |
| } | |
| text_lower = text.lower() | |
| for topic, keywords in topic_categories.items(): | |
| if any(keyword in text_lower for keyword in keywords): | |
| topics.append(topic) | |
| return topics[:3] | |
| def _detect_intent(self, text: str) -> str: | |
| """تشخیص قصد کاربر""" | |
| text_lower = text.lower() | |
| if any(q in text_lower for q in ['چطور', 'چگونه', 'راهنمایی']): | |
| return 'guidance' | |
| elif any(q in text_lower for q in ['چه', 'اطلاعات', 'معرفی']): | |
| return 'information' | |
| elif any(q in text_lower for q in ['چرا', 'دلیل', 'علت']): | |
| return 'explanation' | |
| elif any(q in text_lower for q in ['کمک', 'راه حل', 'مشکل']): | |
| return 'help' | |
| elif any(q in text_lower for q in ['توصیه', 'پیشنهاد', 'نظر']): | |
| return 'advice' | |
| elif any(q in text_lower for q in ['بحث', 'بحث کنیم', 'نظرت']): | |
| return 'discussion' | |
| else: | |
| return 'general' | |
| def _calculate_complexity(self, text: str) -> float: | |
| """محاسبه پیچیدگی متن""" | |
| # میانگین طول کلمات | |
| words = text.split() | |
| if not words: | |
| return 0.0 | |
| avg_word_length = sum(len(w) for w in words) / len(words) | |
| # تعداد جملات | |
| sentences = re.split(r'[.!?]', text) | |
| num_sentences = max(len(sentences), 1) | |
| # نسبت کلمات منحصر به فرد | |
| unique_words = len(set(words)) | |
| diversity = unique_words / len(words) if words else 0 | |
| complexity = (avg_word_length / 10.0 + diversity + min(len(words) / 50.0, 1.0)) / 3.0 | |
| return min(complexity, 1.0) | |
| def _extract_personal_info(self, text: str) -> Dict[str, Any]: | |
| """استخراج اطلاعات شخصی""" | |
| info = {} | |
| for info_type, patterns in self.keyword_patterns.items(): | |
| for pattern in patterns: | |
| matches = re.findall(pattern, text) | |
| if matches: | |
| info[info_type] = matches[0] | |
| break | |
| return info | |
| def _extract_preferences(self, text: str) -> Dict[str, Any]: | |
| """استخراج ترجیحات""" | |
| preferences = {} | |
| text_lower = text.lower() | |
| # ترجیحات ساده | |
| if 'دوست دارم' in text_lower: | |
| parts = text_lower.split('دوست دارم') | |
| if len(parts) > 1: | |
| preference = parts[1].split('.')[0].strip() | |
| if preference: | |
| preferences['likes'] = preferences.get('likes', []) + [preference] | |
| if 'دوست ندارم' in text_lower: | |
| parts = text_lower.split('دوست ندارم') | |
| if len(parts) > 1: | |
| preference = parts[1].split('.')[0].strip() | |
| if preference: | |
| preferences['dislikes'] = preferences.get('dislikes', []) + [preference] | |
| return preferences | |
| # ==================== کلاس Intelligent Context Manager ==================== | |
| class IntelligentContextManager: | |
| """مدیر هوشمند context""" | |
| def __init__(self, user_id: int): | |
| self.user_id = user_id | |
| self.embedding_manager = EmbeddingManager() | |
| self.analyzer = ContextAnalyzer() | |
| self.memory_graph = MemoryGraph() | |
| self.user_profile = UserProfile(user_id=user_id) | |
| # لایههای حافظه | |
| self.memory_layers = { | |
| 'ephemeral': deque(maxlen=20), # حافظه زودگذر (چند دقیقه) | |
| 'working': deque(maxlen=50), # حافظه فعال (مکالمه جاری) | |
| 'recent': deque(maxlen=100), # حافظه اخیر (چند روز) | |
| 'long_term': [], # حافظه بلندمدت (اهمیت بالا) | |
| 'core': [] # حافظه هسته (اطلاعات حیاتی) | |
| } | |
| # تنظیمات | |
| self.max_working_tokens = 512 | |
| self.max_context_tokens = 2048 | |
| self.min_importance_threshold = 0.3 | |
| self.semantic_similarity_threshold = 0.7 | |
| # آمار | |
| self.stats = { | |
| 'total_messages': 0, | |
| 'compressed_messages': 0, | |
| 'retrieved_memories': 0, | |
| 'profile_updates': 0, | |
| 'average_importance': 0.0 | |
| } | |
| # بارگذاری دادههای ذخیره شده | |
| self._load_saved_data() | |
| def _load_saved_data(self): | |
| """بارگذاری دادههای ذخیره شده""" | |
| try: | |
| # بارگذاری از data_manager | |
| user_data = data_manager.DATA['users'].get(str(self.user_id), {}) | |
| if 'smart_context' in user_data: | |
| saved_data = user_data['smart_context'] | |
| # بارگذاری پروفایل کاربر | |
| if 'profile' in saved_data: | |
| self.user_profile = UserProfile(**saved_data['profile']) | |
| # بارگذاری آمار | |
| if 'stats' in saved_data: | |
| self.stats.update(saved_data['stats']) | |
| logger.info(f"Loaded smart context for user {self.user_id}") | |
| except Exception as e: | |
| logger.error(f"Error loading saved context data: {e}") | |
| def _save_data(self): | |
| """ذخیره دادهها""" | |
| try: | |
| user_id_str = str(self.user_id) | |
| if user_id_str not in data_manager.DATA['users']: | |
| data_manager.DATA['users'][user_id_str] = {} | |
| # ذخیره دادههای هوشمند | |
| data_manager.DATA['users'][user_id_str]['smart_context'] = { | |
| 'profile': { | |
| 'user_id': self.user_profile.user_id, | |
| 'personality_traits': dict(self.user_profile.personality_traits), | |
| 'interests': list(self.user_profile.interests), | |
| 'preferences': dict(self.user_profile.preferences), | |
| 'conversation_style': self.user_profile.conversation_style, | |
| 'knowledge_level': dict(self.user_profile.knowledge_level), | |
| 'emotional_patterns': dict(self.user_profile.emotional_patterns), | |
| 'learning_style': self.user_profile.learning_style | |
| }, | |
| 'stats': self.stats, | |
| 'last_updated': datetime.now().isoformat() | |
| } | |
| data_manager.save_data() | |
| except Exception as e: | |
| logger.error(f"Error saving smart context data: {e}") | |
| async def process_message(self, role: str, content: str) -> Dict[str, Any]: | |
| """پرداش کامل یک پیام جدید""" | |
| start_time = datetime.now() | |
| # 1. تحلیل پیام | |
| analysis = self.analyzer.analyze_message(content, role) | |
| # 2. ایجاد گره حافظه | |
| message_id = self._generate_message_id(content) | |
| # ایجاد embedding به صورت غیرهمزمان | |
| embedding_task = asyncio.create_task( | |
| self._get_embedding_async(content) | |
| ) | |
| node = MessageNode( | |
| id=message_id, | |
| content=content, | |
| role=role, | |
| timestamp=datetime.now(), | |
| message_type=analysis['type'], | |
| importance_score=analysis['importance'], | |
| emotion_score=analysis['emotion'], | |
| tokens=data_manager.count_tokens(content), | |
| embeddings=None, # موقتاً None | |
| metadata={ | |
| 'analysis': analysis, | |
| 'topics': analysis['topics'], | |
| 'intent': analysis['intent'], | |
| 'complexity': analysis['complexity'] | |
| } | |
| ) | |
| # دریافت embedding (اگر موجود باشد) | |
| try: | |
| node.embeddings = await asyncio.wait_for(embedding_task, timeout=2.0) | |
| except asyncio.TimeoutError: | |
| logger.warning(f"Embedding generation timeout for message {message_id}") | |
| node.embeddings = self.embedding_manager.get_embedding(content) | |
| # 3. افزودن به حافظه و گراف | |
| await asyncio.to_thread(self._add_to_memory_layers, node, analysis) | |
| await asyncio.to_thread(self.memory_graph.add_node, node) | |
| # 4. ایجاد ارتباطات | |
| await asyncio.to_thread(self._create_memory_connections, node) | |
| # 5. بهروزرسانی پروفایل کاربر | |
| if role == 'user': | |
| await asyncio.to_thread(self._update_user_profile, content, analysis) | |
| # 6. بهینهسازی حافظه | |
| await asyncio.to_thread(self._optimize_memory) | |
| # 7. بهروزرسانی آمار | |
| self.stats['total_messages'] += 1 | |
| self.stats['average_importance'] = ( | |
| self.stats['average_importance'] * (self.stats['total_messages'] - 1) + | |
| analysis['importance'] | |
| ) / self.stats['total_messages'] | |
| # 8. ذخیره دادهها | |
| await asyncio.to_thread(self._save_data) | |
| processing_time = (datetime.now() - start_time).total_seconds() | |
| logger.info(f"Processed message {message_id} in {processing_time:.2f}s, importance: {analysis['importance']:.2f}") | |
| return { | |
| 'node_id': message_id, | |
| 'analysis': analysis, | |
| 'processing_time': processing_time | |
| } | |
| async def _get_embedding_async(self, text: str) -> np.ndarray: | |
| """دریافت embedding به صورت async""" | |
| loop = asyncio.get_event_loop() | |
| return await loop.run_in_executor( | |
| None, | |
| self.embedding_manager.get_embedding, | |
| text | |
| ) | |
| def _generate_message_id(self, content: str) -> str: | |
| """تولید شناسه منحصر به فرد برای پیام""" | |
| timestamp = datetime.now().strftime('%Y%m%d%H%M%S%f') | |
| content_hash = hashlib.md5(content.encode()).hexdigest()[:8] | |
| return f"{self.user_id}_{timestamp}_{content_hash}" | |
| def _add_to_memory_layers(self, node: MessageNode, analysis: Dict[str, Any]): | |
| """افزودن پیام به لایههای حافظه مناسب""" | |
| # همیشه به حافظه زودگذر و فعال اضافه میشود | |
| self.memory_layers['ephemeral'].append(node) | |
| self.memory_layers['working'].append(node) | |
| # بررسی برای حافظه اخیر | |
| if analysis['importance'] > 0.2: | |
| self.memory_layers['recent'].append(node) | |
| # بررسی برای حافظه بلندمدت | |
| if analysis['importance'] > self.min_importance_threshold: | |
| self.memory_layers['long_term'].append(node) | |
| # بررسی برای حافظه هسته (اطلاعات حیاتی) | |
| if analysis.get('has_personal_info', False) or analysis['importance'] > 0.8: | |
| core_entry = { | |
| 'node': node, | |
| 'info': analysis.get('personal_info', {}), | |
| 'timestamp': datetime.now() | |
| } | |
| self.memory_layers['core'].append(core_entry) | |
| def _create_memory_connections(self, node: MessageNode): | |
| """ایجاد ارتباطات حافظه برای گره جدید""" | |
| # اگر گرههای قبلی وجود دارند، ارتباط ایجاد کن | |
| if len(self.memory_graph.nodes) > 1: | |
| # ارتباط زمانی با آخرین گره | |
| last_nodes = list(self.memory_graph.nodes.values())[-5:] | |
| for last_node in last_nodes: | |
| if last_node.id != node.id: | |
| temporal_conn = MemoryConnection( | |
| source_id=last_node.id, | |
| target_id=node.id, | |
| connection_type='temporal', | |
| strength=0.8 | |
| ) | |
| self.memory_graph.add_connection(temporal_conn) | |
| # ارتباط معنایی با گرههای مشابه | |
| if node.embeddings is not None: | |
| similar_nodes = self.memory_graph.find_similar_nodes( | |
| node.embeddings, | |
| threshold=self.semantic_similarity_threshold | |
| ) | |
| for similar_id, similarity in similar_nodes: | |
| semantic_conn = MemoryConnection( | |
| source_id=node.id, | |
| target_id=similar_id, | |
| connection_type='semantic', | |
| strength=similarity | |
| ) | |
| self.memory_graph.add_connection(semantic_conn) | |
| def _update_user_profile(self, content: str, analysis: Dict[str, Any]): | |
| """بهروزرسانی پروفایل کاربر""" | |
| # بهروزرسانی علاقهمندیها | |
| if 'topics' in analysis: | |
| for topic in analysis['topics']: | |
| self.user_profile.interests.add(topic) | |
| # بهروزرسانی ترجیحات | |
| if 'preferences' in analysis: | |
| self.user_profile.preferences.update(analysis['preferences']) | |
| # تشخیص سبک مکالمه | |
| complexity = analysis.get('complexity', 0.5) | |
| if complexity > 0.7: | |
| self.user_profile.conversation_style = "detailed" | |
| elif complexity < 0.3: | |
| self.user_profile.conversation_style = "concise" | |
| # بهروزرسانی الگوهای احساسی | |
| emotion = analysis.get('emotion', {}) | |
| for emotion_type, score in emotion.items(): | |
| if score > 0.3: | |
| emotion_name = emotion_type.value if hasattr(emotion_type, 'value') else str(emotion_type) | |
| if emotion_name not in self.user_profile.emotional_patterns: | |
| self.user_profile.emotional_patterns[emotion_name] = [] | |
| self.user_profile.emotional_patterns[emotion_name].append(score) | |
| self.stats['profile_updates'] += 1 | |
| def _optimize_memory(self): | |
| """بهینهسازی و فشردهسازی حافظه""" | |
| # فشردهسازی حافظه فعال اگر توکنها زیاد شد | |
| working_tokens = sum(node.tokens for node in self.memory_layers['working']) | |
| if working_tokens > self.max_working_tokens: | |
| self._compress_working_memory() | |
| self.stats['compressed_messages'] += 1 | |
| # پاکسازی حافظه زودگذر قدیمی | |
| if len(self.memory_layers['ephemeral']) > 50: | |
| self.memory_layers['ephemeral'].clear() | |
| # مرتبسازی حافظه بلندمدت بر اساس اهمیت | |
| self.memory_layers['long_term'].sort(key=lambda x: x.importance_score, reverse=True) | |
| if len(self.memory_layers['long_term']) > 100: | |
| self.memory_layers['long_term'] = self.memory_layers['long_term'][:100] | |
| def _compress_working_memory(self): | |
| """فشردهسازی هوشمند حافظه فعال""" | |
| if len(self.memory_layers['working']) <= 10: | |
| return | |
| working_memory = list(self.memory_layers['working']) | |
| # 1. محاسبه امتیاز برای هر پیام | |
| scored_messages = [] | |
| for i, node in enumerate(working_memory): | |
| score = self._calculate_compression_score(node, i, len(working_memory)) | |
| scored_messages.append((score, node)) | |
| # 2. مرتبسازی بر اساس امتیاز | |
| scored_messages.sort(key=lambda x: x[0], reverse=True) | |
| # 3. انتخاب پیامهای برتر تا سقف توکن | |
| compressed = [] | |
| total_tokens = 0 | |
| for score, node in scored_messages: | |
| if total_tokens + node.tokens <= self.max_working_tokens: | |
| compressed.append(node) | |
| total_tokens += node.tokens | |
| else: | |
| break | |
| # 4. مرتبسازی دوباره بر اساس زمان | |
| compressed.sort(key=lambda x: x.timestamp) | |
| # 5. جایگزینی حافظه فعال | |
| self.memory_layers['working'] = deque(compressed, maxlen=50) | |
| logger.info(f"Compressed working memory: {len(working_memory)} -> {len(compressed)} messages") | |
| def _calculate_compression_score(self, node: MessageNode, index: int, total: int) -> float: | |
| """محاسبه امتیاز فشردهسازی برای یک پیام""" | |
| score = 0.0 | |
| # 1. اهمیت پیام | |
| score += node.importance_score * 0.4 | |
| # 2. تازگی (پیامهای جدیدتر مهمتر) | |
| recency = (index / total) * 0.3 | |
| score += recency | |
| # 3. تنوع اطلاعات (بر اساس topics) | |
| topics = node.metadata.get('topics', []) | |
| topic_diversity = min(len(topics) / 3.0, 0.2) | |
| score += topic_diversity | |
| # 4. نوع پیام | |
| type_weights = { | |
| MessageType.QUESTION: 0.2, | |
| MessageType.PREFERENCE: 0.2, | |
| MessageType.DECISION: 0.2, | |
| MessageType.EMOTION: 0.1, | |
| MessageType.FACT: 0.1, | |
| MessageType.ANSWER: 0.1, | |
| MessageType.ACTION: 0.2, | |
| MessageType.CHITCHAT: 0.05 | |
| } | |
| score += type_weights.get(node.message_type, 0.1) | |
| # 5. اطلاعات شخصی | |
| if 'has_personal_info' in node.metadata.get('analysis', {}): | |
| if node.metadata['analysis']['has_personal_info']: | |
| score += 0.2 | |
| return score | |
| async def retrieve_context(self, query: str, max_tokens: int = None) -> List[Dict[str, Any]]: | |
| """بازیابی هوشمند context مرتبط با query""" | |
| try: | |
| if max_tokens is None: | |
| max_tokens = self.max_context_tokens | |
| start_time = datetime.now() | |
| # دریافت embedding با timeout | |
| try: | |
| embedding_task = asyncio.create_task( | |
| self._get_embedding_async(query) | |
| ) | |
| query_embedding = await asyncio.wait_for(embedding_task, timeout=3.0) | |
| except asyncio.TimeoutError: | |
| logger.warning(f"Embedding timeout for query: {query[:50]}") | |
| query_embedding = self.embedding_manager.get_embedding(query) | |
| # بازیابی از حافظههای مختلف به صورت موازی | |
| tasks = [] | |
| # حافظه فعال | |
| tasks.append(asyncio.create_task( | |
| asyncio.to_thread(self._retrieve_from_working_memory) | |
| )) | |
| # حافظه معنایی | |
| tasks.append(self._retrieve_semantic_memories(query_embedding, 'recent')) | |
| tasks.append(self._retrieve_semantic_memories(query_embedding, 'long_term')) | |
| # حافظه هسته | |
| tasks.append(asyncio.create_task( | |
| asyncio.to_thread(self._retrieve_core_memories, query) | |
| )) | |
| # اجرای موازی همه tasks | |
| results = await asyncio.gather(*tasks, return_exceptions=True) | |
| # جمعآوری نتایج | |
| retrieved_memories = [] | |
| for result in results: | |
| if isinstance(result, Exception): | |
| logger.error(f"Error retrieving memory: {result}") | |
| continue | |
| retrieved_memories.extend(result) | |
| except Exception as e: | |
| logger.error(f"Error in retrieve_context: {e}") | |
| # Fallback: برگرداندن حافظه فعال | |
| return self._retrieve_from_working_memory() | |
| # 1. دریافت embedding برای query | |
| query_embedding = self.embedding_manager.get_embedding(query) | |
| # 2. بازیابی از لایههای مختلف حافظه | |
| retrieved_memories = [] | |
| # از حافظه فعال (همیشه) | |
| retrieved_memories.extend(self._retrieve_from_working_memory()) | |
| # از حافظه اخیر (بر اساس شباهت) | |
| recent_memories = await self._retrieve_semantic_memories(query_embedding, 'recent') | |
| retrieved_memories.extend(recent_memories) | |
| # از حافظه بلندمدت (اطلاعات مهم) | |
| long_term_memories = await self._retrieve_semantic_memories(query_embedding, 'long_term') | |
| retrieved_memories.extend(long_term_memories) | |
| # از حافظه هسته (اطلاعات حیاتی کاربر) | |
| core_memories = self._retrieve_core_memories(query) | |
| retrieved_memories.extend(core_memories) | |
| # 3. حذف تکراریها و مرتبسازی | |
| unique_memories = self._deduplicate_memories(retrieved_memories) | |
| prioritized_memories = self._prioritize_memories(unique_memories, query_embedding) | |
| # 4. انتخاب تا سقف توکن | |
| final_context = [] | |
| total_tokens = 0 | |
| for memory in prioritized_memories: | |
| memory_tokens = memory['node'].tokens if 'node' in memory else 50 | |
| if total_tokens + memory_tokens <= max_tokens: | |
| final_context.append(memory) | |
| total_tokens += memory_tokens | |
| else: | |
| break | |
| # 5. بهروزرسانی آمار | |
| self.stats['retrieved_memories'] += len(final_context) | |
| retrieval_time = (datetime.now() - start_time).total_seconds() | |
| logger.info(f"Retrieved {len(final_context)} memories in {retrieval_time:.2f}s") | |
| return final_context | |
| def _retrieve_from_working_memory(self) -> List[Dict[str, Any]]: | |
| """بازیابی از حافظه فعال""" | |
| memories = [] | |
| for node in list(self.memory_layers['working'])[-10:]: # 10 پیام آخر | |
| memories.append({ | |
| 'node': node, | |
| 'source': 'working', | |
| 'relevance': 1.0, | |
| 'recency': 1.0 | |
| }) | |
| return memories | |
| async def _retrieve_semantic_memories(self, query_embedding: np.ndarray, | |
| layer: str) -> List[Dict[str, Any]]: | |
| """بازیابی حافظههای معنایی""" | |
| memories = [] | |
| if layer not in self.memory_layers: | |
| return memories | |
| layer_memories = self.memory_layers[layer] | |
| for item in layer_memories: | |
| node = item if hasattr(item, 'embeddings') else item['node'] if isinstance(item, dict) else None | |
| if node and node.embeddings is not None: | |
| similarity = self.embedding_manager.cosine_similarity( | |
| query_embedding, node.embeddings | |
| ) | |
| if similarity > self.semantic_similarity_threshold: | |
| recency_weight = 1.0 if layer == 'working' else 0.7 | |
| memories.append({ | |
| 'node': node, | |
| 'source': layer, | |
| 'relevance': similarity, | |
| 'recency': recency_weight, | |
| 'importance': node.importance_score | |
| }) | |
| return memories | |
| def _retrieve_core_memories(self, query: str) -> List[Dict[str, Any]]: | |
| """بازیابی حافظههای هسته""" | |
| memories = [] | |
| query_lower = query.lower() | |
| for core_entry in self.memory_layers['core']: | |
| node = core_entry['node'] | |
| info = core_entry.get('info', {}) | |
| # بررسی تطابق با query | |
| relevance = 0.0 | |
| # تطابق با اطلاعات شخصی | |
| for key, value in info.items(): | |
| if isinstance(value, str) and value.lower() in query_lower: | |
| relevance = 0.9 | |
| break | |
| # تطابق با محتوای پیام | |
| if relevance == 0.0 and node.content.lower() in query_lower: | |
| relevance = 0.7 | |
| if relevance > 0.5: | |
| memories.append({ | |
| 'node': node, | |
| 'source': 'core', | |
| 'relevance': relevance, | |
| 'recency': 0.8, | |
| 'importance': 1.0, | |
| 'personal_info': info | |
| }) | |
| return memories | |
| def _deduplicate_memories(self, memories: List[Dict[str, Any]]) -> List[Dict[str, Any]]: | |
| """حذف حافظههای تکراری""" | |
| seen_ids = set() | |
| unique_memories = [] | |
| for memory in memories: | |
| node = memory.get('node') | |
| if node and node.id not in seen_ids: | |
| seen_ids.add(node.id) | |
| unique_memories.append(memory) | |
| return unique_memories | |
| def _prioritize_memories(self, memories: List[Dict[str, Any]], | |
| query_embedding: np.ndarray) -> List[Dict[str, Any]]: | |
| """اولویتبندی حافظههای بازیابی شده""" | |
| def calculate_priority(memory: Dict[str, Any]) -> float: | |
| """محاسبه اولویت برای یک حافظه""" | |
| priority = 0.0 | |
| # 1. ارتباط معنایی | |
| priority += memory.get('relevance', 0.0) * 0.4 | |
| # 2. تازگی | |
| priority += memory.get('recency', 0.0) * 0.3 | |
| # 3. اهمیت | |
| priority += memory.get('importance', 0.5) * 0.2 | |
| # 4. منبع (حافظه هسته اولویت بالاتری دارد) | |
| source = memory.get('source', '') | |
| if source == 'core': | |
| priority += 0.2 | |
| elif source == 'long_term': | |
| priority += 0.1 | |
| return priority | |
| # محاسبه اولویت و مرتبسازی | |
| prioritized = [] | |
| for memory in memories: | |
| priority = calculate_priority(memory) | |
| prioritized.append((priority, memory)) | |
| prioritized.sort(key=lambda x: x[0], reverse=True) | |
| return [memory for _, memory in prioritized] | |
| async def get_context_for_api(self, query: str = None) -> List[Dict[str, Any]]: | |
| """تهیه context برای ارسال به API""" | |
| # اگر query داریم، context هوشمند بازیابی کن | |
| if query: | |
| retrieved = await self.retrieve_context(query) | |
| # تبدیل به فرمت API | |
| api_messages = [] | |
| # ابتدا اطلاعات پروفایل کاربر | |
| api_messages.append({ | |
| 'role': 'system', | |
| 'content': f"User profile: {self._format_user_profile()}" | |
| }) | |
| # سپس حافظههای بازیابی شده | |
| for memory in retrieved: | |
| node = memory['node'] | |
| api_messages.append({ | |
| 'role': node.role, | |
| 'content': node.content | |
| }) | |
| return api_messages | |
| else: | |
| # حالت ساده: فقط حافظه فعال | |
| api_messages = [] | |
| for node in list(self.memory_layers['working'])[-6:]: | |
| api_messages.append({ | |
| 'role': node.role, | |
| 'content': node.content | |
| }) | |
| return api_messages | |
| def _format_user_profile(self) -> str: | |
| """قالببندی پروفایل کاربر برای سیستم""" | |
| profile_parts = [] | |
| if self.user_profile.interests: | |
| interests_str = ', '.join(list(self.user_profile.interests)[:5]) | |
| profile_parts.append(f"Interests: {interests_str}") | |
| if self.user_profile.preferences: | |
| prefs = list(self.user_profile.preferences.items())[:3] | |
| prefs_str = ', '.join(f"{k}: {v}" for k, v in prefs) | |
| profile_parts.append(f"Preferences: {prefs_str}") | |
| if self.user_profile.conversation_style: | |
| profile_parts.append(f"Conversation style: {self.user_profile.conversation_style}") | |
| if self.user_profile.learning_style: | |
| profile_parts.append(f"Learning style: {self.user_profile.learning_style}") | |
| if profile_parts: | |
| return ' | '.join(profile_parts) | |
| else: | |
| return "New user, minimal profile information available." | |
| def get_summary(self) -> Dict[str, Any]: | |
| """دریافت خلاصه وضعیت""" | |
| return { | |
| 'user_id': self.user_id, | |
| 'total_messages': self.stats['total_messages'], | |
| 'working_memory': len(self.memory_layers['working']), | |
| 'recent_memory': len(self.memory_layers['recent']), | |
| 'long_term_memory': len(self.memory_layers['long_term']), | |
| 'core_memory': len(self.memory_layers['core']), | |
| 'profile_interests': list(self.user_profile.interests)[:10], | |
| 'average_importance': self.stats['average_importance'], | |
| 'compression_ratio': self.stats.get('compressed_messages', 0) / max(self.stats['total_messages'], 1), | |
| 'retrieval_efficiency': self.stats.get('retrieved_memories', 0) / max(self.stats['total_messages'], 1) | |
| } | |
| def clear_context(self): | |
| """پاک کردن context کاربر""" | |
| self.memory_layers['working'].clear() | |
| self.memory_layers['ephemeral'].clear() | |
| # حافظه هسته و بلندمدت پاک نمیشوند | |
| logger.info(f"Cleared context for user {self.user_id}") | |
| def export_debug_info(self) -> Dict[str, Any]: | |
| """دریافت اطلاعات دیباگ""" | |
| return { | |
| 'memory_graph_size': len(self.memory_graph.nodes), | |
| 'memory_graph_connections': len(self.memory_graph.connections), | |
| 'user_profile': { | |
| 'interests_count': len(self.user_profile.interests), | |
| 'preferences_count': len(self.user_profile.preferences), | |
| 'personality_traits': dict(self.user_profile.personality_traits) | |
| }, | |
| 'layer_sizes': {k: len(v) for k, v in self.memory_layers.items()}, | |
| 'stats': dict(self.stats) | |
| } |