Ali2206 commited on
Commit
49bff0f
Β·
verified Β·
1 Parent(s): 8b2f9a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -130
app.py CHANGED
@@ -1,162 +1,104 @@
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
- )
 
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.basicConfig(level=logging.DEBUG)
 
 
 
 
 
 
 
 
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
+ app.include_router(api_router)
 
25
 
26
  @app.get("/")
27
+ def root():
28
+ logger.debug("Root endpoint accessed")
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=307)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
+ # Gradio doctor creation logic
38
+ BACKEND_URL = "https://rocketfarmstudios-cps-api.hf.space"
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
+ res = requests.post(f"{BACKEND_URL}/auth/admin/doctors", json=payload)
50
+ if res.status_code == 201:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  return "βœ… Doctor created successfully!"
52
+ return f"❌ {res.json().get('detail', 'Error occurred')}"
 
 
 
 
 
 
 
53
  except Exception as e:
54
+ return f"❌ Network Error: {str(e)}"
55
+
56
+ # Define Gradio interface as a separate function
57
+ def setup_gradio():
58
+ logger.debug("Setting up Gradio interface")
59
+ with gr.Blocks(css="""
60
+ .gradio-container {
61
+ background-color: #1A1B1F;
62
+ color: #E2E8F0;
63
+ font-family: 'Segoe UI', sans-serif;
64
+ padding: 3rem;
65
+ }
66
+ .title-text { text-align: center; font-size: 2rem; font-weight: 700; color: #37B6E9; margin-bottom: 0.5rem; }
67
+ .description-text { text-align: center; font-size: 1rem; color: #A0AEC0; margin-bottom: 2rem; }
68
+ .gr-box, .gr-form, .gr-column, .gr-panel { background-color: #2D2F36 !important; border-radius: 16px !important; padding: 2rem !important; max-width: 600px; margin: auto; box-shadow: 0 0 0 1px #3B3E47; }
69
+ label { font-weight: 600; color: #F7FAFC; margin-bottom: 6px; }
70
+ input, select, textarea { background-color: #1A1B1F !important; color: #F7FAFC !important; border: 1px solid #4A5568 !important; font-size: 14px; padding: 10px; border-radius: 10px; }
71
+ button { background-color: #37B6E9 !important; color: #1A1B1F !important; border-radius: 10px !important; font-weight: 600; padding: 12px; width: 100%; margin-top: 1.5rem; }
72
+ .output-box textarea { background-color: transparent !important; border: none; color: #90CDF4; font-size: 14px; margin-top: 1rem; }
73
+ """) as admin_ui:
74
+ gr.Markdown("<div class='title-text'>πŸ‘¨β€βš•οΈ Doctor Account Creator</div>")
75
+ gr.Markdown("<div class='description-text'>Admins can register new doctors using this secure panel. Generated at 03:43 PM CET on Saturday, May 17, 2025.</div>")
76
 
77
+ with gr.Column():
78
+ full_name = gr.Textbox(label="Full Name", placeholder="e.g. Dr. Sarah Hopkins")
79
+ email = gr.Textbox(label="Email", placeholder="e.g. doctor@clinic.org")
80
+ matricule = gr.Textbox(label="Matricule", placeholder="e.g. DOC-1234")
81
+ specialty = gr.Dropdown(
82
+ label="Specialty",
83
+ choices=["Cardiology", "Neurology", "Pediatrics", "Oncology", "General Practice", "Psychiatry", "Dermatology", "Orthopedics"],
84
+ value="Cardiology"
85
+ )
86
+ password = gr.Textbox(label="Password", type="password", placeholder="Secure password")
87
+ submit_btn = gr.Button("Create Doctor Account")
88
+ output = gr.Textbox(label="", show_label=False, elem_classes=["output-box"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
+ submit_btn.click(
91
+ fn=create_doctor,
92
+ inputs=[full_name, email, matricule, specialty, password],
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(app, host="0.0.0.0", port=7860) # Hugging Face Spaces default port