Skip to content

Commit bb011f2

Browse files
Created using Colab
1 parent f5a0e9c commit bb011f2

File tree

1 file changed

+39
-17
lines changed

1 file changed

+39
-17
lines changed

agi_pipeline.ipynb

Lines changed: 39 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"colab": {
66
"private_outputs": true,
77
"provenance": [],
8-
"authorship_tag": "ABX9TyNk2WJFhV2VGr1cGsUqJ/ai",
8+
"authorship_tag": "ABX9TyP6x+LjGFpdmRf+qQwoCRrX",
99
"include_colab_link": true
1010
},
1111
"kernelspec": {
@@ -31,35 +31,51 @@
3131
"cell_type": "code",
3232
"source": [
3333
"import os\n",
34-
"import asyncio\n",
34+
"import json\n",
3535
"import torch\n",
36+
"import asyncio\n",
3637
"from typing import List\n",
3738
"from PIL import Image\n",
3839
"from fastapi import FastAPI, UploadFile, Depends, HTTPException\n",
3940
"from fastapi.security import OAuth2PasswordBearer\n",
40-
"from pydantic import BaseModel, SecretStr\n",
41+
"from pydantic import BaseModel\n",
42+
"import jwt\n",
4143
"import pyttsx3\n",
4244
"from loguru import logger\n",
4345
"import io\n",
4446
"import uvicorn\n",
45-
"import nest_asyncio\n",
47+
"import signal\n",
48+
"import sys\n",
4649
"from transformers import T5Tokenizer, T5ForConditionalGeneration\n",
4750
"from ultralytics import YOLO\n",
4851
"import whisper\n",
4952
"\n",
53+
"# === Load Configuration ===\n",
54+
"with open('config.json', 'r') as f:\n",
55+
" config = json.load(f)\n",
56+
"\n",
5057
"# === Configuration and Logging Setup ===\n",
5158
"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",
5360
"logger.info(\"Application startup\")\n",
5461
"\n",
5562
"# === 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",
5765
"oauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"token\")\n",
5866
"\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",
5972
"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",
6176
" logger.warning(\"Authentication failed.\")\n",
6277
" raise HTTPException(status_code=401, detail=\"Invalid token\")\n",
78+
" return payload\n",
6379
"\n",
6480
"# === Pydantic Models ===\n",
6581
"class TextRequest(BaseModel):\n",
@@ -71,7 +87,7 @@
7187
"# === NLP Module (T5 Transformer) ===\n",
7288
"class NLPModule:\n",
7389
" def __init__(self):\n",
74-
" model_name = \"google/flan-t5-small\"\n",
90+
" model_name = config[\"nlp_model\"][\"model_name\"]\n",
7591
" self.tokenizer = T5Tokenizer.from_pretrained(model_name)\n",
7692
" self.model = T5ForConditionalGeneration.from_pretrained(model_name)\n",
7793
" logger.info(\"NLP model loaded successfully.\")\n",
@@ -90,7 +106,8 @@
90106
"# === CV Module (YOLOv8 for Object Detection) ===\n",
91107
"class CVModule:\n",
92108
" 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",
94111
" logger.info(\"CV model loaded successfully.\")\n",
95112
"\n",
96113
" def detect_objects(self, image: Image.Image) -> str:\n",
@@ -101,7 +118,8 @@
101118
"# === Speech Processor (Whisper for Speech-to-Text, PyTTSX3 for Text-to-Speech) ===\n",
102119
"class SpeechProcessor:\n",
103120
" 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",
105123
" self.tts = pyttsx3.init()\n",
106124
" logger.info(\"Speech processor initialized successfully.\")\n",
107125
"\n",
@@ -143,6 +161,14 @@
143161
"\n",
144162
"pipeline = EnhancedAGIPipeline()\n",
145163
"\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",
146172
"# === Endpoints ===\n",
147173
"@app.post(\"/process-nlp/\", response_model=TextResponse, dependencies=[Depends(authenticate_user)])\n",
148174
"async def process_nlp(request: TextRequest):\n",
@@ -157,11 +183,8 @@
157183
"\n",
158184
"@app.post(\"/batch-cv-detection/\", dependencies=[Depends(authenticate_user)])\n",
159185
"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",
165188
" return {\"batch_detections\": responses}\n",
166189
"\n",
167190
"@app.post(\"/speech-to-text/\", response_model=TextResponse, dependencies=[Depends(authenticate_user)])\n",
@@ -174,9 +197,8 @@
174197
" await pipeline.process_text_to_speech(request.text)\n",
175198
" return {\"response\": \"Speech synthesis complete.\"}\n",
176199
"\n",
177-
"# === Run the Application with HTTPS (uvicorn) ===\n",
200+
"# === Run the Application ===\n",
178201
"if __name__ == \"__main__\":\n",
179-
" nest_asyncio.apply()\n",
180202
" uvicorn.run(app, host=\"0.0.0.0\", port=8000)"
181203
],
182204
"metadata": {

0 commit comments

Comments
 (0)