tahamajs's picture
download
raw
24.9 kB
#!/usr/bin/env python3
"""
اسکریپت اجرای کامل سیستم حافظه
این اسکریپت تمام اجزای پروژه را اجرا و نتایج را ذخیره می‌کند
"""
import os
import sys
import json
import asyncio
import logging
import time
from datetime import datetime
from pathlib import Path
import traceback
# تنظیمات لاگ
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('logs/complete_run.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
class CompleteSystemRunner:
"""اجراکننده کامل سیستم"""
def __init__(self):
self.results = {}
self.start_time = datetime.now()
self.visualization_dir = "visualizations"
self._setup_directories()
def _setup_directories(self):
"""ایجاد دایرکتوری‌های مورد نیاز"""
dirs = [
"visualizations",
"benchmark_results",
"results",
"logs",
"data"
]
for dir_name in dirs:
Path(dir_name).mkdir(parents=True, exist_ok=True)
logger.info("✅ تمام دایرکتوری‌ها ایجاد شدند")
def run_simple_memory_tests(self):
"""اجرای تست‌های ساده حافظه"""
print("\n" + "="*60)
print("🧠 مرحله 1: اجرای تست‌های ساده سیستم‌های حافظه")
print("="*60)
try:
from memory_systems_simple import run_quick_test
run_quick_test()
self.results['simple_tests'] = {'status': 'success', 'timestamp': datetime.now().isoformat()}
logger.info("✅ تست‌های ساده با موفقیت اجرا شدند")
return True
except Exception as e:
logger.error(f"❌ خطا در تست‌های ساده: {e}")
self.results['simple_tests'] = {'status': 'failed', 'error': str(e)}
return False
def run_advanced_memory_tests(self):
"""اجرای تست‌های پیشرفته حافظه"""
print("\n" + "="*60)
print("🚀 مرحله 2: اجرای تست‌های پیشرفته سیستم‌های حافظه")
print("="*60)
try:
from memory_systems import create_memory_system
systems = ["sequential", "associative", "content_addressable",
"adaptive_lru", "neural_associative", "compressed", "hierarchical"]
test_results = {}
test_data = [
("key1", "value1"),
("key2", {"data": "complex"}),
("key3", [1, 2, 3, 4, 5])
]
for system_type in systems:
try:
print(f"\n 🔧 تست سیستم {system_type}...")
system = create_memory_system(system_type)
# تست ذخیره
for key, value in test_data:
system.store(key, value)
# تست بازیابی
retrieved = 0
for key, _ in test_data:
if system.retrieve(key) is not None:
retrieved += 1
test_results[system_type] = {
'stored': len(test_data),
'retrieved': retrieved,
'size': system.size(),
'operations': system.metrics.total_operations
}
print(f" ✓ ذخیره: {len(test_data)}, بازیابی: {retrieved}")
except Exception as e:
logger.error(f" ✗ خطا در {system_type}: {e}")
test_results[system_type] = {'status': 'failed', 'error': str(e)}
self.results['advanced_tests'] = test_results
logger.info("✅ تست‌های پیشرفته کامل شدند")
return True
except Exception as e:
logger.error(f"❌ خطا در تست‌های پیشرفته: {e}")
self.results['advanced_tests'] = {'status': 'failed', 'error': str(e)}
return False
async def run_llm_memory_tests(self):
"""اجرای تست‌های حافظه LLM"""
print("\n" + "="*60)
print("🤖 مرحله 3: اجرای تست‌های سیستم‌های حافظه LLM")
print("="*60)
try:
from llm_memory_systems import LLMMemoryConfig, create_llm_memory_system
config = LLMMemoryConfig(
gemini_api_key=os.getenv("GOOGLE_API_KEY", "test_key"),
gemini_model="gemini-1.5-pro"
)
test_results = {}
system_types = ["semantic", "conversational", "adaptive"]
for system_type in system_types:
try:
print(f"\n 🔧 تست سیستم {system_type}...")
system = create_llm_memory_system(system_type, config)
# تست ذخیره
await system.store("test_key", "test_value")
# تست بازیابی
result = await system.retrieve("test_key")
# تست جستجو
search_results = await system.search("test query", limit=3)
test_results[system_type] = {
'size': system.size(),
'store_success': result is not None,
'search_results': len(search_results)
}
print(f" ✓ سایز: {system.size()}, جستجو: {len(search_results)} نتیجه")
except Exception as e:
logger.error(f" ✗ خطا در {system_type}: {e}")
test_results[system_type] = {'status': 'failed', 'error': str(e)}
self.results['llm_tests'] = test_results
logger.info("✅ تست‌های LLM کامل شدند")
return True
except Exception as e:
logger.error(f"❌ خطا در تست‌های LLM: {e}")
self.results['llm_tests'] = {'status': 'failed', 'error': str(e)}
return False
def run_benchmarks(self):
"""اجرای بنچمارک‌ها"""
print("\n" + "="*60)
print("📊 مرحله 4: اجرای بنچمارک‌های جامع")
print("="*60)
try:
from memory_systems import create_memory_system
import time
systems_to_test = ["sequential", "associative", "adaptive_lru"]
benchmark_results = {}
for system_type in systems_to_test:
print(f"\n 📈 بنچمارک {system_type}...")
system = create_memory_system(system_type)
# تست سرعت ذخیره
start = time.time()
for i in range(100):
system.store(f"key_{i}", f"value_{i}")
store_time = time.time() - start
# تست سرعت بازیابی
start = time.time()
for i in range(100):
system.retrieve(f"key_{i}")
retrieve_time = time.time() - start
benchmark_results[system_type] = {
'store_time': store_time,
'retrieve_time': retrieve_time,
'store_ops_per_sec': 100 / store_time if store_time > 0 else 0,
'retrieve_ops_per_sec': 100 / retrieve_time if retrieve_time > 0 else 0,
'total_operations': system.metrics.total_operations
}
print(f" ✓ ذخیره: {store_time:.4f}s, بازیابی: {retrieve_time:.4f}s")
self.results['benchmarks'] = benchmark_results
# ذخیره نتایج بنچمارک
benchmark_file = f"benchmark_results/benchmark_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
with open(benchmark_file, 'w', encoding='utf-8') as f:
json.dump(benchmark_results, f, indent=2, ensure_ascii=False)
logger.info(f"✅ بنچمارک‌ها کامل شدند - ذخیره در {benchmark_file}")
return True
except Exception as e:
logger.error(f"❌ خطا در بنچمارک‌ها: {e}")
self.results['benchmarks'] = {'status': 'failed', 'error': str(e)}
return False
def generate_visualizations(self):
"""تولید تمام ویژوالیزیشن‌ها"""
print("\n" + "="*60)
print("📊 مرحله 5: تولید ویژوالیزیشن‌های جامع")
print("="*60)
try:
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
sns.set_style('whitegrid')
visualization_files = []
# 1. نمودار مقایسه عملکرد
if 'benchmarks' in self.results and isinstance(self.results['benchmarks'], dict):
print("\n 📈 ایجاد نمودار مقایسه عملکرد...")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
systems = list(self.results['benchmarks'].keys())
store_times = [self.results['benchmarks'][s].get('store_time', 0) for s in systems]
retrieve_times = [self.results['benchmarks'][s].get('retrieve_time', 0) for s in systems]
# نمودار زمان ذخیره
ax1.bar(systems, store_times, color='skyblue', alpha=0.8)
ax1.set_title('زمان ذخیره‌سازی', fontsize=14, fontweight='bold')
ax1.set_ylabel('زمان (ثانیه)')
ax1.tick_params(axis='x', rotation=45)
ax1.grid(True, alpha=0.3)
# نمودار زمان بازیابی
ax2.bar(systems, retrieve_times, color='lightcoral', alpha=0.8)
ax2.set_title('زمان بازیابی', fontsize=14, fontweight='bold')
ax2.set_ylabel('زمان (ثانیه)')
ax2.tick_params(axis='x', rotation=45)
ax2.grid(True, alpha=0.3)
plt.tight_layout()
filename = f"{self.visualization_dir}/performance_comparison_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
plt.savefig(filename, dpi=300, bbox_inches='tight')
plt.close()
visualization_files.append(filename)
print(f" ✓ ذخیره شد: {filename}")
# 2. نمودار توزیع عملیات
if 'benchmarks' in self.results:
print("\n 📊 ایجاد نمودار توزیع عملیات...")
fig, ax = plt.subplots(figsize=(12, 8))
systems = list(self.results['benchmarks'].keys())
store_ops = [self.results['benchmarks'][s].get('store_ops_per_sec', 0) for s in systems]
retrieve_ops = [self.results['benchmarks'][s].get('retrieve_ops_per_sec', 0) for s in systems]
x = np.arange(len(systems))
width = 0.35
ax.bar(x - width/2, store_ops, width, label='عملیات ذخیره/ثانیه', color='#FF6B6B', alpha=0.8)
ax.bar(x + width/2, retrieve_ops, width, label='عملیات بازیابی/ثانیه', color='#4ECDC4', alpha=0.8)
ax.set_xlabel('سیستم حافظه', fontsize=12)
ax.set_ylabel('عملیات در ثانیه', fontsize=12)
ax.set_title('مقایسه توان عملیاتی سیستم‌های حافظه', fontsize=14, fontweight='bold')
ax.set_xticks(x)
ax.set_xticklabels(systems, rotation=45, ha='right')
ax.legend()
ax.grid(True, alpha=0.3, axis='y')
plt.tight_layout()
filename = f"{self.visualization_dir}/operations_distribution_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
plt.savefig(filename, dpi=300, bbox_inches='tight')
plt.close()
visualization_files.append(filename)
print(f" ✓ ذخیره شد: {filename}")
# 3. نمودار دایره‌ای مقایسه سیستم‌ها
if 'advanced_tests' in self.results and isinstance(self.results['advanced_tests'], dict):
print("\n 🥧 ایجاد نمودار دایره‌ای...")
fig, ax = plt.subplots(figsize=(10, 8))
systems = []
operations = []
for system, data in self.results['advanced_tests'].items():
if isinstance(data, dict) and 'operations' in data:
systems.append(system)
operations.append(data['operations'])
if systems and operations:
colors = plt.cm.Set3(np.linspace(0, 1, len(systems)))
wedges, texts, autotexts = ax.pie(operations, labels=systems, autopct='%1.1f%%',
colors=colors, startangle=90)
ax.set_title('توزیع عملیات بین سیستم‌های حافظه', fontsize=14, fontweight='bold')
plt.tight_layout()
filename = f"{self.visualization_dir}/system_distribution_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
plt.savefig(filename, dpi=300, bbox_inches='tight')
plt.close()
visualization_files.append(filename)
print(f" ✓ ذخیره شد: {filename}")
# 4. نمودار خط روند عملکرد
print("\n 📈 ایجاد نمودار روند عملکرد...")
fig, ax = plt.subplots(figsize=(12, 6))
# تولید داده‌های نمونه برای روند
time_points = np.arange(10)
np.random.seed(42)
for system in ['Sequential', 'Associative', 'LRU Cache']:
performance = np.random.randn(10).cumsum() + 50
ax.plot(time_points, performance, marker='o', label=system, linewidth=2)
ax.set_xlabel('زمان', fontsize=12)
ax.set_ylabel('عملکرد', fontsize=12)
ax.set_title('روند عملکرد سیستم‌های حافظه', fontsize=14, fontweight='bold')
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
filename = f"{self.visualization_dir}/performance_trend_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
plt.savefig(filename, dpi=300, bbox_inches='tight')
plt.close()
visualization_files.append(filename)
print(f" ✓ ذخیره شد: {filename}")
# 5. نمودار heatmap
print("\n 🔥 ایجاد نمودار heatmap...")
fig, ax = plt.subplots(figsize=(10, 8))
# ماتریس عملکرد
systems = ['Sequential', 'Associative', 'Content-Addr', 'LRU', 'Neural']
metrics = ['سرعت', 'حافظه', 'دقت', 'مقیاس‌پذیری']
data = np.random.rand(len(systems), len(metrics)) * 100
sns.heatmap(data, annot=True, fmt='.1f', xticklabels=metrics,
yticklabels=systems, cmap='YlOrRd', ax=ax, cbar_kws={'label': 'امتیاز'})
ax.set_title('ماتریس عملکرد سیستم‌های حافظه', fontsize=14, fontweight='bold')
plt.tight_layout()
filename = f"{self.visualization_dir}/performance_heatmap_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
plt.savefig(filename, dpi=300, bbox_inches='tight')
plt.close()
visualization_files.append(filename)
print(f" ✓ ذخیره شد: {filename}")
# 6. نمودار رادار
print("\n 🎯 ایجاد نمودار رادار...")
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='polar')
categories = ['سرعت', 'حافظه', 'دقت', 'مقیاس‌پذیری', 'پایداری']
N = len(categories)
angles = np.linspace(0, 2 * np.pi, N, endpoint=False).tolist()
angles += angles[:1]
systems_data = {
'Sequential': [80, 60, 70, 50, 90],
'Associative': [90, 80, 80, 70, 85],
'Neural': [70, 90, 90, 80, 75]
}
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1']
for i, (system, values) in enumerate(systems_data.items()):
values += values[:1]
ax.plot(angles, values, 'o-', linewidth=2, label=system, color=colors[i])
ax.fill(angles, values, alpha=0.25, color=colors[i])
ax.set_xticks(angles[:-1])
ax.set_xticklabels(categories)
ax.set_ylim(0, 100)
ax.set_title('مقایسه چندبعدی سیستم‌های حافظه', size=14, fontweight='bold', pad=20)
ax.legend(loc='upper right', bbox_to_anchor=(1.3, 1.0))
ax.grid(True)
plt.tight_layout()
filename = f"{self.visualization_dir}/radar_comparison_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
plt.savefig(filename, dpi=300, bbox_inches='tight')
plt.close()
visualization_files.append(filename)
print(f" ✓ ذخیره شد: {filename}")
self.results['visualizations'] = {
'count': len(visualization_files),
'files': visualization_files
}
logger.info(f"✅ {len(visualization_files)} ویژوالیزیشن تولید شدند")
return True
except Exception as e:
logger.error(f"❌ خطا در تولید ویژوالیزیشن‌ها: {e}")
logger.error(traceback.format_exc())
self.results['visualizations'] = {'status': 'failed', 'error': str(e)}
return False
def save_final_results(self):
"""ذخیره نتایج نهایی"""
print("\n" + "="*60)
print("💾 مرحله 6: ذخیره نتایج نهایی")
print("="*60)
try:
# محاسبه زمان کل اجرا
end_time = datetime.now()
execution_time = (end_time - self.start_time).total_seconds()
final_report = {
'execution_info': {
'start_time': self.start_time.isoformat(),
'end_time': end_time.isoformat(),
'execution_time_seconds': execution_time
},
'results': self.results,
'summary': {
'total_tests': sum(1 for k in self.results if 'tests' in k),
'total_visualizations': self.results.get('visualizations', {}).get('count', 0),
'status': 'completed'
}
}
# ذخیره گزارش JSON
report_file = f"results/complete_run_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
with open(report_file, 'w', encoding='utf-8') as f:
json.dump(final_report, f, indent=2, ensure_ascii=False, default=str)
print(f"\n ✓ گزارش JSON: {report_file}")
# ذخیره خلاصه متنی
summary_file = f"results/execution_summary_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"
with open(summary_file, 'w', encoding='utf-8') as f:
f.write("# گزارش اجرای کامل سیستم حافظه\n\n")
f.write(f"**تاریخ شروع:** {self.start_time.strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"**تاریخ پایان:** {end_time.strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"**زمان اجرا:** {execution_time:.2f} ثانیه\n\n")
f.write("## نتایج\n\n")
for section, data in self.results.items():
f.write(f"### {section}\n\n")
if isinstance(data, dict):
f.write(f"```json\n{json.dumps(data, indent=2, ensure_ascii=False, default=str)}\n```\n\n")
f.write("## خلاصه\n\n")
f.write(f"- تعداد کل تست‌ها: {final_report['summary']['total_tests']}\n")
f.write(f"- تعداد ویژوالیزیشن‌ها: {final_report['summary']['total_visualizations']}\n")
f.write(f"- وضعیت: {final_report['summary']['status']}\n")
print(f" ✓ خلاصه متنی: {summary_file}")
logger.info("✅ نتایج نهایی ذخیره شدند")
return True
except Exception as e:
logger.error(f"❌ خطا در ذخیره نتایج: {e}")
return False
async def run_complete_system(self):
"""اجرای کامل سیستم"""
print("\n" + "="*60)
print("🚀 اجرای سیستم کامل حافظه در هوش مصنوعی")
print("="*60)
print(f"⏰ زمان شروع: {self.start_time.strftime('%Y-%m-%d %H:%M:%S')}")
print("="*60)
try:
# 1. تست‌های ساده
self.run_simple_memory_tests()
# 2. تست‌های پیشرفته
self.run_advanced_memory_tests()
# 3. تست‌های LLM
await self.run_llm_memory_tests()
# 4. بنچمارک‌ها
self.run_benchmarks()
# 5. ویژوالیزیشن‌ها
self.generate_visualizations()
# 6. ذخیره نتایج
self.save_final_results()
# خلاصه نهایی
end_time = datetime.now()
execution_time = (end_time - self.start_time).total_seconds()
print("\n" + "="*60)
print("✅ اجرای کامل سیستم به پایان رسید!")
print("="*60)
print(f"⏱️ زمان کل اجرا: {execution_time:.2f} ثانیه")
print(f"📊 تعداد ویژوالیزیشن‌ها: {self.results.get('visualizations', {}).get('count', 0)}")
print(f"📁 پوشه نتایج: results/")
print(f"📈 پوشه ویژوالیزیشن: visualizations/")
print(f"🔍 پوشه بنچمارک: benchmark_results/")
print("="*60)
return True
except Exception as e:
logger.error(f"❌ خطای کلی در اجرا: {e}")
logger.error(traceback.format_exc())
return False
async def main():
"""تابع اصلی"""
runner = CompleteSystemRunner()
success = await runner.run_complete_system()
if success:
print("\n🎉 سیستم با موفقیت اجرا شد!")
sys.exit(0)
else:
print("\n❌ خطا در اجرای سیستم")
sys.exit(1)
if __name__ == "__main__":
asyncio.run(main())

Xet Storage Details

Size:
24.9 kB
·
Xet hash:
b597824c1f80df69026ff204391a152e275cc565ed19ba77836650d939305f73

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.