-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1878 lines (1612 loc) · 75.1 KB
/
main.py
File metadata and controls
1878 lines (1612 loc) · 75.1 KB
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# main.py — aligned to /data/<email>/<TICKER>/<timestamp>/... layout
"""
Stock Analyst API Runner
A FastAPI service that manages and runs stock analysis jobs using Docker containers.
Features:
- Run stock analysis jobs in Docker containers
- Real-time streaming of analysis progress
- Download analysis results (articles, reports)
- Health monitoring and job management
"""
import os
import json
import asyncio
import logging
import time
import concurrent.futures
from datetime import datetime
from typing import Dict, List, Optional
from pathlib import Path
import tempfile
import zipfile
import shutil
from io import BytesIO
import shlex
import codecs
from fastapi import Request
import subprocess
import docker
import docker.errors
from fastapi import FastAPI, HTTPException, BackgroundTasks, WebSocket
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, FileResponse, PlainTextResponse
from pydantic import BaseModel, Field
import uvicorn
from fastapi import Response
import shlex, time, io, zipfile, hashlib
from starlette.middleware.sessions import SessionMiddleware
from starlette.middleware import Middleware
from news_feed.news_manager import NewsManager
# Load environment variables FIRST before any imports that use them
from dotenv import load_dotenv
load_dotenv()
# Import shared configuration
import config
from config import (
BACKEND_IMAGE, DATA_VOLUME,
SERPAPI_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY,
MONGO_URI, MONGO_DB,
csv_env
)
# Auth routers (imported after .env is loaded)
from auth_oauth import router as oauth_router
from auth_code_login import router as code_router
from md_pdf_converter import convert_md_to_pdf
# Real-time stock price system
from realtime import (
PriceManager,
stock_router,
PriceFetchConfig
)
from realtime.stock_api import init_realtime_api
# News feed system
from news_feed import news_router
from news_feed.api import init_news_manager, close_news_manager
from news_feed.news_auto_updater import NewsUpdateManager, NewsUpdateConfig
from news_feed.news_websocket import init_news_websocket_manager, get_news_websocket_manager
# Daily reports system
from reports.daily import daily_reports_router, initialize_scheduler, shutdown_scheduler
from reports.daily.api import set_docker_client
# Tunables
POLL_INTERVAL_SEC = 0.75
IDLE_HEARTBEAT_SEC = 12
FINAL_DRAIN_STABLE_CYCLES = 3 # how many consecutive polls with no growth before we finalize
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Global real-time services
price_manager: Optional[PriceManager] = None
websocket_manager = None
news_auto_updater: Optional[NewsUpdateManager] = None
news_websocket_manager = None
# Frontend origins from config
FRONTEND_ORIGINS = csv_env("FRONTEND_ORIGIN")
ROOT_PATH = config.ROOT_PATH
SESSION_SECRET = config.SESSION_SECRET
SESSION_HTTPS_ONLY = config.SESSION_HTTPS_ONLY
SESSION_STORE_COOKIE = config.SESSION_STORE_COOKIE
# SameSite configuration
SESSION_SAMESITE = config.SESSION_SAMESITE
if SESSION_SAMESITE not in {"lax", "none", "strict"}:
SESSION_SAMESITE = "lax"
if SESSION_SAMESITE == "none" and not SESSION_HTTPS_ONLY:
SESSION_HTTPS_ONLY = True # browsers require Secure when SameSite=None
# Build app with explicit middleware order: Session -> CORS
middleware = [
Middleware(
SessionMiddleware,
secret_key=SESSION_SECRET,
same_site=SESSION_SAMESITE,
https_only=SESSION_HTTPS_ONLY,
max_age=60 * 60 * 8,
path="/",
session_cookie=SESSION_STORE_COOKIE,
),
Middleware(
CORSMiddleware,
allow_origins=FRONTEND_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["Content-Disposition"],
),
]
app = FastAPI(
title="Stock Analyst API Runner",
description="API service for running stock analysis jobs in Docker containers",
version="1.0.0",
root_path=ROOT_PATH,
middleware=middleware,
)
# Routers
app.include_router(oauth_router)
app.include_router(code_router)
app.include_router(stock_router)
app.include_router(news_router)
app.include_router(daily_reports_router)
# Health endpoint (useful for container probes)
@app.get("/healthz")
def healthz():
return {"ok": True}
# Global variables
docker_client = None
jobs: Dict[str, Dict] = {}
# --------- Utilities for new layout ---------
def job_root(job: Dict) -> str:
"""
Return canonical path under the Docker-mounted volume for this job:
/data/<email>/<TICKER>/<timestamp>
"""
email = (job.get("user_email") or "").strip()
ticker = (job.get("ticker") or "").upper().strip()
timestamp = (job.get("timestamp") or "").strip()
if not (email and ticker and timestamp):
raise HTTPException(status_code=500, detail="Job missing email/ticker/timestamp")
# All reads are in containers with /data bound to the named volume
return f"/data/{email}/{ticker}/{timestamp}"
# ------------- Pydantic models -------------
class JobRequest(BaseModel):
ticker: str = Field(..., description="Stock ticker symbol (e.g., NVDA)")
company: str = Field(..., description="Company name (e.g., 'NVIDIA')")
email: str = Field(..., description="User email for data organization")
llm: Optional[str] = Field(default="gpt-4o-mini", description="LLM model to use for analysis")
pipeline: Optional[str] = Field(default=None, description="Pipeline to run (default: comprehensive)")
query: Optional[str] = Field(default=None, description="Search query for news-related pipelines (e.g., 'AAPL earnings Q3')")
class JobResponse(BaseModel):
job_id: str
ticker: str
status: str
message: str
class ChatRequest(BaseModel):
"""Chat request model for conversational AI analysis"""
email: str = Field(..., description="User email for data organization")
timestamp: str = Field(..., description="Timestamp for the chat session")
user_prompt: str = Field(..., description="User's chat message/question")
session_id: Optional[str] = Field(default=None, description="Session ID for continuing conversation (optional)")
class JobStatus(BaseModel):
job_id: str
ticker: str
company: Optional[str] = None
status: str
progress: Optional[str] = None
created_at: str
completed_at: Optional[str] = None
error: Optional[str] = None
latest_log: Optional[str] = None
last_activity: Optional[str] = None
recent_logs: Optional[List[str]] = None
# ------------- Docker helpers -------------
def init_docker_client():
global docker_client
try:
logger.info("Initializing Docker client...")
docker_client = docker.from_env()
docker_client.ping()
logger.info("✅ Docker client connected successfully")
return True
except Exception as e:
logger.error(f"❌ Failed to connect to Docker: {e}")
docker_client = None
return False
def ensure_volume_exists():
if not docker_client:
return False
try:
docker_client.volumes.get(DATA_VOLUME)
logger.info(f"✅ Volume '{DATA_VOLUME}' exists")
return True
except docker.errors.NotFound:
try:
docker_client.volumes.create(name=DATA_VOLUME)
logger.info(f"✅ Created volume '{DATA_VOLUME}'")
return True
except Exception as e:
logger.error(f"❌ Failed to create volume '{DATA_VOLUME}': {e}")
return False
except Exception as e:
logger.error(f"❌ Error checking volume '{DATA_VOLUME}': {e}")
return False
# ------------- Log monitoring (polls info.log) -------------
async def monitor_info_log(job_id: str, container):
"""Monitor info.log file in real-time and update job progress"""
try:
def monitor_logs():
try:
job = jobs.get(job_id) or {}
base = job_root(job) # /data/<email>/<TICKER>/<timestamp>
last_info_log_size = 0
container_running = True
while container_running:
if job_id not in jobs:
break
# Check if container is still running
try:
container.reload()
container_running = (container.status == 'running')
except docker.errors.NotFound:
logger.info(f"Container {container.id[:12]} was removed during log monitoring")
container_running = False
except Exception as e:
logger.warning(f"Error checking container status during log monitoring: {e}")
container_running = False
try:
# Get current file size of info.log
temp_container = docker_client.containers.run(
"alpine:latest",
command=f"sh -c 'if [ -f {shlex.quote(base)}/info.log ]; then wc -c {shlex.quote(base)}/info.log | cut -d\" \" -f1; else echo 0; fi'",
volumes={DATA_VOLUME: {'bind': '/data', 'mode': 'rw'}},
remove=True,
detach=False
)
current_size = int(temp_container.decode('utf-8').strip())
if current_size > last_info_log_size:
# Read appended bytes
temp_container2 = docker_client.containers.run(
"alpine:latest",
command=f"sh -c 'if [ -f {shlex.quote(base)}/info.log ]; then tail -c +{last_info_log_size + 1} {shlex.quote(base)}/info.log; fi'",
volumes={DATA_VOLUME: {'bind': '/data', 'mode': 'rw'}},
remove=True,
detach=False
)
new_content = temp_container2.decode('utf-8').strip()
if new_content:
for line in new_content.split('\n'):
if line.strip():
jobs[job_id]["latest_log"] = line.strip()
jobs[job_id]["last_activity"] = datetime.now().isoformat()
jobs[job_id].setdefault("recent_logs", []).append(line.strip())
if len(jobs[job_id]["recent_logs"]) > 100:
jobs[job_id]["recent_logs"].pop(0)
if "Stock Analysis Pipeline Session Started" in line:
jobs[job_id]["progress"] = "Analysis started..."
elif "STAGE: COMPREHENSIVE PIPELINE" in line:
jobs[job_id]["progress"] = "Starting comprehensive analysis..."
elif "STAGE: FINANCIAL SCRAPING" in line:
jobs[job_id]["progress"] = "Scraping financial data..."
elif "STAGE: FINANCIAL MODEL GENERATION" in line:
jobs[job_id]["progress"] = "Generating financial model..."
elif "STAGE: ARTICLE SCRAPING" in line:
jobs[job_id]["progress"] = "Scraping new articles..."
elif "STAGE: ARTICLE FILTERING" in line:
jobs[job_id]["progress"] = "Filtering news articles..."
elif "STAGE: ARTICLE SCREENING" in line:
jobs[job_id]["progress"] = "Screening news articles..."
elif "STAGE: PRICE ADJUSTMENT" in line:
jobs[job_id]["progress"] = "Adjusting price based on news..."
elif "STAGE: PROFESSIONAL REPORT GENERATION" in line:
jobs[job_id]["progress"] = "Generating professional report..."
elif "PIPELINE SESSION COMPLETED" in line:
jobs[job_id]["progress"] = "Finalizing analysis..."
elif "THE ENTIRE PROGRAM IS COMPLETED" in line:
jobs[job_id]["progress"] = "Analysis completed successfully"
jobs[job_id]["status"] = "completed"
last_info_log_size = current_size
except Exception:
# info.log may not exist yet; that's OK
pass
# If container stopped, do one final read
if not container_running:
try:
final_temp = docker_client.containers.run(
"alpine:latest",
command=f"sh -c 'if [ -f {shlex.quote(base)}/info.log ]; then tail -c +{last_info_log_size + 1} {shlex.quote(base)}/info.log; fi'",
volumes={DATA_VOLUME: {'bind': '/data', 'mode': 'rw'}},
remove=True,
detach=False
)
final_content = final_temp.decode('utf-8').strip()
if final_content:
for line in final_content.split('\n'):
if line.strip():
jobs[job_id].setdefault("recent_logs", []).append(line.strip())
if "THE ENTIRE PROGRAM IS COMPLETED" in line:
jobs[job_id]["status"] = "completed"
jobs[job_id]["progress"] = "Analysis completed successfully"
except:
pass
break
time.sleep(2)
except Exception as e:
logger.error(f"Error in log monitoring for job {job_id}: {e}")
loop = asyncio.get_event_loop()
with concurrent.futures.ThreadPoolExecutor() as executor:
await loop.run_in_executor(executor, monitor_logs)
except Exception as e:
logger.error(f"Error monitoring logs for job {job_id}: {e}")
# ------------- Job runner -------------
async def run_analysis_job(job_id: str, ticker: str, company: Optional[str],
email: Optional[str], timestamp: Optional[str],
llm: Optional[str] = None, pipeline: Optional[str] = None,
query: Optional[str] = None):
"""
Run stock analysis job in Docker container.
"""
if not docker_client:
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = "Docker client not available"
return
try:
jobs[job_id]["status"] = "running"
jobs[job_id]["progress"] = "Starting analysis container..."
jobs[job_id]["recent_logs"] = []
env_vars = {
"SERPAPI_API_KEY": SERPAPI_API_KEY,
"OPENAI_API_KEY": OPENAI_API_KEY,
"ANTHROPIC_API_KEY": ANTHROPIC_API_KEY,
"MONGO_URI": MONGO_URI,
"MONGO_DB": MONGO_DB,
"DATA_PATH": "/data",
}
cmd = ["--ticker", ticker, "--email", email, "--timestamp", timestamp]
if llm:
cmd.extend(["--llm", llm])
if pipeline:
cmd.extend(["--pipeline", pipeline])
if query:
cmd.extend(["--query", query])
logger.info(f"🚀 Starting analysis for {ticker} ({company}) with command: {cmd}")
jobs[job_id]["progress"] = f"Running {pipeline} analysis for {ticker} ({company})..."
container = docker_client.containers.run(
BACKEND_IMAGE,
command=cmd,
environment=env_vars,
volumes={DATA_VOLUME: {'bind': '/data', 'mode': 'rw'}},
detach=True,
remove=False,
name=f"analysis-{job_id}"
)
jobs[job_id]["container_id"] = container.id
jobs[job_id]["progress"] = "Analysis running..."
loop = asyncio.get_event_loop()
log_task = asyncio.create_task(monitor_info_log(job_id, container))
try:
def wait_for_container():
return container.wait(timeout=1800)
# Monitor for stop requests while container is running
stop_check_task = None
async def check_stop_request():
"""Periodically check if job should be stopped"""
while True:
await asyncio.sleep(2) # Check every 2 seconds
current_status = jobs[job_id].get("status")
if current_status in ["stopping", "stopped"]:
logger.info(f"Stop request detected for job {job_id}, killing container")
try:
# Check if container still exists before trying to kill it
try:
container.reload()
if container.status in ['running', 'paused']:
container.kill()
logger.info(f"Container {container.id[:12]} killed due to stop request")
except docker.errors.NotFound:
logger.info(f"Container {container.id[:12]} already removed")
except Exception as kill_e:
logger.error(f"Error killing container on stop request: {kill_e}")
return
# Start stop monitoring task
stop_check_task = asyncio.create_task(check_stop_request())
try:
with concurrent.futures.ThreadPoolExecutor() as executor:
await loop.run_in_executor(executor, wait_for_container)
finally:
if stop_check_task:
stop_check_task.cancel()
except Exception as e:
logger.error(f"Container wait timeout or error: {e}")
try:
# Check if container still exists before trying to kill it
try:
container.reload()
if container.status in ['running', 'paused']:
container.kill()
except docker.errors.NotFound:
logger.info(f"Container {container.id[:12]} already removed during error handling")
except Exception as kill_e:
logger.error(f"Failed to kill container during error handling: {kill_e}")
current_progress = jobs[job_id].get("progress", "").lower()
if "llm analysis" in current_progress or "running llm" in current_progress:
jobs[job_id]["status"] = "llm_timeout"
jobs[job_id]["error"] = f"LLM analysis timeout after 30 minutes: {str(e)}"
jobs[job_id]["progress"] = "LLM analysis timed out - retrying may help"
else:
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = f"Analysis timeout: {str(e)}"
log_task.cancel()
return
except Exception as cleanup_e:
logger.error(f"Error during cleanup: {cleanup_e}")
# Cancel log monitoring task
log_task.cancel()
# Try to get container exit code, but handle case where container was removed
exit_code = None
try:
container.reload()
exit_code = container.attrs['State']['ExitCode']
except docker.errors.NotFound:
logger.info(f"Container {container.id[:12]} was removed before exit code check")
except Exception as e:
logger.warning(f"Could not get container exit code: {e}")
# Check if job was stopped by user before checking exit code
current_status = jobs[job_id].get("status")
if current_status in ["stopping", "stopped"]:
if current_status == "stopping":
jobs[job_id]["status"] = "stopped"
jobs[job_id]["progress"] = "Analysis stopped by user"
jobs[job_id]["completed_at"] = datetime.now().isoformat()
logger.info(f"✅ Analysis job {job_id} stopped by user request")
elif exit_code == 0:
if jobs[job_id]["status"] != "completed":
jobs[job_id]["status"] = "completed"
jobs[job_id]["progress"] = "Analysis completed successfully"
jobs[job_id]["completed_at"] = datetime.now().isoformat()
logger.info(f"✅ Analysis job {job_id} completed successfully")
elif exit_code is not None and exit_code != 0:
if current_status == "llm_timeout":
jobs[job_id]["progress"] = "LLM analysis timed out - retrying may help"
else:
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = f"Analysis failed with exit code {exit_code}"
logger.error(f"❌ Analysis job {job_id} failed with exit code {exit_code}")
# Only try to remove container if job wasn't stopped by user (stop endpoint handles removal)
current_final_status = jobs[job_id].get("status")
if current_final_status not in ["stopped"]:
try:
container.remove()
logger.info(f"Container {container.id[:12]} removed after job completion")
except docker.errors.NotFound:
logger.info(f"Container {container.id[:12]} already removed")
except Exception as e:
logger.warning(f"Failed to remove container: {e}")
else:
logger.info(f"Container removal skipped - job was stopped by user")
except Exception as e:
logger.error(f"❌ Error in analysis job {job_id}: {e}")
error_str = str(e).lower()
current_progress = jobs[job_id].get("progress", "").lower()
if (("timeout" in error_str or "timed out" in error_str or "llm" in error_str) and
("llm analysis" in current_progress or "running llm" in current_progress)):
jobs[job_id]["status"] = "llm_timeout"
jobs[job_id]["error"] = f"LLM analysis timeout: {str(e)}"
jobs[job_id]["progress"] = "LLM analysis timed out - retrying may help"
else:
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
# ------------- Chat job runner -------------
async def run_chat_job(
job_id: str,
email: str,
timestamp: str,
user_prompt: str,
session_id: Optional[str] = None
):
"""
Run chat job in Docker container with the chat pipeline.
Args:
job_id: Unique job identifier
email: User email
timestamp: ISO timestamp
user_prompt: User's chat message/question
session_id: Optional session ID for continuing conversation
"""
if not docker_client:
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = "Docker client not available"
return
try:
jobs[job_id]["status"] = "running"
jobs[job_id]["progress"] = "Starting chat session..."
jobs[job_id]["recent_logs"] = []
env_vars = {
"SERPAPI_API_KEY": SERPAPI_API_KEY,
"OPENAI_API_KEY": OPENAI_API_KEY,
"ANTHROPIC_API_KEY": ANTHROPIC_API_KEY,
"MONGO_URI": MONGO_URI,
"MONGO_DB": MONGO_DB,
"DATA_PATH": "/data",
}
# Build command for chat pipeline (4 required args: email, timestamp, pipeline, user-prompt, session-id)
cmd = [
"--email", email,
"--timestamp", timestamp,
"--pipeline", "chat",
"--user-prompt", user_prompt
]
# Add optional session-id if provided
if session_id:
cmd.extend(["--session-id", session_id])
logger.info(f"🚀 Starting chat session with command: {cmd}")
jobs[job_id]["progress"] = f"Running chat session..."
container = docker_client.containers.run(
BACKEND_IMAGE,
command=cmd,
environment=env_vars,
volumes={DATA_VOLUME: {'bind': '/data', 'mode': 'rw'}},
detach=True,
remove=False,
name=f"chat-{job_id}"
)
jobs[job_id]["container_id"] = container.id
jobs[job_id]["progress"] = "Waiting for ticker identification..."
# Listen to container stdout to extract ticker
# The backend prints: "[SUPERVISOR] ✅ Identified ticker: {ticker}"
ticker_identified = False
identified_ticker = None
def extract_ticker_from_logs():
"""Extract ticker from container logs (synchronous function for executor)"""
nonlocal ticker_identified, identified_ticker
try:
# Stream container logs to extract ticker
log_stream = container.logs(stream=True, follow=True)
for log_line in log_stream:
try:
line = log_line.decode('utf-8').strip()
logger.info(f"[CHAT CONTAINER] {line}")
# Look for ticker identification line
if "[SUPERVISOR] ✅ Identified ticker:" in line:
# Extract ticker: "[SUPERVISOR] ✅ Identified ticker: NVDA"
parts = line.split("Identified ticker:")
if len(parts) > 1:
identified_ticker = parts[1].strip().upper()
ticker_identified = True
logger.info(f"🎯 Extracted ticker from chat: {identified_ticker}")
# Update job with identified ticker
jobs[job_id]["ticker"] = identified_ticker
jobs[job_id]["progress"] = f"Analyzing {identified_ticker}..."
# Break after finding ticker
break
except Exception as decode_error:
logger.warning(f"Error decoding log line: {decode_error}")
continue
except Exception as e:
logger.error(f"Error extracting ticker from logs: {e}")
# Run ticker extraction with timeout
loop = asyncio.get_event_loop()
try:
with concurrent.futures.ThreadPoolExecutor() as executor:
# Wait up to 30 seconds for ticker identification
await asyncio.wait_for(
loop.run_in_executor(executor, extract_ticker_from_logs),
timeout=30.0
)
except asyncio.TimeoutError:
logger.warning(f"⚠️ Ticker identification timeout for job {job_id}, continuing anyway...")
# If we couldn't identify ticker, keep "pending" as ticker
if not ticker_identified:
logger.info(f"Ticker not identified for job {job_id}, keeping 'pending' status")
except Exception as e:
logger.error(f"Error during ticker extraction: {e}")
# Now start monitoring info.log with the identified ticker
if ticker_identified and identified_ticker:
logger.info(f"✅ Ticker identified: {identified_ticker}, starting log monitoring...")
else:
logger.warning(f"⚠️ Ticker not identified, keeping 'pending' status")
log_task = asyncio.create_task(monitor_info_log(job_id, container))
try:
def wait_for_container():
result = container.wait(timeout=1800)
return result
# Monitor for stop requests while container is running
stop_check_task = None
async def check_stop_request():
"""Periodically check if job should be stopped"""
while True:
await asyncio.sleep(2)
current_status = jobs[job_id].get("status")
if current_status in ["stopping", "stopped"]:
logger.info(f"Stop request detected for job {job_id}, killing container")
try:
container.reload()
if container.status in ['running', 'paused']:
container.kill()
logger.info(f"Container {container.id[:12]} killed for chat job {job_id}")
except Exception as kill_e:
logger.error(f"Failed to kill container: {kill_e}")
return
# Start stop monitoring task
stop_check_task = asyncio.create_task(check_stop_request())
try:
with concurrent.futures.ThreadPoolExecutor() as executor:
await loop.run_in_executor(executor, wait_for_container)
finally:
if stop_check_task:
stop_check_task.cancel()
except Exception as e:
logger.error(f"Container wait timeout or error: {e}")
try:
container.reload()
if container.status in ['running', 'paused']:
container.kill()
except docker.errors.NotFound:
logger.info(f"Container {container.id[:12]} already removed during error handling")
except Exception as kill_e:
logger.error(f"Failed to kill container during error handling: {kill_e}")
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = f"Chat session timeout: {str(e)}"
log_task.cancel()
return
# Cancel log monitoring task
log_task.cancel()
# Try to get container exit code
exit_code = None
try:
container.reload()
exit_code = container.attrs['State']['ExitCode']
except docker.errors.NotFound:
logger.info(f"Container {container.id[:12]} was removed before exit code check")
except Exception as e:
logger.warning(f"Could not get container exit code: {e}")
# Check if job was stopped by user
current_status = jobs[job_id].get("status")
if current_status in ["stopping", "stopped"]:
if current_status == "stopping":
jobs[job_id]["status"] = "stopped"
jobs[job_id]["progress"] = "Chat stopped by user"
jobs[job_id]["completed_at"] = datetime.now().isoformat()
logger.info(f"✅ Chat job {job_id} stopped by user request")
elif exit_code == 0:
if jobs[job_id]["status"] != "completed":
jobs[job_id]["status"] = "completed"
jobs[job_id]["progress"] = "Chat session completed successfully"
jobs[job_id]["completed_at"] = datetime.now().isoformat()
logger.info(f"✅ Chat job {job_id} completed successfully")
elif exit_code is not None and exit_code != 0:
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = f"Chat failed with exit code {exit_code}"
logger.error(f"❌ Chat job {job_id} failed with exit code {exit_code}")
# Remove container
current_final_status = jobs[job_id].get("status")
if current_final_status not in ["stopped"]:
try:
container.remove()
logger.info(f"Container {container.id[:12]} removed after chat completion")
except docker.errors.NotFound:
logger.info(f"Container {container.id[:12]} already removed")
except Exception as e:
logger.warning(f"Failed to remove container: {e}")
else:
logger.info(f"Container removal skipped - job was stopped by user")
except Exception as e:
logger.error(f"❌ Error in chat job {job_id}: {e}")
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
# ------------- Startup / health -------------
@app.on_event("startup")
async def startup_event():
global price_manager, websocket_manager, news_auto_updater, news_websocket_manager
logger.info("🚀 Starting Stock Analyst API Runner...")
docker_ready = init_docker_client()
if not docker_ready:
logger.warning("⚠️ Docker not available - running in limited mode")
else:
ensure_volume_exists()
# Set docker client for daily reports module
set_docker_client(docker_client)
if not SERPAPI_API_KEY:
logger.warning("⚠️ SERPAPI_API_KEY not set")
else:
logger.info("✅ SERPAPI_API_KEY configured")
if not OPENAI_API_KEY:
logger.warning("⚠️ OPENAI_API_KEY not set")
else:
logger.info("✅ OPENAI_API_KEY configured")
if not ANTHROPIC_API_KEY:
logger.warning("⚠️ ANTHROPIC_API_KEY not set")
else:
logger.info("✅ ANTHROPIC_API_KEY configured")
# Initialize news feed system (REQUIRED for news WebSocket to work)
news_ready = await init_news_manager()
if news_ready:
logger.info("✅ News feed system initialized successfully")
# Initialize news WebSocket manager (WITHOUT auto-updater)
try:
news_manager = NewsManager()
await news_manager.initialize()
# Initialize WebSocket manager WITHOUT auto-updater (passing None)
news_websocket_manager = init_news_websocket_manager(news_manager, auto_updater=None)
logger.info("✅ News WebSocket manager initialized (manual updates only)")
logger.info("📡 News WebSocket endpoint available at /api/news/ws")
except Exception as e:
logger.error(f"❌ Failed to initialize news WebSocket manager: {e}")
logger.warning("⚠️ News WebSocket will be unavailable")
# OPTIONAL: Initialize news auto-updater (currently disabled)
# Uncomment this section if you want automatic background news updates
# try:
# logger.info("🚀 Starting automatic news update system...")
#
# # Create optimized news auto-updater with 30-minute intervals and API rate limiting
# news_config = NewsUpdateConfig(
# update_interval=7200, # 2 hours in seconds (reduced from 5 min)
# max_tickers_per_batch=2, # Reduced from 10 for API limits
# days_back=1, # Only check last 1 day (reduced from 7)
# articles_limit=10, # Reduced from 20
# timeout_seconds=180,
# force_refresh=False,
# min_update_interval=3600, # Minimum 1 hour between updates per ticker
# max_api_calls_per_hour=20 # SerpAPI rate limiting
# )
# news_auto_updater = NewsUpdateManager(news_config)
#
# # Initialize and start auto-updater
# auto_update_ready = await news_auto_updater.initialize()
# if auto_update_ready:
# await news_auto_updater.start()
# logger.info("✅ News auto-updater started - updating every 30 minutes with smart rate limiting")
#
# # Connect auto-updater to WebSocket manager
# if news_websocket_manager:
# news_websocket_manager.set_auto_updater(news_auto_updater)
# logger.info("✅ Auto-updater connected to WebSocket manager")
# else:
# logger.warning("⚠️ News auto-updater failed to initialize")
#
# except Exception as e:
# logger.error(f"❌ Failed to start news auto-updater: {e}")
# logger.warning("⚠️ Automatic news updates will be unavailable")
else:
logger.warning("⚠️ News feed system not available")
# Initialize real-time stock price system
try:
logger.info("🚀 Starting real-time stock price system...")
# Create price manager with configuration
price_config = PriceFetchConfig(
fetch_interval=10, # 10 seconds as requested
max_symbols_per_request=50,
retry_attempts=3,
timeout=30
)
price_manager = PriceManager(price_config)
# Start price manager
await price_manager.start()
# Initialize FastAPI WebSocket manager (integrated with main FastAPI app)
from realtime.fastapi_websocket import init_fastapi_websocket_manager
websocket_manager = init_fastapi_websocket_manager(price_manager)
# Initialize API endpoints with services
init_realtime_api(price_manager, websocket_manager)
logger.info("✅ Real-time stock price system started")
logger.info("📡 WebSocket endpoint available at /api/realtime/ws")
except Exception as e:
logger.error(f"❌ Failed to start real-time system: {e}")
logger.warning("⚠️ Real-time features will be unavailable")
# # Initialize daily reports scheduler
# try:
# logger.info("🚀 Starting daily reports scheduler...")
# scheduler_ready = await initialize_scheduler()
# if scheduler_ready:
# logger.info("✅ Daily reports scheduler started - auto-generates reports at 8:30 AM ET (Mon-Fri)")
# else:
# logger.warning("⚠️ Daily reports scheduler failed to initialize")
# except Exception as e:
# logger.error(f"❌ Failed to start daily reports scheduler: {e}")
# logger.warning("⚠️ Automatic daily report generation will be unavailable")
logger.info("✅ API Runner started successfully")
@app.on_event("shutdown")
async def shutdown_event():
global price_manager, websocket_manager, news_auto_updater, news_websocket_manager
logger.info("🔌 Shutting down API Runner...")
# Shutdown real-time services
try:
if price_manager:
logger.info("🛑 Stopping real-time stock price system...")
await price_manager.stop()
logger.info("✅ Real-time services stopped")
except Exception as e:
logger.error(f"❌ Error stopping real-time services: {e}")
# Shutdown news auto-updater
try:
if news_auto_updater:
logger.info("🛑 Stopping news auto-updater...")
await news_auto_updater.stop()
logger.info("✅ News auto-updater stopped")
except Exception as e:
logger.error(f"❌ Error stopping news auto-updater: {e}")
# Shutdown daily reports scheduler
try:
logger.info("🛑 Stopping daily reports scheduler...")
await shutdown_scheduler()
logger.info("✅ Daily reports scheduler stopped")
except Exception as e:
logger.error(f"❌ Error stopping daily reports scheduler: {e}")
# Shutdown news feed system
try:
await close_news_manager()
logger.info("✅ News feed system stopped")
except Exception as e:
logger.error(f"❌ Error stopping news feed system: {e}")
logger.info("✅ API Runner shutdown complete")
@app.get("/")
async def root():
return {
"status": "healthy",
"service": "Stock Analyst API Runner",
"docker_available": docker_client is not None,
"timestamp": datetime.now().isoformat()
}
@app.get("/health")
async def health_check():
docker_status = "connected" if docker_client else "disconnected"
# Check real-time service status
realtime_status = "stopped"
websocket_status = "integrated" # WebSocket is now integrated with FastAPI
if price_manager and price_manager.is_running:
realtime_status = "running"
# Check news feed status
try:
from news_feed.api import get_news_manager
news_manager = get_news_manager()
news_status = "running" if news_manager else "stopped"
except:
news_status = "not_initialized"
return {
"status": "healthy",
"docker": docker_status,
"realtime_prices": realtime_status,
"websocket_server": websocket_status,
"news_feed": news_status,
"backend_image": BACKEND_IMAGE,
"data_volume": DATA_VOLUME,
"api_keys_configured": {
"serpapi": bool(SERPAPI_API_KEY),
"openai": bool(OPENAI_API_KEY),
"anthropic": bool(ANTHROPIC_API_KEY)
}
}
@app.get("/api/news/auto-updater/status")
async def news_auto_updater_status():
"""Get status of the news auto-updater system."""
global news_auto_updater, news_websocket_manager
if not news_auto_updater:
return {
"status": "not_initialized",
"message": "News auto-updater not initialized"
}
try:
status = news_auto_updater.get_status()
# Add WebSocket connection info
if news_websocket_manager:
status["websocket_connections"] = news_websocket_manager.get_connection_count()
status["subscribed_tickers_websocket"] = news_websocket_manager.get_all_subscribed_tickers()
return status
except Exception as e:
return {