Spaces:
Sleeping
Sleeping
File size: 5,776 Bytes
4e8a858 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
# ==========================================================
# ๐งฎ 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()
|