Spaces:
Sleeping
Sleeping
Fix TxAgent integration: remove external API dependency and use integrated service
Browse files- api/routes/txagent.py +24 -23
- api/services/txagent_service.py +14 -0
- app.py +9 -111
api/routes/txagent.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form
|
| 2 |
from fastapi.responses import StreamingResponse
|
| 3 |
from typing import Optional, List
|
| 4 |
from pydantic import BaseModel
|
|
@@ -33,6 +33,29 @@ async def get_txagent_status(current_user: dict = Depends(get_current_user)):
|
|
| 33 |
logger.error(f"Error getting TxAgent status: {e}")
|
| 34 |
raise HTTPException(status_code=500, detail="Failed to get TxAgent status")
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
@router.post("/txagent/chat")
|
| 37 |
async def chat_with_txagent(
|
| 38 |
request: ChatRequest,
|
|
@@ -146,25 +169,3 @@ async def get_chats(current_user: dict = Depends(get_current_user)):
|
|
| 146 |
except Exception as e:
|
| 147 |
logger.error(f"Error getting chats: {e}")
|
| 148 |
raise HTTPException(status_code=500, detail="Failed to get chats")
|
| 149 |
-
|
| 150 |
-
@router.get("/txagent/patients/analysis-results")
|
| 151 |
-
async def get_analysis_results(
|
| 152 |
-
risk_filter: Optional[str] = None,
|
| 153 |
-
current_user: dict = Depends(get_current_user)
|
| 154 |
-
):
|
| 155 |
-
"""Obtient les résultats d'analyse des patients"""
|
| 156 |
-
try:
|
| 157 |
-
if not any(role in current_user.get('roles', []) for role in ['doctor', 'admin']):
|
| 158 |
-
raise HTTPException(status_code=403, detail="Only doctors and admins can access analysis results")
|
| 159 |
-
|
| 160 |
-
# Cette fonction devra être implémentée dans le service TxAgent
|
| 161 |
-
results = await txagent_service.get_analysis_results(risk_filter)
|
| 162 |
-
|
| 163 |
-
return {
|
| 164 |
-
"status": "success",
|
| 165 |
-
"results": results,
|
| 166 |
-
"mode": txagent_service.config.get_txagent_mode()
|
| 167 |
-
}
|
| 168 |
-
except Exception as e:
|
| 169 |
-
logger.error(f"Error getting analysis results: {e}")
|
| 170 |
-
raise HTTPException(status_code=500, detail="Failed to get analysis results")
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, Query
|
| 2 |
from fastapi.responses import StreamingResponse
|
| 3 |
from typing import Optional, List
|
| 4 |
from pydantic import BaseModel
|
|
|
|
| 33 |
logger.error(f"Error getting TxAgent status: {e}")
|
| 34 |
raise HTTPException(status_code=500, detail="Failed to get TxAgent status")
|
| 35 |
|
| 36 |
+
@router.get("/txagent/patients/analysis-results")
|
| 37 |
+
async def get_patient_analysis_results(
|
| 38 |
+
name: Optional[str] = Query(None),
|
| 39 |
+
current_user: dict = Depends(get_current_user)
|
| 40 |
+
):
|
| 41 |
+
"""Get patient analysis results from integrated TxAgent service"""
|
| 42 |
+
try:
|
| 43 |
+
# Check if user has appropriate permissions
|
| 44 |
+
if not any(role in current_user.get('roles', []) for role in ['doctor', 'admin']):
|
| 45 |
+
raise HTTPException(status_code=403, detail="Only doctors and admins can access analysis results")
|
| 46 |
+
|
| 47 |
+
# Use the integrated TxAgent service to get analysis results
|
| 48 |
+
results = await txagent_service.get_analysis_results(name)
|
| 49 |
+
|
| 50 |
+
return {
|
| 51 |
+
"status": "success",
|
| 52 |
+
"results": results,
|
| 53 |
+
"mode": txagent_service.config.get_txagent_mode()
|
| 54 |
+
}
|
| 55 |
+
except Exception as e:
|
| 56 |
+
logger.error(f"Error getting analysis results: {e}")
|
| 57 |
+
raise HTTPException(status_code=500, detail="Failed to get analysis results")
|
| 58 |
+
|
| 59 |
@router.post("/txagent/chat")
|
| 60 |
async def chat_with_txagent(
|
| 61 |
request: ChatRequest,
|
|
|
|
| 169 |
except Exception as e:
|
| 170 |
logger.error(f"Error getting chats: {e}")
|
| 171 |
raise HTTPException(status_code=500, detail="Failed to get chats")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/services/txagent_service.py
CHANGED
|
@@ -97,6 +97,20 @@ class TxAgentService:
|
|
| 97 |
"""Obtient le statut du service TxAgent"""
|
| 98 |
return await self._make_request("/status")
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
async def get_chats(self) -> List[Dict[str, Any]]:
|
| 101 |
"""Obtient l'historique des chats"""
|
| 102 |
return await self._make_request("/chats")
|
|
|
|
| 97 |
"""Obtient le statut du service TxAgent"""
|
| 98 |
return await self._make_request("/status")
|
| 99 |
|
| 100 |
+
async def get_analysis_results(self, name: Optional[str] = None) -> List[Dict[str, Any]]:
|
| 101 |
+
"""Get patient analysis results from TxAgent service"""
|
| 102 |
+
params = {}
|
| 103 |
+
if name:
|
| 104 |
+
params['name'] = name
|
| 105 |
+
|
| 106 |
+
# Build URL with query parameters
|
| 107 |
+
endpoint = "/patients/analysis-results"
|
| 108 |
+
if params:
|
| 109 |
+
query_string = "&".join([f"{k}={v}" for k, v in params.items()])
|
| 110 |
+
endpoint = f"{endpoint}?{query_string}"
|
| 111 |
+
|
| 112 |
+
return await self._make_request(endpoint, "GET")
|
| 113 |
+
|
| 114 |
async def get_chats(self) -> List[Dict[str, Any]]:
|
| 115 |
"""Obtient l'historique des chats"""
|
| 116 |
return await self._make_request("/chats")
|
app.py
CHANGED
|
@@ -3,12 +3,7 @@ from fastapi.middleware.cors import CORSMiddleware
|
|
| 3 |
from fastapi.responses import RedirectResponse, HTMLResponse
|
| 4 |
from api import api_router
|
| 5 |
import gradio as gr
|
| 6 |
-
import requests
|
| 7 |
import logging
|
| 8 |
-
import time
|
| 9 |
-
import aiohttp
|
| 10 |
-
import asyncio
|
| 11 |
-
from typing import Optional
|
| 12 |
|
| 13 |
# Configure logging
|
| 14 |
logging.basicConfig(level=logging.DEBUG)
|
|
@@ -29,69 +24,13 @@ app.add_middleware(
|
|
| 29 |
app.include_router(api_router)
|
| 30 |
|
| 31 |
# Constants
|
| 32 |
-
BACKEND_URL = "https://rocketfarmstudios-cps-api.hf.space"
|
| 33 |
ADMIN_EMAIL = "[email protected]"
|
| 34 |
ADMIN_PASSWORD = "123456"
|
| 35 |
-
MAX_TOKEN_RETRIES = 3
|
| 36 |
-
TOKEN_RETRY_DELAY = 2 # seconds
|
| 37 |
-
|
| 38 |
-
class TokenManager:
|
| 39 |
-
def __init__(self):
|
| 40 |
-
self.token = None
|
| 41 |
-
self.last_refresh = 0
|
| 42 |
-
self.expires_in = 3600 # 1 hour default expiry
|
| 43 |
-
self.lock = asyncio.Lock()
|
| 44 |
-
|
| 45 |
-
async def _make_login_request(self) -> Optional[str]:
|
| 46 |
-
try:
|
| 47 |
-
async with aiohttp.ClientSession() as session:
|
| 48 |
-
async with session.post(
|
| 49 |
-
f"{BACKEND_URL}/auth/login",
|
| 50 |
-
json={
|
| 51 |
-
"username": ADMIN_EMAIL,
|
| 52 |
-
"password": ADMIN_PASSWORD,
|
| 53 |
-
"device_token": "admin-device-token"
|
| 54 |
-
},
|
| 55 |
-
timeout=10
|
| 56 |
-
) as response:
|
| 57 |
-
if response.status == 200:
|
| 58 |
-
data = await response.json()
|
| 59 |
-
return data.get("access_token")
|
| 60 |
-
else:
|
| 61 |
-
error = await response.text()
|
| 62 |
-
logger.error(f"Login failed: {response.status} - {error}")
|
| 63 |
-
return None
|
| 64 |
-
except Exception as e:
|
| 65 |
-
logger.error(f"Login request error: {str(e)}")
|
| 66 |
-
return None
|
| 67 |
-
|
| 68 |
-
async def refresh_token(self) -> str:
|
| 69 |
-
async with self.lock:
|
| 70 |
-
for attempt in range(MAX_TOKEN_RETRIES):
|
| 71 |
-
token = await self._make_login_request()
|
| 72 |
-
if token:
|
| 73 |
-
self.token = token
|
| 74 |
-
self.last_refresh = time.time()
|
| 75 |
-
logger.info("Successfully refreshed admin token")
|
| 76 |
-
return token
|
| 77 |
-
|
| 78 |
-
wait_time = min(5, (attempt + 1) * 2) # Exponential backoff with max 5s
|
| 79 |
-
logger.warning(f"Attempt {attempt + 1} failed, retrying in {wait_time}s...")
|
| 80 |
-
await asyncio.sleep(wait_time)
|
| 81 |
-
|
| 82 |
-
raise Exception("Failed to obtain admin token after multiple attempts")
|
| 83 |
-
|
| 84 |
-
async def get_token(self) -> str:
|
| 85 |
-
if not self.token or (time.time() - self.last_refresh) > (self.expires_in - 60):
|
| 86 |
-
return await self.refresh_token()
|
| 87 |
-
return self.token
|
| 88 |
-
|
| 89 |
-
token_manager = TokenManager()
|
| 90 |
|
| 91 |
@app.get("/")
|
| 92 |
def root():
|
| 93 |
logger.debug("Root endpoint accessed")
|
| 94 |
-
return {"message": "🚀
|
| 95 |
|
| 96 |
@app.post("/login")
|
| 97 |
async def redirect_login(request: Request):
|
|
@@ -106,54 +45,16 @@ def authenticate_admin(email: str = None, password: str = None):
|
|
| 106 |
logger.info(f"Admin authenticated successfully: {email}")
|
| 107 |
return True
|
| 108 |
|
| 109 |
-
|
|
|
|
| 110 |
try:
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
"full_name": full_name,
|
| 115 |
-
"email": email,
|
| 116 |
-
"license_number": matricule,
|
| 117 |
-
"password": password,
|
| 118 |
-
"specialty": specialty,
|
| 119 |
-
}
|
| 120 |
-
headers = {
|
| 121 |
-
"Authorization": f"Bearer {token}",
|
| 122 |
-
"Content-Type": "application/json"
|
| 123 |
-
}
|
| 124 |
-
|
| 125 |
-
async with aiohttp.ClientSession() as session:
|
| 126 |
-
async with session.post(
|
| 127 |
-
f"{BACKEND_URL}/auth/admin/doctors",
|
| 128 |
-
json=payload,
|
| 129 |
-
headers=headers,
|
| 130 |
-
timeout=10
|
| 131 |
-
) as response:
|
| 132 |
-
if response.status == 201:
|
| 133 |
-
return "✅ Doctor created successfully!"
|
| 134 |
-
elif response.status == 401: # Token might be expired
|
| 135 |
-
logger.warning("Token expired, attempting refresh...")
|
| 136 |
-
token = await token_manager.refresh_token()
|
| 137 |
-
headers["Authorization"] = f"Bearer {token}"
|
| 138 |
-
async with session.post(
|
| 139 |
-
f"{BACKEND_URL}/auth/admin/doctors",
|
| 140 |
-
json=payload,
|
| 141 |
-
headers=headers,
|
| 142 |
-
timeout=10
|
| 143 |
-
) as retry_response:
|
| 144 |
-
if retry_response.status == 201:
|
| 145 |
-
return "✅ Doctor created successfully!"
|
| 146 |
-
|
| 147 |
-
error_detail = await response.text()
|
| 148 |
-
return f"❌ Error: {error_detail} (Status: {response.status})"
|
| 149 |
-
|
| 150 |
except Exception as e:
|
| 151 |
logger.error(f"Doctor creation failed: {str(e)}")
|
| 152 |
return f"❌ System Error: {str(e)}"
|
| 153 |
|
| 154 |
-
def sync_create_doctor(*args):
|
| 155 |
-
return asyncio.run(async_create_doctor(*args))
|
| 156 |
-
|
| 157 |
admin_ui = gr.Blocks(
|
| 158 |
css="""
|
| 159 |
.gradio-container {
|
|
@@ -198,7 +99,7 @@ with admin_ui:
|
|
| 198 |
output = gr.Textbox(label="Status", interactive=False)
|
| 199 |
|
| 200 |
submit_btn.click(
|
| 201 |
-
fn=
|
| 202 |
inputs=[full_name, email, matricule, specialty, password],
|
| 203 |
outputs=output
|
| 204 |
)
|
|
@@ -220,11 +121,8 @@ async def admin_dashboard(email: str = None, password: str = None, response: Res
|
|
| 220 |
|
| 221 |
@app.on_event("startup")
|
| 222 |
async def startup_event():
|
| 223 |
-
"""Initialize
|
| 224 |
-
|
| 225 |
-
await token_manager.get_token()
|
| 226 |
-
except Exception as e:
|
| 227 |
-
logger.error(f"Initial token fetch failed: {str(e)}")
|
| 228 |
|
| 229 |
if __name__ == "__main__":
|
| 230 |
logger.info("Starting application")
|
|
|
|
| 3 |
from fastapi.responses import RedirectResponse, HTMLResponse
|
| 4 |
from api import api_router
|
| 5 |
import gradio as gr
|
|
|
|
| 6 |
import logging
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
# Configure logging
|
| 9 |
logging.basicConfig(level=logging.DEBUG)
|
|
|
|
| 24 |
app.include_router(api_router)
|
| 25 |
|
| 26 |
# Constants
|
|
|
|
| 27 |
ADMIN_EMAIL = "[email protected]"
|
| 28 |
ADMIN_PASSWORD = "123456"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
@app.get("/")
|
| 31 |
def root():
|
| 32 |
logger.debug("Root endpoint accessed")
|
| 33 |
+
return {"message": "🚀 CPS API with TxAgent Integration is running."}
|
| 34 |
|
| 35 |
@app.post("/login")
|
| 36 |
async def redirect_login(request: Request):
|
|
|
|
| 45 |
logger.info(f"Admin authenticated successfully: {email}")
|
| 46 |
return True
|
| 47 |
|
| 48 |
+
def create_doctor_account(full_name, email, matricule, password, specialty):
|
| 49 |
+
"""Simple doctor account creation without external API calls"""
|
| 50 |
try:
|
| 51 |
+
# This is a simplified version - in production you'd want to integrate with your user management system
|
| 52 |
+
logger.info(f"Creating doctor account for: {email}")
|
| 53 |
+
return "✅ Doctor account creation initiated. Please contact system administrator for account activation."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
except Exception as e:
|
| 55 |
logger.error(f"Doctor creation failed: {str(e)}")
|
| 56 |
return f"❌ System Error: {str(e)}"
|
| 57 |
|
|
|
|
|
|
|
|
|
|
| 58 |
admin_ui = gr.Blocks(
|
| 59 |
css="""
|
| 60 |
.gradio-container {
|
|
|
|
| 99 |
output = gr.Textbox(label="Status", interactive=False)
|
| 100 |
|
| 101 |
submit_btn.click(
|
| 102 |
+
fn=create_doctor_account,
|
| 103 |
inputs=[full_name, email, matricule, specialty, password],
|
| 104 |
outputs=output
|
| 105 |
)
|
|
|
|
| 121 |
|
| 122 |
@app.on_event("startup")
|
| 123 |
async def startup_event():
|
| 124 |
+
"""Initialize application on startup"""
|
| 125 |
+
logger.info("🚀 CPS API with TxAgent Integration starting up...")
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
if __name__ == "__main__":
|
| 128 |
logger.info("Starting application")
|