File size: 23,116 Bytes
8b7b267 |
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 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 |
#!/usr/bin/env python3
"""
Direct API Router - Complete REST Endpoints
All external API integrations exposed through REST endpoints
NO PIPELINES - Direct model loading and inference
"""
from fastapi import APIRouter, HTTPException, Query, Body
from fastapi.responses import JSONResponse
from typing import Optional, List, Dict, Any
from pydantic import BaseModel
from datetime import datetime
import logging
# Import all clients and services
from backend.services.direct_model_loader import direct_model_loader
from backend.services.dataset_loader import crypto_dataset_loader
from backend.services.external_api_clients import (
alternative_me_client,
reddit_client,
rss_feed_client
)
from backend.services.coingecko_client import coingecko_client
from backend.services.binance_client import binance_client
from backend.services.crypto_news_client import crypto_news_client
logger = logging.getLogger(__name__)
router = APIRouter(
prefix="/api/v1",
tags=["Direct API - External Services"]
)
# ============================================================================
# Pydantic Models
# ============================================================================
class SentimentRequest(BaseModel):
"""Sentiment analysis request"""
text: str
model_key: Optional[str] = "cryptobert_elkulako"
class BatchSentimentRequest(BaseModel):
"""Batch sentiment analysis request"""
texts: List[str]
model_key: Optional[str] = "cryptobert_elkulako"
class DatasetQueryRequest(BaseModel):
"""Dataset query request"""
dataset_key: str
filters: Optional[Dict[str, Any]] = None
limit: int = 100
# ============================================================================
# CoinGecko Endpoints
# ============================================================================
@router.get("/coingecko/price")
async def get_coingecko_prices(
symbols: Optional[str] = Query(None, description="Comma-separated symbols (e.g., BTC,ETH)"),
limit: int = Query(100, description="Maximum number of coins")
):
"""
Get real-time cryptocurrency prices from CoinGecko
Examples:
- `/api/v1/coingecko/price?symbols=BTC,ETH`
- `/api/v1/coingecko/price?limit=50`
"""
try:
symbol_list = symbols.split(",") if symbols else None
result = await coingecko_client.get_market_prices(
symbols=symbol_list,
limit=limit
)
return {
"success": True,
"data": result,
"source": "coingecko",
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
logger.error(f"β CoinGecko price endpoint failed: {e}")
raise HTTPException(status_code=503, detail=str(e))
@router.get("/coingecko/trending")
async def get_coingecko_trending(
limit: int = Query(10, description="Number of trending coins")
):
"""
Get trending cryptocurrencies from CoinGecko
"""
try:
result = await coingecko_client.get_trending_coins(limit=limit)
return {
"success": True,
"data": result,
"source": "coingecko",
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
logger.error(f"β CoinGecko trending endpoint failed: {e}")
raise HTTPException(status_code=503, detail=str(e))
# ============================================================================
# Binance Endpoints
# ============================================================================
@router.get("/binance/klines")
async def get_binance_klines(
symbol: str = Query(..., description="Symbol (e.g., BTC, BTCUSDT)"),
timeframe: str = Query("1h", description="Timeframe (1m, 5m, 15m, 1h, 4h, 1d)"),
limit: int = Query(1000, description="Number of candles (max 1000)")
):
"""
Get OHLCV candlestick data from Binance
Examples:
- `/api/v1/binance/klines?symbol=BTC&timeframe=1h&limit=100`
- `/api/v1/binance/klines?symbol=ETHUSDT&timeframe=4h&limit=500`
"""
try:
result = await binance_client.get_ohlcv(
symbol=symbol,
timeframe=timeframe,
limit=limit
)
return {
"success": True,
"data": result,
"source": "binance",
"symbol": symbol,
"timeframe": timeframe,
"count": len(result),
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
logger.error(f"β Binance klines endpoint failed: {e}")
raise HTTPException(status_code=503, detail=str(e))
@router.get("/ohlcv/{symbol}")
async def get_ohlcv(
symbol: str,
interval: str = Query("1d", description="Interval: 1m, 5m, 15m, 1h, 4h, 1d"),
limit: int = Query(30, description="Number of candles")
):
"""
Get OHLCV data for a cryptocurrency symbol
This endpoint provides a unified interface for OHLCV data with automatic fallback.
Tries Binance first, then CoinGecko as fallback.
Examples:
- `/api/v1/ohlcv/BTC?interval=1d&limit=30`
- `/api/v1/ohlcv/ETH?interval=1h&limit=100`
"""
try:
# Try Binance first (best for OHLCV)
try:
binance_symbol = f"{symbol.upper()}USDT"
result = await binance_client.get_ohlcv(
symbol=binance_symbol,
timeframe=interval,
limit=limit
)
return {
"success": True,
"symbol": symbol.upper(),
"interval": interval,
"data": result,
"source": "binance",
"count": len(result),
"timestamp": datetime.utcnow().isoformat()
}
except Exception as binance_error:
logger.warning(f"β Binance failed for {symbol}: {binance_error}")
# Fallback to CoinGecko
try:
coin_id = symbol.lower()
result = await coingecko_client.get_ohlc(
coin_id=coin_id,
days=30 if interval == "1d" else 7
)
return {
"success": True,
"symbol": symbol.upper(),
"interval": interval,
"data": result,
"source": "coingecko",
"count": len(result),
"timestamp": datetime.utcnow().isoformat(),
"fallback_used": True
}
except Exception as coingecko_error:
logger.error(f"β Both Binance and CoinGecko failed for {symbol}")
raise HTTPException(
status_code=503,
detail=f"Failed to fetch OHLCV data: Binance error: {str(binance_error)}, CoinGecko error: {str(coingecko_error)}"
)
except HTTPException:
raise
except Exception as e:
logger.error(f"β OHLCV endpoint failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/binance/ticker")
async def get_binance_ticker(
symbol: str = Query(..., description="Symbol (e.g., BTC)")
):
"""
Get 24-hour ticker data from Binance
"""
try:
result = await binance_client.get_24h_ticker(symbol=symbol)
return {
"success": True,
"data": result,
"source": "binance",
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
logger.error(f"β Binance ticker endpoint failed: {e}")
raise HTTPException(status_code=503, detail=str(e))
# ============================================================================
# Alternative.me Endpoints
# ============================================================================
@router.get("/alternative/fng")
async def get_fear_greed_index(
limit: int = Query(1, description="Number of historical data points")
):
"""
Get Fear & Greed Index from Alternative.me
Examples:
- `/api/v1/alternative/fng` - Current index
- `/api/v1/alternative/fng?limit=30` - Last 30 days
"""
try:
result = await alternative_me_client.get_fear_greed_index(limit=limit)
return result
except Exception as e:
logger.error(f"β Alternative.me endpoint failed: {e}")
raise HTTPException(status_code=503, detail=str(e))
# ============================================================================
# Reddit Endpoints
# ============================================================================
@router.get("/reddit/top")
async def get_reddit_top_posts(
subreddit: str = Query("cryptocurrency", description="Subreddit name"),
time_filter: str = Query("day", description="Time filter (hour, day, week, month)"),
limit: int = Query(25, description="Number of posts")
):
"""
Get top posts from Reddit cryptocurrency subreddits
Examples:
- `/api/v1/reddit/top?subreddit=cryptocurrency&time_filter=day&limit=25`
- `/api/v1/reddit/top?subreddit=bitcoin&time_filter=week&limit=50`
"""
try:
result = await reddit_client.get_top_posts(
subreddit=subreddit,
time_filter=time_filter,
limit=limit
)
return result
except Exception as e:
logger.error(f"β Reddit endpoint failed: {e}")
raise HTTPException(status_code=503, detail=str(e))
@router.get("/reddit/new")
async def get_reddit_new_posts(
subreddit: str = Query("cryptocurrency", description="Subreddit name"),
limit: int = Query(25, description="Number of posts")
):
"""
Get new posts from Reddit cryptocurrency subreddits
"""
try:
result = await reddit_client.get_new_posts(
subreddit=subreddit,
limit=limit
)
return result
except Exception as e:
logger.error(f"β Reddit endpoint failed: {e}")
raise HTTPException(status_code=503, detail=str(e))
# ============================================================================
# RSS Feed Endpoints
# ============================================================================
@router.get("/rss/feed")
async def get_rss_feed(
feed_name: str = Query(..., description="Feed name (coindesk, cointelegraph, bitcoinmagazine, decrypt, theblock)"),
limit: int = Query(20, description="Number of articles")
):
"""
Get news articles from RSS feeds
Available feeds: coindesk, cointelegraph, bitcoinmagazine, decrypt, theblock
Examples:
- `/api/v1/rss/feed?feed_name=coindesk&limit=20`
- `/api/v1/rss/feed?feed_name=cointelegraph&limit=10`
"""
try:
result = await rss_feed_client.fetch_feed(
feed_name=feed_name,
limit=limit
)
return result
except Exception as e:
logger.error(f"β RSS feed endpoint failed: {e}")
raise HTTPException(status_code=503, detail=str(e))
@router.get("/rss/all")
async def get_all_rss_feeds(
limit_per_feed: int = Query(10, description="Articles per feed")
):
"""
Get news articles from all RSS feeds
"""
try:
result = await rss_feed_client.fetch_all_feeds(
limit_per_feed=limit_per_feed
)
return result
except Exception as e:
logger.error(f"β RSS all feeds endpoint failed: {e}")
raise HTTPException(status_code=503, detail=str(e))
@router.get("/coindesk/rss")
async def get_coindesk_rss(
limit: int = Query(20, description="Number of articles")
):
"""
Get CoinDesk RSS feed
Direct endpoint: https://www.coindesk.com/arc/outboundfeeds/rss/
"""
try:
result = await rss_feed_client.fetch_feed("coindesk", limit)
return result
except Exception as e:
logger.error(f"β CoinDesk RSS failed: {e}")
raise HTTPException(status_code=503, detail=str(e))
@router.get("/cointelegraph/rss")
async def get_cointelegraph_rss(
limit: int = Query(20, description="Number of articles")
):
"""
Get CoinTelegraph RSS feed
Direct endpoint: https://cointelegraph.com/rss
"""
try:
result = await rss_feed_client.fetch_feed("cointelegraph", limit)
return result
except Exception as e:
logger.error(f"β CoinTelegraph RSS failed: {e}")
raise HTTPException(status_code=503, detail=str(e))
# ============================================================================
# Crypto News Endpoints (Aggregated)
# ============================================================================
@router.get("/news/latest")
async def get_latest_crypto_news(
limit: int = Query(20, description="Number of articles")
):
"""
Get latest cryptocurrency news from multiple sources
(Aggregates NewsAPI, CryptoPanic, and RSS feeds)
"""
try:
result = await crypto_news_client.get_latest_news(limit=limit)
return {
"success": True,
"data": result,
"count": len(result),
"source": "aggregated",
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
logger.error(f"β Crypto news endpoint failed: {e}")
raise HTTPException(status_code=503, detail=str(e))
# ============================================================================
# Hugging Face Model Endpoints (Direct Loading - NO PIPELINES)
# ============================================================================
@router.post("/hf/sentiment")
async def analyze_sentiment(request: SentimentRequest):
"""
Analyze sentiment using HuggingFace models with automatic fallback
Available models (in fallback order):
- cryptobert_elkulako (default): ElKulako/cryptobert
- cryptobert_kk08: kk08/CryptoBERT
- finbert: ProsusAI/finbert
- twitter_sentiment: cardiffnlp/twitter-roberta-base-sentiment
Example:
```json
{
"text": "Bitcoin price is surging to new heights!",
"model_key": "cryptobert_elkulako"
}
```
"""
# Fallback model order
fallback_models = [
request.model_key,
"cryptobert_kk08",
"finbert",
"twitter_sentiment"
]
last_error = None
for model_key in fallback_models:
try:
result = await direct_model_loader.predict_sentiment(
text=request.text,
model_key=model_key
)
# Add fallback indicator if not primary model
if model_key != request.model_key:
result["fallback_used"] = True
result["primary_model"] = request.model_key
result["actual_model"] = model_key
return result
except Exception as e:
logger.warning(f"β Model {model_key} failed: {e}")
last_error = e
continue
# All models failed - return graceful degradation
logger.error(f"β All sentiment models failed. Last error: {last_error}")
raise HTTPException(
status_code=503,
detail={
"error": "All sentiment models unavailable",
"message": "Sentiment analysis service is temporarily unavailable",
"tried_models": fallback_models,
"last_error": str(last_error),
"degraded_response": {
"sentiment": "neutral",
"score": 0.5,
"confidence": 0.0,
"method": "fallback",
"warning": "Using degraded mode - all models unavailable"
}
}
)
@router.post("/hf/sentiment/batch")
async def analyze_sentiment_batch(request: BatchSentimentRequest):
"""
Batch sentiment analysis (NO PIPELINE)
Example:
```json
{
"texts": [
"Bitcoin is mooning!",
"Ethereum looks bearish today",
"Market is neutral"
],
"model_key": "cryptobert_elkulako"
}
```
"""
try:
result = await direct_model_loader.batch_predict_sentiment(
texts=request.texts,
model_key=request.model_key
)
return result
except Exception as e:
logger.error(f"β Batch sentiment analysis failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/hf/models")
async def get_loaded_models():
"""
Get list of loaded HuggingFace models
"""
try:
result = direct_model_loader.get_loaded_models()
return result
except Exception as e:
logger.error(f"β Get models failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/hf/models/load")
async def load_model(
model_key: str = Query(..., description="Model key to load")
):
"""
Load a specific HuggingFace model
Available models:
- cryptobert_elkulako
- cryptobert_kk08
- finbert
- twitter_sentiment
"""
try:
result = await direct_model_loader.load_model(model_key)
return result
except Exception as e:
logger.error(f"β Load model failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/hf/models/load-all")
async def load_all_models():
"""
Load all configured HuggingFace models
"""
try:
result = await direct_model_loader.load_all_models()
return result
except Exception as e:
logger.error(f"β Load all models failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
# ============================================================================
# Hugging Face Dataset Endpoints
# ============================================================================
@router.get("/hf/datasets")
async def get_loaded_datasets():
"""
Get list of loaded HuggingFace datasets
"""
try:
result = crypto_dataset_loader.get_loaded_datasets()
return result
except Exception as e:
logger.error(f"β Get datasets failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/hf/datasets/load")
async def load_dataset(
dataset_key: str = Query(..., description="Dataset key to load"),
split: Optional[str] = Query(None, description="Dataset split"),
streaming: bool = Query(False, description="Enable streaming")
):
"""
Load a specific HuggingFace dataset
Available datasets:
- cryptocoin: linxy/CryptoCoin
- bitcoin_btc_usdt: WinkingFace/CryptoLM-Bitcoin-BTC-USDT
- ethereum_eth_usdt: WinkingFace/CryptoLM-Ethereum-ETH-USDT
- solana_sol_usdt: WinkingFace/CryptoLM-Solana-SOL-USDT
- ripple_xrp_usdt: WinkingFace/CryptoLM-Ripple-XRP-USDT
"""
try:
result = await crypto_dataset_loader.load_dataset(
dataset_key=dataset_key,
split=split,
streaming=streaming
)
return result
except Exception as e:
logger.error(f"β Load dataset failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/hf/datasets/load-all")
async def load_all_datasets(
streaming: bool = Query(False, description="Enable streaming")
):
"""
Load all configured HuggingFace datasets
"""
try:
result = await crypto_dataset_loader.load_all_datasets(streaming=streaming)
return result
except Exception as e:
logger.error(f"β Load all datasets failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/hf/datasets/sample")
async def get_dataset_sample(
dataset_key: str = Query(..., description="Dataset key"),
num_samples: int = Query(10, description="Number of samples"),
split: Optional[str] = Query(None, description="Dataset split")
):
"""
Get sample rows from a dataset
"""
try:
result = await crypto_dataset_loader.get_dataset_sample(
dataset_key=dataset_key,
num_samples=num_samples,
split=split
)
return result
except Exception as e:
logger.error(f"β Get dataset sample failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/hf/datasets/query")
async def query_dataset(request: DatasetQueryRequest):
"""
Query dataset with filters
Example:
```json
{
"dataset_key": "bitcoin_btc_usdt",
"filters": {"price": 50000},
"limit": 100
}
```
"""
try:
result = await crypto_dataset_loader.query_dataset(
dataset_key=request.dataset_key,
filters=request.filters,
limit=request.limit
)
return result
except Exception as e:
logger.error(f"β Query dataset failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/hf/datasets/stats")
async def get_dataset_stats(
dataset_key: str = Query(..., description="Dataset key")
):
"""
Get statistics about a dataset
"""
try:
result = await crypto_dataset_loader.get_dataset_stats(dataset_key=dataset_key)
return result
except Exception as e:
logger.error(f"β Get dataset stats failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
# ============================================================================
# System Status Endpoint
# ============================================================================
@router.get("/status")
async def get_system_status():
"""
Get overall system status
"""
try:
models_info = direct_model_loader.get_loaded_models()
datasets_info = crypto_dataset_loader.get_loaded_datasets()
return {
"success": True,
"status": "operational",
"models": {
"total_configured": models_info["total_configured"],
"total_loaded": models_info["total_loaded"],
"device": models_info["device"]
},
"datasets": {
"total_configured": datasets_info["total_configured"],
"total_loaded": datasets_info["total_loaded"]
},
"external_apis": {
"coingecko": "available",
"binance": "available",
"alternative_me": "available",
"reddit": "available",
"rss_feeds": "available"
},
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
logger.error(f"β System status failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
# Export router
__all__ = ["router"]
|