Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,104 +1,162 @@
|
|
| 1 |
-
from fastapi import FastAPI, Request
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
-
from fastapi.responses import RedirectResponse
|
|
|
|
| 4 |
from api import api_router
|
| 5 |
import gradio as gr
|
| 6 |
import requests
|
| 7 |
import logging
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
logging
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
logger = logging.getLogger(__name__)
|
| 11 |
-
logger.debug("Initializing application")
|
| 12 |
|
| 13 |
-
app = FastAPI(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
# CORS
|
| 16 |
app.add_middleware(
|
| 17 |
CORSMiddleware,
|
| 18 |
allow_origins=["*"],
|
| 19 |
allow_credentials=True,
|
| 20 |
allow_methods=["*"],
|
| 21 |
allow_headers=["*"],
|
|
|
|
| 22 |
)
|
| 23 |
|
| 24 |
-
|
|
|
|
| 25 |
|
| 26 |
@app.get("/")
|
| 27 |
-
def root():
|
| 28 |
-
logger.
|
| 29 |
-
return {"message": "π FastAPI with MongoDB + JWT is running
|
| 30 |
|
| 31 |
-
# Redirect /login to /auth/login
|
| 32 |
@app.post("/login")
|
| 33 |
async def redirect_login(request: Request):
|
| 34 |
-
logger.info("Redirecting /login to /auth/login")
|
| 35 |
-
return RedirectResponse(url="/auth/login", status_code=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
# Gradio
|
| 38 |
-
BACKEND_URL = "
|
| 39 |
|
| 40 |
-
def create_doctor(full_name, email, matricule, password, specialty):
|
| 41 |
-
payload = {
|
| 42 |
-
"full_name": full_name,
|
| 43 |
-
"email": email,
|
| 44 |
-
"license_number": matricule,
|
| 45 |
-
"password": password,
|
| 46 |
-
"specialty": specialty,
|
| 47 |
-
}
|
| 48 |
try:
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
return "β
Doctor created successfully!"
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
return f"β Network Error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
.gradio-container {
|
| 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 |
-
outputs=output
|
| 94 |
-
)
|
| 95 |
-
return admin_ui
|
| 96 |
|
| 97 |
-
# Mount Gradio at /admin
|
| 98 |
if __name__ == "__main__":
|
| 99 |
-
logger.debug("Running main block")
|
| 100 |
-
admin_ui = setup_gradio()
|
| 101 |
-
app = gr.mount_gradio_app(app, admin_ui, path="/admin")
|
| 102 |
-
logger.debug("Gradio mounted, starting app")
|
| 103 |
import uvicorn
|
| 104 |
-
uvicorn.run(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request, HTTPException
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from fastapi.responses import RedirectResponse, JSONResponse
|
| 4 |
+
from fastapi.exceptions import RequestValidationError
|
| 5 |
from api import api_router
|
| 6 |
import gradio as gr
|
| 7 |
import requests
|
| 8 |
import logging
|
| 9 |
+
import os
|
| 10 |
+
from datetime import datetime
|
| 11 |
|
| 12 |
+
# Configure logging
|
| 13 |
+
logging.basicConfig(
|
| 14 |
+
level=logging.INFO,
|
| 15 |
+
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
|
| 16 |
+
handlers=[
|
| 17 |
+
logging.StreamHandler(),
|
| 18 |
+
logging.FileHandler('app.log')
|
| 19 |
+
]
|
| 20 |
+
)
|
| 21 |
logger = logging.getLogger(__name__)
|
|
|
|
| 22 |
|
| 23 |
+
app = FastAPI(
|
| 24 |
+
title="Medical EHR System",
|
| 25 |
+
description="Electronic Health Records Management API",
|
| 26 |
+
version="1.0.0",
|
| 27 |
+
docs_url="/docs",
|
| 28 |
+
redoc_url="/redoc"
|
| 29 |
+
)
|
| 30 |
|
| 31 |
+
# CORS Configuration
|
| 32 |
app.add_middleware(
|
| 33 |
CORSMiddleware,
|
| 34 |
allow_origins=["*"],
|
| 35 |
allow_credentials=True,
|
| 36 |
allow_methods=["*"],
|
| 37 |
allow_headers=["*"],
|
| 38 |
+
expose_headers=["*"]
|
| 39 |
)
|
| 40 |
|
| 41 |
+
# Include API routes
|
| 42 |
+
app.include_router(api_router, prefix="/api/v1")
|
| 43 |
|
| 44 |
@app.get("/")
|
| 45 |
+
async def root():
|
| 46 |
+
logger.info("Root endpoint accessed")
|
| 47 |
+
return {"message": "π FastAPI with MongoDB + JWT is running", "status": "healthy"}
|
| 48 |
|
|
|
|
| 49 |
@app.post("/login")
|
| 50 |
async def redirect_login(request: Request):
|
| 51 |
+
logger.info(f"Redirecting /login to /auth/login from {request.client.host}")
|
| 52 |
+
return RedirectResponse(url="/auth/login", status_code=status.HTTP_307_TEMPORARY_REDIRECT)
|
| 53 |
+
|
| 54 |
+
@app.exception_handler(RequestValidationError)
|
| 55 |
+
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
| 56 |
+
logger.error(f"Validation error: {exc.errors()}")
|
| 57 |
+
return JSONResponse(
|
| 58 |
+
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
| 59 |
+
content={"detail": exc.errors(), "body": exc.body},
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
@app.exception_handler(HTTPException)
|
| 63 |
+
async def http_exception_handler(request: Request, exc: HTTPException):
|
| 64 |
+
logger.error(f"HTTP error: {exc.detail}")
|
| 65 |
+
return JSONResponse(
|
| 66 |
+
status_code=exc.status_code,
|
| 67 |
+
content={"detail": exc.detail},
|
| 68 |
+
headers=exc.headers
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
@app.exception_handler(Exception)
|
| 72 |
+
async def general_exception_handler(request: Request, exc: Exception):
|
| 73 |
+
logger.error(f"Unhandled exception: {str(exc)}", exc_info=True)
|
| 74 |
+
return JSONResponse(
|
| 75 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 76 |
+
content={"detail": "Internal server error"},
|
| 77 |
+
)
|
| 78 |
|
| 79 |
+
# Gradio Interface Configuration
|
| 80 |
+
BACKEND_URL = os.getenv("BACKEND_URL", "http://localhost:8000")
|
| 81 |
|
| 82 |
+
def create_doctor(full_name: str, email: str, matricule: str, password: str, specialty: str):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
try:
|
| 84 |
+
payload = {
|
| 85 |
+
"full_name": full_name,
|
| 86 |
+
"email": email,
|
| 87 |
+
"license_number": matricule,
|
| 88 |
+
"password": password,
|
| 89 |
+
"specialty": specialty,
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
logger.info(f"Attempting to create doctor: {email}")
|
| 93 |
+
response = requests.post(
|
| 94 |
+
f"{BACKEND_URL}/auth/admin/doctors",
|
| 95 |
+
json=payload,
|
| 96 |
+
headers={"Content-Type": "application/json"},
|
| 97 |
+
timeout=10
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
if response.status_code == 201:
|
| 101 |
+
logger.info(f"Successfully created doctor: {email}")
|
| 102 |
return "β
Doctor created successfully!"
|
| 103 |
+
else:
|
| 104 |
+
error_msg = response.json().get("detail", "Unknown error occurred")
|
| 105 |
+
logger.error(f"Failed to create doctor {email}: {error_msg}")
|
| 106 |
+
return f"β Error: {error_msg}"
|
| 107 |
+
|
| 108 |
+
except requests.exceptions.RequestException as e:
|
| 109 |
+
logger.error(f"Network error during doctor creation: {str(e)}")
|
| 110 |
return f"β Network Error: {str(e)}"
|
| 111 |
+
except Exception as e:
|
| 112 |
+
logger.error(f"Unexpected error during doctor creation: {str(e)}")
|
| 113 |
+
return f"β Unexpected Error: {str(e)}"
|
| 114 |
|
| 115 |
+
def setup_gradio_interface():
|
| 116 |
+
with gr.Blocks(
|
| 117 |
+
title="Doctor Management Portal",
|
| 118 |
+
css="""
|
| 119 |
+
.gradio-container { max-width: 800px; margin: 0 auto; }
|
| 120 |
+
.success { color: #4CAF50; }
|
| 121 |
+
.error { color: #F44336; }
|
| 122 |
+
"""
|
| 123 |
+
) as interface:
|
| 124 |
+
gr.Markdown("# π¨ββοΈ Doctor Account Management")
|
| 125 |
+
|
| 126 |
+
with gr.Row():
|
| 127 |
+
with gr.Column():
|
| 128 |
+
full_name = gr.Textbox(label="Full Name", placeholder="Dr. John Smith")
|
| 129 |
+
email = gr.Textbox(label="Email", placeholder="doctor@hospital.org")
|
| 130 |
+
matricule = gr.Textbox(label="License Number", placeholder="MD-12345")
|
| 131 |
+
specialty = gr.Dropdown(
|
| 132 |
+
label="Specialty",
|
| 133 |
+
choices=["Cardiology", "Neurology", "Pediatrics", "General Practice"],
|
| 134 |
+
value="General Practice"
|
| 135 |
+
)
|
| 136 |
+
password = gr.Textbox(label="Password", type="password")
|
| 137 |
+
submit_btn = gr.Button("Create Doctor Account", variant="primary")
|
| 138 |
+
|
| 139 |
+
with gr.Column():
|
| 140 |
+
output = gr.Textbox(label="Result", interactive=False)
|
| 141 |
+
|
| 142 |
+
submit_btn.click(
|
| 143 |
+
fn=create_doctor,
|
| 144 |
+
inputs=[full_name, email, matricule, specialty, password],
|
| 145 |
+
outputs=output
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
return interface
|
| 149 |
|
| 150 |
+
# Mount Gradio interface
|
| 151 |
+
gradio_ui = setup_gradio_interface()
|
| 152 |
+
app = gr.mount_gradio_app(app, gradio_ui, path="/admin")
|
|
|
|
|
|
|
|
|
|
| 153 |
|
|
|
|
| 154 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
import uvicorn
|
| 156 |
+
uvicorn.run(
|
| 157 |
+
app,
|
| 158 |
+
host="0.0.0.0",
|
| 159 |
+
port=int(os.getenv("PORT", 8000)),
|
| 160 |
+
log_level="info",
|
| 161 |
+
reload=True
|
| 162 |
+
)
|