Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,109 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
| 2 |
import time
|
| 3 |
-
import json
|
| 4 |
-
import gradio as gr
|
| 5 |
-
import requests
|
| 6 |
from datetime import datetime
|
| 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 |
return False
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
return
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Eroha AgentAPI v5.8 — AutoRecovery + Smart Dashboard Edition
|
| 3 |
+
Production-grade архитектура для Hugging Face Spaces
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
import os
|
| 7 |
+
import asyncio
|
| 8 |
+
import aiohttp
|
| 9 |
import time
|
|
|
|
|
|
|
|
|
|
| 10 |
from datetime import datetime
|
| 11 |
+
import gradio as gr
|
| 12 |
+
from fastapi import FastAPI
|
| 13 |
+
from fastapi.responses import JSONResponse
|
| 14 |
+
from transformers import pipeline
|
| 15 |
+
import psutil
|
| 16 |
+
|
| 17 |
+
# ==============================
|
| 18 |
+
# CONFIGURATION
|
| 19 |
+
# ==============================
|
| 20 |
+
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 21 |
+
ROUTER_URL = "https://api-inference.huggingface.co/models"
|
| 22 |
+
FALLBACK_MODEL = "sshleifer/tiny-gpt2"
|
| 23 |
+
CHECK_INTERVAL = 300 # 5 min
|
| 24 |
+
|
| 25 |
+
# ==============================
|
| 26 |
+
# CORE CLASSES
|
| 27 |
+
# ==============================
|
| 28 |
+
class CircuitBreaker:
|
| 29 |
+
def __init__(self, threshold=3, timeout=60):
|
| 30 |
+
self.failures = 0
|
| 31 |
+
self.threshold = threshold
|
| 32 |
+
self.timeout = timeout
|
| 33 |
+
self.state = "CLOSED"
|
| 34 |
+
self.last_failure = 0
|
| 35 |
+
|
| 36 |
+
def allow(self):
|
| 37 |
+
if self.state == "OPEN" and time.time() - self.last_failure < self.timeout:
|
| 38 |
return False
|
| 39 |
+
if self.state == "OPEN" and time.time() - self.last_failure >= self.timeout:
|
| 40 |
+
self.state = "HALF_OPEN"
|
| 41 |
+
return True
|
| 42 |
+
|
| 43 |
+
def record_success(self):
|
| 44 |
+
self.failures = 0
|
| 45 |
+
if self.state in ["HALF_OPEN", "OPEN"]:
|
| 46 |
+
self.state = "CLOSED"
|
| 47 |
+
|
| 48 |
+
def record_failure(self):
|
| 49 |
+
self.failures += 1
|
| 50 |
+
if self.failures >= self.threshold:
|
| 51 |
+
self.state = "OPEN"
|
| 52 |
+
self.last_failure = time.time()
|
| 53 |
+
|
| 54 |
+
circuit = CircuitBreaker()
|
| 55 |
+
|
| 56 |
+
class HFClient:
|
| 57 |
+
def __init__(self):
|
| 58 |
+
self.token = HF_TOKEN
|
| 59 |
+
self.headers = {"Authorization": f"Bearer {self.token}"} if self.token else {}
|
| 60 |
+
self.valid = False
|
| 61 |
+
|
| 62 |
+
async def validate(self):
|
| 63 |
+
try:
|
| 64 |
+
async with aiohttp.ClientSession() as s:
|
| 65 |
+
async with s.get("https://huggingface.co/api/whoami-v2", headers=self.headers) as r:
|
| 66 |
+
self.valid = r.status == 200
|
| 67 |
+
return self.valid
|
| 68 |
+
except:
|
| 69 |
+
self.valid = False
|
| 70 |
+
return False
|
| 71 |
+
|
| 72 |
+
async def infer(self, model, text):
|
| 73 |
+
if not circuit.allow():
|
| 74 |
+
return {"error": "Circuit breaker open — fallback engaged"}
|
| 75 |
+
|
| 76 |
+
try:
|
| 77 |
+
async with aiohttp.ClientSession() as s:
|
| 78 |
+
payload = {"inputs": text, "parameters": {"max_new_tokens": 250}}
|
| 79 |
+
async with s.post(f"{ROUTER_URL}/{model}", headers=self.headers, json=payload, timeout=30) as r:
|
| 80 |
+
if r.status == 200:
|
| 81 |
+
circuit.record_success()
|
| 82 |
+
data = await r.json()
|
| 83 |
+
return data
|
| 84 |
+
else:
|
| 85 |
+
circuit.record_failure()
|
| 86 |
+
if r.status == 401:
|
| 87 |
+
self.valid = False
|
| 88 |
+
return {"error": f"Router error {r.status}"}
|
| 89 |
+
except Exception as e:
|
| 90 |
+
circuit.record_failure()
|
| 91 |
+
return {"error": str(e)}
|
| 92 |
+
|
| 93 |
+
client = HFClient()
|
| 94 |
+
|
| 95 |
+
class Fallback:
|
| 96 |
+
def __init__(self):
|
| 97 |
+
self.pipe = None
|
| 98 |
+
self.ready = False
|
| 99 |
+
|
| 100 |
+
async def load(self):
|
| 101 |
+
if not self.ready:
|
| 102 |
+
self.pipe = pipeline("text-generation", model=FALLBACK_MODEL)
|
| 103 |
+
self.ready = True
|
| 104 |
+
|
| 105 |
+
async def generate(self, text):
|
| 106 |
+
await self.load()
|
| 107 |
+
out = self.pipe(text, max_new_tokens=100)[0]["generated_text"]
|
| 108 |
+
return out
|
| 109 |
+
|
| 110 |
+
fallback = Fallback()
|
| 111 |
+
|
| 112 |
+
# ==============================
|
| 113 |
+
# WATCHDOG
|
| 114 |
+
# ==============================
|
| 115 |
+
async def watchdog():
|
| 116 |
+
while True:
|
| 117 |
+
print(f"[{datetime.now().isoformat()}] 🔍 Watchdog check...")
|
| 118 |
+
await client.validate()
|
| 119 |
+
mem = psutil.virtual_memory().percent
|
| 120 |
+
if mem > 85:
|
| 121 |
+
print(f"⚠️ High memory usage: {mem}%")
|
| 122 |
+
await asyncio.sleep(CHECK_INTERVAL)
|
| 123 |
+
|
| 124 |
+
# ==============================
|
| 125 |
+
# FASTAPI CORE
|
| 126 |
+
# ==============================
|
| 127 |
+
app = FastAPI(title="Eroha AgentAPI v5.8")
|
| 128 |
+
|
| 129 |
+
@app.on_event("startup")
|
| 130 |
+
async def startup():
|
| 131 |
+
asyncio.create_task(watchdog())
|
| 132 |
+
await client.validate()
|
| 133 |
+
|
| 134 |
+
@app.get("/health")
|
| 135 |
+
async def health():
|
| 136 |
+
return JSONResponse({
|
| 137 |
+
"status": "ok" if client.valid else "degraded",
|
| 138 |
+
"circuit": circuit.state,
|
| 139 |
+
"memory": psutil.virtual_memory().percent,
|
| 140 |
+
"timestamp": datetime.now().isoformat()
|
| 141 |
+
})
|
| 142 |
+
|
| 143 |
+
@app.post("/inference")
|
| 144 |
+
async def inference(data: dict):
|
| 145 |
+
text = data.get("prompt", "")
|
| 146 |
+
model = data.get("model", "microsoft/phi-3-mini-4k-instruct")
|
| 147 |
+
|
| 148 |
+
res = await client.infer(model, text)
|
| 149 |
+
if "error" in res:
|
| 150 |
+
fb = await fallback.generate(text)
|
| 151 |
+
return {"source": "fallback", "response": fb, "note": res["error"]}
|
| 152 |
+
return {"source": "router", "response": res}
|
| 153 |
+
|
| 154 |
+
# ==============================
|
| 155 |
+
# GRADIO INTERFACE
|
| 156 |
+
# ==============================
|
| 157 |
+
def gradio_infer(prompt, model_choice):
|
| 158 |
+
loop = asyncio.new_event_loop()
|
| 159 |
+
asyncio.set_event_loop(loop)
|
| 160 |
+
result = loop.run_until_complete(client.infer(model_choice, prompt))
|
| 161 |
+
loop.close()
|
| 162 |
+
if "error" in result:
|
| 163 |
+
fb = asyncio.run(fallback.generate(prompt))
|
| 164 |
+
return f"⚠️ Router failed ({result['error']})\n\n🧠 Fallback:\n{fb}"
|
| 165 |
+
if isinstance(result, list):
|
| 166 |
+
return result[0].get("generated_text", str(result))
|
| 167 |
+
return str(result)
|
| 168 |
+
|
| 169 |
+
def show_dashboard():
|
| 170 |
+
mem = psutil.virtual_memory().percent
|
| 171 |
+
status = "✅ OK" if client.valid else "⚠️ Token Invalid"
|
| 172 |
+
return f"""
|
| 173 |
+
### 🧠 Eroha AgentAPI Dashboard
|
| 174 |
+
| Metric | Status |
|
| 175 |
+
|--------|--------|
|
| 176 |
+
| Token Valid | {status} |
|
| 177 |
+
| Circuit | {circuit.state} |
|
| 178 |
+
| Memory Usage | {mem}% |
|
| 179 |
+
| Time | {datetime.now().strftime("%H:%M:%S")} |
|
| 180 |
+
"""
|
| 181 |
+
|
| 182 |
+
demo = gr.Blocks(title="Eroha AgentAPI v5.8 — AutoRecovery Edition")
|
| 183 |
+
with demo:
|
| 184 |
+
gr.Markdown("# 🤖 Eroha AgentAPI v5.8 — AutoRecovery + Smart Dashboard")
|
| 185 |
+
with gr.Tab("💬 Chat"):
|
| 186 |
+
inp = gr.Textbox(label="Введите запрос")
|
| 187 |
+
model = gr.Dropdown(
|
| 188 |
+
["microsoft/phi-3-mini-4k-instruct", "google/gemma-2-2b-it", "meta-llama/Meta-Llama-3-8B-Instruct"],
|
| 189 |
+
value="microsoft/phi-3-mini-4k-instruct", label="Модель"
|
| 190 |
+
)
|
| 191 |
+
out = gr.Textbox(label="Ответ")
|
| 192 |
+
btn = gr.Button("🚀 Отправить")
|
| 193 |
+
btn.click(fn=gradio_infer, inputs=[inp, model], outputs=out)
|
| 194 |
+
with gr.Tab("📊 Dashboard"):
|
| 195 |
+
dash = gr.Markdown()
|
| 196 |
+
refresh = gr.Button("🔄 Обновить состояние")
|
| 197 |
+
refresh.click(fn=show_dashboard, outputs=dash)
|
| 198 |
+
dash.value = show_dashboard()
|
| 199 |
+
|
| 200 |
+
app = gr.mount_gradio_app(app, demo, path="/ui")
|
| 201 |
+
|
| 202 |
+
if __name__ == "__main__":
|
| 203 |
+
import uvicorn
|
| 204 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|