Ali2206 commited on
Commit
55f5f10
·
verified ·
1 Parent(s): 3d3fda1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -46
app.py CHANGED
@@ -1,67 +1,91 @@
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,11 +99,11 @@ class TokenManager:
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,6 +112,9 @@ class TokenManager:
88
 
89
  token_manager = TokenManager()
90
 
 
 
 
91
  @app.get("/")
92
  def root():
93
  logger.debug("Root endpoint accessed")
@@ -95,8 +122,17 @@ def root():
95
 
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,54 +142,69 @@ def authenticate_admin(email: str = None, password: str = None):
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,14 +237,15 @@ with admin_ui:
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,11 +270,21 @@ async def admin_dashboard(email: str = None, password: str = None, response: Res
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
 
 
1
  from fastapi import FastAPI, Request, HTTPException, Response
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.responses import RedirectResponse, HTMLResponse
4
+ from pydantic import BaseModel
5
  import gradio as gr
 
 
 
6
  import aiohttp
7
  import asyncio
8
+ import logging
9
+ import time
10
+ import os
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 (restrict in production)
26
  app.add_middleware(
27
  CORSMiddleware,
28
+ allow_origins=["http://localhost:7860", "https://rocketfarmstudios-cps-api.hf.space"],
29
  allow_credentials=True,
30
  allow_methods=["*"],
31
  allow_headers=["*"],
32
  )
33
 
34
+ # API Router (placeholder; replace with actual api.py content)
35
+ api_router = APIRouter()
36
 
37
+ # Constants (load from environment variables)
38
+ BACKEND_URL = os.getenv("BACKEND_URL", "https://rocketfarmstudios-cps-api.hf.space")
39
+ ADMIN_EMAIL = os.getenv("ADMIN_EMAIL", "yakdhanali97@gmail.com")
40
+ ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "123456")
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 = TOKEN_EXPIRY
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
+ login_url = f"{BACKEND_URL}/auth/login"
69
+ logger.debug(f"Sending login request to {login_url} with payload: {payload.dict()}")
70
  async with session.post(
71
+ login_url,
72
+ json=payload.dict(),
 
 
 
 
73
  timeout=10
74
  ) as response:
75
+ logger.debug(f"Login response status: {response.status}")
76
  if response.status == 200:
77
  data = await response.json()
78
+ token = data.get("access_token")
79
+ if not token:
80
+ logger.error("No access_token in response")
81
+ return None
82
+ logger.info(f"Received token: {token[:10]}...")
83
+ return token
84
  else:
85
  error = await response.text()
86
  logger.error(f"Login failed: {response.status} - {error}")
87
  return None
88
+ except aiohttp.ClientError as e:
89
  logger.error(f"Login request error: {str(e)}")
90
  return None
91
 
 
99
  logger.info("Successfully refreshed admin token")
100
  return token
101
 
102
+ wait_time = min(5, (attempt + 1) * TOKEN_RETRY_DELAY)
103
  logger.warning(f"Attempt {attempt + 1} failed, retrying in {wait_time}s...")
104
  await asyncio.sleep(wait_time)
105
 
106
+ raise HTTPException(status_code=500, detail="Failed to obtain admin token after multiple attempts")
107
 
108
  async def get_token(self) -> str:
109
  if not self.token or (time.time() - self.last_refresh) > (self.expires_in - 60):
 
112
 
113
  token_manager = TokenManager()
114
 
115
+ # Include API router
116
+ app.include_router(api_router)
117
+
118
  @app.get("/")
119
  def root():
120
  logger.debug("Root endpoint accessed")
 
122
 
123
  @app.post("/login")
124
  async def redirect_login(request: Request):
125
+ logger.info("Redirecting /login to /admin-auth")
126
+ return RedirectResponse(url="/admin-auth", status_code=307)
127
+
128
+ # Handle local /auth/login requests to prevent 422 errors
129
+ @app.post("/auth/login")
130
+ async def handle_local_auth_login(request: Request):
131
+ logger.warning(f"Local /auth/login endpoint called with body: {await request.json()}")
132
+ raise HTTPException(
133
+ status_code=400,
134
+ detail="This endpoint is not meant to be called locally. Use the external backend API: https://rocketfarmstudios-cps-api.hf.space/auth/login"
135
+ )
136
 
137
  def authenticate_admin(email: str = None, password: str = None):
138
  if email != ADMIN_EMAIL or password != ADMIN_PASSWORD:
 
142
  logger.info(f"Admin authenticated successfully: {email}")
