BasitAliii commited on
Commit
4e8a858
ยท
verified ยท
1 Parent(s): ec1d637

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +168 -0
app.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ==========================================================
2
+ # ๐Ÿงฎ Decentralized Compute Network Simulation (Hugging Face Ready)
3
+ # ==========================================================
4
+ import gradio as gr
5
+ import threading
6
+ import time
7
+ import random
8
+ import queue
9
+
10
+ # ==========================================================
11
+ # โš™๏ธ Worker Node Class (With Trust & Reliability)
12
+ # ==========================================================
13
+ class WorkerNode:
14
+ def __init__(self, node_id, reliability=0.9, speed=1.0):
15
+ self.node_id = node_id
16
+ self.reliability = reliability
17
+ self.speed = speed
18
+ self.trust_score = 100
19
+ self.jobs_completed = 0
20
+ self.jobs_failed = 0
21
+
22
+ def process_job(self, job_data):
23
+ """Simulate compute job."""
24
+ complexity = len(job_data) / 10
25
+ delay = random.uniform(1, 3) * complexity / self.speed
26
+ time.sleep(delay)
27
+
28
+ try:
29
+ correct_result = eval(job_data)
30
+ except Exception as e:
31
+ return {"node": self.node_id, "result": str(e), "status": "error", "trust": self.trust_score}
32
+
33
+ if random.random() < self.reliability:
34
+ result = correct_result
35
+ self.trust_score = min(100, self.trust_score + 1)
36
+ self.jobs_completed += 1
37
+ status = "โœ…"
38
+ else:
39
+ result = correct_result + random.randint(1, 10)
40
+ self.trust_score = max(0, self.trust_score - 5)
41
+ self.jobs_failed += 1
42
+ status = "โŒ"
43
+
44
+ return {"node": self.node_id, "result": result, "status": status, "trust": self.trust_score}
45
+
46
+
47
+ # ==========================================================
48
+ # ๐Ÿงฉ Scheduler (Job Distribution + Verification)
49
+ # ==========================================================
50
+ class Scheduler:
51
+ def __init__(self, num_nodes=4):
52
+ self.nodes = [
53
+ WorkerNode(f"Node-{i+1}", reliability=random.uniform(0.7, 0.98), speed=random.uniform(0.8, 1.5))
54
+ for i in range(num_nodes)
55
+ ]
56
+ self.job_queue = queue.Queue()
57
+
58
+ def distribute_job(self, job_data):
59
+ """Send job to all nodes concurrently."""
60
+ results = {}
61
+ threads = []
62
+
63
+ def worker_task(node):
64
+ res = node.process_job(job_data)
65
+ results[node.node_id] = res
66
+
67
+ for node in self.nodes:
68
+ t = threading.Thread(target=worker_task, args=(node,))
69
+ t.start()
70
+ threads.append(t)
71
+
72
+ for t in threads:
73
+ t.join()
74
+ return results
75
+
76
+ def verify_results(self, results):
77
+ """Consensus based on trust-weighted voting."""
78
+ trust_weight = {}
79
+ for res in results.values():
80
+ val = res["result"]
81
+ trust_weight[val] = trust_weight.get(val, 0) + res["trust"]
82
+
83
+ verified_result = max(trust_weight, key=trust_weight.get)
84
+ agreement = trust_weight[verified_result] / sum(trust_weight.values())
85
+ return verified_result, round(agreement * 100, 2)
86
+
87
+
88
+ # ==========================================================
89
+ # ๐Ÿง  Job Handler
90
+ # ==========================================================
91
+ scheduler = Scheduler(num_nodes=4)
92
+
93
+ def submit_job(job_expression):
94
+ """Handle job execution request."""
95
+ if not job_expression.strip():
96
+ return "โš ๏ธ Please enter a valid Python expression.", "", "", "", ""
97
+
98
+ start_time = time.time()
99
+ results = scheduler.distribute_job(job_expression)
100
+ verified_result, agreement = scheduler.verify_results(results)
101
+ elapsed = round(time.time() - start_time, 2)
102
+
103
+ # Node result logs
104
+ node_logs = "\n".join([
105
+ f"{r['node']}: {r['status']} โ†’ {r['result']} (Trust: {r['trust']})"
106
+ for r in results.values()
107
+ ])
108
+
109
+ # Node statistics
110
+ performance = "\n".join([
111
+ f"{node.node_id} | Reliability: {node.reliability:.2f} | Trust: {node.trust_score} | Jobs: {node.jobs_completed}/{node.jobs_failed}"
112
+ for node in scheduler.nodes
113
+ ])
114
+
115
+ summary = (
116
+ f"โœ… **Job Completed in {elapsed}s**\n\n"
117
+ f"**Verified Result:** {verified_result}\n"
118
+ f"**Node Agreement:** {agreement}%"
119
+ )
120
+
121
+ return summary, node_logs, verified_result, agreement, performance
122
+
123
+
124
+ # ==========================================================
125
+ # ๐ŸŽจ Gradio Interface
126
+ # ==========================================================
127
+ with gr.Blocks(
128
+ theme=gr.themes.Soft(primary_hue="cyan", secondary_hue="indigo"),
129
+ title="๐Ÿงฎ Decentralized Compute Network Simulation"
130
+ ) as demo:
131
+
132
+ gr.Markdown("""
133
+ # ๐ŸŒ **Decentralized Compute Network Simulation**
134
+ Simulate how multiple worker nodes compute, verify, and agree on results.
135
+ ๐Ÿง  Experience a simple *distributed computing model* with **consensus and trust mechanisms**.
136
+
137
+ ---
138
+ ### ๐Ÿ’ก Example Jobs:
139
+ - `(2 + 3) ** 4`
140
+ - `10 * (5 + 6)`
141
+ - `(50 / 2) + (3 * 9)`
142
+ ---
143
+ """)
144
+
145
+ with gr.Row():
146
+ job_input = gr.Textbox(label="๐Ÿ’ป Job Expression", placeholder="Enter Python expression...")
147
+ submit_btn = gr.Button("๐Ÿš€ Run Job", variant="primary")
148
+
149
+ with gr.Row():
150
+ result_output = gr.Markdown(label="๐Ÿงพ Verified Result")
151
+
152
+ with gr.Row():
153
+ node_outputs = gr.Textbox(label="๐Ÿ“ก Node Responses", lines=6)
154
+ verified_value = gr.Textbox(label="โœ… Verified Output")
155
+ agreement_value = gr.Textbox(label="๐Ÿค Agreement (%)")
156
+
157
+ gr.Markdown("---")
158
+ gr.Markdown("### โš™๏ธ **Node Performance & Trust Levels**")
159
+ performance_box = gr.Textbox(label="Node Statistics", lines=6)
160
+
161
+ submit_btn.click(
162
+ fn=submit_job,
163
+ inputs=job_input,
164
+ outputs=[result_output, node_outputs, verified_value, agreement_value, performance_box]
165
+ )
166
+
167
+ # โœ… For Hugging Face Spaces
168
+ demo.launch()