Upload 322 files
Browse filesFiles changed (2)
- api_server_extended.py+734-698
- hf_unified_server.py-190
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698#!/usr/bin/env python3"""API Server Extended - HuggingFace Spaces Deployment ReadyComplete Admin API with Real Data Only - NO MOCKS"""import osimport asyncioimport sqlite3import httpximport jsonimport subprocessfrom pathlib import Pathfrom typing import Optional, Dict, Any, Listfrom datetime import datetimefrom contextlib import asynccontextmanagerfrom collections import defaultdictfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse, FileResponse, HTMLResponsefrom fastapi.staticfiles import StaticFilesfrom pydantic import BaseModel# Environment variablesUSE_MOCK_DATA = os.getenv("USE_MOCK_DATA", "false").lower() == "true"PORT = int(os.getenv("PORT", "7860"))# PathsWORKSPACE_ROOT = Path("/workspace" if Path("/workspace").exists() else ".")DB_PATH = WORKSPACE_ROOT / "data" / "database" / "crypto_monitor.db"LOG_DIR = WORKSPACE_ROOT / "logs"PROVIDERS_CONFIG_PATH = WORKSPACE_ROOT / "providers_config_extended.json"APL_REPORT_PATH = WORKSPACE_ROOT / "PROVIDER_AUTO_DISCOVERY_REPORT.json"# Ensure directories existDB_PATH.parent.mkdir(parents=True, exist_ok=True)LOG_DIR.mkdir(parents=True, exist_ok=True)# Global state for providers_provider_state = {"providers": {},"pools": {},"logs": [],"last_check": None,"stats": {"total": 0, "online": 0, "offline": 0, "degraded": 0}}# ===== Database Setup =====def init_database():"""Initialize SQLite database with required tables"""conn = sqlite3.connect(str(DB_PATH))cursor = conn.cursor()cursor.execute("""CREATE TABLE IF NOT EXISTS prices (id INTEGER PRIMARY KEY AUTOINCREMENT,symbol TEXT NOT NULL,name TEXT,price_usd REAL NOT NULL,volume_24h REAL,market_cap REAL,percent_change_24h REAL,rank INTEGER,timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)""")cursor.execute("CREATE INDEX IF NOT EXISTS idx_prices_symbol ON prices(symbol)")cursor.execute("CREATE INDEX IF NOT EXISTS idx_prices_timestamp ON prices(timestamp)")conn.commit()conn.close()print(f"✓ Database initialized at {DB_PATH}")def save_price_to_db(price_data: Dict[str, Any]):"""Save price data to SQLite"""try:conn = sqlite3.connect(str(DB_PATH))cursor = conn.cursor()cursor.execute("""INSERT INTO prices (symbol, name, price_usd, volume_24h, market_cap, percent_change_24h, rank)VALUES (?, ?, ?, ?, ?, ?, ?)""", (price_data.get("symbol"),price_data.get("name"),price_data.get("price_usd", 0.0),price_data.get("volume_24h"),price_data.get("market_cap"),price_data.get("percent_change_24h"),price_data.get("rank")))conn.commit()conn.close()except Exception as e:print(f"Error saving price to database: {e}")def get_price_history_from_db(symbol: str, limit: int = 10) -> List[Dict[str, Any]]:"""Get price history from SQLite"""try:conn = sqlite3.connect(str(DB_PATH))conn.row_factory = sqlite3.Rowcursor = conn.cursor()cursor.execute("""SELECT * FROM pricesWHERE symbol = ?ORDER BY timestamp DESCLIMIT ?""", (symbol, limit))rows = cursor.fetchall()conn.close()return [dict(row) for row in rows]except Exception as e:print(f"Error fetching price history: {e}")return []# ===== Provider Management =====def load_providers_config() -> Dict[str, Any]:"""Load providers from config file"""try:if PROVIDERS_CONFIG_PATH.exists():with open(PROVIDERS_CONFIG_PATH, 'r') as f:return json.load(f)return {"providers": {}}except Exception as e:print(f"Error loading providers config: {e}")return {"providers": {}}def load_apl_report() -> Dict[str, Any]:"""Load APL validation report"""try:if APL_REPORT_PATH.exists():with open(APL_REPORT_PATH, 'r') as f:return json.load(f)return {}except Exception as e:print(f"Error loading APL report: {e}")return {}# ===== Real Data Providers =====HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36","Accept": "application/json"}async def fetch_coingecko_simple_price() -> Dict[str, Any]:"""Fetch real price data from CoinGecko API"""url = "https://api.coingecko.com/api/v3/simple/price"params = {"ids": "bitcoin,ethereum,binancecoin","vs_currencies": "usd","include_market_cap": "true","include_24hr_vol": "true","include_24hr_change": "true"}async with httpx.AsyncClient(timeout=15.0, headers=HEADERS) as client:response = await client.get(url, params=params)if response.status_code != 200:raise HTTPException(status_code=503, detail=f"CoinGecko API error: HTTP {response.status_code}")return response.json()async def fetch_fear_greed_index() -> Dict[str, Any]:"""Fetch real Fear & Greed Index from Alternative.me"""url = "https://api.alternative.me/fng/"params = {"limit": "1", "format": "json"}async with httpx.AsyncClient(timeout=15.0, headers=HEADERS) as client:response = await client.get(url, params=params)if response.status_code != 200:raise HTTPException(status_code=503, detail=f"Alternative.me API error: HTTP {response.status_code}")return response.json()async def fetch_coingecko_trending() -> Dict[str, Any]:"""Fetch real trending coins from CoinGecko"""url = "https://api.coingecko.com/api/v3/search/trending"async with httpx.AsyncClient(timeout=15.0, headers=HEADERS) as client:response = await client.get(url)if response.status_code != 200:raise HTTPException(status_code=503, detail=f"CoinGecko trending API error: HTTP {response.status_code}")return response.json()# ===== Lifespan Management =====@asynccontextmanagerasync def lifespan(app: FastAPI):"""Application lifespan manager"""print("=" * 80)print("🚀 Starting Crypto Monitor Admin API")print("=" * 80)init_database()# Load providersconfig = load_providers_config()_provider_state["providers"] = config.get("providers", {})print(f"✓ Loaded {len(_provider_state['providers'])} providers from config")# Load APL reportapl_report = load_apl_report()if apl_report:print(f"✓ Loaded APL report with validation data")print(f"✓ Server ready on port {PORT}")print("=" * 80)yieldprint("Shutting down...")# ===== FastAPI Application =====app = FastAPI(title="Crypto Monitor Admin API",description="Real-time cryptocurrency data API with Admin Dashboard",version="5.0.0",lifespan=lifespan)# CORS Middlewareapp.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)# Mount static filestry:static_path = WORKSPACE_ROOT / "static"if static_path.exists():app.mount("/static", StaticFiles(directory=str(static_path)), name="static")print(f"✓ Mounted static files from {static_path}")except Exception as e:print(f"⚠ Could not mount static files: {e}")# ===== HTML UI Endpoints =====@app.get("/", response_class=HTMLResponse)async def serve_admin_dashboard():"""Serve admin dashboard"""html_path = WORKSPACE_ROOT / "admin.html"if html_path.exists():return FileResponse(html_path)return HTMLResponse("<h1>Admin Dashboard</h1><p>admin.html not found</p>")# ===== Health & Status Endpoints =====@app.get("/health")async def health():"""Health check endpoint"""return {"status": "healthy","timestamp": datetime.now().isoformat(),"database": str(DB_PATH),"use_mock_data": USE_MOCK_DATA,"providers_loaded": len(_provider_state["providers"])}@app.get("/api/status")async def get_status():"""System status"""config = load_providers_config()providers = config.get("providers", {})# Count by validation statusvalidated_count = sum(1 for p in providers.values() if p.get("validated"))return {"system_health": "healthy","timestamp": datetime.now().isoformat(),"total_providers": len(providers),"validated_providers": validated_count,"database_status": "connected","apl_available": APL_REPORT_PATH.exists(),"use_mock_data": USE_MOCK_DATA}@app.get("/api/stats")async def get_stats():"""System statistics"""config = load_providers_config()providers = config.get("providers", {})# Group by categorycategories = defaultdict(int)for p in providers.values():cat = p.get("category", "unknown")categories[cat] += 1return {"total_providers": len(providers),"categories": dict(categories),"total_categories": len(categories),"timestamp": datetime.now().isoformat()}# ===== Market Data Endpoint =====@app.get("/api/market")async def get_market_data():"""Market data from CoinGecko - REAL DATA ONLY"""try:data = await fetch_coingecko_simple_price()cryptocurrencies = []coin_mapping = {"bitcoin": {"name": "Bitcoin", "symbol": "BTC", "rank": 1, "image": "https://assets.coingecko.com/coins/images/1/small/bitcoin.png"},"ethereum": {"name": "Ethereum", "symbol": "ETH", "rank": 2, "image": "https://assets.coingecko.com/coins/images/279/small/ethereum.png"},"binancecoin": {"name": "BNB", "symbol": "BNB", "rank": 3, "image": "https://assets.coingecko.com/coins/images/825/small/bnb-icon2_2x.png"}}for coin_id, coin_info in coin_mapping.items():if coin_id in data:coin_data = data[coin_id]crypto_entry = {"rank": coin_info["rank"],"name": coin_info["name"],"symbol": coin_info["symbol"],"price": coin_data.get("usd", 0),"change_24h": coin_data.get("usd_24h_change", 0),"market_cap": coin_data.get("usd_market_cap", 0),"volume_24h": coin_data.get("usd_24h_vol", 0),"image": coin_info["image"]}cryptocurrencies.append(crypto_entry)# Save to databasesave_price_to_db({"symbol": coin_info["symbol"],"name": coin_info["name"],"price_usd": crypto_entry["price"],"volume_24h": crypto_entry["volume_24h"],"market_cap": crypto_entry["market_cap"],"percent_change_24h": crypto_entry["change_24h"],"rank": coin_info["rank"]})# Calculate dominancetotal_market_cap = sum(c["market_cap"] for c in cryptocurrencies)btc_dominance = 0if total_market_cap > 0:btc_entry = next((c for c in cryptocurrencies if c["symbol"] == "BTC"), None)if btc_entry:btc_dominance = (btc_entry["market_cap"] / total_market_cap) * 100return {"cryptocurrencies": cryptocurrencies,"total_market_cap": total_market_cap,"btc_dominance": btc_dominance,"timestamp": datetime.now().isoformat(),"source": "CoinGecko API (Real Data)"}except Exception as e:raise HTTPException(status_code=503, detail=f"Failed to fetch market data: {str(e)}")@app.get("/api/market/history")async def get_market_history(symbol: str = "BTC", limit: int = 10):"""Get price history from database - REAL DATA ONLY"""history = get_price_history_from_db(symbol.upper(), limit)if not history:return {"symbol": symbol,"history": [],"count": 0,"message": "No history available"}return {"symbol": symbol,"history": history,"count": len(history),"source": "SQLite Database (Real Data)"}@app.get("/api/sentiment")async def get_sentiment():"""Sentiment data from Alternative.me - REAL DATA ONLY"""try:data = await fetch_fear_greed_index()if "data" in data and len(data["data"]) > 0:fng_data = data["data"][0]return {"fear_greed_index": int(fng_data["value"]),"fear_greed_label": fng_data["value_classification"],"timestamp": datetime.now().isoformat(),"source": "Alternative.me API (Real Data)"}raise HTTPException(status_code=503, detail="Invalid response from Alternative.me")except Exception as e:raise HTTPException(status_code=503, detail=f"Failed to fetch sentiment: {str(e)}")@app.get("/api/trending")async def get_trending():"""Trending coins from CoinGecko - REAL DATA ONLY"""try:data = await fetch_coingecko_trending()trending_coins = []if "coins" in data:for item in data["coins"][:10]:coin = item.get("item", {})trending_coins.append({"id": coin.get("id"),"name": coin.get("name"),"symbol": coin.get("symbol"),"market_cap_rank": coin.get("market_cap_rank"),"thumb": coin.get("thumb"),"score": coin.get("score", 0)})return {"trending": trending_coins,"count": len(trending_coins),"timestamp": datetime.now().isoformat(),"source": "CoinGecko API (Real Data)"}except Exception as e:raise HTTPException(status_code=503, detail=f"Failed to fetch trending: {str(e)}")# ===== Providers Management Endpoints =====@app.get("/api/providers")async def get_providers():"""Get all providers - REAL DATA from config"""config = load_providers_config()providers = config.get("providers", {})result = []for provider_id, provider_data in providers.items():result.append({"provider_id": provider_id,"name": provider_data.get("name", provider_id),"category": provider_data.get("category", "unknown"),"type": provider_data.get("type", "unknown"),"status": "validated" if provider_data.get("validated") else "unvalidated","validated_at": provider_data.get("validated_at"),"response_time_ms": provider_data.get("response_time_ms"),"added_by": provider_data.get("added_by", "manual")})return {"providers": result,"total": len(result),"source": "providers_config_extended.json (Real Data)"}@app.get("/api/providers/{provider_id}")async def get_provider_detail(provider_id: str):"""Get specific provider details"""config = load_providers_config()providers = config.get("providers", {})if provider_id not in providers:raise HTTPException(status_code=404, detail=f"Provider {provider_id} not found")return {"provider_id": provider_id,**providers[provider_id]}@app.get("/api/providers/category/{category}")async def get_providers_by_category(category: str):"""Get providers by category"""config = load_providers_config()providers = config.get("providers", {})filtered = {pid: data for pid, data in providers.items()if data.get("category") == category}return {"category": category,"providers": filtered,"count": len(filtered)}# ===== Pools Endpoints (Placeholder - to be implemented) =====@app.get("/api/pools")async def get_pools():"""Get provider pools"""return {"pools": [],"message": "Pools feature not yet implemented in this version"}# ===== Logs Endpoints =====@app.get("/api/logs/recent")async def get_recent_logs():"""Get recent logs"""return {"logs": _provider_state.get("logs", [])[-50:],"count": min(50, len(_provider_state.get("logs", [])))}@app.get("/api/logs/errors")async def get_error_logs():"""Get error logs"""all_logs = _provider_state.get("logs", [])errors = [log for log in all_logs if log.get("level") == "ERROR"]return {"errors": errors[-50:],"count": len(errors)}# ===== Diagnostics Endpoints =====@app.post("/api/diagnostics/run")async def run_diagnostics(auto_fix: bool = False):"""Run system diagnostics"""issues = []fixes_applied = []# Check databaseif not DB_PATH.exists():issues.append({"type": "database", "message": "Database file not found"})if auto_fix:init_database()fixes_applied.append("Initialized database")# Check providers configif not PROVIDERS_CONFIG_PATH.exists():issues.append({"type": "config", "message": "Providers config not found"})# Check APL reportif not APL_REPORT_PATH.exists():issues.append({"type": "apl", "message": "APL report not found"})return {"status": "completed","issues_found": len(issues),"issues": issues,"fixes_applied": fixes_applied if auto_fix else [],"timestamp": datetime.now().isoformat()}@app.get("/api/diagnostics/last")async def get_last_diagnostics():"""Get last diagnostics results"""# Would load from file in real implementationreturn {"status": "no_previous_run","message": "No previous diagnostics run found"}# ===== APL (Auto Provider Loader) Endpoints =====@app.post("/api/apl/run")async def run_apl_scan():"""Run APL provider scan"""try:# Run APL scriptresult = subprocess.run(["python3", str(WORKSPACE_ROOT / "auto_provider_loader.py")],capture_output=True,text=True,timeout=300,cwd=str(WORKSPACE_ROOT))# Reload providers after APL runconfig = load_providers_config()_provider_state["providers"] = config.get("providers", {})return {"status": "completed","stdout": result.stdout[-1000:], # Last 1000 chars"returncode": result.returncode,"providers_count": len(_provider_state["providers"]),"timestamp": datetime.now().isoformat()}except subprocess.TimeoutExpired:return {"status": "timeout","message": "APL scan timed out after 5 minutes"}except Exception as e:raise HTTPException(status_code=500, detail=f"APL scan failed: {str(e)}")@app.get("/api/apl/report")async def get_apl_report():"""Get APL validation report"""report = load_apl_report()if not report:return {"status": "not_available","message": "APL report not found. Run APL scan first."}return report@app.get("/api/apl/summary")async def get_apl_summary():"""Get APL summary statistics"""report = load_apl_report()if not report or "stats" not in report:return {"status": "not_available","message": "APL report not found"}stats = report.get("stats", {})return {"http_candidates": stats.get("total_http_candidates", 0),"http_valid": stats.get("http_valid", 0),"http_invalid": stats.get("http_invalid", 0),"http_conditional": stats.get("http_conditional", 0),"hf_candidates": stats.get("total_hf_candidates", 0),"hf_valid": stats.get("hf_valid", 0),"hf_invalid": stats.get("hf_invalid", 0),"hf_conditional": stats.get("hf_conditional", 0),"total_active": stats.get("total_active_providers", 0),"timestamp": stats.get("timestamp", "")}# ===== HF Models Endpoints =====@app.get("/api/hf/models")async def get_hf_models():"""Get HuggingFace models from APL report"""report = load_apl_report()if not report:return {"models": [], "count": 0}hf_models = report.get("hf_models", {}).get("results", [])return {"models": hf_models,"count": len(hf_models),"source": "APL Validation Report (Real Data)"}@app.get("/api/hf/health")async def get_hf_health():"""Get HF services health"""try:from backend.services.hf_registry import REGISTRYhealth = REGISTRY.health()return healthexcept Exception as e:return {"ok": False,"error": f"HF registry not available: {str(e)}"}# ===== DeFi Endpoint - NOT IMPLEMENTED =====@app.get("/api/defi")async def get_defi():"""DeFi endpoint - Not implemented"""raise HTTPException(status_code=503, detail="DeFi endpoint not implemented. Real data only - no fakes.")# ===== HuggingFace ML Sentiment - NOT IMPLEMENTED =====@app.post("/api/hf/run-sentiment")async def run_sentiment(data: Dict[str, Any]):"""ML sentiment analysis - Not implemented"""raise HTTPException(status_code=501, detail="ML sentiment not implemented. Real data only - no fakes.")# ===== Main Entry Point =====if __name__ == "__main__":import uvicornprint(f"Starting Crypto Monitor Admin Server on port {PORT}")uvicorn.run(app, host="0.0.0.0", port=PORT, log_level="info")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734#!/usr/bin/env python3"""API Server Extended - HuggingFace Spaces Deployment ReadyComplete Admin API with Real Data Only - NO MOCKS"""import osimport asyncioimport sqlite3import httpximport jsonimport subprocessfrom pathlib import Pathfrom typing import Optional, Dict, Any, Listfrom datetime import datetimefrom contextlib import asynccontextmanagerfrom collections import defaultdictfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse, FileResponse, HTMLResponsefrom fastapi.staticfiles import StaticFilesfrom pydantic import BaseModel# Environment variablesUSE_MOCK_DATA = os.getenv("USE_MOCK_DATA", "false").lower() == "true"PORT = int(os.getenv("PORT", "7860"))# PathsWORKSPACE_ROOT = Path("/workspace" if Path("/workspace").exists() else ".")DB_PATH = WORKSPACE_ROOT / "data" / "database" / "crypto_monitor.db"LOG_DIR = WORKSPACE_ROOT / "logs"PROVIDERS_CONFIG_PATH = WORKSPACE_ROOT / "providers_config_extended.json"APL_REPORT_PATH = WORKSPACE_ROOT / "PROVIDER_AUTO_DISCOVERY_REPORT.json"# Ensure directories existDB_PATH.parent.mkdir(parents=True, exist_ok=True)LOG_DIR.mkdir(parents=True, exist_ok=True)# Global state for providers_provider_state = {"providers": {},"pools": {},"logs": [],"alerts": [],"last_check": None,"stats": {"total": 0, "online": 0, "offline": 0, "degraded": 0}}# ===== Database Setup =====def init_database():"""Initialize SQLite database with required tables"""conn = sqlite3.connect(str(DB_PATH))cursor = conn.cursor()cursor.execute("""CREATE TABLE IF NOT EXISTS prices (id INTEGER PRIMARY KEY AUTOINCREMENT,symbol TEXT NOT NULL,name TEXT,price_usd REAL NOT NULL,volume_24h REAL,market_cap REAL,percent_change_24h REAL,rank INTEGER,timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)""")cursor.execute("CREATE INDEX IF NOT EXISTS idx_prices_symbol ON prices(symbol)")cursor.execute("CREATE INDEX IF NOT EXISTS idx_prices_timestamp ON prices(timestamp)")conn.commit()conn.close()print(f"✓ Database initialized at {DB_PATH}")def save_price_to_db(price_data: Dict[str, Any]):"""Save price data to SQLite"""try:conn = sqlite3.connect(str(DB_PATH))cursor = conn.cursor()cursor.execute("""INSERT INTO prices (symbol, name, price_usd, volume_24h, market_cap, percent_change_24h, rank)VALUES (?, ?, ?, ?, ?, ?, ?)""", (price_data.get("symbol"),price_data.get("name"),price_data.get("price_usd", 0.0),price_data.get("volume_24h"),price_data.get("market_cap"),price_data.get("percent_change_24h"),price_data.get("rank")))conn.commit()conn.close()except Exception as e:print(f"Error saving price to database: {e}")def get_price_history_from_db(symbol: str, limit: int = 10) -> List[Dict[str, Any]]:"""Get price history from SQLite"""try:conn = sqlite3.connect(str(DB_PATH))conn.row_factory = sqlite3.Rowcursor = conn.cursor()cursor.execute("""SELECT * FROM pricesWHERE symbol = ?ORDER BY timestamp DESCLIMIT ?""", (symbol, limit))rows = cursor.fetchall()conn.close()return [dict(row) for row in rows]except Exception as e:print(f"Error fetching price history: {e}")return []# ===== Provider Management =====def load_providers_config() -> Dict[str, Any]:"""Load providers from config file"""try:if PROVIDERS_CONFIG_PATH.exists():with open(PROVIDERS_CONFIG_PATH, 'r') as f:return json.load(f)return {"providers": {}}except Exception as e:print(f"Error loading providers config: {e}")return {"providers": {}}def load_apl_report() -> Dict[str, Any]:"""Load APL validation report"""try:if APL_REPORT_PATH.exists():with open(APL_REPORT_PATH, 'r') as f:return json.load(f)return {}except Exception as e:print(f"Error loading APL report: {e}")return {}# ===== Real Data Providers =====HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36","Accept": "application/json"}async def fetch_coingecko_simple_price() -> Dict[str, Any]:"""Fetch real price data from CoinGecko API"""url = "https://api.coingecko.com/api/v3/simple/price"params = {"ids": "bitcoin,ethereum,binancecoin","vs_currencies": "usd","include_market_cap": "true","include_24hr_vol": "true","include_24hr_change": "true"}async with httpx.AsyncClient(timeout=15.0, headers=HEADERS) as client:response = await client.get(url, params=params)if response.status_code != 200:raise HTTPException(status_code=503, detail=f"CoinGecko API error: HTTP {response.status_code}")return response.json()async def fetch_fear_greed_index() -> Dict[str, Any]:"""Fetch real Fear & Greed Index from Alternative.me"""url = "https://api.alternative.me/fng/"params = {"limit": "1", "format": "json"}async with httpx.AsyncClient(timeout=15.0, headers=HEADERS) as client:response = await client.get(url, params=params)if response.status_code != 200:raise HTTPException(status_code=503, detail=f"Alternative.me API error: HTTP {response.status_code}")return response.json()async def fetch_coingecko_trending() -> Dict[str, Any]:"""Fetch real trending coins from CoinGecko"""url = "https://api.coingecko.com/api/v3/search/trending"async with httpx.AsyncClient(timeout=15.0, headers=HEADERS) as client:response = await client.get(url)if response.status_code != 200:raise HTTPException(status_code=503, detail=f"CoinGecko trending API error: HTTP {response.status_code}")return response.json()# ===== Lifespan Management =====@asynccontextmanagerasync def lifespan(app: FastAPI):"""Application lifespan manager"""print("=" * 80)print("🚀 Starting Crypto Monitor Admin API")print("=" * 80)init_database()# Load providersconfig = load_providers_config()_provider_state["providers"] = config.get("providers", {})print(f"✓ Loaded {len(_provider_state['providers'])} providers from config")# Load APL reportapl_report = load_apl_report()if apl_report:print(f"✓ Loaded APL report with validation data")print(f"✓ Server ready on port {PORT}")print("=" * 80)yieldprint("Shutting down...")# ===== FastAPI Application =====app = FastAPI(title="Crypto Monitor Admin API",description="Real-time cryptocurrency data API with Admin Dashboard",version="5.0.0",lifespan=lifespan)# CORS Middlewareapp.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)# Mount static filestry:static_path = WORKSPACE_ROOT / "static"if static_path.exists():app.mount("/static", StaticFiles(directory=str(static_path)), name="static")print(f"✓ Mounted static files from {static_path}")except Exception as e:print(f"⚠ Could not mount static files: {e}")# ===== HTML UI Endpoints =====@app.get("/", response_class=HTMLResponse)async def serve_admin_dashboard():"""Serve admin dashboard"""html_path = WORKSPACE_ROOT / "admin.html"if html_path.exists():return FileResponse(html_path)return HTMLResponse("<h1>Admin Dashboard</h1><p>admin.html not found</p>")# ===== Health & Status Endpoints =====@app.get("/health")async def health():"""Health check endpoint"""return {"status": "healthy","timestamp": datetime.now().isoformat(),"database": str(DB_PATH),"use_mock_data": USE_MOCK_DATA,"providers_loaded": len(_provider_state["providers"])}@app.get("/api/status")async def get_status():"""System status"""config = load_providers_config()providers = config.get("providers", {})# Count by validation statusvalidated_count = sum(1 for p in providers.values() if p.get("validated"))return {"system_health": "healthy","timestamp": datetime.now().isoformat(),"total_providers": len(providers),"validated_providers": validated_count,"database_status": "connected","apl_available": APL_REPORT_PATH.exists(),"use_mock_data": USE_MOCK_DATA}@app.get("/api/stats")async def get_stats():"""System statistics"""config = load_providers_config()providers = config.get("providers", {})# Group by categorycategories = defaultdict(int)for p in providers.values():cat = p.get("category", "unknown")categories[cat] += 1return {"total_providers": len(providers),"categories": dict(categories),"total_categories": len(categories),"timestamp": datetime.now().isoformat()}# ===== Market Data Endpoint =====@app.get("/api/market")async def get_market_data():"""Market data from CoinGecko - REAL DATA ONLY"""try:data = await fetch_coingecko_simple_price()cryptocurrencies = []coin_mapping = {"bitcoin": {"name": "Bitcoin", "symbol": "BTC", "rank": 1, "image": "https://assets.coingecko.com/coins/images/1/small/bitcoin.png"},"ethereum": {"name": "Ethereum", "symbol": "ETH", "rank": 2, "image": "https://assets.coingecko.com/coins/images/279/small/ethereum.png"},"binancecoin": {"name": "BNB", "symbol": "BNB", "rank": 3, "image": "https://assets.coingecko.com/coins/images/825/small/bnb-icon2_2x.png"}}for coin_id, coin_info in coin_mapping.items():if coin_id in data:coin_data = data[coin_id]crypto_entry = {"rank": coin_info["rank"],"name": coin_info["name"],"symbol": coin_info["symbol"],"price": coin_data.get("usd", 0),"change_24h": coin_data.get("usd_24h_change", 0),"market_cap": coin_data.get("usd_market_cap", 0),"volume_24h": coin_data.get("usd_24h_vol", 0),"image": coin_info["image"]}cryptocurrencies.append(crypto_entry)# Save to databasesave_price_to_db({"symbol": coin_info["symbol"],"name": coin_info["name"],"price_usd": crypto_entry["price"],"volume_24h": crypto_entry["volume_24h"],"market_cap": crypto_entry["market_cap"],"percent_change_24h": crypto_entry["change_24h"],"rank": coin_info["rank"]})# Calculate dominancetotal_market_cap = sum(c["market_cap"] for c in cryptocurrencies)btc_dominance = 0if total_market_cap > 0:btc_entry = next((c for c in cryptocurrencies if c["symbol"] == "BTC"), None)if btc_entry:btc_dominance = (btc_entry["market_cap"] / total_market_cap) * 100return {"cryptocurrencies": cryptocurrencies,"total_market_cap": total_market_cap,"btc_dominance": btc_dominance,"timestamp": datetime.now().isoformat(),"source": "CoinGecko API (Real Data)"}except Exception as e:raise HTTPException(status_code=503, detail=f"Failed to fetch market data: {str(e)}")@app.get("/api/market/history")async def get_market_history(symbol: str = "BTC", limit: int = 10):"""Get price history from database - REAL DATA ONLY"""history = get_price_history_from_db(symbol.upper(), limit)if not history:return {"symbol": symbol,"history": [],"count": 0,"message": "No history available"}return {"symbol": symbol,"history": history,"count": len(history),"source": "SQLite Database (Real Data)"}@app.get("/api/sentiment")async def get_sentiment():"""Sentiment data from Alternative.me - REAL DATA ONLY"""try:data = await fetch_fear_greed_index()if "data" in data and len(data["data"]) > 0:fng_data = data["data"][0]return {"fear_greed_index": int(fng_data["value"]),"fear_greed_label": fng_data["value_classification"],"timestamp": datetime.now().isoformat(),"source": "Alternative.me API (Real Data)"}raise HTTPException(status_code=503, detail="Invalid response from Alternative.me")except Exception as e:raise HTTPException(status_code=503, detail=f"Failed to fetch sentiment: {str(e)}")@app.get("/api/trending")async def get_trending():"""Trending coins from CoinGecko - REAL DATA ONLY"""try:data = await fetch_coingecko_trending()trending_coins = []if "coins" in data:for item in data["coins"][:10]:coin = item.get("item", {})trending_coins.append({"id": coin.get("id"),"name": coin.get("name"),"symbol": coin.get("symbol"),"market_cap_rank": coin.get("market_cap_rank"),"thumb": coin.get("thumb"),"score": coin.get("score", 0)})return {"trending": trending_coins,"count": len(trending_coins),"timestamp": datetime.now().isoformat(),"source": "CoinGecko API (Real Data)"}except Exception as e:raise HTTPException(status_code=503, detail=f"Failed to fetch trending: {str(e)}")# ===== Providers Management Endpoints =====@app.get("/api/providers")async def get_providers():"""Get all providers - REAL DATA from config"""config = load_providers_config()providers = config.get("providers", {})result = []for provider_id, provider_data in providers.items():result.append({"provider_id": provider_id,"name": provider_data.get("name", provider_id),"category": provider_data.get("category", "unknown"),"type": provider_data.get("type", "unknown"),"status": "validated" if provider_data.get("validated") else "unvalidated","validated_at": provider_data.get("validated_at"),"response_time_ms": provider_data.get("response_time_ms"),"added_by": provider_data.get("added_by", "manual")})return {"providers": result,"total": len(result),"source": "providers_config_extended.json (Real Data)"}@app.get("/api/providers/config")async def get_providers_config():"""Return raw providers configuration file"""config = load_providers_config()return config@app.get("/api/providers/{provider_id}")async def get_provider_detail(provider_id: str):"""Get specific provider details"""config = load_providers_config()providers = config.get("providers", {})if provider_id not in providers:raise HTTPException(status_code=404, detail=f"Provider {provider_id} not found")return {"provider_id": provider_id,**providers[provider_id]}@app.get("/api/providers/category/{category}")async def get_providers_by_category(category: str):"""Get providers by category"""config = load_providers_config()providers = config.get("providers", {})filtered = {pid: data for pid, data in providers.items()if data.get("category") == category}return {"category": category,"providers": filtered,"count": len(filtered)}# ===== Pools Endpoints (Placeholder - to be implemented) =====@app.get("/api/pools")async def get_pools():"""Get provider pools"""return {"pools": [],"message": "Pools feature not yet implemented in this version"}# ===== Logs Endpoints =====@app.get("/api/logs")async def get_logs(limit: int = 50):"""Get recent logs with an optional limit parameter for the admin UI."""all_logs = _provider_state.get("logs", [])if limit <= 0:limit = 50sliced = all_logs[-limit:]return {"logs": sliced,"count": len(sliced),}@app.get("/api/alerts")async def get_alerts():"""Get system alerts for the admin UI."""alerts = _provider_state.get("alerts", [])return {"alerts": alerts,"count": len(alerts),"timestamp": datetime.now().isoformat(),}@app.get("/api/logs/recent")async def get_recent_logs():"""Get recent logs"""return {"logs": _provider_state.get("logs", [])[-50:],"count": min(50, len(_provider_state.get("logs", [])))}@app.get("/api/logs/errors")async def get_error_logs():"""Get error logs"""all_logs = _provider_state.get("logs", [])errors = [log for log in all_logs if log.get("level") == "ERROR"]return {"errors": errors[-50:],"count": len(errors)}# ===== Diagnostics Endpoints =====@app.post("/api/diagnostics/run")async def run_diagnostics(auto_fix: bool = False):"""Run system diagnostics"""issues = []fixes_applied = []# Check databaseif not DB_PATH.exists():issues.append({"type": "database", "message": "Database file not found"})if auto_fix:init_database()fixes_applied.append("Initialized database")# Check providers configif not PROVIDERS_CONFIG_PATH.exists():issues.append({"type": "config", "message": "Providers config not found"})# Check APL reportif not APL_REPORT_PATH.exists():issues.append({"type": "apl", "message": "APL report not found"})return {"status": "completed","issues_found": len(issues),"issues": issues,"fixes_applied": fixes_applied if auto_fix else [],"timestamp": datetime.now().isoformat()}@app.get("/api/diagnostics/last")async def get_last_diagnostics():"""Get last diagnostics results"""# Would load from file in real implementationreturn {"status": "no_previous_run","message": "No previous diagnostics run found"}# ===== APL (Auto Provider Loader) Endpoints =====@app.post("/api/apl/run")async def run_apl_scan():"""Run APL provider scan"""try:# Run APL scriptresult = subprocess.run(["python3", str(WORKSPACE_ROOT / "auto_provider_loader.py")],capture_output=True,text=True,timeout=300,cwd=str(WORKSPACE_ROOT))# Reload providers after APL runconfig = load_providers_config()_provider_state["providers"] = config.get("providers", {})return {"status": "completed","stdout": result.stdout[-1000:], # Last 1000 chars"returncode": result.returncode,"providers_count": len(_provider_state["providers"]),"timestamp": datetime.now().isoformat()}except subprocess.TimeoutExpired:return {"status": "timeout","message": "APL scan timed out after 5 minutes"}except Exception as e:raise HTTPException(status_code=500, detail=f"APL scan failed: {str(e)}")@app.get("/api/apl/report")async def get_apl_report():"""Get APL validation report"""report = load_apl_report()if not report:return {"status": "not_available","message": "APL report not found. Run APL scan first."}return report@app.get("/api/apl/summary")async def get_apl_summary():"""Get APL summary statistics"""report = load_apl_report()if not report or "stats" not in report:return {"status": "not_available","message": "APL report not found"}stats = report.get("stats", {})return {"http_candidates": stats.get("total_http_candidates", 0),"http_valid": stats.get("http_valid", 0),"http_invalid": stats.get("http_invalid", 0),"http_conditional": stats.get("http_conditional", 0),"hf_candidates": stats.get("total_hf_candidates", 0),"hf_valid": stats.get("hf_valid", 0),"hf_invalid": stats.get("hf_invalid", 0),"hf_conditional": stats.get("hf_conditional", 0),"total_active": stats.get("total_active_providers", 0),"timestamp": stats.get("timestamp", "")}# ===== HF Models Endpoints =====@app.get("/api/hf/models")async def get_hf_models():"""Get HuggingFace models from APL report"""report = load_apl_report()if not report:return {"models": [], "count": 0}hf_models = report.get("hf_models", {}).get("results", [])return {"models": hf_models,"count": len(hf_models),"source": "APL Validation Report (Real Data)"}@app.get("/api/hf/health")async def get_hf_health():"""Get HF services health"""try:from backend.services.hf_registry import REGISTRYhealth = REGISTRY.health()return healthexcept Exception as e:return {"ok": False,"error": f"HF registry not available: {str(e)}"}# ===== DeFi Endpoint - NOT IMPLEMENTED =====@app.get("/api/defi")async def get_defi():"""DeFi endpoint - Not implemented"""raise HTTPException(status_code=503, detail="DeFi endpoint not implemented. Real data only - no fakes.")# ===== HuggingFace ML Sentiment - NOT IMPLEMENTED =====@app.post("/api/hf/run-sentiment")async def run_sentiment(data: Dict[str, Any]):"""ML sentiment analysis - Not implemented"""raise HTTPException(status_code=501, detail="ML sentiment not implemented. Real data only - no fakes.")# ===== Main Entry Point =====if __name__ == "__main__":import uvicornprint(f"Starting Crypto Monitor Admin Server on port {PORT}")uvicorn.run(app, host="0.0.0.0", port=PORT, log_level="info")
34 unmodified lines353637383940414243 unmodified lines8687888990919293949596979899100101102103104105106107108109110111112553 unmodified lines6666676686696706716726736746756766776786796806816826836846856866876886891764 unmodified lines2454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260534 unmodified linesfrom pathlib import Pathimport httpxfrom database import CryptoDatabasefrom ai_models import (analyze_chart_points,analyze_crypto_sentiment,43 unmodified linesWORKSPACE_ROOT = Path(__file__).parentPROVIDERS_CONFIG_PATH = settings.providers_config_pathFALLBACK_RESOURCE_PATH = WORKSPACE_ROOT / "crypto_resources_unified_2025-11-11.json"LOG_DIR = WORKSPACE_ROOT / "logs"APL_REPORT_PATH = WORKSPACE_ROOT / "PROVIDER_AUTO_DISCOVERY_REPORT.json"# Ensure log directory existsLOG_DIR.mkdir(parents=True, exist_ok=True)# Initialize SQLite database for real market data persistencedb = CryptoDatabase()def tail_log_file(path: Path, max_lines: int = 200) -> List[str]:"""Return the last max_lines from a log file, if it exists."""if not path.exists():return []try:with path.open("r", encoding="utf-8", errors="ignore") as f:lines = f.readlines()return lines[-max_lines:]except Exception as e:logger.error(f"Error reading log file {path}: {e}")return []def load_providers_config():"""Load providers from providers_config_extended.json"""553 unmodified linesif not prices:raise HTTPException(status_code=503, detail="Unable to fetch market data")# Persist real market data into SQLite database (no mocks)try:for item in prices:payload = {"symbol": item.get("symbol", "").upper(),"name": item.get("name"),"price_usd": item.get("current_price") or item.get("price"),"volume_24h": item.get("total_volume"),"market_cap": item.get("market_cap"),"percent_change_1h": item.get("price_change_1h") or item.get("price_change_percentage_1h_in_currency"),"percent_change_24h": item.get("price_change_percentage_24h"),"percent_change_7d": item.get("price_change_percentage_7d_in_currency"),"rank": item.get("market_cap_rank"),}db.save_price(payload)except Exception as db_err:logger.warning(f"Failed to save market data to DB: {db_err}")return {"total_market_cap": overview.get("total_market_cap", 0),"btc_dominance": overview.get("btc_dominance", 0),1764 unmodified linesws_manager.disconnect(websocket)except:pass@app.get("/api/market/history")async def get_market_history(symbol: str = "BTC", limit: int = 10):"""Get historical prices from the real SQLite database.This uses only stored real market data inserted by /api/marketand never generates synthetic or mock values."""symbol = symbol.upper()try:history = db.get_price_history(symbol, limit=limit)except Exception as e:logger.error(f"Error reading history for {symbol}: {e}")raise HTTPException(status_code=500, detail="Error reading market history")if not history:return {"symbol": symbol,"history": [],"count": 0,"message": "No history available",}return {"symbol": symbol,"history": history,"count": len(history),"source": "SQLite database (real data)",}@app.get("/api/status")async def get_status():"""System status endpoint used by the admin UI.This reports real-time information about providers and database,without fabricating any market data."""providers_cfg = load_providers_config()providers = providers_cfg or {}validated_count = sum(1 for p in providers.values() if p.get("validated"))db_path = Path(db.db_path)db_status = "connected" if db_path.exists() else "initializing"return {"system_health": "healthy","timestamp": datetime.now().isoformat(),"total_providers": len(providers),"validated_providers": validated_count,"database_status": db_status,"apl_available": APL_REPORT_PATH.exists(),"use_mock_data": False,}@app.get("/api/logs/recent")async def get_recent_logs():"""Return recent log lines for the admin UI.We read from the main server log file if available.This does not fabricate content; if there are no logs,an empty list is returned."""log_file = LOG_DIR / "server.log"lines = tail_log_file(log_file, max_lines=200)# Wrap plain text lines as structured entrieslogs = [{"line": line.rstrip("\n")} for line in lines]return {"logs": logs, "count": len(logs)}@app.get("/api/logs/errors")async def get_error_logs():"""Return recent error log lines from the same log file.This is a best-effort filter based on typical ERROR prefixes."""log_file = LOG_DIR / "server.log"lines = tail_log_file(log_file, max_lines=400)error_lines = [line for line in lines if "ERROR" in line or "WARNING" in line]logs = [{"line": line.rstrip("\n")} for line in error_lines[-200:]]return {"errors": logs, "count": len(logs)}def _load_apl_report() -> Optional[Dict[str, Any]]:"""Load the APL (Auto Provider Loader) validation report if available."""if not APL_REPORT_PATH.exists():return Nonetry:with APL_REPORT_PATH.open("r", encoding="utf-8") as f:return json.load(f)except Exception as e:logger.error(f"Error reading APL report: {e}")return None@app.get("/api/apl/summary")async def get_apl_summary():"""Summary of the Auto Provider Loader (APL) report.If the report is missing, we return a clear not_available statusinstead of fabricating metrics."""report = _load_apl_report()if not report or "stats" not in report:return {"status": "not_available","message": "APL report not found",}stats = report.get("stats", {})return {"status": "ok","http_candidates": stats.get("total_http_candidates", 0),"http_valid": stats.get("http_valid", 0),"http_invalid": stats.get("http_invalid", 0),"http_conditional": stats.get("http_conditional", 0),"hf_candidates": stats.get("total_hf_candidates", 0),"hf_valid": stats.get("hf_valid", 0),"hf_invalid": stats.get("hf_invalid", 0),"hf_conditional": stats.get("hf_conditional", 0),"timestamp": datetime.now().isoformat(),}@app.get("/api/hf/models")async def get_hf_models_from_apl():"""Return the list of Hugging Face models discovered by the APL report.This is used by the admin UI. The data comes from the realPROVIDER_AUTO_DISCOVERY_REPORT.json file if present."""report = _load_apl_report()if not report:return {"models": [], "count": 0, "source": "none"}hf_models = report.get("hf_models", {}).get("results", [])return {"models": hf_models,"count": len(hf_models),"source": "APL report",}34 unmodified lines35363738394043 unmodified lines848586878889553 unmodified lines6436446456466476481764 unmodified lines24132414241534 unmodified linesfrom pathlib import Pathimport httpxfrom ai_models import (analyze_chart_points,analyze_crypto_sentiment,43 unmodified linesWORKSPACE_ROOT = Path(__file__).parentPROVIDERS_CONFIG_PATH = settings.providers_config_pathFALLBACK_RESOURCE_PATH = WORKSPACE_ROOT / "crypto_resources_unified_2025-11-11.json"def load_providers_config():"""Load providers from providers_config_extended.json"""553 unmodified linesif not prices:raise HTTPException(status_code=503, detail="Unable to fetch market data")return {"total_market_cap": overview.get("total_market_cap", 0),"btc_dominance": overview.get("btc_dominance", 0),1764 unmodified linesws_manager.disconnect(websocket)except:pass
api_server_extended.py+734-698
hf_unified_server.py-190