File size: 10,120 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 |
#!/usr/bin/env python3
"""
FastAPI Router for Unified AI Services
"""
from fastapi import APIRouter, HTTPException, Query, Body
from typing import Dict, Any, Optional, List
from pydantic import BaseModel, Field
import logging
import sys
import os
# اضافه کردن مسیر root
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
from backend.services.ai_service_unified import get_unified_service, analyze_text
from backend.services.hf_dataset_loader import HFDatasetService, quick_price_data, quick_crypto_news
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/ai", tags=["AI Services"])
# ===== Models =====
class SentimentRequest(BaseModel):
"""درخواست تحلیل sentiment"""
text: str = Field(..., description="متن برای تحلیل", min_length=1, max_length=2000)
category: str = Field("crypto", description="دستهبندی: crypto, financial, social")
use_ensemble: bool = Field(True, description="استفاده از ensemble")
class BulkSentimentRequest(BaseModel):
"""درخواست تحلیل چند متن"""
texts: List[str] = Field(..., description="لیست متنها", min_items=1, max_items=50)
category: str = Field("crypto", description="دستهبندی")
use_ensemble: bool = Field(True, description="استفاده از ensemble")
class PriceDataRequest(BaseModel):
"""درخواست داده قیمت"""
symbol: str = Field("BTC", description="نماد کریپتو")
days: int = Field(7, description="تعداد روز", ge=1, le=90)
timeframe: str = Field("1h", description="بازه زمانی")
# ===== Endpoints =====
@router.get("/health")
async def health_check():
"""
بررسی وضعیت سلامت سرویس AI
"""
try:
service = await get_unified_service()
health = service.get_health_status()
return {
"status": "ok",
"service": "AI Unified",
"health": health
}
except Exception as e:
logger.error(f"Health check failed: {e}")
return {
"status": "error",
"error": str(e)
}
@router.get("/info")
async def get_service_info():
"""
دریافت اطلاعات سرویس
"""
try:
service = await get_unified_service()
info = service.get_service_info()
return {
"status": "ok",
"info": info
}
except Exception as e:
logger.error(f"Failed to get service info: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/sentiment")
async def analyze_sentiment(request: SentimentRequest):
"""
تحلیل sentiment یک متن
### مثال:
```json
{
"text": "Bitcoin is showing strong bullish momentum!",
"category": "crypto",
"use_ensemble": true
}
```
### پاسخ:
```json
{
"status": "success",
"label": "bullish",
"confidence": 0.85,
"engine": "hf_inference_api_ensemble"
}
```
"""
try:
result = await analyze_text(
text=request.text,
category=request.category,
use_ensemble=request.use_ensemble
)
return result
except Exception as e:
logger.error(f"Sentiment analysis failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/sentiment/bulk")
async def analyze_bulk_sentiment(request: BulkSentimentRequest):
"""
تحلیل sentiment چند متن به صورت همزمان
### مثال:
```json
{
"texts": [
"Bitcoin is pumping!",
"Market is crashing",
"Consolidation phase"
],
"category": "crypto",
"use_ensemble": true
}
```
"""
try:
import asyncio
# تحلیل موازی
tasks = [
analyze_text(text, request.category, request.use_ensemble)
for text in request.texts
]
results = await asyncio.gather(*tasks, return_exceptions=True)
# پردازش نتایج
processed_results = []
for i, result in enumerate(results):
if isinstance(result, Exception):
processed_results.append({
"text": request.texts[i],
"status": "error",
"error": str(result)
})
else:
processed_results.append({
"text": request.texts[i],
**result
})
# خلاصه
successful = sum(1 for r in processed_results if r.get("status") == "success")
return {
"status": "ok",
"total": len(request.texts),
"successful": successful,
"failed": len(request.texts) - successful,
"results": processed_results
}
except Exception as e:
logger.error(f"Bulk sentiment analysis failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/sentiment/quick")
async def quick_sentiment_analysis(
text: str = Query(..., description="متن برای تحلیل", min_length=1),
category: str = Query("crypto", description="دستهبندی")
):
"""
تحلیل سریع sentiment (GET request)
### مثال:
```
GET /api/ai/sentiment/quick?text=Bitcoin%20to%20the%20moon&category=crypto
```
"""
try:
result = await analyze_text(text=text, category=category, use_ensemble=False)
return result
except Exception as e:
logger.error(f"Quick sentiment failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/data/prices")
async def get_historical_prices(request: PriceDataRequest):
"""
دریافت داده قیمت تاریخی از HuggingFace Datasets
### مثال:
```json
{
"symbol": "BTC",
"days": 7,
"timeframe": "1h"
}
```
"""
try:
service = HFDatasetService()
if not service.is_available():
return {
"status": "error",
"error": "datasets library not available",
"installation": "pip install datasets"
}
result = await service.get_historical_prices(
symbol=request.symbol,
days=request.days,
timeframe=request.timeframe
)
return result
except Exception as e:
logger.error(f"Failed to get historical prices: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/data/prices/quick/{symbol}")
async def quick_historical_prices(
symbol: str,
days: int = Query(7, ge=1, le=90)
):
"""
دریافت سریع داده قیمت
### مثال:
```
GET /api/ai/data/prices/quick/BTC?days=7
```
"""
try:
result = await quick_price_data(symbol=symbol.upper(), days=days)
return result
except Exception as e:
logger.error(f"Quick price data failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/data/news")
async def get_crypto_news(
limit: int = Query(10, ge=1, le=100, description="تعداد خبر")
):
"""
دریافت اخبار کریپتو از HuggingFace Datasets
### مثال:
```
GET /api/ai/data/news?limit=10
```
"""
try:
news = await quick_crypto_news(limit=limit)
return {
"status": "ok",
"count": len(news),
"news": news
}
except Exception as e:
logger.error(f"Failed to get crypto news: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/datasets/available")
async def get_available_datasets():
"""
لیست Datasetهای موجود
"""
try:
service = HFDatasetService()
datasets = service.get_available_datasets()
return {
"status": "ok",
"datasets": datasets
}
except Exception as e:
logger.error(f"Failed to get datasets: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/models/available")
async def get_available_models():
"""
لیست مدلهای AI موجود
"""
try:
from backend.services.hf_inference_api_client import HFInferenceAPIClient
async with HFInferenceAPIClient() as client:
models = client.get_available_models()
return {
"status": "ok",
"models": models
}
except Exception as e:
logger.error(f"Failed to get models: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/stats")
async def get_service_statistics():
"""
آمار استفاده از سرویس
"""
try:
service = await get_unified_service()
return {
"status": "ok",
"stats": service.stats
}
except Exception as e:
logger.error(f"Failed to get stats: {e}")
raise HTTPException(status_code=500, detail=str(e))
# ===== مثال استفاده در app.py =====
"""
# در فایل app.py یا production_server.py:
from backend.routers.ai_unified import router as ai_router
app = FastAPI()
app.include_router(ai_router)
# حالا endpointهای زیر در دسترس هستند:
# - POST /api/ai/sentiment
# - POST /api/ai/sentiment/bulk
# - GET /api/ai/sentiment/quick
# - POST /api/ai/data/prices
# - GET /api/ai/data/prices/quick/{symbol}
# - GET /api/ai/data/news
# - GET /api/ai/datasets/available
# - GET /api/ai/models/available
# - GET /api/ai/health
# - GET /api/ai/info
# - GET /api/ai/stats
"""
|