|
5 | 5 | "colab": { |
6 | 6 | "private_outputs": true, |
7 | 7 | "provenance": [], |
8 | | - "authorship_tag": "ABX9TyNk2WJFhV2VGr1cGsUqJ/ai", |
| 8 | + "authorship_tag": "ABX9TyP6x+LjGFpdmRf+qQwoCRrX", |
9 | 9 | "include_colab_link": true |
10 | 10 | }, |
11 | 11 | "kernelspec": { |
|
31 | 31 | "cell_type": "code", |
32 | 32 | "source": [ |
33 | 33 | "import os\n", |
34 | | - "import asyncio\n", |
| 34 | + "import json\n", |
35 | 35 | "import torch\n", |
| 36 | + "import asyncio\n", |
36 | 37 | "from typing import List\n", |
37 | 38 | "from PIL import Image\n", |
38 | 39 | "from fastapi import FastAPI, UploadFile, Depends, HTTPException\n", |
39 | 40 | "from fastapi.security import OAuth2PasswordBearer\n", |
40 | | - "from pydantic import BaseModel, SecretStr\n", |
| 41 | + "from pydantic import BaseModel\n", |
| 42 | + "import jwt\n", |
41 | 43 | "import pyttsx3\n", |
42 | 44 | "from loguru import logger\n", |
43 | 45 | "import io\n", |
44 | 46 | "import uvicorn\n", |
45 | | - "import nest_asyncio\n", |
| 47 | + "import signal\n", |
| 48 | + "import sys\n", |
46 | 49 | "from transformers import T5Tokenizer, T5ForConditionalGeneration\n", |
47 | 50 | "from ultralytics import YOLO\n", |
48 | 51 | "import whisper\n", |
49 | 52 | "\n", |
| 53 | + "# === Load Configuration ===\n", |
| 54 | + "with open('config.json', 'r') as f:\n", |
| 55 | + " config = json.load(f)\n", |
| 56 | + "\n", |
50 | 57 | "# === Configuration and Logging Setup ===\n", |
51 | 58 | "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", |
52 | | - "logger.add(\"pipeline_{time}.log\", rotation=\"1 MB\", level=\"DEBUG\", enqueue=True, backtrace=True, diagnose=True)\n", |
| 59 | + "logger.add(config[\"logging\"][\"log_file\"], rotation=config[\"logging\"][\"rotation\"], level=config[\"logging\"][\"level\"], enqueue=config[\"logging\"][\"enqueue\"], backtrace=config[\"logging\"][\"backtrace\"], diagnose=config[\"logging\"][\"diagnose\"])\n", |
53 | 60 | "logger.info(\"Application startup\")\n", |
54 | 61 | "\n", |
55 | 62 | "# === Security Setup ===\n", |
56 | | - "SECURE_TOKEN = SecretStr(os.getenv(\"SECURE_TOKEN\", \"YvZz9Hni0hWJPh_UWW4dQYf9rhIe9nNYcC5ZQTTZz0Q\"))\n", |
| 63 | + "SECRET_KEY = os.getenv(\"SECRET_KEY\", config[\"security\"][\"secret_key\"])\n", |
| 64 | + "ALGORITHM = config[\"security\"][\"algorithm\"]\n", |
57 | 65 | "oauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"token\")\n", |
58 | 66 | "\n", |
| 67 | + "def create_access_token(data: dict):\n", |
| 68 | + " to_encode = data.copy()\n", |
| 69 | + " encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)\n", |
| 70 | + " return encoded_jwt\n", |
| 71 | + "\n", |
59 | 72 | "def authenticate_user(token: str = Depends(oauth2_scheme)):\n", |
60 | | - " if token != SECURE_TOKEN.get_secret_value():\n", |
| 73 | + " try:\n", |
| 74 | + " payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])\n", |
| 75 | + " except jwt.PyJWTError:\n", |
61 | 76 | " logger.warning(\"Authentication failed.\")\n", |
62 | 77 | " raise HTTPException(status_code=401, detail=\"Invalid token\")\n", |
| 78 | + " return payload\n", |
63 | 79 | "\n", |
64 | 80 | "# === Pydantic Models ===\n", |
65 | 81 | "class TextRequest(BaseModel):\n", |
|
71 | 87 | "# === NLP Module (T5 Transformer) ===\n", |
72 | 88 | "class NLPModule:\n", |
73 | 89 | " def __init__(self):\n", |
74 | | - " model_name = \"google/flan-t5-small\"\n", |
| 90 | + " model_name = config[\"nlp_model\"][\"model_name\"]\n", |
75 | 91 | " self.tokenizer = T5Tokenizer.from_pretrained(model_name)\n", |
76 | 92 | " self.model = T5ForConditionalGeneration.from_pretrained(model_name)\n", |
77 | 93 | " logger.info(\"NLP model loaded successfully.\")\n", |
|
90 | 106 | "# === CV Module (YOLOv8 for Object Detection) ===\n", |
91 | 107 | "class CVModule:\n", |
92 | 108 | " def __init__(self):\n", |
93 | | - " self.model = YOLO('yolov8n.pt').to(device)\n", |
| 109 | + " model_path = config[\"cv_model\"][\"model_path\"]\n", |
| 110 | + " self.model = YOLO(model_path).to(device)\n", |
94 | 111 | " logger.info(\"CV model loaded successfully.\")\n", |
95 | 112 | "\n", |
96 | 113 | " def detect_objects(self, image: Image.Image) -> str:\n", |
|
101 | 118 | "# === Speech Processor (Whisper for Speech-to-Text, PyTTSX3 for Text-to-Speech) ===\n", |
102 | 119 | "class SpeechProcessor:\n", |
103 | 120 | " def __init__(self):\n", |
104 | | - " self.whisper_model = whisper.load_model(\"base\")\n", |
| 121 | + " whisper_model = config[\"speech_processor\"][\"whisper_model\"]\n", |
| 122 | + " self.whisper_model = whisper.load_model(whisper_model)\n", |
105 | 123 | " self.tts = pyttsx3.init()\n", |
106 | 124 | " logger.info(\"Speech processor initialized successfully.\")\n", |
107 | 125 | "\n", |
|
143 | 161 | "\n", |
144 | 162 | "pipeline = EnhancedAGIPipeline()\n", |
145 | 163 | "\n", |
| 164 | + "# === Graceful Shutdown ===\n", |
| 165 | + "def shutdown_signal_handler(sig, frame):\n", |
| 166 | + " print('Shutting down gracefully...')\n", |
| 167 | + " sys.exit(0)\n", |
| 168 | + "\n", |
| 169 | + "signal.signal(signal.SIGINT, shutdown_signal_handler)\n", |
| 170 | + "signal.signal(signal.SIGTERM, shutdown_signal_handler)\n", |
| 171 | + "\n", |
146 | 172 | "# === Endpoints ===\n", |
147 | 173 | "@app.post(\"/process-nlp/\", response_model=TextResponse, dependencies=[Depends(authenticate_user)])\n", |
148 | 174 | "async def process_nlp(request: TextRequest):\n", |
|
157 | 183 | "\n", |
158 | 184 | "@app.post(\"/batch-cv-detection/\", dependencies=[Depends(authenticate_user)])\n", |
159 | 185 | "async def batch_cv_detection(files: List[UploadFile]):\n", |
160 | | - " responses = []\n", |
161 | | - " for file in files:\n", |
162 | | - " image = Image.open(io.BytesIO(await file.read()))\n", |
163 | | - " response = await pipeline.process_cv(image)\n", |
164 | | - " responses.append(response)\n", |
| 186 | + " tasks = [pipeline.process_cv(Image.open(io.BytesIO(await file.read()))) for file in files]\n", |
| 187 | + " responses = await asyncio.gather(*tasks)\n", |
165 | 188 | " return {\"batch_detections\": responses}\n", |
166 | 189 | "\n", |
167 | 190 | "@app.post(\"/speech-to-text/\", response_model=TextResponse, dependencies=[Depends(authenticate_user)])\n", |
|
174 | 197 | " await pipeline.process_text_to_speech(request.text)\n", |
175 | 198 | " return {\"response\": \"Speech synthesis complete.\"}\n", |
176 | 199 | "\n", |
177 | | - "# === Run the Application with HTTPS (uvicorn) ===\n", |
| 200 | + "# === Run the Application ===\n", |
178 | 201 | "if __name__ == \"__main__\":\n", |
179 | | - " nest_asyncio.apply()\n", |
180 | 202 | " uvicorn.run(app, host=\"0.0.0.0\", port=8000)" |
181 | 203 | ], |
182 | 204 | "metadata": { |
|
0 commit comments