143
  return True
144
 
145
+ async def async_create_doctor(full_name: str, email: str, license_number: str, specialty: str, password: str):
146
  try:
147
+ # Validate inputs
148
+ if not all([full_name, email, license_number, specialty, password]):
149
+ logger.error("Doctor creation failed: All fields are required")
150
+ raise HTTPException(status_code=422, detail="All fields are required")
151
+
152
  token = await token_manager.get_token()
153
 
154
+ payload = DoctorPayload(
155
+ full_name=full_name,
156
+ email=email,
157
+ license_number=license_number,
158
+ password=password,
159
+ specialty=specialty
160
+ )
161
  headers = {
162
  "Authorization": f"Bearer {token}",
163
  "Content-Type": "application/json"
164
  }
165
 
166
+ doctor_url = f"{BACKEND_URL}/auth/admin/doctors"
167
+ logger.debug(f"Sending doctor creation request to {doctor_url} with payload: {payload.dict()}")
168
  async with aiohttp.ClientSession() as session:
169
  async with session.post(
170
+ doctor_url,
171
+ json=payload.dict(),
172
  headers=headers,
173
  timeout=10
174
  ) as response:
175
+ logger.debug(f"Doctor creation response status: {response.status}")
176
  if response.status == 201:
177
  return "✅ Doctor created successfully!"
178
+ elif response.status == 401:
179
  logger.warning("Token expired, attempting refresh...")
180
  token = await token_manager.refresh_token()
181
  headers["Authorization"] = f"Bearer {token}"
182
  async with session.post(
183
+ doctor_url,
184
+ json=payload.dict(),
185
  headers=headers,
186
  timeout=10
187
  ) as retry_response:
188
+ logger.debug(f"Retry doctor creation response status: {retry_response.status}")
189
  if retry_response.status == 201:
190
  return "✅ Doctor created successfully!"
191
+ error_detail = await retry_response.text()
192
+ return f"❌ Error: {error_detail} (Status: {retry_response.status})"
193
 
194
  error_detail = await response.text()
195
  return f"❌ Error: {error_detail} (Status: {response.status})"
196
 
197
+ except HTTPException as e:
198
+ logger.error(f"Doctor creation failed: {str(e)}")
199
+ return f"❌ Error: {str(e)}"
200
  except Exception as e:
201
  logger.error(f"Doctor creation failed: {str(e)}")
202
  return f"❌ System Error: {str(e)}"
203
 
204
+ def sync_create_doctor(full_name: str, email: str, license_number: str, specialty: str, password: str):
205
+ return asyncio.run(async_create_doctor(full_name, email, license_number, specialty, password))
206
 
207
+ # Gradio UI
208
  admin_ui = gr.Blocks(
209
  css="""
210
  .gradio-container {
 
237
  gr.Markdown("# Doctor Account Creator")
238
 
239
  with gr.Column():
240
+ full_name = gr.Textbox(label="Full Name", placeholder="e.g., Dr. John Doe")
241
+ email = gr.Textbox(label="Email", placeholder="e.g., john.doe@example.com")
242
+ matricule = gr.Textbox(label="License Number", placeholder="e.g., 12345")
243
  specialty = gr.Dropdown(
244
  label="Specialty",
245
+ choices=["General Practice", "Cardiology", "Neurology", "Pediatrics"],
246
+ value="General Practice"
247
  )
248
+ password = gr.Textbox(label="Password", type="password", placeholder="Enter a secure password")
249
  submit_btn = gr.Button("Create Account")
250
  output = gr.Textbox(label="Status", interactive=False)
251
 
 
270
  <p>Invalid admin credentials</p>
271
  """)
272
 
273
+ @app.get("/admin-auth/gradio_api/queue/data")
274
+ async def gradio_queue_data(session_hash: str):
275
+ logger.debug(f"Gradio queue data accessed with session_hash: {session_hash}")
276
+ return {"status": "ok", "session_hash": session_hash}
277
+
278
+ @app.get("/manifest.json")
279
+ async def manifest():
280
+ logger.debug("Manifest.json accessed")
281
+ return {"name": "Doctor Account Creator", "short_name": "Doctor App", "start_url": "/admin-auth"}
282
+
283
  @app.on_event("startup")
284
  async def startup_event():
 
285
  try:
286
  await token_manager.get_token()
287
+ logger.info("Initial token fetch successful")
288
  except Exception as e:
289
  logger.error(f"Initial token fetch failed: {str(e)}")
290