Spaces:
Running
Running
Update app/main.py
Browse files- app/main.py +113 -52
app/main.py
CHANGED
@@ -1,81 +1,142 @@
|
|
1 |
"""
|
2 |
-
CryptoSentinel AI β FastAPI
|
3 |
-
- Fetches live prices from CoinGecko
|
4 |
-
- Provides real-time sentiment analysis via SSE
|
5 |
-
- Compatible with Hugging Face Spaces
|
6 |
-
"""
|
7 |
|
8 |
-
|
|
|
|
|
|
|
|
|
|
|
9 |
import asyncio
|
10 |
-
|
|
|
11 |
|
|
|
12 |
from fastapi import FastAPI, Request, BackgroundTasks
|
13 |
-
from fastapi.responses import HTMLResponse,
|
14 |
from fastapi.templating import Jinja2Templates
|
15 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
17 |
-
|
18 |
-
from sentiment import SentimentCache
|
19 |
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
-
|
23 |
-
|
|
|
|
|
24 |
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
|
|
31 |
|
32 |
-
|
33 |
-
def shutdown():
|
34 |
-
scheduler.shutdown(wait=False)
|
35 |
|
36 |
-
|
37 |
-
|
38 |
-
# Preload the sentiment model once on startup
|
39 |
-
SentimentCache.compute("The market is pumping π")
|
40 |
|
41 |
-
#
|
42 |
|
43 |
@app.get("/", response_class=HTMLResponse)
|
44 |
async def index(request: Request):
|
|
|
|
|
|
|
|
|
|
|
45 |
"""
|
46 |
-
|
47 |
-
|
48 |
"""
|
49 |
-
|
|
|
50 |
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
|
|
|
|
55 |
|
56 |
-
@app.post("/sentiment")
|
57 |
-
async def
|
|
|
|
|
|
|
|
|
58 |
"""
|
59 |
-
|
60 |
-
|
61 |
"""
|
62 |
-
|
63 |
-
|
64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
|
66 |
-
@app.get("/sentiment/stream")
|
67 |
-
async def sentiment_stream():
|
68 |
"""
|
69 |
-
Server-Sent Events endpoint
|
70 |
-
|
|
|
71 |
"""
|
|
|
|
|
72 |
async def event_generator():
|
73 |
-
last_id = 0
|
74 |
while True:
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
|
|
|
|
|
|
|
|
80 |
|
81 |
-
return StreamingResponse(event_generator(), media_type="text/event-stream")
|
|
|
1 |
"""
|
2 |
+
CryptoSentinel AI β High-performance FastAPI application.
|
|
|
|
|
|
|
|
|
3 |
|
4 |
+
Features:
|
5 |
+
- Fully asynchronous architecture using modern FastAPI lifespan and background tasks.
|
6 |
+
- Integrates a robust, async PriceFetcher with multi-API fallback.
|
7 |
+
- Provides real-time sentiment analysis via an efficient, non-polling SSE stream.
|
8 |
+
- Centralized state management for testability and clarity.
|
9 |
+
"""
|
10 |
import asyncio
|
11 |
+
import json
|
12 |
+
from contextlib import asynccontextmanager
|
13 |
|
14 |
+
import httpx
|
15 |
from fastapi import FastAPI, Request, BackgroundTasks
|
16 |
+
from fastapi.responses import HTMLResponse, StreamingResponse
|
17 |
from fastapi.templating import Jinja2Templates
|
18 |
+
from pydantic import BaseModel, constr
|
19 |
+
|
20 |
+
from .price_fetcher import PriceFetcher
|
21 |
+
from .sentiment import SentimentAnalyzer
|
22 |
+
|
23 |
+
# --- Configuration & Models ---
|
24 |
+
|
25 |
+
class SentimentRequest(BaseModel):
|
26 |
+
"""Pydantic model for validating sentiment analysis requests."""
|
27 |
+
text: constr(strip_whitespace=True, min_length=1)
|
28 |
|
29 |
+
# --- Application Lifespan Management ---
|
|
|
30 |
|
31 |
+
@asynccontextmanager
|
32 |
+
async def lifespan(app: FastAPI):
|
33 |
+
"""
|
34 |
+
Manages application startup and shutdown events. This is the modern
|
35 |
+
replacement for @app.on_event("startup") and "shutdown".
|
36 |
+
"""
|
37 |
+
# -- Startup --
|
38 |
+
# Create a single, shared httpx client for the application's lifespan.
|
39 |
+
async with httpx.AsyncClient() as client:
|
40 |
+
# Initialize our stateful services
|
41 |
+
price_fetcher = PriceFetcher(client=client, coins=["bitcoin", "ethereum", "dogecoin"])
|
42 |
+
sentiment_analyzer = SentimentAnalyzer()
|
43 |
|
44 |
+
# Store service instances in the app's state for access in routes
|
45 |
+
app.state.price_fetcher = price_fetcher
|
46 |
+
app.state.sentiment_analyzer = sentiment_analyzer
|
47 |
+
app.state.request_counter = 0
|
48 |
|
49 |
+
# Create a cancellable background task for periodic price updates
|
50 |
+
price_update_task = asyncio.create_task(
|
51 |
+
run_periodic_updates(price_fetcher, interval_seconds=10)
|
52 |
+
)
|
53 |
+
|
54 |
+
print("π CryptoSentinel AI started successfully.")
|
55 |
+
yield # The application is now running
|
56 |
+
|
57 |
+
# -- Shutdown --
|
58 |
+
print("β³ Shutting down background tasks...")
|
59 |
+
price_update_task.cancel()
|
60 |
+
try:
|
61 |
+
await price_update_task
|
62 |
+
except asyncio.CancelledError:
|
63 |
+
print("Price update task cancelled successfully.")
|
64 |
+
print("β
Shutdown complete.")
|
65 |
|
66 |
+
async def run_periodic_updates(fetcher: PriceFetcher, interval_seconds: int):
|
67 |
+
"""A simple, robust asyncio background task runner."""
|
68 |
+
while True:
|
69 |
+
await fetcher.update_prices_async()
|
70 |
+
await asyncio.sleep(interval_seconds)
|
71 |
|
72 |
+
# --- FastAPI App Initialization ---
|
|
|
|
|
73 |
|
74 |
+
templates = Jinja2Templates(directory="app/templates")
|
75 |
+
app = FastAPI(title="CryptoSentinel AI", lifespan=lifespan)
|
|
|
|
|
76 |
|
77 |
+
# --- Routes ---
|
78 |
|
79 |
@app.get("/", response_class=HTMLResponse)
|
80 |
async def index(request: Request):
|
81 |
+
"""Renders the main single-page application view."""
|
82 |
+
return templates.TemplateResponse("index.html", {"request": request})
|
83 |
+
|
84 |
+
@app.get("/api/prices", response_class=HTMLResponse)
|
85 |
+
async def get_prices_fragment(request: Request):
|
86 |
"""
|
87 |
+
Returns an HTML fragment with the latest crypto prices.
|
88 |
+
Designed to be called by HTMX.
|
89 |
"""
|
90 |
+
price_fetcher: PriceFetcher = request.app.state.price_fetcher
|
91 |
+
prices = price_fetcher.get_current_prices()
|
92 |
|
93 |
+
html_fragment = ""
|
94 |
+
for coin, price in prices.items():
|
95 |
+
price_str = f"${price:,.2f}" if isinstance(price, (int, float)) else price
|
96 |
+
html_fragment += f"<div><strong>{coin.capitalize()}:</strong> {price_str}</div>"
|
97 |
+
|
98 |
+
return HTMLResponse(content=html_fragment)
|
99 |
|
100 |
+
@app.post("/api/sentiment")
|
101 |
+
async def analyze_sentiment(
|
102 |
+
payload: SentimentRequest,
|
103 |
+
request: Request,
|
104 |
+
background_tasks: BackgroundTasks
|
105 |
+
):
|
106 |
"""
|
107 |
+
Accepts text for sentiment analysis, validates it, and queues it
|
108 |
+
for processing in the background.
|
109 |
"""
|
110 |
+
analyzer: SentimentAnalyzer = request.app.state.sentiment_analyzer
|
111 |
+
|
112 |
+
# Use a simple counter for unique event IDs
|
113 |
+
request.app.state.request_counter += 1
|
114 |
+
request_id = request.app.state.request_counter
|
115 |
+
|
116 |
+
# Add the heavy computation to the background so the API returns instantly
|
117 |
+
background_tasks.add_task(analyzer.compute_and_publish, payload.text, request_id)
|
118 |
+
|
119 |
+
return {"status": "queued", "request_id": request_id}
|
120 |
|
121 |
+
@app.get("/api/sentiment/stream")
|
122 |
+
async def sentiment_stream(request: Request):
|
123 |
"""
|
124 |
+
Server-Sent Events (SSE) endpoint.
|
125 |
+
This long-lived connection efficiently waits for new sentiment results
|
126 |
+
from the queue and pushes them to the client.
|
127 |
"""
|
128 |
+
analyzer: SentimentAnalyzer = request.app.state.sentiment_analyzer
|
129 |
+
|
130 |
async def event_generator():
|
|
|
131 |
while True:
|
132 |
+
try:
|
133 |
+
# This is the key: efficiently wait for a result to be put in the queue
|
134 |
+
result_payload = await analyzer.get_next_result()
|
135 |
+
payload_str = json.dumps(result_payload)
|
136 |
+
yield f"id:{result_payload['id']}\nevent: sentiment_update\ndata:{payload_str}\n\n"
|
137 |
+
except asyncio.CancelledError:
|
138 |
+
# Handle client disconnect
|
139 |
+
print("Client disconnected from SSE stream.")
|
140 |
+
break
|
141 |
|
142 |
+
return StreamingResponse(event_generator(), media_type="text/event-stream")
|