File size: 29,487 Bytes
8925616
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "6100e275-6725-4a0c-bb43-c6b4ed84267f",
   "metadata": {
    "executionCancelledAt": null,
    "executionTime": 3691,
    "lastExecutedAt": 1743099151623,
    "lastExecutedByKernel": "4c9f5db9-464b-4a72-9464-a5e93fb850cd",
    "lastScheduledRunId": null,
    "lastSuccessfullyExecutedCode": "%%capture\n%pip install google-genai ",
    "outputsMetadata": {
     "0": {
      "height": 469,
      "type": "stream"
     }
    }
   },
   "outputs": [],
   "source": [
    "%%capture\n",
    "%pip install google-genai "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "af15a428-a6c4-44a7-86c7-2075a55764f3",
   "metadata": {
    "executionCancelledAt": null,
    "executionTime": 51190,
    "lastExecutedAt": 1743102270437,
    "lastExecutedByKernel": "4c9f5db9-464b-4a72-9464-a5e93fb850cd",
    "lastScheduledRunId": null,
    "lastSuccessfullyExecutedCode": "import os\nfrom google import genai\nfrom google.genai import types\nfrom IPython.display import Markdown, HTML, Image, display\n\nAPI_KEY = os.environ.get(\"GEMINI_API_KEY\")\n\nclient = genai.Client(api_key=API_KEY)\n\n# Load the Python file as text\n\nfile_path = \"secure_app.py\"\nwith open(file_path, \"r\") as file:\n    doc_data = file.read()\nprompt = \"Please integrate user management into the FastAPI application.\"\n\ncontents = [\n    types.Part.from_bytes(\n        data=doc_data.encode(\"utf-8\"),\n        mime_type=\"text/x-python\",\n    ),\n    prompt,\n]\n\nchat = client.aio.chats.create(\n    model=\"gemini-2.5-pro-exp-03-25\",\n    config=types.GenerateContentConfig(\n        tools=[types.Tool(code_execution=types.ToolCodeExecution)]\n    ),\n)\n\nresponse = await chat.send_message(contents)\nMarkdown(response.text)\n",
    "outputsMetadata": {
     "0": {
      "height": 469,
      "type": "stream"
     }
    }
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "Okay, let's integrate user management into the FastAPI application using OAuth2 with Password Flow and JWT tokens. This is a standard approach for securing APIs where users log in with a username and password.\n",
       "\n",
       "We will:\n",
       "\n",
       "1.  **Add necessary dependencies:** `python-jose[cryptography]` for JWT handling and `passlib[bcrypt]` for password hashing.\n",
       "2.  **Define User Models:** Using Pydantic for request/response validation.\n",
       "3.  **Implement Password Hashing:** Securely store and verify passwords.\n",
       "4.  **Create JWT Utilities:** Functions to create and decode access tokens.\n",
       "5.  **Set up OAuth2 Scheme:** Configure FastAPI's security utilities.\n",
       "6.  **Implement Authentication Logic:** Create functions to authenticate users and get the current logged-in user from a token.\n",
       "7.  **Add Login Endpoint:** Create a `/token` endpoint for users to exchange credentials for a JWT.\n",
       "8.  **Protect Endpoints:** Modify existing endpoints to require authentication via JWT.\n",
       "9.  **Use an In-Memory User \"Database\":** For simplicity in this example. **Note:** For production, replace this with a proper database (SQL or NoSQL).\n",
       "10. **Update Environment Variables:** Add a `SECRET_KEY` for JWT signing.\n",
       "\n",
       "**Step 1: Add necessary configurations to `.env`**\n",
       "\n",
       "Make sure your `.env` file includes a `SECRET_KEY`:\n",
       "\n",
       "```.env\n",
       "API_KEY=your_existing_api_key # This might become redundant or used differently\n",
       "SECRET_KEY=your_very_strong_secret_key_here # e.g., generate using: openssl rand -hex 32\n",
       "ALGORITHM=HS256\n",
       "ACCESS_TOKEN_EXPIRE_MINUTES=30\n",
       "```\n",
       "\n",
       "**Step 2: Modify the Python Code**\n",
       "\n",
       "Here's the updated code (`secure_app_with_users.py`). I've added comments explaining the changes.\n",
       "\n",
       "```python\n",
       "# secure_app_with_users.py\n",
       "import io\n",
       "import os\n",
       "import logging\n",
       "from datetime import datetime, timedelta, timezone\n",
       "from typing import Optional, List, Dict, Any\n",
       "\n",
       "import torch\n",
       "import torch.nn as nn\n",
       "import torchvision.transforms as transforms\n",
       "import uvicorn\n",
       "from fastapi import FastAPI, File, HTTPException, UploadFile, Depends, Query, status\n",
       "from fastapi.responses import JSONResponse\n",
       "# Removed APIKeyHeader, replaced with OAuth2\n",
       "# from fastapi.security.api_key import APIKeyHeader\n",
       "from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm\n",
       "from dotenv import load_dotenv\n",
       "from PIL import Image, UnidentifiedImageError\n",
       "from torchvision import models\n",
       "from pydantic import BaseModel\n",
       "\n",
       "# --- User Management Imports ---\n",
       "from passlib.context import CryptContext\n",
       "from jose import JWTError, jwt\n",
       "\n",
       "# Load environment variables from .env file\n",
       "if not load_dotenv():\n",
       "    # Try loading from parent directory if running from a subdirectory\n",
       "    if not load_dotenv(\"../.env\"):\n",
       "         raise ValueError(\"Failed to load .env file from current or parent directory\")\n",
       "\n",
       "\n",
       "# --- User Management Configuration ---\n",
       "SECRET_KEY = os.getenv(\"SECRET_KEY\")\n",
       "ALGORITHM = os.getenv(\"ALGORITHM\", \"HS256\")\n",
       "ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv(\"ACCESS_TOKEN_EXPIRE_MINUTES\", 30))\n",
       "\n",
       "if not SECRET_KEY:\n",
       "    raise ValueError(\"SECRET_KEY environment variable not set in .env file\")\n",
       "\n",
       "pwd_context = CryptContext(schemes=[\"bcrypt\"], deprecated=\"auto\")\n",
       "oauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"token\") # Points to the login endpoint\n",
       "\n",
       "# --- User Models ---\n",
       "class User(BaseModel):\n",
       "    username: str\n",
       "    email: Optional[str] = None\n",
       "    full_name: Optional[str] = None\n",
       "    disabled: Optional[bool] = None\n",
       "\n",
       "class UserInDB(User):\n",
       "    hashed_password: str\n",
       "\n",
       "class Token(BaseModel):\n",
       "    access_token: str\n",
       "    token_type: str\n",
       "\n",
       "class TokenData(BaseModel):\n",
       "    username: Optional[str] = None\n",
       "\n",
       "# --- Mock User Database (Replace with real DB in production) ---\n",
       "# Store hashed passwords!\n",
       "fake_users_db = {\n",
       "    \"testuser\": {\n",
       "        \"username\": \"testuser\",\n",
       "        \"full_name\": \"Test User\",\n",
       "        \"email\": \"[email protected]\",\n",
       "        # Replace \"secret\" with a desired password, it will be hashed below\n",
       "        \"hashed_password\": pwd_context.hash(\"secret\"),\n",
       "        \"disabled\": False,\n",
       "    }\n",
       "}\n",
       "\n",
       "# --- Utility Functions ---\n",
       "def verify_password(plain_password, hashed_password):\n",
       "    return pwd_context.verify(plain_password, hashed_password)\n",
       "\n",
       "def get_password_hash(password):\n",
       "    return pwd_context.hash(password)\n",
       "\n",
       "def get_user(db, username: str) -> Optional[UserInDB]:\n",
       "    if username in db:\n",
       "        user_dict = db[username]\n",
       "        return UserInDB(**user_dict)\n",
       "    return None\n",
       "\n",
       "def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):\n",
       "    to_encode = data.copy()\n",
       "    if expires_delta:\n",
       "        expire = datetime.now(timezone.utc) + expires_delta\n",
       "    else:\n",
       "        expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)\n",
       "    to_encode.update({\"exp\": expire})\n",
       "    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)\n",
       "    return encoded_jwt\n",
       "\n",
       "async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:\n",
       "    credentials_exception = HTTPException(\n",
       "        status_code=status.HTTP_401_UNAUTHORIZED,\n",
       "        detail=\"Could not validate credentials\",\n",
       "        headers={\"WWW-Authenticate\": \"Bearer\"},\n",
       "    )\n",
       "    try:\n",
       "        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])\n",
       "        username: str = payload.get(\"sub\")\n",
       "        if username is None:\n",
       "            raise credentials_exception\n",
       "        token_data = TokenData(username=username)\n",
       "    except JWTError:\n",
       "        logger.warning(\"JWTError during token decoding\")\n",
       "        raise credentials_exception\n",
       "\n",
       "    user = get_user(fake_users_db, username=token_data.username)\n",
       "    if user is None:\n",
       "        logger.warning(f\"User '{token_data.username}' from token not found\")\n",
       "        raise credentials_exception\n",
       "    return User(**user.dict()) # Return basic User model, not UserInDB\n",
       "\n",
       "async def get_current_active_user(current_user: User = Depends(get_current_user)) -> User:\n",
       "    if current_user.disabled:\n",
       "        logger.warning(f\"Attempt to use disabled user account: {current_user.username}\")\n",
       "        raise HTTPException(status_code=400, detail=\"Inactive user\")\n",
       "    return current_user\n",
       "\n",
       "# --- FastAPI App Initialization ---\n",
       "app = FastAPI(\n",
       "    title=\"CIFAR10 Image Classification APP with User Auth\",\n",
       "    description=\"A production-ready API for image classification using a fine-tuned model on CIFAR10, secured with OAuth2.\",\n",
       ")\n",
       "\n",
       "# Set up logging\n",
       "logging.basicConfig(level=logging.INFO)\n",
       "logger = logging.getLogger(__name__)\n",
       "\n",
       "# --- Model Loading --- (Same as before)\n",
       "class_names = [\n",
       "    \"airplane\", \"automobile\", \"bird\", \"cat\", \"deer\",\n",
       "    \"dog\", \"frog\", \"horse\", \"ship\", \"truck\",\n",
       "]\n",
       "num_classes = len(class_names)\n",
       "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
       "model_path = \"finetuned_model.pth\"\n",
       "if not os.path.exists(model_path):\n",
       "    # Attempt relative path for common deployment scenarios\n",
       "    model_path = os.path.join(os.path.dirname(__file__), model_path)\n",
       "    if not os.path.exists(model_path):\n",
       "        raise FileNotFoundError(f\"Model file not found at specified path: {model_path}\")\n",
       "\n",
       "try:\n",
       "    model = models.resnet18(weights=None) # Changed weights=None as per original code\n",
       "    num_ftrs = model.fc.in_features\n",
       "    model.fc = nn.Linear(num_ftrs, num_classes)\n",
       "    model.load_state_dict(torch.load(model_path, map_location=device))\n",
       "    model.to(device)\n",
       "    model.eval()\n",
       "    logger.info(f\"Model loaded successfully from {model_path} onto {device}\")\n",
       "except Exception as e:\n",
       "    logger.error(f\"Error loading model: {e}\")\n",
       "    raise RuntimeError(f\"Could not load the model from {model_path}\")\n",
       "\n",
       "\n",
       "# Preprocessing transforms (Same as before)\n",
       "preprocess = transforms.Compose(\n",
       "    [\n",
       "        transforms.Resize((224, 224)),\n",
       "        transforms.ToTensor(),\n",
       "        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n",
       "    ]\n",
       ")\n",
       "\n",
       "# --- API Endpoints ---\n",
       "\n",
       "@app.post(\"/token\", response_model=Token, tags=[\"Authentication\"])\n",
       "async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):\n",
       "    \"\"\"\n",
       "    Authenticate user and return an access token.\n",
       "    \"\"\"\n",
       "    user = get_user(fake_users_db, form_data.username)\n",
       "    if not user or not verify_password(form_data.password, user.hashed_password):\n",
       "        logger.warning(f\"Authentication failed for user: {form_data.username}\")\n",
       "        raise HTTPException(\n",
       "            status_code=status.HTTP_401_UNAUTHORIZED,\n",
       "            detail=\"Incorrect username or password\",\n",
       "            headers={\"WWW-Authenticate\": \"Bearer\"},\n",
       "        )\n",
       "    if user.disabled:\n",
       "        logger.warning(f\"Authentication attempt for disabled user: {form_data.username}\")\n",
       "        raise HTTPException(status_code=400, detail=\"Inactive user\")\n",
       "\n",
       "    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)\n",
       "    access_token = create_access_token(\n",
       "        data={\"sub\": user.username}, expires_delta=access_token_expires\n",
       "    )\n",
       "    logger.info(f\"Token generated for user: {form_data.username}\")\n",
       "    return {\"access_token\": access_token, \"token_type\": \"bearer\"}\n",
       "\n",
       "@app.get(\"/users/me\", response_model=User, tags=[\"Users\"])\n",
       "async def read_users_me(current_user: User = Depends(get_current_active_user)):\n",
       "    \"\"\"\n",
       "    Get information about the currently logged-in user.\n",
       "    \"\"\"\n",
       "    return current_user\n",
       "\n",
       "@app.get(\"/health\", summary=\"Health Check\", tags=[\"Status\"])\n",
       "async def health_check():\n",
       "    \"\"\"Endpoint for checking if the API is running.\"\"\"\n",
       "    # Added check for model status based on successful loading\n",
       "    model_status = \"loaded\" if 'model' in globals() and isinstance(model, nn.Module) else \"error\"\n",
       "    return {\"status\": \"ok\", \"message\": \"API is running\", \"device\": str(device), \"model_status\": model_status}\n",
       "\n",
       "@app.get(\"/model-info\", summary=\"Get Model Information\", tags=[\"Metadata\"])\n",
       "async def get_model_info(current_user: User = Depends(get_current_active_user)): # Protected endpoint\n",
       "    \"\"\"\n",
       "    Combined endpoint for retrieving model metadata and class names.\n",
       "    Requires authentication.\n",
       "    \"\"\"\n",
       "    model_info = {\n",
       "        \"model_architecture\": \"ResNet18\",\n",
       "        \"num_classes\": num_classes,\n",
       "        \"class_names\": class_names,\n",
       "        \"device\": str(device),\n",
       "        \"model_weights_file\": model_path,\n",
       "        \"description\": \"Model fine-tuned on CIFAR10 dataset\",\n",
       "    }\n",
       "    return JSONResponse(model_info)\n",
       "\n",
       "\n",
       "@app.post(\"/predict\", summary=\"Predict Image Class\", tags=[\"Inference\"])\n",
       "async def predict(\n",
       "    file: UploadFile = File(...),\n",
       "    include_confidence: bool = Query(\n",
       "        False, description=\"Include confidence scores for top predictions\"\n",
       "    ),\n",
       "    top_k: int = Query(\n",
       "        1, ge=1, le=num_classes, description=\"Number of top predictions to return\"\n",
       "    ),\n",
       "    current_user: User = Depends(get_current_active_user), # Protected endpoint\n",
       "):\n",
       "    \"\"\"\n",
       "    Unified prediction endpoint that can return either simple class prediction\n",
       "    or detailed predictions with confidence scores. Requires authentication.\n",
       "    \"\"\"\n",
       "    logger.info(f\"Prediction request received from user: {current_user.username}, file: {file.filename}\")\n",
       "    # Validate file type\n",
       "    if not file.content_type.startswith(\"image/\"):\n",
       "         logger.error(f\"Invalid file content type: {file.content_type} from user {current_user.username}\")\n",
       "         raise HTTPException(\n",
       "             status_code=400,\n",
       "             detail=f\"Invalid file type: {file.content_type}. Only image/* types are supported.\",\n",
       "         )\n",
       "\n",
       "    # Limit file size (e.g., 10MB)\n",
       "    MAX_FILE_SIZE = 10 * 1024 * 1024\n",
       "    size = 0\n",
       "    contents = b\"\"\n",
       "    # Read file chunk by chunk to prevent large files exhausting memory\n",
       "    # and check size on the fly\n",
       "    for chunk in iter(lambda: file.file.read(4096), b\"\"):\n",
       "        size += len(chunk)\n",
       "        if size > MAX_FILE_SIZE:\n",
       "            await file.close() # Ensure file is closed\n",
       "            logger.error(f\"File size {size} exceeds limit {MAX_FILE_SIZE} for user {current_user.username}\")\n",
       "            raise HTTPException(status_code=413, detail=f\"File too large. Limit is {MAX_FILE_SIZE / (1024 * 1024)} MB.\")\n",
       "        contents += chunk\n",
       "    await file.close() # Close the file after reading\n",
       "\n",
       "\n",
       "    if not contents:\n",
       "        logger.error(f\"Empty file uploaded by user {current_user.username}\")\n",
       "        raise HTTPException(status_code=400, detail=\"Empty file uploaded.\")\n",
       "\n",
       "\n",
       "    try:\n",
       "        image = Image.open(io.BytesIO(contents)).convert(\"RGB\")\n",
       "        # Verify image integrity (optional but good)\n",
       "        image.verify()\n",
       "        # Reopen after verify\n",
       "        image = Image.open(io.BytesIO(contents)).convert(\"RGB\")\n",
       "    except UnidentifiedImageError:\n",
       "        logger.error(f\"Uploaded file is not a valid image for user {current_user.username}\")\n",
       "        raise HTTPException(\n",
       "            status_code=400, detail=\"Uploaded file is not a valid image or is corrupted.\"\n",
       "        )\n",
       "    except Exception as e:\n",
       "        logger.error(f\"Error processing image for user {current_user.username}: {str(e)}\")\n",
       "        raise HTTPException(status_code=400, detail=f\"Error processing image: {str(e)}\")\n",
       "\n",
       "\n",
       "    # Preprocess the image\n",
       "    try:\n",
       "        input_tensor = preprocess(image).unsqueeze(0).to(device)\n",
       "    except Exception as e:\n",
       "        logger.error(f\"Error during image preprocessing for user {current_user.username}: {str(e)}\")\n",
       "        raise HTTPException(status_code=500, detail=f\"Error during image preprocessing: {str(e)}\")\n",
       "\n",
       "\n",
       "    try:\n",
       "        with torch.no_grad():\n",
       "            outputs = model(input_tensor)\n",
       "\n",
       "            if include_confidence:\n",
       "                probabilities = torch.nn.functional.softmax(outputs, dim=1)\n",
       "                # Ensure top_k is not greater than num_classes\n",
       "                k = min(top_k, num_classes)\n",
       "                top_probs, top_idxs = torch.topk(probabilities, k=k)\n",
       "                top_probs_list = top_probs.cpu().numpy().tolist()[0]\n",
       "                top_idxs_list = top_idxs.cpu().numpy().tolist()[0]\n",
       "                predictions = [\n",
       "                    {\"class\": class_names[idx], \"confidence\": float(prob)} # Ensure JSON serializable\n",
       "                    for idx, prob in zip(top_idxs_list, top_probs_list)\n",
       "                ]\n",
       "                logger.info(f\"Prediction successful for user: {current_user.username}, file: {file.filename}, top_k={k}\")\n",
       "                return JSONResponse({\"predictions\": predictions})\n",
       "            else:\n",
       "                _, preds = torch.max(outputs, 1)\n",
       "                predicted_class = class_names[preds[0].item()] # Use .item()\n",
       "                logger.info(f\"Prediction successful for user: {current_user.username}, file: {file.filename}, predicted_class={predicted_class}\")\n",
       "                return JSONResponse({\"predicted_class\": predicted_class})\n",
       "    except Exception as e:\n",
       "        logger.error(f\"Error during model inference for user {current_user.username}: {str(e)}\")\n",
       "        raise HTTPException(status_code=500, detail=f\"Error during model inference: {str(e)}\")\n",
       "\n",
       "\n",
       "if __name__ == \"__main__\":\n",
       "    # Make sure to run this file, e.g., secure_app_with_users.py\n",
       "    # Use the filename in the uvicorn command string\n",
       "    uvicorn.run(\"secure_app_with_users:app\", host=\"0.0.0.0\", port=5454, reload=True) # Added reload=True for development\n",
       "```\n",
       "\n",
       "**Step 3: Install Dependencies**\n",
       "\n",
       "```bash\n",
       "pip install \"fastapi[all]\" uvicorn python-dotenv torch torchvision Pillow \"python-jose[cryptography]\" \"passlib[bcrypt]\"\n",
       "```\n",
       "\n",
       "*   `fastapi[all]` includes `pydantic` and `python-multipart` (needed for `OAuth2PasswordRequestForm`).\n",
       "*   `python-jose[cryptography]` provides JWT functionality.\n",
       "*   `passlib[bcrypt]` provides password hashing.\n",
       "\n",
       "**Step 4: Run the Application**\n",
       "\n",
       "Save the updated code (e.g., as `secure_app_with_users.py`). Make sure your `.env` file is in the same directory (or parent directory) and contains `SECRET_KEY`, `ALGORITHM`, and `ACCESS_TOKEN_EXPIRE_MINUTES`. Also ensure the `finetuned_model.pth` file is accessible.\n",
       "\n",
       "Run the app:\n",
       "\n",
       "```bash\n",
       "uvicorn secure_app_with_users:app --host 0.0.0.0 --port 5454 --reload\n",
       "```\n",
       "\n",
       "**How to Use the Updated API:**\n",
       "\n",
       "1.  **Login:** Send a POST request to `/token` with `username` and `password` as form data (e.g., `username=testuser`, `password=secret`).\n",
       "    *   You'll receive an `access_token` in the response.\n",
       "2.  **Access Protected Endpoints:** For requests to `/model-info` or `/predict`, include the received token in the `Authorization` header:\n",
       "    `Authorization: Bearer <your_access_token>`\n",
       "\n",
       "The original API key mechanism (`X-API-Key`) is no longer used for `/model-info` and `/predict` in this version. Authentication is now handled entirely by the JWT bearer token obtained via the `/token` endpoint. You could potentially re-introduce the API key as an alternative or additional layer if needed, but this implementation replaces it with standard user login."
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "from google import genai\n",
    "from google.genai import types\n",
    "from IPython.display import Markdown\n",
    "from IPython.display import Markdown\n",
    "\n",
    "API_KEY = os.environ.get(\"GEMINI_API_KEY\")\n",
    "\n",
    "client = genai.Client(api_key=API_KEY)\n",
    "\n",
    "# Load the Python file as text\n",
    "\n",
    "file_path = \"secure_app.py\"\n",
    "with open(file_path, \"r\") as file:\n",
    "    doc_data = file.read()\n",
    "prompt = \"Please integrate user management into the FastAPI application.\"\n",
    "\n",
    "contents = [\n",
    "    types.Part.from_bytes(\n",
    "        data=doc_data.encode(\"utf-8\"),\n",
    "        mime_type=\"text/x-python\",\n",
    "    ),\n",
    "    prompt,\n",
    "]\n",
    "\n",
    "chat = client.aio.chats.create(\n",
    "    model=\"gemini-2.5-pro-exp-03-25\",\n",
    "    config=types.GenerateContentConfig(\n",
    "        tools=[types.Tool(code_execution=types.ToolCodeExecution)]\n",
    "    ),\n",
    ")\n",
    "\n",
    "response = await chat.send_message(contents)\n",
    "Markdown(response.text)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "7f2ddc6d-e54d-47c4-9c59-bf91b0f67c79",
   "metadata": {
    "executionCancelledAt": null,
    "executionTime": 66222,
    "lastExecutedAt": 1743102350445,
    "lastExecutedByKernel": "4c9f5db9-464b-4a72-9464-a5e93fb850cd",
    "lastScheduledRunId": null,
    "lastSuccessfullyExecutedCode": "response = await chat.send_message('Please run the code to ensure that everything is functioning properly.')\nMarkdown(response.text)",
    "outputsMetadata": {
     "0": {
      "height": 469,
      "type": "stream"
     }
    }
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "Okay, I can execute the Python code provided to check for syntax errors, import issues, and basic structural validity.\n",
       "\n",
       "However, please note the following limitations:\n",
       "\n",
       "1.  **Cannot Run the Web Server:** I cannot actually start the `uvicorn` web server process within this environment. The `uvicorn.run(...)` call will be skipped.\n",
       "2.  **No File System Access:** I cannot access local files like `.env` or `finetuned_model.pth`.\n",
       "    *   I will mock the environment variables (`SECRET_KEY`, `ALGORITHM`, `ACCESS_TOKEN_EXPIRE_MINUTES`).\n",
       "    *   The code related to loading the `finetuned_model.pth` will likely fail or be skipped/mocked because the file doesn't exist here. This means the model itself won't be loaded or tested.\n",
       "3.  **No Network Access:** I cannot test the API endpoints by sending actual HTTP requests.\n",
       "4.  **Dependency Check:** While I can attempt to import the required libraries (FastAPI, PyTorch, etc.), this only confirms they are *available* in the execution environment, not necessarily the exact versions you might have locally.\n",
       "\n",
       "The purpose of this run is primarily to catch immediate code errors (like typos, incorrect syntax, missing imports) *before* the server tries to start.\n",
       "\n",
       "Here is the execution attempt:\n",
       "It seems the execution environment doesn't have the `torch`, `torchvision`, and potentially `PIL` (Pillow) libraries installed. The script failed during the import stage.\n",
       "\n",
       "**Findings:**\n",
       "\n",
       "1.  **Missing Dependencies:** The primary issue is that the core machine learning libraries (`torch`, `torchvision`) required by the application are not available in the environment where the code was just executed. `PIL` (Pillow) might also be missing if `torchvision` didn't pull it in.\n",
       "2.  **Code Structure (Up to Failure):** The code structure *before* the failed import (including environment variable mocking, basic imports like `os`, `logging`, `datetime`, `fastapi`, `pydantic`, `passlib`, `jose`) seems syntactically correct.\n",
       "3.  **Next Steps:** To run this code successfully, it needs to be executed in a Python environment where all the dependencies listed in the `pip install` command from the previous step are present:\n",
       "    ```bash\n",
       "    pip install \"fastapi[all]\" uvicorn python-dotenv torch torchvision Pillow \"python-jose[cryptography]\" \"passlib[bcrypt]\"\n",
       "    ```\n",
       "4.  **File Requirements:** Remember that even with the dependencies installed, running the application fully (using `uvicorn`) will *also* require:\n",
       "    *   The `.env` file with your actual `SECRET_KEY` and other variables in the correct location.\n",
       "    *   The `finetuned_model.pth` file accessible at the path specified in the script.\n",
       "\n",
       "**Conclusion:**\n",
       "\n",
       "The verification failed due to missing essential libraries (`torch`, `torchvision`). While the initial parts of the script related to FastAPI setup, user models, and JWT utilities appear structurally sound, the application cannot run without its core ML dependencies installed."
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response = await chat.send_message(\n",
    "    \"Please run the code to ensure that everything is functioning properly.\"\n",
    ")\n",
    "Markdown(response.text)"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "name": "Welcome to DataCamp Workspaces.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}