Spaces:
Running
Running
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """ | |
| ูุธุงู ุชูุฒูุน ุงูู ูุงู ุงูุฐูู - ุงูุฎุงุฏู ุงูู ุฑูุฒู ุนูู Hugging Face | |
| ูุฌู ุน ุจูู ูุงุฌูุฉ Gradio ูุฎุงุฏู ุงูุชูุฒูุน ุงูู ุฑูุฒู | |
| """ | |
| import os | |
| import sys | |
| import time | |
| import json | |
| import logging | |
| import threading | |
| import random | |
| import queue | |
| from datetime import datetime | |
| from typing import Dict, List, Optional, Any | |
| from dataclasses import dataclass, field, asdict | |
| import gradio as gr | |
| from flask import Flask, request, jsonify | |
| from flask_cors import CORS | |
| import requests | |
| # โโโโโโโโโโโโโโโ ุฅุนุฏุงุฏ ุงูุณุฌูุงุช โโโโโโโโโโโโโโโ | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' | |
| ) | |
| logger = logging.getLogger("CentralServerHF") | |
| # โโโโโโโโโโโโโโโ ููุงูู ุงูุจูุงูุงุช โโโโโโโโโโโโโโโ | |
| class NodeInfo: | |
| """ู ุนููู ุงุช ุงูุนูุฏุฉ ุงูู ุชุตูุฉ""" | |
| node_id: str | |
| ip: str | |
| port: int | |
| url: str | |
| capabilities: List[str] | |
| cpu_usage: float = 0.0 | |
| memory_usage: float = 0.0 | |
| status: str = "online" | |
| last_seen: datetime = field(default_factory=datetime.now) | |
| success_rate: float = 1.0 | |
| response_time: float = 0.0 | |
| tasks_completed: int = 0 | |
| tasks_failed: int = 0 | |
| current_tasks: int = 0 | |
| weight: float = 1.0 # ููุฃูุฒุงู ุงูุฐููุฉ | |
| def score(self) -> float: | |
| """ุญุณุงุจ ุฏุฑุฌุฉ ุงูุนูุฏุฉ""" | |
| health = 0.4 * (100 - (self.cpu_usage + self.memory_usage) / 2) / 100 | |
| performance = 0.3 * self.success_rate | |
| availability = 0.2 * (1.0 - self.current_tasks / 5) | |
| speed = 0.1 * max(0, 1 - self.response_time / 10) | |
| return (health + performance + availability + speed) * self.weight | |
| class TaskInfo: | |
| """ู ุนููู ุงุช ุงูู ูู ุฉ""" | |
| task_id: str | |
| task_type: str | |
| params: Dict[str, Any] | |
| sender: str | |
| status: str = "pending" # pending, processing, completed, failed | |
| assigned_to: Optional[str] = None | |
| result: Optional[Any] = None | |
| error: Optional[str] = None | |
| created_at: datetime = field(default_factory=datetime.now) | |
| started_at: Optional[datetime] = None | |
| completed_at: Optional[datetime] = None | |
| priority: int = 2 # 1=high, 2=medium, 3=low | |
| # โโโโโโโโโโโโโโโ ูุฆุฉ ุงูุฎุงุฏู ุงูู ุฑูุฒู โโโโโโโโโโโโโโโ | |
| class CentralServer: | |
| """ุงูุฎุงุฏู ุงูู ุฑูุฒู ุงูุฐูู ูุชูุฒูุน ุงูู ูุงู """ | |
| def __init__(self): | |
| self.nodes: Dict[str, NodeInfo] = {} | |
| self.tasks: Dict[str, TaskInfo] = {} | |
| self.task_queue = queue.PriorityQueue() | |
| self.lock = threading.RLock() | |
| self.is_running = True | |
| # ุฅุญุตุงุฆูุงุช ุงููุธุงู | |
| self.metrics = { | |
| "total_nodes": 0, | |
| "online_nodes": 0, | |
| "total_tasks": 0, | |
| "completed_tasks": 0, | |
| "failed_tasks": 0, | |
| "avg_response_time": 0.0, | |
| "system_uptime": time.time() | |
| } | |
| # ุจุฏุก ุงูุฎุฏู ุงุช ุงูุฎูููุฉ | |
| self._start_background_services() | |
| logger.info("๐ ุจุฏุก ุชุดุบูู ุงูุฎุงุฏู ุงูู ุฑูุฒู ุนูู Hugging Face") | |
| def _start_background_services(self): | |
| """ุจุฏุก ุงูุฎุฏู ุงุช ุงูุฎูููุฉ""" | |
| # ุฎูุท ุชูุฒูุน ุงูู ูุงู | |
| self.dispatcher = threading.Thread(target=self._dispatch_loop, daemon=True) | |
| self.dispatcher.start() | |
| # ุฎูุท ูุญุต ุตุญุฉ ุงูุนูุฏ | |
| self.health_checker = threading.Thread(target=self._health_check_loop, daemon=True) | |
| self.health_checker.start() | |
| # ุฎูุท ู ุญุงูุงุฉ ุงูุนูุฏ (ููุชุฌุฑุจุฉ) | |
| self.simulator = threading.Thread(target=self._simulate_nodes, daemon=True) | |
| self.simulator.start() | |
| def register_node(self, node_data: Dict) -> Dict: | |
| """ุชุณุฌูู ุนูุฏุฉ ุฌุฏูุฏุฉ""" | |
| with self.lock: | |
| node_id = node_data.get('node_id', f"node_{len(self.nodes)+1}") | |
| node = NodeInfo( | |
| node_id=node_id, | |
| ip=node_data.get('ip', '127.0.0.1'), | |
| port=node_data.get('port', 0), | |
| url=node_data.get('url', ''), | |
| capabilities=node_data.get('capabilities', ['general']), | |
| cpu_usage=node_data.get('cpu_usage', 0.0), | |
| memory_usage=node_data.get('memory_usage', 0.0), | |
| status='online' | |
| ) | |
| self.nodes[node_id] = node | |
| self.metrics["total_nodes"] = len(self.nodes) | |
| self.metrics["online_nodes"] = len([n for n in self.nodes.values() if n.status == 'online']) | |
| logger.info(f"โ ุนูุฏุฉ ู ุณุฌูุฉ: {node_id}") | |
| return { | |
| "status": "success", | |
| "node_id": node_id, | |
| "message": "ุชู ุงูุชุณุฌูู ุจูุฌุงุญ", | |
| "server_time": datetime.now().isoformat() | |
| } | |
| def update_node_status(self, node_id: str, metrics: Dict): | |
| """ุชุญุฏูุซ ุญุงูุฉ ุงูุนูุฏุฉ""" | |
| with self.lock: | |
| if node_id in self.nodes: | |
| node = self.nodes[node_id] | |
| if 'cpu_usage' in metrics: | |
| node.cpu_usage = metrics['cpu_usage'] | |
| if 'memory_usage' in metrics: | |
| node.memory_usage = metrics['memory_usage'] | |
| if 'current_tasks' in metrics: | |
| node.current_tasks = metrics['current_tasks'] | |
| if 'status' in metrics: | |
| node.status = metrics['status'] | |
| node.last_seen = datetime.now() | |
| # ุชุญุฏูุซ ู ุนุฏู ุงููุฌุงุญ | |
| total = node.tasks_completed + node.tasks_failed | |
| if total > 0: | |
| node.success_rate = node.tasks_completed / total | |
| return {"status": "updated"} | |
| return {"error": "ุงูุนูุฏุฉ ุบูุฑ ู ูุฌูุฏุฉ"} | |
| def submit_task(self, task_data: Dict) -> Dict: | |
| """ุฅุฑุณุงู ู ูู ุฉ ุฌุฏูุฏุฉ""" | |
| task_id = task_data.get('task_id', f"task_{int(time.time())}_{random.randint(1000,9999)}") | |
| task = TaskInfo( | |
| task_id=task_id, | |
| task_type=task_data.get('task_type', 'general'), | |
| params=task_data.get('params', {}), | |
| sender=task_data.get('sender', 'unknown'), | |
| priority=task_data.get('priority', 2) | |
| ) | |
| with self.lock: | |
| self.tasks[task_id] = task | |
| self.metrics["total_tasks"] = len(self.tasks) | |
| # ุฅุถุงูุฉ ุฅูู ูุงุฆู ุฉ ุงูุงูุชุธุงุฑ | |
| self.task_queue.put((task.priority, task_id)) | |
| logger.info(f"๐จ ู ูู ุฉ ู ุณุชูู ุฉ: {task_id} ({task.task_type})") | |
| return { | |
| "status": "accepted", | |
| "task_id": task_id, | |
| "queue_position": self.task_queue.qsize(), | |
| "estimated_wait": self.task_queue.qsize() * 2 # ุซุงููุชูู ููู ู ูู ุฉ | |
| } | |
| def _dispatch_loop(self): | |
| """ุญููุฉ ุชูุฒูุน ุงูู ูุงู """ | |
| while self.is_running: | |
| try: | |
| # ุงูุชุธุงุฑ ู ูู ุฉ | |
| priority, task_id = self.task_queue.get(timeout=1.0) | |
| with self.lock: | |
| task = self.tasks.get(task_id) | |
| if not task or task.status != "pending": | |
| continue | |
| # ุฅูุฌุงุฏ ุฃูุถู ุนูุฏุฉ | |
| best_node = self._select_best_node(task.task_type) | |
| if best_node: | |
| # ุชุนููู ุงูู ูู ุฉ | |
| self._assign_task(task, best_node) | |
| else: | |
| # ุฅุนุงุฏุฉ ุงูู ุญุงููุฉ | |
| time.sleep(3) | |
| self.task_queue.put((priority, task_id)) | |
| except queue.Empty: | |
| continue | |
| except Exception as e: | |
| logger.error(f"โ ุฎุทุฃ ูู ุงูุชูุฒูุน: {e}") | |
| time.sleep(5) | |
| def _select_best_node(self, task_type: str) -> Optional[NodeInfo]: | |
| """ุงุฎุชูุงุฑ ุฃูุถู ุนูุฏุฉ ููู ูู ุฉ""" | |
| with self.lock: | |
| # ููุชุฑุฉ ุงูุนูุฏ ุงูู ุชุงุญุฉ | |
| available = [] | |
| for node in self.nodes.values(): | |
| if node.status != 'online': | |
| continue | |
| if node.cpu_usage > 85 or node.memory_usage > 85: | |
| continue | |
| if node.current_tasks >= 3: | |
| continue | |
| # ุงูุชุญูู ู ู ุงููุฏุฑุงุช | |
| capabilities_needed = [] | |
| if task_type in ['matrix', 'fibonacci']: | |
| capabilities_needed = ['cpu_intensive'] | |
| elif task_type in ['data', 'processing']: | |
| capabilities_needed = ['memory'] | |
| if capabilities_needed: | |
| if not any(cap in node.capabilities for cap in capabilities_needed): | |
| continue | |
| available.append(node) | |
| if not available: | |
| return None | |
| # ุงุฎุชูุงุฑ ุงูุฃุนูู ุฏุฑุฌุฉ | |
| return max(available, key=lambda n: n.score) | |
| def _assign_task(self, task: TaskInfo, node: NodeInfo): | |
| """ุชุนููู ู ูู ุฉ ูุนูุฏุฉ""" | |
| try: | |
| # ุชุญุฏูุซ ุญุงูุฉ ุงูู ูู ุฉ | |
| with self.lock: | |
| task.status = "processing" | |
| task.assigned_to = node.node_id | |
| task.started_at = datetime.now() | |
| node.current_tasks += 1 | |
| logger.info(f"๐ฏ ุชุนููู {task.task_id} โ {node.node_id}") | |
| # ู ุญุงูุงุฉ ุงูุชูููุฐ | |
| execution_time = self._simulate_task_execution(task, node) | |
| # ุชุญุฏูุซ ุงููุชูุฌุฉ | |
| with self.lock: | |
| task.status = "completed" | |
| task.completed_at = datetime.now() | |
| task.result = { | |
| "executed_on": node.node_id, | |
| "execution_time": execution_time, | |
| "task_type": task.task_type, | |
| "result": f"ูุชูุฌุฉ ู ุญุงูุงุฉ ูู {task.task_type}" | |
| } | |
| node.current_tasks -= 1 | |
| node.tasks_completed += 1 | |
| node.response_time = execution_time | |
| self.metrics["completed_tasks"] += 1 | |
| logger.info(f"โ ู ูุชู ูุฉ: {task.task_id} ูู {execution_time:.2f}s") | |
| except Exception as e: | |
| logger.error(f"โ ูุดูุช ุงูู ูู ุฉ {task.task_id}: {e}") | |
| with self.lock: | |
| task.status = "failed" | |
| task.error = str(e) | |
| self.metrics["failed_tasks"] += 1 | |
| if node.node_id in self.nodes: | |
| self.nodes[node.node_id].tasks_failed += 1 | |
| self.nodes[node.node_id].current_tasks -= 1 | |
| def _simulate_task_execution(self, task: TaskInfo, node: NodeInfo) -> float: | |
| """ู ุญุงูุงุฉ ุชูููุฐ ุงูู ูู ุฉ""" | |
| # ุฃููุงุช ุชูููุฐ ู ุฎุชููุฉ ุญุณุจ ููุน ุงูู ูู ุฉ | |
| base_times = { | |
| 'matrix': 1.5, | |
| 'fibonacci': 0.8, | |
| 'primes': 1.2, | |
| 'data': 0.5, | |
| 'image': 2.0, | |
| 'general': 0.3 | |
| } | |
| base_time = base_times.get(task.task_type, 0.5) | |
| # ุชุฃุซูุฑ ุญู ู ุงูุนูุฏุฉ | |
| load_factor = 1 + (node.cpu_usage + node.memory_usage) / 200 | |
| # ุชุฃุซูุฑ ุญุฌู ุงูู ูู ุฉ | |
| size = task.params.get('size', 10) if isinstance(task.params, dict) else 10 | |
| size_factor = 1 + (size / 1000) | |
| # ููุช ุชูููุฐ ู ุญุงูู | |
| execution_time = base_time * load_factor * size_factor | |
| # ู ุญุงูุงุฉ ุงูุงูุชุธุงุฑ | |
| time.sleep(min(execution_time, 3.0)) | |
| return execution_time | |
| def _health_check_loop(self): | |
| """ูุญุต ุตุญุฉ ุงูุนูุฏ""" | |
| while self.is_running: | |
| try: | |
| with self.lock: | |
| now = datetime.now() | |
| for node in self.nodes.values(): | |
| # ุฅุฐุง ู ุฑ ุฃูุซุฑ ู ู 2 ุฏูููุฉ ุฏูู ุชุญุฏูุซ | |
| if (now - node.last_seen).total_seconds() > 120: | |
| node.status = "offline" | |
| # ุชุญุฏูุซ ุงูุฅุญุตุงุฆูุงุช | |
| self.metrics["online_nodes"] = len( | |
| [n for n in self.nodes.values() if n.status == 'online'] | |
| ) | |
| time.sleep(30) | |
| except Exception as e: | |
| logger.error(f"โ ุฎุทุฃ ูู ูุญุต ุงูุตุญุฉ: {e}") | |
| time.sleep(60) | |
| def _simulate_nodes(self): | |
| """ู ุญุงูุงุฉ ุนูุฏ ุงูุชุฑุงุถูุฉ (ููุชุฌุฑุจุฉ)""" | |
| # ุฅูุดุงุก ุนูุฏ ุงูุชุฑุงุถูุฉ | |
| virtual_nodes = [ | |
| {"id": "node_cpu1", "capabilities": ["cpu_intensive"], "cpu": 20, "memory": 40}, | |
| {"id": "node_mem1", "capabilities": ["memory"], "cpu": 30, "memory": 25}, | |
| {"id": "node_gpu1", "capabilities": ["gpu", "image"], "cpu": 25, "memory": 50}, | |
| {"id": "node_gen1", "capabilities": ["general"], "cpu": 15, "memory": 35} | |
| ] | |
| for vnode in virtual_nodes: | |
| self.register_node({ | |
| "node_id": vnode["id"], | |
| "ip": "192.168.1." + str(random.randint(100, 200)), | |
| "port": random.randint(5000, 6000), | |
| "url": f"http://192.168.1.{random.randint(100,200)}:{random.randint(5000,6000)}", | |
| "capabilities": vnode["capabilities"], | |
| "cpu_usage": vnode["cpu"], | |
| "memory_usage": vnode["memory"] | |
| }) | |
| # ู ุญุงูุงุฉ ุชุญุฏูุซุงุช ุฏูุฑูุฉ | |
| while self.is_running: | |
| try: | |
| with self.lock: | |
| for node_id in list(self.nodes.keys())[:4]: # ุฃูู 4 ุนูุฏ (ุงูุงูุชุฑุงุถูุฉ) | |
| if node_id in self.nodes: | |
| node = self.nodes[node_id] | |
| node.cpu_usage = max(5, min(80, node.cpu_usage + random.uniform(-5, 5))) | |
| node.memory_usage = max(10, min(70, node.memory_usage + random.uniform(-3, 3))) | |
| node.current_tasks = random.randint(0, 2) | |
| node.last_seen = datetime.now() | |
| time.sleep(10) | |
| except Exception as e: | |
| logger.error(f"โ ุฎุทุฃ ูู ู ุญุงูุงุฉ ุงูุนูุฏ: {e}") | |
| time.sleep(30) | |
| def get_system_overview(self) -> Dict: | |
| """ูุธุฑุฉ ุนุงู ุฉ ุนูู ุงููุธุงู """ | |
| with self.lock: | |
| now = datetime.now() | |
| # ุญุณุงุจ ู ุชูุณุท ููุช ุงูุงุณุชุฌุงุจุฉ | |
| response_times = [n.response_time for n in self.nodes.values() if n.response_time > 0] | |
| avg_response = sum(response_times) / len(response_times) if response_times else 0 | |
| # ุงูู ูุงู ุงูุฃุฎูุฑุฉ | |
| recent_tasks = list(self.tasks.values())[-10:] # ุขุฎุฑ 10 ู ูุงู | |
| return { | |
| "metrics": { | |
| **self.metrics, | |
| "uptime": time.time() - self.metrics["system_uptime"], | |
| "avg_response_time": avg_response, | |
| "queue_size": self.task_queue.qsize(), | |
| "timestamp": now.isoformat() | |
| }, | |
| "nodes": [ | |
| { | |
| "id": n.node_id, | |
| "status": n.status, | |
| "score": round(n.score, 3), | |
| "cpu": n.cpu_usage, | |
| "memory": n.memory_usage, | |
| "tasks": n.current_tasks, | |
| "success_rate": round(n.success_rate, 2), | |
| "last_seen": (now - n.last_seen).total_seconds() | |
| } | |
| for n in self.nodes.values() | |
| ], | |
| "recent_tasks": [ | |
| { | |
| "id": t.task_id, | |
| "type": t.task_type, | |
| "status": t.status, | |
| "assigned_to": t.assigned_to, | |
| "created": t.created_at.strftime("%H:%M:%S") | |
| } | |
| for t in recent_tasks | |
| ] | |
| } | |
| # โโโโโโโโโโโโโโโ ุฅูุดุงุก ุงูุฎุงุฏู ุงูู ุฑูุฒู โโโโโโโโโโโโโโโ | |
| central_server = CentralServer() | |
| # โโโโโโโโโโโโโโโ ุฏูุงู Gradio โโโโโโโโโโโโโโโ | |
| def get_system_status(): | |
| """ุงูุญุตูู ุนูู ุญุงูุฉ ุงููุธุงู """ | |
| overview = central_server.get_system_overview() | |
| metrics = overview["metrics"] | |
| nodes = overview["nodes"] | |
| tasks = overview["recent_tasks"] | |
| # ุชูุณูู ุงููุต | |
| status_text = f""" | |
| # ๐ ุงูุฎุงุฏู ุงูู ุฑูุฒู ูุชูุฒูุน ุงูู ูุงู | |
| ## ๐ ุฅุญุตุงุฆูุงุช ุงููุธุงู | |
| - **ุงูููุช:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} | |
| - **ู ุฏุฉ ุงูุชุดุบูู:** {metrics['uptime']/3600:.1f} ุณุงุนุฉ | |
| - **ุงูุนูุฏ ุงูุฅุฌู ุงููุฉ:** {metrics['total_nodes']} | |
| - **ุงูุนูุฏ ุงููุดุทุฉ:** {metrics['online_nodes']} | |
| - **ุงูู ูุงู ุงูุฅุฌู ุงููุฉ:** {metrics['total_tasks']} | |
| - **ุงูู ูุงู ุงูู ูุชู ูุฉ:** {metrics['completed_tasks']} | |
| - **ุงูู ูุงู ุงููุงุดูุฉ:** {metrics['failed_tasks']} | |
| - **ู ุชูุณุท ููุช ุงูุงุณุชุฌุงุจุฉ:** {metrics['avg_response_time']:.2f} ุซุงููุฉ | |
| - **ุงูู ูุงู ูู ุงูุงูุชุธุงุฑ:** {metrics['queue_size']} | |
| ## ๐ฅ ุงูุนูุฏ ุงูู ุชุตูุฉ ({len(nodes)}) | |
| """ | |
| for node in nodes: | |
| status_emoji = "๐ข" if node['status'] == 'online' else "๐ด" if node['status'] == 'offline' else "๐ก" | |
| status_text += f"\n**{status_emoji} {node['id']}**" | |
| status_text += f"\n - ุงูููุงุท: {node['score']:.3f}" | |
| status_text += f"\n - CPU: {node['cpu']:.1f}% | ุฐุงูุฑุฉ: {node['memory']:.1f}%" | |
| status_text += f"\n - ุงูู ูุงู ุงููุดุทุฉ: {node['tasks']}" | |
| status_text += f"\n - ู ุนุฏู ุงููุฌุงุญ: {node['success_rate']*100:.1f}%" | |
| status_text += f"\n - ุขุฎุฑ ุธููุฑ: {node['last_seen']:.0f} ุซุงููุฉ ู ุถุช" | |
| if tasks: | |
| status_text += f"\n\n## ๐ ุขุฎุฑ ุงูู ูุงู ({len(tasks)})" | |
| for task in tasks[-5:]: # ุขุฎุฑ 5 ู ูุงู | |
| status_emoji = "๐ข" if task['status'] == 'completed' else "๐ก" if task['status'] == 'processing' else "๐ด" | |
| status_text += f"\n{status_emoji} **{task['id']}** ({task['type']}) โ {task['assigned_to'] or 'ูู ุงูุงูุชุธุงุฑ'}" | |
| return status_text | |
| def submit_task_ui(task_type, params_json): | |
| """ุฅุฑุณุงู ู ูู ุฉ ุฌุฏูุฏุฉ""" | |
| try: | |
| params = json.loads(params_json) if params_json else {} | |
| except: | |
| params = {"size": 10} | |
| task_data = { | |
| "task_type": task_type, | |
| "params": params, | |
| "sender": "gradio_ui", | |
| "priority": 2 | |
| } | |
| result = central_server.submit_task(task_data) | |
| if "error" in result: | |
| return f"## โ ุฎุทุฃ\n{result['error']}" | |
| return f""" | |
| ## โ ุชู ูุจูู ุงูู ูู ุฉ | |
| ### ๐ ู ุนููู ุงุช ุงูู ูู ุฉ | |
| - **ู ุนุฑู ุงูู ูู ุฉ:** {result['task_id']} | |
| - **ููุน ุงูู ูู ุฉ:** {task_type} | |
| - **ุงูุญุงูุฉ:** ูู ูุงุฆู ุฉ ุงูุงูุชุธุงุฑ | |
| - **ุงูู ููุน ูู ุงูุทุงุจูุฑ:** {result['queue_position']} | |
| - **ุงูููุช ุงูู ุชููุน:** {result['estimated_wait']} ุซุงููุฉ | |
| - **ุงูููุช:** {datetime.now().strftime('%H:%M:%S')} | |
| ### ๐ ุชุชุจุน ุงูู ูู ุฉ | |
| ุณูุชู ุชุนููู ุงูู ูู ุฉ ูุฃูุถู ุนูุฏุฉ ู ุชุงุญุฉ ุชููุงุฆูุงู. | |
| """ | |
| def get_node_details(): | |
| """ุงูุญุตูู ุนูู ุชูุงุตูู ุงูุนูุฏ""" | |
| overview = central_server.get_system_overview() | |
| nodes = overview["nodes"] | |
| headers = ["ุงูุนูุฏุฉ", "ุงูุญุงูุฉ", "ุงูููุงุท", "CPU%", "ุงูุฐุงูุฑุฉ%", "ุงูู ูุงู ", "ู ุนุฏู ุงููุฌุงุญ", "ุขุฎุฑ ุธููุฑ"] | |
| data = [] | |
| for node in nodes: | |
| status_emoji = "๐ข" if node['status'] == 'online' else "๐ด" | |
| data.append([ | |
| node['id'], | |
| f"{status_emoji} {node['status']}", | |
| f"{node['score']:.3f}", | |
| f"{node['cpu']:.1f}", | |
| f"{node['memory']:.1f}", | |
| str(node['tasks']), | |
| f"{node['success_rate']*100:.1f}%", | |
| f"{node['last_seen']:.0f}s" | |
| ]) | |
| return data | |
| def simulate_new_node(): | |
| """ู ุญุงูุงุฉ ุนูุฏุฉ ุฌุฏูุฏุฉ""" | |
| node_id = f"node_{int(time.time())}" | |
| caps = random.choice([['cpu_intensive'], ['memory'], ['general'], ['gpu', 'image']]) | |
| result = central_server.register_node({ | |
| "node_id": node_id, | |
| "ip": f"10.0.0.{random.randint(1, 255)}", | |
| "port": random.randint(5000, 6000), | |
| "url": f"http://10.0.0.{random.randint(1,255)}:{random.randint(5000,6000)}", | |
| "capabilities": caps, | |
| "cpu_usage": random.uniform(10, 40), | |
| "memory_usage": random.uniform(20, 60) | |
| }) | |
| return f"## ๐ ุนูุฏุฉ ู ุญุงูุงุฉ\n**{node_id}** - {', '.join(caps)}\n\nุชู ุงูุชุณุฌูู ุจูุฌุงุญ!" | |
| def simulate_task_load(count: int): | |
| """ู ุญุงูุงุฉ ุญู ู ู ูุงู """ | |
| task_types = ['matrix', 'fibonacci', 'primes', 'data', 'image', 'general'] | |
| for i in range(min(count, 10)): # ุญุฏ ุฃูุตู 10 ู ูุงู | |
| task_type = random.choice(task_types) | |
| central_server.submit_task({ | |
| "task_type": task_type, | |
| "params": {"size": random.randint(10, 1000)}, | |
| "sender": "simulation", | |
| "priority": random.randint(1, 3) | |
| }) | |
| time.sleep(0.1) | |
| return f"## ๐จ ู ุญุงูุงุฉ ุญู ู\nุชู ุฅุฑุณุงู {min(count, 10)} ู ูุงู ุนุดูุงุฆูุฉ!" | |
| # โโโโโโโโโโโโโโโ ูุงุฌูุฉ Gradio โโโโโโโโโโโโโโโ | |
| def create_interface(): | |
| """ุฅูุดุงุก ูุงุฌูุฉ Gradio""" | |
| with gr.Blocks( | |
| title="ุงูุฎุงุฏู ุงูู ุฑูุฒู ูุชูุฒูุน ุงูู ูุงู ", | |
| theme=gr.themes.Soft(primary_hue="blue", secondary_hue="teal") | |
| ) as demo: | |
| gr.Markdown("# ๐ ุงูุฎุงุฏู ุงูู ุฑูุฒู ุงูุฐูู ูุชูุฒูุน ุงูู ูุงู ") | |
| gr.Markdown("### ูุณุฎุฉ Hugging Face Spaces - ุฎุงุฏู ุญูููู") | |
| with gr.Tabs(): | |
| # ุชุจููุจ ุญุงูุฉ ุงููุธุงู | |
| with gr.TabItem("๐ ููุญุฉ ุงูุชุญูู "): | |
| status_output = gr.Markdown() | |
| refresh_btn = gr.Button("๐ ุชุญุฏูุซ ุงูุญุงูุฉ", variant="primary") | |
| refresh_btn.click(get_system_status, outputs=status_output) | |
| demo.load(get_system_status, outputs=status_output) | |
| # ุชุจููุจ ุฅุฑุณุงู ุงูู ูุงู | |
| with gr.TabItem("๐ ุฅุฑุณุงู ุงูู ูุงู "): | |
| with gr.Row(): | |
| with gr.Column(): | |
| gr.Markdown("### ุฅุฑุณุงู ู ูู ุฉ ุฌุฏูุฏุฉ") | |
| task_type = gr.Dropdown( | |
| choices=[ | |
| ("ุถุฑุจ ุงูู ุตูููุงุช (CPU)", "matrix"), | |
| ("ู ุชุณูุณูุฉ ููุจููุงุชุดู", "fibonacci"), | |
| ("ุงูุฃุนุฏุงุฏ ุงูุฃูููุฉ", "primes"), | |
| ("ู ุนุงูุฌุฉ ุงูุจูุงูุงุช", "data"), | |
| ("ู ุญุงูุงุฉ ู ุนุงูุฌุฉ ุงูุตูุฑ", "image"), | |
| ("ู ูู ุฉ ุนุงู ุฉ", "general") | |
| ], | |
| label="ููุน ุงูู ูู ุฉ", | |
| value="matrix" | |
| ) | |
| params_input = gr.Textbox( | |
| label="ู ุนุงู ูุงุช ุงูู ูู ุฉ (JSON)", | |
| value='{"size": 100}', | |
| placeholder='{"size": 100} ุฃู {"limit": 1000}' | |
| ) | |
| submit_btn = gr.Button("๐จ ุฅุฑุณุงู ุงูู ูู ุฉ", variant="primary") | |
| with gr.Column(): | |
| gr.Markdown("### ูุชูุฌุฉ ุงูุฅุฑุณุงู") | |
| task_result = gr.Markdown() | |
| submit_btn.click(submit_task_ui, [task_type, params_input], task_result) | |
| # ุชุจููุจ ุงูุนูุฏ | |
| with gr.TabItem("๐ฅ ุฅุฏุงุฑุฉ ุงูุนูุฏ"): | |
| gr.Markdown("### ุงูุนูุฏ ุงูู ุชุตูุฉ") | |
| nodes_table = gr.Dataframe( | |
| headers=["ุงูุนูุฏุฉ", "ุงูุญุงูุฉ", "ุงูููุงุท", "CPU%", "ุงูุฐุงูุฑุฉ%", "ุงูู ูุงู ", "ู ุนุฏู ุงููุฌุงุญ", "ุขุฎุฑ ุธููุฑ"], | |
| interactive=False, | |
| datatype=["str", "str", "str", "str", "str", "str", "str", "str"] | |
| ) | |
| with gr.Row(): | |
| refresh_nodes = gr.Button("๐ ุชุญุฏูุซ ูุงุฆู ุฉ ุงูุนูุฏ") | |
| sim_node = gr.Button("โ ู ุญุงูุงุฉ ุนูุฏุฉ ุฌุฏูุฏุฉ") | |
| sim_tasks = gr.Button("๐จ ู ุญุงูุงุฉ ุญู ู ู ูุงู ") | |
| task_count = gr.Slider(1, 10, value=3, label="ุนุฏุฏ ุงูู ูุงู ") | |
| sim_result = gr.Markdown() | |
| refresh_nodes.click(get_node_details, outputs=nodes_table) | |
| sim_node.click(simulate_new_node, outputs=sim_result) | |
| sim_tasks.click(simulate_task_load, task_count, sim_result) | |
| demo.load(get_node_details, outputs=nodes_table) | |
| # ุชุจููุจ ุงูู ุนููู ุงุช | |
| with gr.TabItem("โน๏ธ ู ุนููู ุงุช ุงููุธุงู "): | |
| gr.Markdown(""" | |
| ## ๐ ุนู ุงูุฎุงุฏู ุงูู ุฑูุฒู | |
| ูุฐุง ุชุทุจูู **ุฎุงุฏู ู ุฑูุฒู ุญูููู** ูุนู ู ุนูู Hugging Face Spaces. | |
| ### โจ ุงูู ู ูุฒุงุช: | |
| - **ุชูุฒูุน ุฐูู ููู ูุงู ** ุนูู ุฃูุถู ุนูุฏุฉ ู ุชุงุญุฉ | |
| - **ู ุฑุงูุจุฉ ูู ุงูููุช ุงููุนูู** ูุฌู ูุน ุงูุนูุฏ | |
| - **ู ุญุงูุงุฉ ู ุชูุฏู ุฉ** ููุนูุฏ ูุงูู ูุงู | |
| - **ุฅุญุตุงุฆูุงุช ู ูุตูุฉ** ุนู ุฃุฏุงุก ุงููุธุงู | |
| - **ูุงุฌูุฉ ุชุญูู ูุงู ูุฉ** ุนุจุฑ Gradio | |
| ### ๐๏ธ ููููุฉ ุงูุนู ู: | |
| 1. **ุงูุนูุฏ ุชุชุตู** ุจุงูุฎุงุฏู ูุชุณุฌู ููุณูุง | |
| 2. **ุงูู ูุงู ุชุฑุณู** ููุฎุงุฏู ุงูู ุฑูุฒู | |
| 3. **ุงูุฎุงุฏู ูุฎุชุงุฑ** ุฃูุถู ุนูุฏุฉ ุจูุงุกู ุนูู: | |
| - ุงุณุชุฎุฏุงู CPU ูุงูุฐุงูุฑุฉ | |
| - ู ุนุฏู ุงููุฌุงุญ ุงูุณุงุจู | |
| - ุนุฏุฏ ุงูู ูุงู ุงููุดุทุฉ | |
| - ููุช ุงูุงุณุชุฌุงุจุฉ | |
| 4. **ุงูู ูุงู ุชููุฐ** ุนูู ุงูุนูุฏ ุงูู ุฎุชุงุฑุฉ | |
| 5. **ุงููุชุงุฆุฌ ุชุฑุฌุน** ููุฎุงุฏู | |
| ### ๐ API ุงูู ุชุงุญ: | |
| ูู ูู ููุนูุฏ ุงูุญููููุฉ ุงูุงุชุตุงู ุนุจุฑ: | |
| - `POST /register` - ุชุณุฌูู ุนูุฏุฉ | |
| - `POST /task/submit` - ุฅุฑุณุงู ู ูู ุฉ | |
| - `POST /status/update` - ุชุญุฏูุซ ุญุงูุฉ | |
| - `GET /nodes` - ูุงุฆู ุฉ ุงูุนูุฏ | |
| - `GET /tasks` - ูุงุฆู ุฉ ุงูู ูุงู | |
| ### ๐ง ุงูุชูููุงุช: | |
| - Python 3 ู ุน ู ุนุงูุฌุฉ ู ุชุนุฏุฏุฉ ุงูุฎููุท | |
| - Gradio ูููุงุฌูุฉ ุงูุฃู ุงู ูุฉ | |
| - ุฎูุงุฑุฒู ูุงุช ุชูุฒูุน ุฐููุฉ | |
| - ูุธุงู ู ุญุงูุงุฉ ู ุชูุงู ู | |
| """) | |
| gr.Markdown("---\n*ุงูุฎุงุฏู ุงูู ุฑูุฒู ูุชูุฒูุน ุงูู ูุงู ุงูุฐูู - ุงูุฅุตุฏุงุฑ 3.0.0*") | |
| return demo | |
| # โโโโโโโโโโโโโโโ API Flask (ููุนูุฏ ุงูุญููููุฉ) โโโโโโโโโโโโโโโ | |
| flask_app = Flask(__name__) | |
| CORS(flask_app) | |
| def api_home(): | |
| return jsonify({ | |
| "message": "ุงูุฎุงุฏู ุงูู ุฑูุฒู ูุชูุฒูุน ุงูู ูุงู ", | |
| "version": "3.0.0", | |
| "status": "running", | |
| "gradio_url": "https://huggingface.co/spaces/your-username/your-space" | |
| }) | |
| def api_register(): | |
| try: | |
| data = request.get_json() | |
| result = central_server.register_node(data) | |
| return jsonify(result) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| def api_submit_task(): | |
| try: | |
| data = request.get_json() | |
| result = central_server.submit_task(data) | |
| return jsonify(result) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| def api_update_status(): | |
| try: | |
| data = request.get_json() | |
| node_id = data.get('node_id') | |
| if not node_id: | |
| return jsonify({"error": "ู ุนุฑู ุงูุนูุฏุฉ ู ุทููุจ"}), 400 | |
| result = central_server.update_node_status(node_id, data) | |
| return jsonify(result) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| def api_get_nodes(): | |
| try: | |
| overview = central_server.get_system_overview() | |
| return jsonify({ | |
| "status": "success", | |
| "count": len(overview["nodes"]), | |
| "nodes": overview["nodes"] | |
| }) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| def api_get_tasks(): | |
| try: | |
| with central_server.lock: | |
| tasks = list(central_server.tasks.values())[-50:] | |
| tasks_data = [] | |
| for task in tasks: | |
| task_dict = asdict(task) | |
| for field in ["created_at", "started_at", "completed_at"]: | |
| if task_dict[field]: | |
| task_dict[field] = task_dict[field].isoformat() | |
| tasks_data.append(task_dict) | |
| return jsonify({ | |
| "status": "success", | |
| "count": len(tasks_data), | |
| "tasks": tasks_data | |
| }) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| def api_get_stats(): | |
| try: | |
| overview = central_server.get_system_overview() | |
| return jsonify({ | |
| "status": "success", | |
| "stats": overview["metrics"] | |
| }) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| # โโโโโโโโโโโโโโโ ุจุฏุก Flask ูู ุฎูุท ู ููุตู โโโโโโโโโโโโโโโ | |
| def start_flask_server(): | |
| """ุจุฏุก ุฎุงุฏู Flask ููุนูุฏ ุงูุญููููุฉ""" | |
| port = 7861 # ู ููุฐ ู ุฎุชูู ุนู Gradio | |
| flask_app.run( | |
| host="0.0.0.0", | |
| port=port, | |
| debug=False, | |
| threaded=True, | |
| use_reloader=False | |
| ) | |
| # โโโโโโโโโโโโโโโ ุงูุฏุงูุฉ ุงูุฑุฆูุณูุฉ โโโโโโโโโโโโโโโ | |
| def main(): | |
| """ุงูุฏุงูุฉ ุงูุฑุฆูุณูุฉ""" | |
| logger.info("๐ ุจุฏุก ุชุดุบูู ุชุทุจูู Hugging Face ูุฎุงุฏู ู ุฑูุฒู") | |
| # ุจุฏุก ุฎุงุฏู Flask ููAPI ูู ุฎูุท ู ููุตู | |
| flask_thread = threading.Thread(target=start_flask_server, daemon=True) | |
| flask_thread.start() | |
| logger.info("โ ุจุฏุก ุฎุงุฏู Flask API ุนูู ุงูู ููุฐ 7861") | |
| # ุฅูุดุงุก ูุงุฌูุฉ Gradio | |
| demo = create_interface() | |
| # ุชุดุบูู Gradio | |
| demo.launch( | |
| server_name="0.0.0.0", | |
| server_port=7860, | |
| share=False, | |
| debug=False | |
| ) | |
| if __name__ == "__main__": | |
| main() |