Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -1,21 +1,19 @@
|
|
| 1 |
"""
|
| 2 |
-
Hugging Face Spaces Cluster - Controller
|
|
|
|
| 3 |
"""
|
| 4 |
|
| 5 |
import os
|
| 6 |
-
import time
|
| 7 |
import json
|
| 8 |
import uuid
|
| 9 |
import threading
|
| 10 |
import numpy as np
|
| 11 |
from datetime import datetime
|
| 12 |
-
from fastapi import FastAPI, Request
|
| 13 |
-
from fastapi.responses import JSONResponse
|
| 14 |
import gradio as gr
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 17 |
CONTROLLER_ID = os.getenv("CONTROLLER_ID", "controller")
|
| 18 |
-
SPACE_NAME = os.getenv("SPACE_NAME", "")
|
| 19 |
|
| 20 |
class ClusterController:
|
| 21 |
def __init__(self):
|
|
@@ -25,7 +23,7 @@ class ClusterController:
|
|
| 25 |
|
| 26 |
def register_worker(self, worker_id):
|
| 27 |
with self.lock:
|
| 28 |
-
self.workers[worker_id] = {"status": "ready", "
|
| 29 |
print(f"β
Worker registriert: {worker_id}")
|
| 30 |
return {"status": "ok"}
|
| 31 |
|
|
@@ -46,12 +44,11 @@ class ClusterController:
|
|
| 46 |
|
| 47 |
def _distribute_task(self, task_id):
|
| 48 |
worker_id = self.get_available_worker()
|
| 49 |
-
if worker_id
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
print(f"π€ Task {task_id[:8]} β {worker_id}")
|
| 55 |
return worker_id
|
| 56 |
|
| 57 |
def submit_result(self, worker_id, task_id, result):
|
|
@@ -65,103 +62,80 @@ class ClusterController:
|
|
| 65 |
print(f"β
Task {task_id[:8]} abgeschlossen")
|
| 66 |
return {"status": "ok"}
|
| 67 |
|
| 68 |
-
def get_task_status(self, task_id):
|
| 69 |
-
with self.lock:
|
| 70 |
-
if task_id in self.tasks:
|
| 71 |
-
t = self.tasks[task_id]
|
| 72 |
-
return {"task_id": task_id, "status": t["status"], "result": t["result"]}
|
| 73 |
-
return {"status": "not_found"}
|
| 74 |
-
|
| 75 |
def get_cluster_status(self):
|
| 76 |
with self.lock:
|
| 77 |
return {
|
| 78 |
-
"workers": {"total": len(self.workers), "ready": sum(1 for w in self.workers.values() if w["status"] == "ready")
|
| 79 |
-
"tasks": {"total": len(self.tasks), "
|
| 80 |
"worker_list": [{"id": wid, "status": info["status"], "tasks": info["tasks_completed"]} for wid, info in self.workers.items()]
|
| 81 |
}
|
| 82 |
|
| 83 |
controller = ClusterController()
|
| 84 |
|
| 85 |
-
#
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
@app.post("/api/register")
|
| 89 |
-
async def register_worker(request: Request):
|
| 90 |
-
data = await request.json()
|
| 91 |
-
return controller.register_worker(data["worker_id"])
|
| 92 |
-
|
| 93 |
-
@app.get("/api/get_task")
|
| 94 |
-
async def get_task(worker_id: str):
|
| 95 |
-
with controller.lock:
|
| 96 |
-
for task_id, task in controller.tasks.items():
|
| 97 |
-
if task["status"] == "pending":
|
| 98 |
-
task["status"] = "assigned"
|
| 99 |
-
task["worker_id"] = worker_id
|
| 100 |
-
return {"id": task_id, "type": task["type"], "data": task["data"].tolist() if hasattr(task["data"], 'tolist') else task["data"]}
|
| 101 |
-
return {}
|
| 102 |
-
|
| 103 |
-
@app.post("/api/submit_result")
|
| 104 |
-
async def submit_result(request: Request):
|
| 105 |
-
data = await request.json()
|
| 106 |
-
return controller.submit_result(data["worker_id"], data["task_id"], data["result"])
|
| 107 |
-
|
| 108 |
-
@app.get("/api/task_status")
|
| 109 |
-
async def task_status(task_id: str):
|
| 110 |
-
return controller.get_task_status(task_id)
|
| 111 |
-
|
| 112 |
-
@app.get("/api/cluster_status")
|
| 113 |
-
async def cluster_status():
|
| 114 |
-
return controller.get_cluster_status()
|
| 115 |
-
|
| 116 |
-
# Gradio UI
|
| 117 |
-
def ui_get_status():
|
| 118 |
status = controller.get_cluster_status()
|
| 119 |
-
workers_html = "<br>".join([f"
|
| 120 |
return f"""## Cluster Status
|
|
|
|
|
|
|
| 121 |
|
| 122 |
-
|
| 123 |
-
- Gesamt: {status['workers']['total']}
|
| 124 |
-
- Bereit: {status['workers']['ready']} π’
|
| 125 |
-
- BeschΓ€ftigt: {status['workers']['busy']} π΄
|
| 126 |
-
|
| 127 |
-
### Worker Liste
|
| 128 |
{workers_html}"""
|
| 129 |
|
| 130 |
-
def
|
| 131 |
try:
|
| 132 |
data = json.loads(data_str)
|
| 133 |
if isinstance(data, list):
|
| 134 |
data = np.array(data)
|
| 135 |
task_id = controller.submit_task(task_type, data)
|
| 136 |
-
return f"β
Task
|
| 137 |
except Exception as e:
|
| 138 |
-
return f"β
|
| 139 |
|
|
|
|
| 140 |
with gr.Blocks(title="Cluster Controller") as demo:
|
| 141 |
gr.Markdown("# π€ Cluster Controller")
|
| 142 |
with gr.Tabs():
|
| 143 |
-
with gr.Tab("
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
demo.load(fn=
|
| 148 |
-
with gr.Tab("Task
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
from gradio.routes import mount_gradio_app
|
| 162 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 163 |
|
| 164 |
-
app.
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
Hugging Face Spaces Cluster - Controller v2
|
| 3 |
+
Funktioniert mit Gradio 4.x
|
| 4 |
"""
|
| 5 |
|
| 6 |
import os
|
|
|
|
| 7 |
import json
|
| 8 |
import uuid
|
| 9 |
import threading
|
| 10 |
import numpy as np
|
| 11 |
from datetime import datetime
|
|
|
|
|
|
|
| 12 |
import gradio as gr
|
| 13 |
+
from fastapi import Request
|
| 14 |
+
from fastapi.responses import JSONResponse
|
| 15 |
|
|
|
|
| 16 |
CONTROLLER_ID = os.getenv("CONTROLLER_ID", "controller")
|
|
|
|
| 17 |
|
| 18 |
class ClusterController:
|
| 19 |
def __init__(self):
|
|
|
|
| 23 |
|
| 24 |
def register_worker(self, worker_id):
|
| 25 |
with self.lock:
|
| 26 |
+
self.workers[worker_id] = {"status": "ready", "tasks_completed": 0}
|
| 27 |
print(f"β
Worker registriert: {worker_id}")
|
| 28 |
return {"status": "ok"}
|
| 29 |
|
|
|
|
| 44 |
|
| 45 |
def _distribute_task(self, task_id):
|
| 46 |
worker_id = self.get_available_worker()
|
| 47 |
+
if worker_id:
|
| 48 |
+
with self.lock:
|
| 49 |
+
self.tasks[task_id]["worker_id"] = worker_id
|
| 50 |
+
self.tasks[task_id]["status"] = "assigned"
|
| 51 |
+
print(f"π€ Task {task_id[:8]} β {worker_id}")
|
|
|
|
| 52 |
return worker_id
|
| 53 |
|
| 54 |
def submit_result(self, worker_id, task_id, result):
|
|
|
|
| 62 |
print(f"β
Task {task_id[:8]} abgeschlossen")
|
| 63 |
return {"status": "ok"}
|
| 64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
def get_cluster_status(self):
|
| 66 |
with self.lock:
|
| 67 |
return {
|
| 68 |
+
"workers": {"total": len(self.workers), "ready": sum(1 for w in self.workers.values() if w["status"] == "ready")},
|
| 69 |
+
"tasks": {"total": len(self.tasks), "completed": sum(1 for t in self.tasks.values() if t["status"] == "completed")},
|
| 70 |
"worker_list": [{"id": wid, "status": info["status"], "tasks": info["tasks_completed"]} for wid, info in self.workers.items()]
|
| 71 |
}
|
| 72 |
|
| 73 |
controller = ClusterController()
|
| 74 |
|
| 75 |
+
# UI Functions
|
| 76 |
+
def get_status():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
status = controller.get_cluster_status()
|
| 78 |
+
workers_html = "<br>".join([f"β’ {w['id']}: {'π’' if w['status'] == 'ready' else 'π΄'} ({w['tasks']} Tasks)" for w in status["worker_list"]]) or "Keine Worker"
|
| 79 |
return f"""## Cluster Status
|
| 80 |
+
**Worker:** {status['workers']['total']} ({status['workers']['ready']} ready)
|
| 81 |
+
**Tasks:** {status['tasks']['total']} ({status['tasks']['completed']} completed)
|
| 82 |
|
| 83 |
+
**Worker Liste:**
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
{workers_html}"""
|
| 85 |
|
| 86 |
+
def submit_task(task_type, data_str):
|
| 87 |
try:
|
| 88 |
data = json.loads(data_str)
|
| 89 |
if isinstance(data, list):
|
| 90 |
data = np.array(data)
|
| 91 |
task_id = controller.submit_task(task_type, data)
|
| 92 |
+
return f"β
Task: `{task_id[:8]}`"
|
| 93 |
except Exception as e:
|
| 94 |
+
return f"β {e}"
|
| 95 |
|
| 96 |
+
# Gradio UI
|
| 97 |
with gr.Blocks(title="Cluster Controller") as demo:
|
| 98 |
gr.Markdown("# π€ Cluster Controller")
|
| 99 |
with gr.Tabs():
|
| 100 |
+
with gr.Tab("Status"):
|
| 101 |
+
btn = gr.Button("π Refresh")
|
| 102 |
+
out = gr.Markdown()
|
| 103 |
+
btn.click(fn=get_status, outputs=out)
|
| 104 |
+
demo.load(fn=get_status, outputs=out)
|
| 105 |
+
with gr.Tab("Task"):
|
| 106 |
+
t = gr.Dropdown(choices=["sum", "mean"], value="sum", label="Typ")
|
| 107 |
+
d = gr.Textbox(label="Daten", value="[1,2,3,4,5]")
|
| 108 |
+
b = gr.Button("Senden")
|
| 109 |
+
r = gr.Textbox(label="Ergebnis")
|
| 110 |
+
b.click(fn=submit_task, inputs=[t,d], outputs=r)
|
| 111 |
+
|
| 112 |
+
# API Routes NACH Gradio mounten
|
| 113 |
+
def setup_api():
|
| 114 |
+
@demo.app.post("/api/register")
|
| 115 |
+
async def register(req: Request):
|
| 116 |
+
data = await req.json()
|
| 117 |
+
return controller.register_worker(data.get("worker_id", "unknown"))
|
|
|
|
|
|
|
| 118 |
|
| 119 |
+
@demo.app.get("/api/get_task")
|
| 120 |
+
async def get_task(worker_id: str):
|
| 121 |
+
with controller.lock:
|
| 122 |
+
for tid, t in controller.tasks.items():
|
| 123 |
+
if t["status"] == "pending":
|
| 124 |
+
t["status"] = "assigned"
|
| 125 |
+
t["worker_id"] = worker_id
|
| 126 |
+
return {"id": tid, "type": t["type"], "data": t["data"].tolist() if hasattr(t["data"], 'tolist') else t["data"]}
|
| 127 |
+
return {}
|
| 128 |
|
| 129 |
+
@demo.app.post("/api/submit_result")
|
| 130 |
+
async def submit_result(req: Request):
|
| 131 |
+
data = await req.json()
|
| 132 |
+
return controller.submit_result(data["worker_id"], data["task_id"], data["result"])
|
| 133 |
+
|
| 134 |
+
@demo.app.get("/api/cluster_status")
|
| 135 |
+
async def cluster_status():
|
| 136 |
+
return controller.get_cluster_status()
|
| 137 |
+
|
| 138 |
+
if __name__ == "__main__":
|
| 139 |
+
setup_api()
|
| 140 |
+
print("π Starte Controller...")
|
| 141 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|