Spaces:
Sleeping
Sleeping
| # ========================================================== | |
| # ๐งฎ Decentralized Compute Network Simulation (Hugging Face Ready) | |
| # ========================================================== | |
| import gradio as gr | |
| import threading | |
| import time | |
| import random | |
| import queue | |
| # ========================================================== | |
| # โ๏ธ Worker Node Class (With Trust & Reliability) | |
| # ========================================================== | |
| class WorkerNode: | |
| def __init__(self, node_id, reliability=0.9, speed=1.0): | |
| self.node_id = node_id | |
| self.reliability = reliability | |
| self.speed = speed | |
| self.trust_score = 100 | |
| self.jobs_completed = 0 | |
| self.jobs_failed = 0 | |
| def process_job(self, job_data): | |
| """Simulate compute job.""" | |
| complexity = len(job_data) / 10 | |
| delay = random.uniform(1, 3) * complexity / self.speed | |
| time.sleep(delay) | |
| try: | |
| correct_result = eval(job_data) | |
| except Exception as e: | |
| return {"node": self.node_id, "result": str(e), "status": "error", "trust": self.trust_score} | |
| if random.random() < self.reliability: | |
| result = correct_result | |
| self.trust_score = min(100, self.trust_score + 1) | |
| self.jobs_completed += 1 | |
| status = "โ " | |
| else: | |
| result = correct_result + random.randint(1, 10) | |
| self.trust_score = max(0, self.trust_score - 5) | |
| self.jobs_failed += 1 | |
| status = "โ" | |
| return {"node": self.node_id, "result": result, "status": status, "trust": self.trust_score} | |
| # ========================================================== | |
| # ๐งฉ Scheduler (Job Distribution + Verification) | |
| # ========================================================== | |
| class Scheduler: | |
| def __init__(self, num_nodes=4): | |
| self.nodes = [ | |
| WorkerNode(f"Node-{i+1}", reliability=random.uniform(0.7, 0.98), speed=random.uniform(0.8, 1.5)) | |
| for i in range(num_nodes) | |
| ] | |
| self.job_queue = queue.Queue() | |
| def distribute_job(self, job_data): | |
| """Send job to all nodes concurrently.""" | |
| results = {} | |
| threads = [] | |
| def worker_task(node): | |
| res = node.process_job(job_data) | |
| results[node.node_id] = res | |
| for node in self.nodes: | |
| t = threading.Thread(target=worker_task, args=(node,)) | |
| t.start() | |
| threads.append(t) | |
| for t in threads: | |
| t.join() | |
| return results | |
| def verify_results(self, results): | |
| """Consensus based on trust-weighted voting.""" | |
| trust_weight = {} | |
| for res in results.values(): | |
| val = res["result"] | |
| trust_weight[val] = trust_weight.get(val, 0) + res["trust"] | |
| verified_result = max(trust_weight, key=trust_weight.get) | |
| agreement = trust_weight[verified_result] / sum(trust_weight.values()) | |
| return verified_result, round(agreement * 100, 2) | |
| # ========================================================== | |
| # ๐ง Job Handler | |
| # ========================================================== | |
| scheduler = Scheduler(num_nodes=4) | |
| def submit_job(job_expression): | |
| """Handle job execution request.""" | |
| if not job_expression.strip(): | |
| return "โ ๏ธ Please enter a valid Python expression.", "", "", "", "" | |
| start_time = time.time() | |
| results = scheduler.distribute_job(job_expression) | |
| verified_result, agreement = scheduler.verify_results(results) | |
| elapsed = round(time.time() - start_time, 2) | |
| # Node result logs | |
| node_logs = "\n".join([ | |
| f"{r['node']}: {r['status']} โ {r['result']} (Trust: {r['trust']})" | |
| for r in results.values() | |
| ]) | |
| # Node statistics | |
| performance = "\n".join([ | |
| f"{node.node_id} | Reliability: {node.reliability:.2f} | Trust: {node.trust_score} | Jobs: {node.jobs_completed}/{node.jobs_failed}" | |
| for node in scheduler.nodes | |
| ]) | |
| summary = ( | |
| f"โ **Job Completed in {elapsed}s**\n\n" | |
| f"**Verified Result:** {verified_result}\n" | |
| f"**Node Agreement:** {agreement}%" | |
| ) | |
| return summary, node_logs, verified_result, agreement, performance | |
| # ========================================================== | |
| # ๐จ Gradio Interface | |
| # ========================================================== | |
| with gr.Blocks( | |
| theme=gr.themes.Soft(primary_hue="cyan", secondary_hue="indigo"), | |
| title="๐งฎ Decentralized Compute Network Simulation" | |
| ) as demo: | |
| gr.Markdown(""" | |
| # ๐ **Decentralized Compute Network Simulation** | |
| Simulate how multiple worker nodes compute, verify, and agree on results. | |
| ๐ง Experience a simple *distributed computing model* with **consensus and trust mechanisms**. | |
| --- | |
| ### ๐ก Example Jobs: | |
| - `(2 + 3) ** 4` | |
| - `10 * (5 + 6)` | |
| - `(50 / 2) + (3 * 9)` | |
| --- | |
| """) | |
| with gr.Row(): | |
| job_input = gr.Textbox(label="๐ป Job Expression", placeholder="Enter Python expression...") | |
| submit_btn = gr.Button("๐ Run Job", variant="primary") | |
| with gr.Row(): | |
| result_output = gr.Markdown(label="๐งพ Verified Result") | |
| with gr.Row(): | |
| node_outputs = gr.Textbox(label="๐ก Node Responses", lines=6) | |
| verified_value = gr.Textbox(label="โ Verified Output") | |
| agreement_value = gr.Textbox(label="๐ค Agreement (%)") | |
| gr.Markdown("---") | |
| gr.Markdown("### โ๏ธ **Node Performance & Trust Levels**") | |
| performance_box = gr.Textbox(label="Node Statistics", lines=6) | |
| submit_btn.click( | |
| fn=submit_job, | |
| inputs=job_input, | |
| outputs=[result_output, node_outputs, verified_value, agreement_value, performance_box] | |
| ) | |
| # โ For Hugging Face Spaces | |
| demo.launch() | |