File size: 16,929 Bytes
b190b45 |
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 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 |
#!/usr/bin/env python3
"""
Real Data API Router - UNIFIED HUGGINGFACE ONLY
=================================================
✅ تمام دادهها از HuggingFace Space
✅ بدون WebSocket (فقط HTTP REST API)
✅ بدون استفاده مستقیم از CoinMarketCap, NewsAPI, etc.
✅ تمام درخواستها از طریق HuggingFaceUnifiedClient
Reference: crypto_resources_unified_2025-11-11.json
"""
from fastapi import APIRouter, HTTPException, Query, Body
from fastapi.responses import JSONResponse
from typing import Optional, List, Dict, Any
from datetime import datetime
from pydantic import BaseModel
import logging
# Import ONLY HuggingFace Unified Client
from backend.services.hf_unified_client import get_hf_client
logger = logging.getLogger(__name__)
router = APIRouter(tags=["Unified HuggingFace API"])
# Get singleton HF client
hf_client = get_hf_client()
# ============================================================================
# Pydantic Models
# ============================================================================
class PredictRequest(BaseModel):
"""Model prediction request"""
symbol: str
context: Optional[str] = None
params: Optional[Dict[str, Any]] = None
class SentimentRequest(BaseModel):
"""Sentiment analysis request"""
text: str
mode: Optional[str] = "crypto"
# ============================================================================
# Market Data Endpoints - از HuggingFace فقط
# ============================================================================
@router.get("/api/market")
async def get_market_snapshot(
limit: int = Query(100, description="Number of symbols"),
symbols: Optional[str] = Query(None, description="Comma-separated symbols (e.g., BTC,ETH)")
):
"""
دریافت دادههای بازار از HuggingFace Space
✅ فقط از HuggingFace
❌ بدون CoinMarketCap
❌ بدون API های دیگر
"""
try:
symbol_list = None
if symbols:
symbol_list = [s.strip() for s in symbols.split(',')]
result = await hf_client.get_market_prices(
symbols=symbol_list,
limit=limit
)
if not result.get("success"):
raise HTTPException(
status_code=503,
detail=result.get("error", "HuggingFace Space returned error")
)
logger.info(f"✅ Market data from HF: {len(result.get('data', []))} symbols")
return result
except HTTPException:
raise
except Exception as e:
logger.error(f"❌ Market data failed: {e}")
raise HTTPException(
status_code=503,
detail=f"Failed to fetch market data from HuggingFace: {str(e)}"
)
@router.get("/api/market/history")
async def get_market_history(
symbol: str = Query(..., description="Symbol (e.g., BTCUSDT)"),
timeframe: str = Query("1h", description="Timeframe (1m, 5m, 15m, 1h, 4h, 1d)"),
limit: int = Query(1000, description="Number of candles")
):
"""
دریافت دادههای OHLCV از HuggingFace Space
✅ فقط از HuggingFace
❌ بدون CoinMarketCap یا Binance
"""
try:
result = await hf_client.get_market_history(
symbol=symbol,
timeframe=timeframe,
limit=limit
)
if not result.get("success"):
raise HTTPException(
status_code=404,
detail=result.get("error", "OHLCV data not available")
)
logger.info(f"✅ OHLCV from HF: {symbol} {timeframe} ({len(result.get('data', []))} candles)")
return result
except HTTPException:
raise
except Exception as e:
logger.error(f"❌ OHLCV data failed: {e}")
raise HTTPException(
status_code=503,
detail=f"Failed to fetch OHLCV data from HuggingFace: {str(e)}"
)
@router.get("/api/market/pairs")
async def get_trading_pairs():
"""
دریافت لیست جفتهای معاملاتی
در صورت عدم وجود endpoint در HuggingFace، از اطلاعات market data استفاده میشود
"""
try:
# Try to get pairs from HF
# If not available, derive from market data
market_data = await hf_client.get_market_prices(limit=50)
if not market_data.get("success"):
raise HTTPException(status_code=503, detail="Failed to fetch market data")
pairs = []
for item in market_data.get("data", []):
symbol = item.get("symbol", "")
if symbol:
pairs.append({
"pair": f"{symbol}/USDT",
"base": symbol,
"quote": "USDT",
"tick_size": 0.01,
"min_qty": 0.001
})
return {
"success": True,
"pairs": pairs,
"meta": {
"cache_ttl_seconds": 300,
"generated_at": datetime.utcnow().isoformat(),
"source": "hf_engine"
}
}
except HTTPException:
raise
except Exception as e:
logger.error(f"❌ Trading pairs failed: {e}")
raise HTTPException(
status_code=503,
detail=f"Failed to fetch trading pairs: {str(e)}"
)
@router.get("/api/market/tickers")
async def get_tickers(
limit: int = Query(100, description="Number of tickers"),
sort: str = Query("market_cap", description="Sort by: market_cap, volume, change")
):
"""
دریافت tickers مرتبشده از HuggingFace
"""
try:
market_data = await hf_client.get_market_prices(limit=limit)
if not market_data.get("success"):
raise HTTPException(status_code=503, detail="Failed to fetch market data")
tickers = []
for item in market_data.get("data", []):
tickers.append({
"symbol": item.get("symbol", ""),
"price": item.get("price", 0),
"change_24h": item.get("change_24h", 0),
"volume_24h": item.get("volume_24h", 0),
"market_cap": item.get("market_cap", 0)
})
# Sort tickers
if sort == "volume":
tickers.sort(key=lambda x: x.get("volume_24h", 0), reverse=True)
elif sort == "change":
tickers.sort(key=lambda x: x.get("change_24h", 0), reverse=True)
elif sort == "market_cap":
tickers.sort(key=lambda x: x.get("market_cap", 0), reverse=True)
return {
"success": True,
"tickers": tickers,
"meta": {
"cache_ttl_seconds": 60,
"generated_at": datetime.utcnow().isoformat(),
"source": "hf_engine",
"sort": sort
}
}
except HTTPException:
raise
except Exception as e:
logger.error(f"❌ Tickers failed: {e}")
raise HTTPException(
status_code=503,
detail=f"Failed to fetch tickers: {str(e)}"
)
# ============================================================================
# Sentiment Analysis - از HuggingFace فقط
# ============================================================================
@router.post("/api/sentiment/analyze")
async def analyze_sentiment(request: SentimentRequest):
"""
تحلیل احساسات با مدلهای AI در HuggingFace
✅ فقط از HuggingFace AI Models
❌ بدون مدلهای محلی
"""
try:
result = await hf_client.analyze_sentiment(text=request.text)
if not result.get("success"):
raise HTTPException(
status_code=500,
detail=result.get("error", "Sentiment analysis failed")
)
logger.info(f"✅ Sentiment from HF: {result.get('data', {}).get('sentiment')}")
return result
except HTTPException:
raise
except Exception as e:
logger.error(f"❌ Sentiment analysis failed: {e}")
raise HTTPException(
status_code=500,
detail=f"Failed to analyze sentiment: {str(e)}"
)
# ============================================================================
# News - از HuggingFace فقط
# ============================================================================
@router.get("/api/news")
async def get_news(
limit: int = Query(20, description="Number of articles"),
source: Optional[str] = Query(None, description="Filter by source")
):
"""
دریافت اخبار از HuggingFace Space
✅ فقط از HuggingFace
❌ بدون NewsAPI مستقیم
"""
try:
result = await hf_client.get_news(limit=limit, source=source)
logger.info(f"✅ News from HF: {len(result.get('articles', []))} articles")
return result
except Exception as e:
logger.error(f"❌ News failed: {e}")
raise HTTPException(
status_code=503,
detail=f"Failed to fetch news from HuggingFace: {str(e)}"
)
@router.get("/api/news/latest")
async def get_latest_news(
symbol: str = Query("BTC", description="Crypto symbol"),
limit: int = Query(10, description="Number of articles")
):
"""
دریافت آخرین اخبار برای سمبل خاص
"""
try:
# HF news endpoint filters by source, we return all and user can filter client-side
result = await hf_client.get_news(limit=limit)
return {
"success": True,
"symbol": symbol,
"news": result.get("articles", []),
"meta": {
"total": len(result.get("articles", [])),
"source": "hf_engine",
"timestamp": datetime.utcnow().isoformat()
}
}
except Exception as e:
logger.error(f"❌ Latest news failed: {e}")
raise HTTPException(
status_code=503,
detail=f"Failed to fetch latest news: {str(e)}"
)
# ============================================================================
# Blockchain Data - از HuggingFace فقط
# ============================================================================
@router.get("/api/blockchain/gas")
async def get_gas_prices(
chain: str = Query("ethereum", description="Blockchain network")
):
"""
دریافت قیمت گس از HuggingFace Space
✅ فقط از HuggingFace
❌ بدون Etherscan/BSCScan مستقیم
"""
try:
result = await hf_client.get_blockchain_gas_prices(chain=chain)
logger.info(f"✅ Gas prices from HF: {chain}")
return result
except Exception as e:
logger.error(f"❌ Gas prices failed: {e}")
raise HTTPException(
status_code=503,
detail=f"Failed to fetch gas prices from HuggingFace: {str(e)}"
)
@router.get("/api/blockchain/stats")
async def get_blockchain_stats(
chain: str = Query("ethereum", description="Blockchain network"),
hours: int = Query(24, description="Time window in hours")
):
"""
دریافت آمار بلاکچین از HuggingFace Space
"""
try:
result = await hf_client.get_blockchain_stats(chain=chain, hours=hours)
logger.info(f"✅ Blockchain stats from HF: {chain}")
return result
except Exception as e:
logger.error(f"❌ Blockchain stats failed: {e}")
raise HTTPException(
status_code=503,
detail=f"Failed to fetch blockchain stats from HuggingFace: {str(e)}"
)
# ============================================================================
# Whale Tracking - از HuggingFace فقط
# ============================================================================
@router.get("/api/whales/transactions")
async def get_whale_transactions(
limit: int = Query(50, description="Number of transactions"),
chain: Optional[str] = Query(None, description="Filter by blockchain"),
min_amount_usd: float = Query(100000, description="Minimum amount in USD")
):
"""
دریافت تراکنشهای نهنگها از HuggingFace Space
"""
try:
result = await hf_client.get_whale_transactions(
limit=limit,
chain=chain,
min_amount_usd=min_amount_usd
)
logger.info(f"✅ Whale transactions from HF: {len(result.get('transactions', []))}")
return result
except Exception as e:
logger.error(f"❌ Whale transactions failed: {e}")
raise HTTPException(
status_code=503,
detail=f"Failed to fetch whale transactions from HuggingFace: {str(e)}"
)
@router.get("/api/whales/stats")
async def get_whale_stats(
hours: int = Query(24, description="Time window in hours")
):
"""
دریافت آمار نهنگها از HuggingFace Space
"""
try:
result = await hf_client.get_whale_stats(hours=hours)
logger.info(f"✅ Whale stats from HF")
return result
except Exception as e:
logger.error(f"❌ Whale stats failed: {e}")
raise HTTPException(
status_code=503,
detail=f"Failed to fetch whale stats from HuggingFace: {str(e)}"
)
# ============================================================================
# Health & Status
# ============================================================================
@router.get("/api/health")
async def health_check():
"""
بررسی سلامت سیستم با چک HuggingFace Space
"""
try:
hf_health = await hf_client.health_check()
return {
"status": "healthy" if hf_health.get("success") else "degraded",
"timestamp": datetime.utcnow().isoformat(),
"huggingface_space": hf_health,
"checks": {
"hf_space_connection": hf_health.get("success", False),
"hf_database": hf_health.get("database", "unknown"),
"hf_ai_models": hf_health.get("ai_models", {})
}
}
except Exception as e:
logger.error(f"❌ Health check failed: {e}")
return {
"status": "unhealthy",
"timestamp": datetime.utcnow().isoformat(),
"error": str(e),
"checks": {
"hf_space_connection": False
}
}
@router.get("/api/status")
async def get_system_status():
"""
دریافت وضعیت کلی سیستم
"""
try:
hf_status = await hf_client.get_system_status()
return {
"status": "operational",
"timestamp": datetime.utcnow().isoformat(),
"mode": "UNIFIED_HUGGINGFACE_ONLY",
"mock_data": False,
"direct_api_calls": False,
"all_via_huggingface": True,
"huggingface_space": hf_status,
"version": "3.0.0-unified-hf"
}
except Exception as e:
logger.error(f"❌ Status check failed: {e}")
return {
"status": "degraded",
"timestamp": datetime.utcnow().isoformat(),
"error": str(e),
"mode": "UNIFIED_HUGGINGFACE_ONLY"
}
@router.get("/api/providers")
async def get_providers():
"""
لیست ارائهدهندگان - فقط HuggingFace
"""
providers = [
{
"id": "huggingface_space",
"name": "HuggingFace Space",
"category": "all",
"status": "active",
"capabilities": [
"market_data",
"ohlcv",
"sentiment_analysis",
"news",
"blockchain_stats",
"whale_tracking",
"ai_models"
],
"has_api_token": True,
"endpoint": hf_client.base_url
}
]
return {
"success": True,
"providers": providers,
"total": len(providers),
"meta": {
"timestamp": datetime.utcnow().isoformat(),
"unified_source": "huggingface_space",
"no_direct_api_calls": True
}
}
# Export router
__all__ = ["router"]
|