Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,89 +1,67 @@
|
|
| 1 |
from fastapi import FastAPI, Request, HTTPException, Response
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from fastapi.responses import RedirectResponse, HTMLResponse
|
| 4 |
-
from
|
| 5 |
import gradio as gr
|
| 6 |
-
import
|
| 7 |
-
import asyncio
|
| 8 |
import logging
|
| 9 |
import time
|
| 10 |
-
import
|
|
|
|
| 11 |
from typing import Optional
|
| 12 |
-
from fastapi import APIRouter
|
| 13 |
|
| 14 |
# Configure logging
|
| 15 |
-
logging.basicConfig(
|
| 16 |
-
level=logging.DEBUG,
|
| 17 |
-
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"
|
| 18 |
-
)
|
| 19 |
logger = logging.getLogger(__name__)
|
| 20 |
logger.debug("Initializing application")
|
| 21 |
|
| 22 |
-
# FastAPI app
|
| 23 |
app = FastAPI()
|
| 24 |
|
| 25 |
-
# CORS Configuration
|
| 26 |
app.add_middleware(
|
| 27 |
CORSMiddleware,
|
| 28 |
-
allow_origins=["
|
| 29 |
allow_credentials=True,
|
| 30 |
allow_methods=["*"],
|
| 31 |
allow_headers=["*"],
|
| 32 |
)
|
| 33 |
|
| 34 |
-
|
| 35 |
-
api_router = APIRouter()
|
| 36 |
|
| 37 |
-
# Constants
|
| 38 |
-
BACKEND_URL =
|
| 39 |
-
ADMIN_EMAIL =
|
| 40 |
-
ADMIN_PASSWORD =
|
| 41 |
MAX_TOKEN_RETRIES = 3
|
| 42 |
TOKEN_RETRY_DELAY = 2 # seconds
|
| 43 |
-
TOKEN_EXPIRY = 3600 # 1 hour default expiry
|
| 44 |
-
|
| 45 |
-
# Pydantic models
|
| 46 |
-
class LoginPayload(BaseModel):
|
| 47 |
-
username: str
|
| 48 |
-
password: str
|
| 49 |
-
|
| 50 |
-
class DoctorPayload(BaseModel):
|
| 51 |
-
full_name: str
|
| 52 |
-
email: str
|
| 53 |
-
license_number: str
|
| 54 |
-
password: str
|
| 55 |
-
specialty: str
|
| 56 |
|
| 57 |
class TokenManager:
|
| 58 |
def __init__(self):
|
| 59 |
self.token = None
|
| 60 |
self.last_refresh = 0
|
| 61 |
-
self.expires_in =
|
| 62 |
self.lock = asyncio.Lock()
|
| 63 |
|
| 64 |
async def _make_login_request(self) -> Optional[str]:
|
| 65 |
try:
|
| 66 |
async with aiohttp.ClientSession() as session:
|
| 67 |
-
payload = LoginPayload(username=ADMIN_EMAIL, password=ADMIN_PASSWORD)
|
| 68 |
-
logger.debug(f"Sending login request to {BACKEND_URL}/auth/login with payload: {payload.dict()}")
|
| 69 |
async with session.post(
|
| 70 |
f"{BACKEND_URL}/auth/login",
|
| 71 |
-
json=
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
timeout=10
|
| 73 |
) as response:
|
| 74 |
-
logger.debug(f"Login response status: {response.status}")
|
| 75 |
if response.status == 200:
|
| 76 |
data = await response.json()
|
| 77 |
-
|
| 78 |
-
if not token:
|
| 79 |
-
logger.error("No access_token in response")
|
| 80 |
-
return None
|
| 81 |
-
return token
|
| 82 |
else:
|
| 83 |
error = await response.text()
|
| 84 |
logger.error(f"Login failed: {response.status} - {error}")
|
| 85 |
return None
|
| 86 |
-
except
|
| 87 |
logger.error(f"Login request error: {str(e)}")
|
| 88 |
return None
|
| 89 |
|
|
@@ -97,11 +75,11 @@ class TokenManager:
|
|
| 97 |
logger.info("Successfully refreshed admin token")
|
| 98 |
return token
|
| 99 |
|
| 100 |
-
wait_time = min(5, (attempt + 1) *
|
| 101 |
logger.warning(f"Attempt {attempt + 1} failed, retrying in {wait_time}s...")
|
| 102 |
await asyncio.sleep(wait_time)
|
| 103 |
|
| 104 |
-
raise
|
| 105 |
|
| 106 |
async def get_token(self) -> str:
|
| 107 |
if not self.token or (time.time() - self.last_refresh) > (self.expires_in - 60):
|
|
@@ -110,9 +88,6 @@ class TokenManager:
|
|
| 110 |
|
| 111 |
token_manager = TokenManager()
|
| 112 |
|
| 113 |
-
# Include API router
|
| 114 |
-
app.include_router(api_router)
|
| 115 |
-
|
| 116 |
@app.get("/")
|
| 117 |
def root():
|
| 118 |
logger.debug("Root endpoint accessed")
|
|
@@ -121,7 +96,7 @@ def root():
|
|
| 121 |
@app.post("/login")
|
| 122 |
async def redirect_login(request: Request):
|
| 123 |
logger.info("Redirecting /login to /auth/login")
|
| 124 |
-
return RedirectResponse(url="/
|
| 125 |
|
| 126 |
def authenticate_admin(email: str = None, password: str = None):
|
| 127 |
if email != ADMIN_EMAIL or password != ADMIN_PASSWORD:
|
|
@@ -131,68 +106,54 @@ def authenticate_admin(email: str = None, password: str = None):
|
|
| 131 |
logger.info(f"Admin authenticated successfully: {email}")
|
| 132 |
return True
|
| 133 |
|
| 134 |
-
async def async_create_doctor(full_name
|
| 135 |
try:
|
| 136 |
-
# Validate inputs
|
| 137 |
-
if not all([full_name, email, license_number, specialty, password]):
|
| 138 |
-
logger.error("Doctor creation failed: All fields are required")
|
| 139 |
-
raise HTTPException(status_code=422, detail="All fields are required")
|
| 140 |
-
|
| 141 |
token = await token_manager.get_token()
|
| 142 |
|
| 143 |
-
payload =
|
| 144 |
-
full_name
|
| 145 |
-
email
|
| 146 |
-
license_number
|
| 147 |
-
password
|
| 148 |
-
specialty
|
| 149 |
-
|
| 150 |
headers = {
|
| 151 |
"Authorization": f"Bearer {token}",
|
| 152 |
"Content-Type": "application/json"
|
| 153 |
}
|
| 154 |
|
| 155 |
-
logger.debug(f"Sending doctor creation request to {BACKEND_URL}/auth/admin/doctors with payload: {payload.dict()}")
|
| 156 |
async with aiohttp.ClientSession() as session:
|
| 157 |
async with session.post(
|
| 158 |
f"{BACKEND_URL}/auth/admin/doctors",
|
| 159 |
-
json=payload
|
| 160 |
headers=headers,
|
| 161 |
timeout=10
|
| 162 |
) as response:
|
| 163 |
-
logger.debug(f"Doctor creation response status: {response.status}")
|
| 164 |
if response.status == 201:
|
| 165 |
return "✅ Doctor created successfully!"
|
| 166 |
-
elif response.status == 401:
|
| 167 |
logger.warning("Token expired, attempting refresh...")
|
| 168 |
token = await token_manager.refresh_token()
|
| 169 |
headers["Authorization"] = f"Bearer {token}"
|
| 170 |
async with session.post(
|
| 171 |
f"{BACKEND_URL}/auth/admin/doctors",
|
| 172 |
-
json=payload
|
| 173 |
headers=headers,
|
| 174 |
timeout=10
|
| 175 |
) as retry_response:
|
| 176 |
-
logger.debug(f"Retry doctor creation response status: {retry_response.status}")
|
| 177 |
if retry_response.status == 201:
|
| 178 |
return "✅ Doctor created successfully!"
|
| 179 |
-
error_detail = await retry_response.text()
|
| 180 |
-
return f"❌ Error: {error_detail} (Status: {retry_response.status})"
|
| 181 |
|
| 182 |
error_detail = await response.text()
|
| 183 |
return f"❌ Error: {error_detail} (Status: {response.status})"
|
| 184 |
|
| 185 |
-
except HTTPException as e:
|
| 186 |
-
logger.error(f"Doctor creation failed: {str(e)}")
|
| 187 |
-
return f"❌ Error: {str(e)}"
|
| 188 |
except Exception as e:
|
| 189 |
logger.error(f"Doctor creation failed: {str(e)}")
|
| 190 |
return f"❌ System Error: {str(e)}"
|
| 191 |
|
| 192 |
-
def sync_create_doctor(
|
| 193 |
-
return asyncio.run(async_create_doctor(
|
| 194 |
|
| 195 |
-
# Gradio UI
|
| 196 |
admin_ui = gr.Blocks(
|
| 197 |
css="""
|
| 198 |
.gradio-container {
|
|
@@ -225,15 +186,14 @@ with admin_ui:
|
|
| 225 |
gr.Markdown("# Doctor Account Creator")
|
| 226 |
|
| 227 |
with gr.Column():
|
| 228 |
-
full_name = gr.Textbox(label="Full Name"
|
| 229 |
-
email = gr.Textbox(label="Email"
|
| 230 |
-
matricule = gr.Textbox(label="License Number"
|
| 231 |
specialty = gr.Dropdown(
|
| 232 |
label="Specialty",
|
| 233 |
-
choices=["General Practice", "Cardiology", "Neurology", "Pediatrics"]
|
| 234 |
-
value="General Practice"
|
| 235 |
)
|
| 236 |
-
password = gr.Textbox(label="Password", type="password"
|
| 237 |
submit_btn = gr.Button("Create Account")
|
| 238 |
output = gr.Textbox(label="Status", interactive=False)
|
| 239 |
|
|
@@ -258,16 +218,11 @@ async def admin_dashboard(email: str = None, password: str = None, response: Res
|
|
| 258 |
<p>Invalid admin credentials</p>
|
| 259 |
""")
|
| 260 |
|
| 261 |
-
@app.get("/admin-auth/gradio_api/queue/data")
|
| 262 |
-
async def gradio_queue_data(session_hash: str):
|
| 263 |
-
logger.debug(f"Gradio queue data accessed with session_hash: {session_hash}")
|
| 264 |
-
return {"status": "ok", "session_hash": session_hash}
|
| 265 |
-
|
| 266 |
@app.on_event("startup")
|
| 267 |
async def startup_event():
|
|
|
|
| 268 |
try:
|
| 269 |
await token_manager.get_token()
|
| 270 |
-
logger.info("Initial token fetch successful")
|
| 271 |
except Exception as e:
|
| 272 |
logger.error(f"Initial token fetch failed: {str(e)}")
|
| 273 |
|
|
|
|
| 1 |
from fastapi import FastAPI, Request, HTTPException, Response
|
| 2 |
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)
|
|
|
|
|
|
|
|
|
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
logger.debug("Initializing application")
|
| 17 |
|
|
|
|
| 18 |
app = FastAPI()
|
| 19 |
|
| 20 |
+
# CORS Configuration
|
| 21 |
app.add_middleware(
|
| 22 |
CORSMiddleware,
|
| 23 |
+
allow_origins=["*"],
|
| 24 |
allow_credentials=True,
|
| 25 |
allow_methods=["*"],
|
| 26 |
allow_headers=["*"],
|
| 27 |
)
|
| 28 |
|
| 29 |
+
app.include_router(api_router)
|
|
|
|
| 30 |
|
| 31 |
+
# Constants
|
| 32 |
+
BACKEND_URL = "https://rocketfarmstudios-cps-api.hf.space"
|
| 33 |
+
ADMIN_EMAIL = "yakdhanali97@gmail.com"
|
| 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 |
|
|
|
|
| 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):
|
|
|
|
| 88 |
|
| 89 |
token_manager = TokenManager()
|
| 90 |
|
|
|
|
|
|
|
|
|
|
| 91 |
@app.get("/")
|
| 92 |
def root():
|
| 93 |
logger.debug("Root endpoint accessed")
|
|
|
|
| 96 |
@app.post("/login")
|
| 97 |
async def redirect_login(request: Request):
|
| 98 |
logger.info("Redirecting /login to /auth/login")
|
| 99 |
+
return RedirectResponse(url="/auth/login", status_code=307)
|
| 100 |
|
| 101 |
def authenticate_admin(email: str = None, password: str = None):
|
| 102 |
if email != ADMIN_EMAIL or password != ADMIN_PASSWORD:
|
|
|
|
| 106 |
logger.info(f"Admin authenticated successfully: {email}")
|
| 107 |
return True
|
| 108 |
|
| 109 |
+
async def async_create_doctor(full_name, email, matricule, password, specialty):
|
| 110 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
token = await token_manager.get_token()
|
| 112 |
|
| 113 |
+
payload = {
|
| 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 {
|
|
|
|
| 186 |
gr.Markdown("# Doctor Account Creator")
|
| 187 |
|
| 188 |
with gr.Column():
|
| 189 |
+
full_name = gr.Textbox(label="Full Name")
|
| 190 |
+
email = gr.Textbox(label="Email")
|
| 191 |
+
matricule = gr.Textbox(label="License Number")
|
| 192 |
specialty = gr.Dropdown(
|
| 193 |
label="Specialty",
|
| 194 |
+
choices=["General Practice", "Cardiology", "Neurology", "Pediatrics"]
|
|
|
|
| 195 |
)
|
| 196 |
+
password = gr.Textbox(label="Password", type="password")
|
| 197 |
submit_btn = gr.Button("Create Account")
|
| 198 |
output = gr.Textbox(label="Status", interactive=False)
|
| 199 |
|
|
|
|
| 218 |
<p>Invalid admin credentials</p>
|
| 219 |
""")
|
| 220 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
@app.on_event("startup")
|
| 222 |
async def startup_event():
|
| 223 |
+
"""Initialize token but don't fail startup"""
|
| 224 |
try:
|
| 225 |
await token_manager.get_token()
|
|
|
|
| 226 |
except Exception as e:
|
| 227 |
logger.error(f"Initial token fetch failed: {str(e)}")
|
| 228 |
|