Ali2206 commited on
Commit
cee9c20
·
verified ·
1 Parent(s): 5d6e4af

Update config.py

Browse files
Files changed (1) hide show
  1. config.py +14 -87
config.py CHANGED
@@ -1,17 +1,12 @@
 
1
  import logging
2
  from fastapi import FastAPI
3
  from txagent.txagent import TxAgent
4
  from db.mongo import get_mongo_client
5
  import asyncio
6
- from pyfcm import FCMNotification
7
- from datetime import datetime
8
- import httpx
9
- import os
10
- import json
11
- import tempfile
12
 
13
  # Logging
14
- logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(name)s - %(message)s")
15
  logger = logging.getLogger("TxAgentAPI")
16
 
17
  # Initialize agent synchronously with error handling
@@ -41,89 +36,21 @@ users_collection = db["users"]
41
  patients_collection = db["patients"]
42
  analysis_collection = db["patient_analysis_results"]
43
  alerts_collection = db["clinical_alerts"]
44
- notifications_collection = db["notifications"]
45
- logger.info("📡 Connected to MongoDB synchronously at %s", datetime.utcnow().isoformat())
46
-
47
- # Retrieve secrets from environment variables (set in Hugging Face Space Secrets)
48
- FCM_SERVICE_ACCOUNT_JSON = os.getenv("FCM_SERVICE_ACCOUNT")
49
- SECRET_KEY = os.getenv("SECRET_KEY")
50
-
51
- if not FCM_SERVICE_ACCOUNT_JSON or not SECRET_KEY:
52
- logger.error("❌ Missing FCM_SERVICE_ACCOUNT or SECRET_KEY in environment variables")
53
- raise ValueError("FCM_SERVICE_ACCOUNT and SECRET_KEY must be set in Hugging Face Space Secrets")
54
-
55
- # Write the FCM service account JSON to a temporary file
56
- with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.json') as temp_file:
57
- json.dump(json.loads(FCM_SERVICE_ACCOUNT_JSON), temp_file)
58
- temp_file_path = temp_file.name
59
-
60
- # FCM settings
61
- push_service = FCMNotification(service_account_file=temp_file_path)
62
-
63
- # Auth Space URL
64
- AUTH_SPACE_URL = "https://rocketfarmstudios-cps-api.hf.space/auth"
65
-
66
- async def send_push_notification(recipient_email, message):
67
- try:
68
- # Fetch the user's device token from the auth Space
69
- async with httpx.AsyncClient() as client:
70
- headers = {"Authorization": f"Bearer {create_access_token(recipient_email)}"}
71
- response = await client.get(f"{AUTH_SPACE_URL}/me", headers=headers)
72
- if response.status_code != 200:
73
- logger.warning(f"Failed to fetch user {recipient_email} from auth Space: {response.text}")
74
- return
75
- user_data = response.json()
76
- device_token = user_data.get("device_token")
77
-
78
- if not device_token:
79
- logger.warning(f"No device token found for {recipient_email} at {datetime.utcnow().isoformat()}")
80
- return
81
-
82
- # Send push notification
83
- result = push_service.notify_single_device(
84
- registration_id=device_token,
85
- message_title="Risk Alert",
86
- message_body=message,
87
- sound="default",
88
- priority="high"
89
- )
90
- logger.info(f"Push notification sent to {recipient_email} at {datetime.utcnow().isoformat()}: {result}")
91
- except Exception as e:
92
- logger.error(f"Failed to send push notification to {recipient_email} at {datetime.utcnow().isoformat()}: {str(e)}")
93
- finally:
94
- # Clean up the temporary file
95
- if os.path.exists(temp_file_path):
96
- os.remove(temp_file_path)
97
-
98
- # JWT settings (minimal implementation for token creation)
99
- from datetime import timedelta
100
- import jwt
101
 
 
 
102
  ALGORITHM = "HS256"
103
- ACCESS_TOKEN_EXPIRE_MINUTES = 30
104
-
105
- def create_access_token(email: str):
106
- to_encode = {"sub": email, "exp": datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)}
107
- return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
108
-
109
- def decode_access_token(token: str):
110
- try:
111
- payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
112
- return payload
113
- except jwt.PyJWTError as e:
114
- logger.error(f"Token decode error: {str(e)}")
115
- return None
116
 
117
  def setup_app(app: FastAPI):
118
  @app.on_event("startup")
119
  async def startup_event():
120
- # Temporarily disable the analyze_all_patients task due to missing analyze_patient function
121
- # asyncio.create_task(analyze_all_patients())
122
- logger.info("Startup event triggered, analyze_all_patients task disabled until implementation.")
123
-
124
- # async def analyze_all_patients():
125
- # from analysis import analyze_patient
126
- # patients = await patients_collection.find({}).to_list(length=None)
127
- # for patient in patients:
128
- # await analyze_patient(patient)
129
- # await asyncio.sleep(0.1)
 
1
+ import os
2
  import logging
3
  from fastapi import FastAPI
4
  from txagent.txagent import TxAgent
5
  from db.mongo import get_mongo_client
6
  import asyncio
 
 
 
 
 
 
7
 
8
  # Logging
9
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
10
  logger = logging.getLogger("TxAgentAPI")
11
 
12
  # Initialize agent synchronously with error handling
 
36
  patients_collection = db["patients"]
37
  analysis_collection = db["patient_analysis_results"]
38
  alerts_collection = db["clinical_alerts"]
39
+ notifications_collection = db["notifications"] # New collection for notifications
40
+ logger.info("📡 Connected to MongoDB synchronously")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
+ # JWT settings
43
+ SECRET_KEY = os.getenv("SECRET_KEY", "your-secret-key")
44
  ALGORITHM = "HS256"
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  def setup_app(app: FastAPI):
47
  @app.on_event("startup")
48
  async def startup_event():
49
+ asyncio.create_task(analyze_all_patients())
50
+
51
+ async def analyze_all_patients():
52
+ from analysis import analyze_patient
53
+ patients = await patients_collection.find({}).to_list(length=None)
54
+ for patient in patients:
55
+ await analyze_patient(patient)
56
+ await asyncio.sleep(0.1)