Spaces:
Sleeping
Sleeping
Update utils/memory_utils.py
Browse files- utils/memory_utils.py +24 -24
utils/memory_utils.py
CHANGED
|
@@ -13,6 +13,7 @@ except ImportError:
|
|
| 13 |
pass
|
| 14 |
|
| 15 |
# Local Imports setup
|
|
|
|
| 16 |
bank_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../memory_bank')
|
| 17 |
sys.path.append(bank_path)
|
| 18 |
|
|
@@ -24,7 +25,7 @@ except ImportError:
|
|
| 24 |
def summarize_memory(*args, **kwargs): return {}
|
| 25 |
|
| 26 |
# ==========================================
|
| 27 |
-
# 1. تنظیمات مسیر و هاب (Cloud Config)
|
| 28 |
# ==========================================
|
| 29 |
|
| 30 |
# !!! مهم: نام کاربری و دیتاست خود را اینجا وارد کنید !!!
|
|
@@ -34,8 +35,9 @@ REPO_TYPE = "dataset"
|
|
| 34 |
# دریافت توکن
|
| 35 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
|
|
|
| 39 |
MEMORIES_DIR = os.path.join(BASE_DIR, "memories")
|
| 40 |
|
| 41 |
# فایل اصلی JSON
|
|
@@ -46,8 +48,14 @@ MEMORY_FILE_PATH = os.path.join(MEMORIES_DIR, MEMORY_FILE_NAME)
|
|
| 46 |
MEMORY_INDEX_DIR_NAME = "memory_index"
|
| 47 |
MEMORY_INDEX_PATH = os.path.join(MEMORIES_DIR, MEMORY_INDEX_DIR_NAME)
|
| 48 |
|
| 49 |
-
# اطمینان از وجود پوشه در زمان ا
|
| 50 |
os.makedirs(MEMORIES_DIR, exist_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
|
| 53 |
# ==========================================
|
|
@@ -84,10 +92,9 @@ def push_to_hub():
|
|
| 84 |
if os.path.exists(MEMORY_INDEX_PATH):
|
| 85 |
# الف) لیست کردن فایلها برای اطمینان از وجود داشتن
|
| 86 |
files_count = sum([len(files) for r, d, files in os.walk(MEMORY_INDEX_PATH)])
|
| 87 |
-
print(f"📂 Found {files_count} files in local index folder. Preparing to upload...")
|
| 88 |
|
| 89 |
# ب) ساخت یک فایل موقت برای فریب دادن سیستم جهت تشخیص تغییر
|
| 90 |
-
# این کار باعث میشود هش پوشه تغییر کند و آپلود انجام شود
|
| 91 |
timestamp_file = os.path.join(MEMORY_INDEX_PATH, "last_sync_log.txt")
|
| 92 |
with open(timestamp_file, "w") as f:
|
| 93 |
f.write(f"Sync triggered at: {time.time()}")
|
|
@@ -99,7 +106,7 @@ def push_to_hub():
|
|
| 99 |
repo_id=REPO_ID,
|
| 100 |
repo_type=REPO_TYPE,
|
| 101 |
commit_message=f"Auto-save Indices (Forced): {time.strftime('%Y-%m-%d %H:%M:%S')}",
|
| 102 |
-
ignore_patterns=[".DS_Store", "*.git*"]
|
| 103 |
)
|
| 104 |
|
| 105 |
print(f"✅ Synced all data to Hub Successfully.")
|
|
@@ -133,8 +140,7 @@ def pull_from_hub():
|
|
| 133 |
else:
|
| 134 |
print("🆕 Memory JSON not found on Hub. Creating fresh.")
|
| 135 |
|
| 136 |
-
# B) دانلود پوشه ایندکسها
|
| 137 |
-
# بررسی میکنیم آیا پوشه memory_index در فایلهای ریپو هست یا نه
|
| 138 |
has_index = any(f.startswith(MEMORY_INDEX_DIR_NAME) for f in files)
|
| 139 |
|
| 140 |
if has_index:
|
|
@@ -143,8 +149,8 @@ def pull_from_hub():
|
|
| 143 |
repo_id=REPO_ID,
|
| 144 |
repo_type=REPO_TYPE,
|
| 145 |
local_dir=MEMORIES_DIR,
|
| 146 |
-
allow_patterns=f"{MEMORY_INDEX_DIR_NAME}/**",
|
| 147 |
-
force_download=True
|
| 148 |
)
|
| 149 |
print("✅ Indices downloaded.")
|
| 150 |
else:
|
|
@@ -187,7 +193,6 @@ def load_memory():
|
|
| 187 |
# 2. Local Read / Create
|
| 188 |
if not os.path.exists(MEMORY_FILE_PATH):
|
| 189 |
print(f"⚠️ Memory file missing locally. Creating new.")
|
| 190 |
-
# فایل خالی میسازیم اما هنوز آپلود نمیکنیم تا وقتی دیتایی بیاید
|
| 191 |
with open(MEMORY_FILE_PATH, "w", encoding="utf-8") as f:
|
| 192 |
json.dump({}, f)
|
| 193 |
return {}
|
|
@@ -210,7 +215,6 @@ def load_memory():
|
|
| 210 |
def enter_name_llamaindex(name, memory_data, data_args, update_memory_index=True):
|
| 211 |
is_new_user = False
|
| 212 |
|
| 213 |
-
# اطمینان از وجود ساختار کاربر در دیکشنری
|
| 214 |
if name not in memory_data:
|
| 215 |
print(f"🆕 Creating new user profile for: {name}")
|
| 216 |
memory_data[name] = {
|
|
@@ -221,7 +225,6 @@ def enter_name_llamaindex(name, memory_data, data_args, update_memory_index=True
|
|
| 221 |
"profile": {}
|
| 222 |
}
|
| 223 |
is_new_user = True
|
| 224 |
-
# اگر کاربر جدید است، همان اول فایل جیسون را ذخیره کن
|
| 225 |
save_memory(memory_data)
|
| 226 |
|
| 227 |
user_memory = memory_data[name]
|
|
@@ -231,35 +234,37 @@ def enter_name_llamaindex(name, memory_data, data_args, update_memory_index=True
|
|
| 231 |
episodic_memory = None
|
| 232 |
semantic_memory = None
|
| 233 |
|
|
|
|
| 234 |
base_index_dir = os.path.join(MEMORY_INDEX_PATH, "llamaindex", name)
|
| 235 |
|
| 236 |
sessions_path = os.path.join(base_index_dir, "sessions_index.json")
|
| 237 |
episodic_path = os.path.join(base_index_dir, "episodic_memory_index.json")
|
| 238 |
semantic_path = os.path.join(base_index_dir, "semantic_memory_index.json")
|
| 239 |
|
| 240 |
-
# بررسی اینکه آیا فایلهای ایندکس به صورت لوکال وجود دارند (یا از ابر دانلود شدهاند)
|
| 241 |
indices_exist = (
|
| 242 |
os.path.exists(sessions_path) and
|
| 243 |
os.path.exists(episodic_path) and
|
| 244 |
os.path.exists(semantic_path)
|
| 245 |
)
|
| 246 |
|
| 247 |
-
# اگر ایندکس وجود ندارد یا درخواست آپدیت داریم، بسازیم
|
| 248 |
if update_memory_index or not indices_exist:
|
| 249 |
try:
|
| 250 |
print(f"⚙️ Building/Updating indices locally for {name}...")
|
|
|
|
| 251 |
os.makedirs(base_index_dir, exist_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
build_memory_index(memory_data, data_args, name=name)
|
| 253 |
|
| 254 |
-
# **نکته مهم:** الان که فایلهای ایندکس ساخته شدند، باید آنها را به ابر بفرستیم
|
| 255 |
-
# تا اگر سرور ریستارت شد، این فایلها نپرند.
|
| 256 |
print("☁️ Syncing new indices to cloud...")
|
| 257 |
push_to_hub()
|
| 258 |
|
| 259 |
except Exception as e:
|
| 260 |
print(f"Warning: Error building memory index (skipping): {e}")
|
| 261 |
|
| 262 |
-
# بارگذاری ایندکسها
|
| 263 |
if os.path.exists(sessions_path):
|
| 264 |
try:
|
| 265 |
storage_context = StorageContext.from_defaults(persist_dir=sessions_path)
|
|
@@ -282,16 +287,11 @@ def enter_name_llamaindex(name, memory_data, data_args, update_memory_index=True
|
|
| 282 |
|
| 283 |
|
| 284 |
def summarize_memory_event_personality(data_args, memory_data, user_name):
|
| 285 |
-
# قبل از عملیات سنگین، وضعیت فعلی را ذخیره کن
|
| 286 |
save_memory(memory_data)
|
| 287 |
|
| 288 |
try:
|
| 289 |
-
# این تابع احتمالا فایلهای ایندکس را تغییر میدهد
|
| 290 |
updated_memory = summarize_memory(MEMORY_FILE_PATH, user_name, language='en')
|
| 291 |
-
|
| 292 |
-
# چون خلاصه سازی ممکن است ایندکسها را تغییر دهد، یک سینک نهایی انجام میدهیم
|
| 293 |
push_to_hub()
|
| 294 |
-
|
| 295 |
return updated_memory.get(user_name, {})
|
| 296 |
except Exception as e:
|
| 297 |
print(f"Error in summarize_memory: {e}")
|
|
|
|
| 13 |
pass
|
| 14 |
|
| 15 |
# Local Imports setup
|
| 16 |
+
# مسیر برای ایمپورت کردن فایلهای کمکی
|
| 17 |
bank_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../memory_bank')
|
| 18 |
sys.path.append(bank_path)
|
| 19 |
|
|
|
|
| 25 |
def summarize_memory(*args, **kwargs): return {}
|
| 26 |
|
| 27 |
# ==========================================
|
| 28 |
+
# 1. تنظیمات مسیر و هاب (Cloud Config) - اصلاح شده
|
| 29 |
# ==========================================
|
| 30 |
|
| 31 |
# !!! مهم: نام کاربری و دیتاست خود را اینجا وارد کنید !!!
|
|
|
|
| 35 |
# دریافت توکن
|
| 36 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 37 |
|
| 38 |
+
# --- اصلاح مسیرها به Absolute Path ---
|
| 39 |
+
# استفاده از os.getcwd() تضمین میکند مسیر همیشه /app/memories است
|
| 40 |
+
BASE_DIR = os.path.abspath(os.getcwd())
|
| 41 |
MEMORIES_DIR = os.path.join(BASE_DIR, "memories")
|
| 42 |
|
| 43 |
# فایل اصلی JSON
|
|
|
|
| 48 |
MEMORY_INDEX_DIR_NAME = "memory_index"
|
| 49 |
MEMORY_INDEX_PATH = os.path.join(MEMORIES_DIR, MEMORY_INDEX_DIR_NAME)
|
| 50 |
|
| 51 |
+
# اطمینان از وجود پوشه در زمان اجرا
|
| 52 |
os.makedirs(MEMORIES_DIR, exist_ok=True)
|
| 53 |
+
os.makedirs(MEMORY_INDEX_PATH, exist_ok=True)
|
| 54 |
+
|
| 55 |
+
print(f"📂 System Paths Configuration:")
|
| 56 |
+
print(f" - Base Dir: {BASE_DIR}")
|
| 57 |
+
print(f" - Memories Dir: {MEMORIES_DIR}")
|
| 58 |
+
print(f" - Index Path: {MEMORY_INDEX_PATH}")
|
| 59 |
|
| 60 |
|
| 61 |
# ==========================================
|
|
|
|
| 92 |
if os.path.exists(MEMORY_INDEX_PATH):
|
| 93 |
# الف) لیست کردن فایلها برای اطمینان از وجود داشتن
|
| 94 |
files_count = sum([len(files) for r, d, files in os.walk(MEMORY_INDEX_PATH)])
|
| 95 |
+
print(f"📂 Found {files_count} files in local index folder ({MEMORY_INDEX_PATH}). Preparing to upload...")
|
| 96 |
|
| 97 |
# ب) ساخت یک فایل موقت برای فریب دادن سیستم جهت تشخیص تغییر
|
|
|
|
| 98 |
timestamp_file = os.path.join(MEMORY_INDEX_PATH, "last_sync_log.txt")
|
| 99 |
with open(timestamp_file, "w") as f:
|
| 100 |
f.write(f"Sync triggered at: {time.time()}")
|
|
|
|
| 106 |
repo_id=REPO_ID,
|
| 107 |
repo_type=REPO_TYPE,
|
| 108 |
commit_message=f"Auto-save Indices (Forced): {time.strftime('%Y-%m-%d %H:%M:%S')}",
|
| 109 |
+
ignore_patterns=[".DS_Store", "*.git*"]
|
| 110 |
)
|
| 111 |
|
| 112 |
print(f"✅ Synced all data to Hub Successfully.")
|
|
|
|
| 140 |
else:
|
| 141 |
print("🆕 Memory JSON not found on Hub. Creating fresh.")
|
| 142 |
|
| 143 |
+
# B) دانلود پوشه ایندکسها
|
|
|
|
| 144 |
has_index = any(f.startswith(MEMORY_INDEX_DIR_NAME) for f in files)
|
| 145 |
|
| 146 |
if has_index:
|
|
|
|
| 149 |
repo_id=REPO_ID,
|
| 150 |
repo_type=REPO_TYPE,
|
| 151 |
local_dir=MEMORIES_DIR,
|
| 152 |
+
allow_patterns=f"{MEMORY_INDEX_DIR_NAME}/**",
|
| 153 |
+
force_download=True
|
| 154 |
)
|
| 155 |
print("✅ Indices downloaded.")
|
| 156 |
else:
|
|
|
|
| 193 |
# 2. Local Read / Create
|
| 194 |
if not os.path.exists(MEMORY_FILE_PATH):
|
| 195 |
print(f"⚠️ Memory file missing locally. Creating new.")
|
|
|
|
| 196 |
with open(MEMORY_FILE_PATH, "w", encoding="utf-8") as f:
|
| 197 |
json.dump({}, f)
|
| 198 |
return {}
|
|
|
|
| 215 |
def enter_name_llamaindex(name, memory_data, data_args, update_memory_index=True):
|
| 216 |
is_new_user = False
|
| 217 |
|
|
|
|
| 218 |
if name not in memory_data:
|
| 219 |
print(f"🆕 Creating new user profile for: {name}")
|
| 220 |
memory_data[name] = {
|
|
|
|
| 225 |
"profile": {}
|
| 226 |
}
|
| 227 |
is_new_user = True
|
|
|
|
| 228 |
save_memory(memory_data)
|
| 229 |
|
| 230 |
user_memory = memory_data[name]
|
|
|
|
| 234 |
episodic_memory = None
|
| 235 |
semantic_memory = None
|
| 236 |
|
| 237 |
+
# استفاده از مسیر مطلق برای ساخت آدرس ایندکس
|
| 238 |
base_index_dir = os.path.join(MEMORY_INDEX_PATH, "llamaindex", name)
|
| 239 |
|
| 240 |
sessions_path = os.path.join(base_index_dir, "sessions_index.json")
|
| 241 |
episodic_path = os.path.join(base_index_dir, "episodic_memory_index.json")
|
| 242 |
semantic_path = os.path.join(base_index_dir, "semantic_memory_index.json")
|
| 243 |
|
|
|
|
| 244 |
indices_exist = (
|
| 245 |
os.path.exists(sessions_path) and
|
| 246 |
os.path.exists(episodic_path) and
|
| 247 |
os.path.exists(semantic_path)
|
| 248 |
)
|
| 249 |
|
|
|
|
| 250 |
if update_memory_index or not indices_exist:
|
| 251 |
try:
|
| 252 |
print(f"⚙️ Building/Updating indices locally for {name}...")
|
| 253 |
+
# اطمینان از وجود پوشه قبل از ساخت
|
| 254 |
os.makedirs(base_index_dir, exist_ok=True)
|
| 255 |
+
|
| 256 |
+
# نکته مهم: اگر build_memory_index از مسیرهای نسبی استفاده کند،
|
| 257 |
+
# باید فایل build_memory_index.py هم بررسی شود.
|
| 258 |
+
# اما اینجا فرض میکنیم مسیرها را از آرگومانها یا گلوبالهای صحیح میگیرد.
|
| 259 |
build_memory_index(memory_data, data_args, name=name)
|
| 260 |
|
|
|
|
|
|
|
| 261 |
print("☁️ Syncing new indices to cloud...")
|
| 262 |
push_to_hub()
|
| 263 |
|
| 264 |
except Exception as e:
|
| 265 |
print(f"Warning: Error building memory index (skipping): {e}")
|
| 266 |
|
| 267 |
+
# بارگذاری ایندکسها
|
| 268 |
if os.path.exists(sessions_path):
|
| 269 |
try:
|
| 270 |
storage_context = StorageContext.from_defaults(persist_dir=sessions_path)
|
|
|
|
| 287 |
|
| 288 |
|
| 289 |
def summarize_memory_event_personality(data_args, memory_data, user_name):
|
|
|
|
| 290 |
save_memory(memory_data)
|
| 291 |
|
| 292 |
try:
|
|
|
|
| 293 |
updated_memory = summarize_memory(MEMORY_FILE_PATH, user_name, language='en')
|
|
|
|
|
|
|
| 294 |
push_to_hub()
|
|
|
|
| 295 |
return updated_memory.get(user_name, {})
|
| 296 |
except Exception as e:
|
| 297 |
print(f"Error in summarize_memory: {e}")
|