ysn-rfd/text-dataset-tiny-code-script-py-format
USED of tahamajs/medicine_ds_persian for .parquet file USED of Alijafarixcs2/persian-it-llama2-2k for .parquet file USED of Abirate/english_quotes for .jsonl file NEW FILES (05/12/2025) NEW FILES (12/26/2025) NEW FILES (02/15/2026)
31.7k
1# main.py2 3import os4import logging5import asyncio6import httpx7import time8from datetime import datetime9from telegram import Update10from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes11from openai import AsyncOpenAI12from keep_alive import start_keep_alive13 14# وارد کردن مدیر دادهها و پنل ادمین15import data_manager16import admin_panel17 18# شروع سرویس نگه داشتن ربات فعال19start_keep_alive()20 21# --- بهبود لاگینگ ---22logging.basicConfig(23 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", 24 level=logging.INFO,25 filename=data_manager.LOG_FILE, 26 filemode='a'27)28logger = logging.getLogger(__name__)29 30try:31 with open(data_manager.LOG_FILE, 'a') as f:32 f.write("")33except Exception as e:34 print(f"FATAL: Could not write to log file at {data_manager.LOG_FILE}. Error: {e}")35 logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")36 37# --- ایجاد یک کلاینت HTTP بهینهسازیشده ---38http_client = httpx.AsyncClient(39 http2=True,40 limits=httpx.Limits(max_keepalive_connections=20, max_connections=100, keepalive_expiry=30.0),41 timeout=httpx.Timeout(timeout=60.0, connect=10.0, read=45.0, write=10.0)42)43 44# کلاینت OpenAI (HuggingFace)45client = AsyncOpenAI(46 base_url="https://router.huggingface.co/v1",47 api_key=os.environ["HF_TOKEN"],48 http_client=http_client49)50 51# --- سیستم Context هوشمند ---52try:53 from smart_context import IntelligentContextManager54 HAS_SMART_CONTEXT = True55 logger.info("Smart context module loaded successfully")56except ImportError as e:57 HAS_SMART_CONTEXT = False58 logger.warning(f"Smart context module not available: {e}. Using basic context.")59 60# --- دیکشنری برای مدیریت وظایف پسزمینه هر کاربر ---61user_tasks = {}62 63# --- دیکشنری برای مدیران Context هوشمند ---64smart_context_managers = {}65 66# --- توابع کمکی برای مدیریت وظایف ---67def _cleanup_task(task: asyncio.Task, user_id: int):68 if user_id in user_tasks and user_tasks[user_id] == task:69 del user_tasks[user_id]70 logger.info(f"Cleaned up finished task for user {user_id}.")71 try:72 exception = task.exception()73 if exception:74 logger.error(f"Background task for user {user_id} failed: {exception}")75 except asyncio.CancelledError:76 logger.info(f"Task for user {user_id} was cancelled.")77 78def _get_or_create_smart_context(user_id: int) -> IntelligentContextManager:79 """دریافت یا ایجاد مدیر Context هوشمند برای کاربر"""80 if user_id not in smart_context_managers:81 smart_context_managers[user_id] = IntelligentContextManager(user_id)82 return smart_context_managers[user_id]83 84async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE):85 chat_id = update.effective_chat.id86 user_message = update.message.text87 user_id = update.effective_user.id88 89 start_time = time.time()90 91 try:92 await context.bot.send_chat_action(chat_id=chat_id, action="typing")93 94 # استفاده از Context هوشمند اگر فعال باشد95 if HAS_SMART_CONTEXT:96 smart_context = _get_or_create_smart_context(user_id)97 98 # پردازش پیام کاربر با سیستم هوشمند99 await smart_context.process_message("user", user_message)100 101 # بازیابی context مرتبط102 retrieved_context = await smart_context.retrieve_context(user_message, max_tokens=1024)103 104 # آمادهسازی پیامها برای API105 messages = await smart_context.get_context_for_api(user_message)106 107 logger.info(f"Smart context: {len(messages)} messages retrieved for user {user_id}")108 else:109 # استفاده از سیستم قدیمی110 user_context = data_manager.get_context_for_api(user_id)111 data_manager.add_to_user_context(user_id, "user", user_message)112 messages = user_context.copy()113 messages.append({"role": "user", "content": user_message})114 115 # ارسال به API116 response = await client.chat.completions.create(117 model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",118 messages=messages,119 temperature=0.7,120 top_p=0.95,121 stream=False,122 )123 124 end_time = time.time()125 response_time = end_time - start_time126 data_manager.update_response_stats(response_time)127 128 ai_response = response.choices[0].message.content129 130 # ذخیره پاسخ در سیستم مناسب131 if HAS_SMART_CONTEXT:132 await smart_context.process_message("assistant", ai_response)133 else:134 data_manager.add_to_user_context(user_id, "assistant", ai_response)135 136 await update.message.reply_text(ai_response)137 data_manager.update_user_stats(user_id, update.effective_user)138 139 except httpx.TimeoutException:140 logger.warning(f"Request timed out for user {user_id}.")141 await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")142 except Exception as e:143 logger.error(f"Error while processing message for user {user_id}: {e}")144 await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")145# --- هندلرهای اصلی ربات ---146async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:147 user = update.effective_user148 user_id = user.id149 150 data_manager.update_user_stats(user_id, user)151 152 welcome_msg = data_manager.DATA.get('welcome_message', "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.")153 await update.message.reply_html(154 welcome_msg.format(user_mention=user.mention_html()),155 disable_web_page_preview=True156 )157 158async def clear_chat(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:159 """پاک کردن تاریخچه چت برای کاربر"""160 user_id = update.effective_user.id161 162 if HAS_SMART_CONTEXT:163 if user_id in smart_context_managers:164 smart_context_managers[user_id].clear_context()165 else:166 data_manager.clear_user_context(user_id)167 168 await update.message.reply_text(169 "🧹 تاریخچه مکالمه شما پاک شد.\n"170 "از این لحظه مکالمه جدیدی شروع خواهد شد."171 )172 173async def context_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:174 """نمایش اطلاعات context کاربر"""175 user_id = update.effective_user.id176 177 if HAS_SMART_CONTEXT:178 if user_id in smart_context_managers:179 summary = smart_context_managers[user_id].get_summary()180 181 info_text = (182 "🧠 **وضعیت حافظه هوشمند شما:**\n\n"183 f"📊 **آمار کلی:**\n"184 f"• کل پیامها: {summary['total_messages']}\n"185 f"• حافظه فعال: {summary['working_memory']} پیام\n"186 f"• حافظه بلندمدت: {summary['long_term_memory']} پیام\n"187 f"• حافظه هسته: {summary['core_memory']} پیام\n\n"188 f"🎯 **علاقهمندیها:**\n"189 )190 191 interests = summary.get('profile_interests', [])192 if interests:193 info_text += "• " + "\n• ".join(interests[:5])194 if len(interests) > 5:195 info_text += f"\n• و {len(interests) - 5} مورد دیگر..."196 else:197 info_text += "هنوز علاقهمندیای ثبت نشده است."198 199 info_text += f"\n\n📈 **کارایی:**\n"200 info_text += f"• میانگین اهمیت: {summary['average_importance']:.2%}\n"201 info_text += f"• نرخ فشردهسازی: {summary['compression_ratio']:.2%}\n"202 info_text += f"• کارایی بازیابی: {summary['retrieval_efficiency']:.2%}"203 else:204 info_text = "هنوز context هوشمندی ایجاد نشده است."205 else:206 context_summary = data_manager.get_context_summary(user_id)207 info_text = (208 f"📊 **اطلاعات تاریخچه مکالمه شما:**\n\n"209 f"{context_summary}\n\n"210 f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."211 )212 213 await update.message.reply_text(info_text, parse_mode='Markdown')214 215async def smart_context_status(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:216 """نمایش وضعیت سیستم Context هوشمند"""217 if not HAS_SMART_CONTEXT:218 await update.message.reply_text("❌ سیستم Context هوشمند فعال نیست.")219 return220 221 user_id = update.effective_user.id222 smart_context = _get_or_create_smart_context(user_id)223 224 # دریافت اطلاعات دقیق225 debug_info = smart_context.export_debug_info()226 227 status_text = (228 "🤖 **وضعیت سیستم Context هوشمند:**\n\n"229 f"✅ **سیستم فعال:** بله\n"230 f"👤 **کاربر:** {user_id}\n"231 f"📊 **تعداد گرههای حافظه:** {debug_info['memory_graph_size']}\n"232 f"🔗 **اتصالات حافظه:** {debug_info['memory_graph_connections']}\n"233 f"🎯 **تعداد علاقهمندیها:** {debug_info['user_profile']['interests_count']}\n"234 f"⚙️ **تنظیمات مکالمه:** {debug_info['user_profile']['conversation_style']}\n\n"235 "📈 **حافظه لایهای:**\n"236 )237 238 for layer, size in debug_info['layer_sizes'].items():239 status_text += f"• {layer}: {size} پیام\n"240 241 await update.message.reply_text(status_text, parse_mode='Markdown')242 243async def optimize_memory(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:244 """بهینهسازی دستی حافظه"""245 if not HAS_SMART_CONTEXT:246 await update.message.reply_text("❌ سیستم Context هوشمند فعال نیست.")247 return248 249 user_id = update.effective_user.id250 251 if user_id in smart_context_managers:252 before_stats = smart_context_managers[user_id].export_debug_info()253 254 # اجرای بهینهسازی255 smart_context_managers[user_id]._optimize_memory()256 257 after_stats = smart_context_managers[user_id].export_debug_info()258 259 # محاسبه بهبود260 improvements = []261 for layer in before_stats['layer_sizes'].keys():262 before = before_stats['layer_sizes'][layer]263 after = after_stats['layer_sizes'][layer]264 if before > after:265 improvement = before - after266 improvements.append(f"• {layer}: {improvement} پیام آزاد شد")267 268 if improvements:269 improvement_text = "\n".join(improvements)270 message = (271 "✅ **حافظه بهینهسازی شد!**\n\n"272 "📊 **بهبودها:**\n"273 f"{improvement_text}\n\n"274 "🔧 حافظههای غیرضروری پاکسازی شدند و اطلاعات مهم اولویتبندی شدند."275 )276 else:277 message = "✅ حافظه قبلاً بهینه بود. هیچ تغییری اعمال نشد."278 else:279 message = "⚠️ هنوز حافظهای برای بهینهسازی وجود ندارد."280 281 await update.message.reply_text(message, parse_mode='Markdown')282 283async def export_context(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:284 """صدور دادههای Context"""285 if not HAS_SMART_CONTEXT:286 await update.message.reply_text("❌ سیستم Context هوشمند فعال نیست.")287 return288 289 user_id = update.effective_user.id290 291 if user_id not in smart_context_managers:292 await update.message.reply_text("⚠️ هنوز context هوشمندی ایجاد نشده است.")293 return294 295 smart_context = smart_context_managers[user_id]296 debug_info = smart_context.export_debug_info()297 298 # ذخیره در فایل موقت299 import tempfile300 import json301 302 with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False, encoding='utf-8') as f:303 json.dump(debug_info, f, indent=4, ensure_ascii=False)304 temp_file_path = f.name305 306 await update.message.reply_document(307 document=open(temp_file_path, 'rb'),308 caption=f"📊 دادههای Context هوشمند کاربر {user_id}"309 )310 311 # پاک کردن فایل موقت312 import os313 os.unlink(temp_file_path)314 315async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:316 """نمایش دستورات کمک"""317 base_commands = (318 "🤖 **دستورات اصلی ربات:**\n\n"319 "🟢 `/start` - شروع کار با ربات\n"320 "🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"321 "🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"322 "🟢 `/help` - نمایش این پیام راهنما\n\n"323 )324 325 smart_commands = ""326 if HAS_SMART_CONTEXT:327 smart_commands = (328 "🧠 **دستورات Context هوشمند:**\n\n"329 "🔷 `/smart_status` - نمایش وضعیت سیستم هوشمند\n"330 "🔷 `/optimize` - بهینهسازی دستی حافظه\n"331 "🔷 `/export_context` - صدور دادههای Context\n\n"332 )333 334 note = (335 "📝 **نکته:** ربات تاریخچه مکالمه شما را هوشمندانه مدیریت میکند.\n"336 "برای شروع مکالمه جدید از دستور /clear استفاده کنید."337 )338 339 await update.message.reply_text(base_commands + smart_commands + note, parse_mode='Markdown')340 341# main.py - اضافه کردن fallback handler342 343async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:344 user_id = update.effective_user.id345 346 # بررسی مسدود بودن کاربر347 if data_manager.is_user_banned(user_id):348 logger.info(f"Banned user {user_id} tried to send a message.")349 return350 351 # بررسی حالت نگهداری (فقط برای کاربران عادی)352 if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_panel.ADMIN_IDS:353 await update.message.reply_text("🔧 ربات در حال حاضر در حالت نگهداری قرار دارد. لطفاً بعداً تلاش کنید.")354 return355 356 # بررسی کلمات مسدود شده357 if data_manager.contains_blocked_words(update.message.text):358 logger.info(f"User {user_id} sent a message with a blocked word.")359 return360 361 # مدیریت وظایف همزمان با timeout362 if user_id in user_tasks:363 try:364 # بررسی اگر task قبلی هنوز در حال اجرا است365 if not user_tasks[user_id].done():366 # منتظر پایان task قبلی با timeout367 try:368 await asyncio.wait_for(user_tasks[user_id], timeout=5.0)369 except asyncio.TimeoutError:370 logger.warning(f"Previous task for user {user_id} timed out, cancelling...")371 user_tasks[user_id].cancel()372 except Exception as e:373 logger.error(f"Error handling previous task for user {user_id}: {e}")374 375 # ایجاد وظیفه جدید با timeout376 task = asyncio.create_task(377 _process_user_request_with_timeout(update, context)378 )379 user_tasks[user_id] = task380 task.add_done_callback(lambda t: _cleanup_task(t, user_id))381 382async def _process_user_request_with_timeout(update: Update, context: ContextTypes.DEFAULT_TYPE):383 """پردازش درخواست کاربر با timeout"""384 try:385 # اجرا با timeout 30 ثانیه386 await asyncio.wait_for(387 _process_user_request(update, context),388 timeout=30.0389 )390 except asyncio.TimeoutError:391 logger.error(f"Processing timed out for user {update.effective_user.id}")392 await update.message.reply_text("⏱️ پردازش درخواست شما زمان زیادی برد. لطفاً دوباره تلاش کنید.")393 except Exception as e:394 logger.error(f"Unexpected error in task for user {update.effective_user.id}: {e}")395 396def main() -> None:397 token = os.environ.get("BOT_TOKEN")398 if not token:399 logger.error("BOT_TOKEN not set in environment variables!")400 return401 402 application = (403 Application.builder()404 .token(token)405 .concurrent_updates(True)406 .build()407 )408 409 # هندلرهای کاربران410 application.add_handler(CommandHandler("start", start))411 application.add_handler(CommandHandler("clear", clear_chat))412 application.add_handler(CommandHandler("context", context_info))413 application.add_handler(CommandHandler("help", help_command))414 415 # هندلرهای Context هوشمند416 if HAS_SMART_CONTEXT:417 application.add_handler(CommandHandler("smart_status", smart_context_status))418 application.add_handler(CommandHandler("optimize", optimize_memory))419 application.add_handler(CommandHandler("export_context", export_context))420 421 application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))422 423 # راهاندازی و ثبت هندلرهای پنل ادمین424 admin_panel.setup_admin_handlers(application)425 426 # تنظیمات Webhook برای Render427 port = int(os.environ.get("PORT", 8443))428 webhook_url = os.environ.get("RENDER_EXTERNAL_URL", "")429 430 if webhook_url:431 # حالت Webhook (برای Render)432 application.run_webhook(433 listen="0.0.0.0",434 port=port,435 webhook_url=webhook_url + "/webhook",436 url_path="webhook",437 drop_pending_updates=True438 )439 logger.info(f"Bot running in webhook mode on port {port}")440 else:441 # حالت Polling (برای توسعه)442 application.run_polling(drop_pending_updates=True)443 logger.info("Bot running in polling mode")444 445if __name__ == "__main__":446 main()