Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions API/__init__.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,35 @@
from __future__ import annotations

import logging

import uvicorn
from fastapi import FastAPI
from fastapi import FastAPI, HTTPException

from API import route

# Initialize logger
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

Fastapp = FastAPI()

# API Router
Fastapp.include_router(route.router)


@Fastapp.get("/")
def read_root():
return {"Hello": "FASTAPI"}
try:
return {"Hello": "FASTAPI"}
except Exception as e:
logger.error(f"Error in root endpoint: {e}")
raise HTTPException(status_code=500, detail="Internal Server Error")


# function to run server of FastAPI
# Function to run FastAPI server
def run_fastapi_app():
uvicorn.run(Fastapp, host="127.0.0.1", port=8000)
try:
uvicorn.run(Fastapp, host="127.0.0.1", port=8000)
except Exception as e:
logger.error(f"Error starting FastAPI server: {e}")
raise
97 changes: 64 additions & 33 deletions API/database.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
from __future__ import annotations

import logging
from datetime import datetime

from pymongo import MongoClient
from pymongo import MongoClient, errors

# Initialize logger
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class Database:
Expand All @@ -14,8 +19,13 @@ def __init__(self, uri="mongodb://localhost:27017/", db_name="ImageDB"):
uri (str): The uri of the MongoDB server. Defaults to 'mongodb://localhost:27017/'.
db_name (str): The name of the MongoDB database. Defaults to 'ImageDB'.
"""
self.client = MongoClient(uri)
self.db = self.client[db_name]
try:
self.client = MongoClient(uri)
self.db = self.client[db_name]
logger.info("Successfully connected to MongoDB.")
except errors.ConnectionError as e:
logger.error(f"Failed to connect to MongoDB: {e}")
raise

def find(self, collection, query=None):
"""
Expand All @@ -28,7 +38,11 @@ def find(self, collection, query=None):
Returns:
pymongo.cursor.Cursor: A cursor pointing to the results of the query.
"""
return self.db[collection].find(query)
try:
return self.db[collection].find(query)
except errors.PyMongoError as e:
logger.error(f"Error finding documents in {collection}: {e}")
return None

def insert_one(self, collection, document):
"""
Expand All @@ -41,8 +55,11 @@ def insert_one(self, collection, document):
Returns:
pymongo.results.InsertOneResult: The result of the insertion.
"""

return self.db[collection].insert_one(document)
try:
return self.db[collection].insert_one(document)
except errors.PyMongoError as e:
logger.error(f"Error inserting document into {collection}: {e}")
return None

def find_one(self, collection, filter, projection=None):
"""
Expand All @@ -56,7 +73,11 @@ def find_one(self, collection, filter, projection=None):
Returns:
dict: The document that matches the query, or None if no documents match.
"""
return self.db[collection].find_one(filter=filter, projection=projection)
try:
return self.db[collection].find_one(filter=filter, projection=projection)
except errors.PyMongoError as e:
logger.error(f"Error finding document in {collection}: {e}")
return None

def find_one_and_delete(self, collection, query):
"""
Expand All @@ -69,7 +90,11 @@ def find_one_and_delete(self, collection, query):
Returns:
dict: The document that matches the query, or None if no documents match.
"""
return self.db[collection].find_one_and_delete(query)
try:
return self.db[collection].find_one_and_delete(query)
except errors.PyMongoError as e:
logger.error(f"Error deleting document in {collection}: {e}")
return None

def update_one(self, collection, query, update):
"""
Expand All @@ -83,10 +108,12 @@ def update_one(self, collection, query, update):
Returns:
pymongo.results.UpdateResult: The result of the update.
"""
try:
return self.db[collection].update_one(query, update)
except errors.PyMongoError as e:
logger.error(f"Error updating document in {collection}: {e}")
return None

return self.db[collection].update_one(query, update)

# add a function for pipeline aggregation vector search
def vector_search(self, collection, embedding):
"""
Perform a vector similarity search on the given collection.
Expand All @@ -98,27 +125,31 @@ def vector_search(self, collection, embedding):
Returns:
list: A list of documents with the closest embedding to the query vector, sorted by score.
"""

result = self.db[collection].aggregate(
[
{
"$vectorSearch": {
"index": "vector_index",
"path": "embedding",
"queryVector": embedding,
"numCandidates": 20,
"limit": 20,
try:
result = self.db[collection].aggregate(
[
{
"$vectorSearch": {
"index": "vector_index",
"path": "embedding",
"queryVector": embedding,
"numCandidates": 20,
"limit": 20,
},
},
},
{
"$project": {
"_id": 0,
"Name": 1,
"Image": 1,
"score": {"$meta": "vectorSearchScore"},
{
"$project": {
"_id": 0,
"Name": 1,
"Image": 1,
"score": {"$meta": "vectorSearchScore"},
},
},
},
],
)
result_arr = [i for i in result]
return result_arr
],
)
result_arr = [i for i in result]
return result_arr
except errors.PyMongoError as e:
logger.error(
f"Error performing vector search in {collection}: {e}")
return []
30 changes: 18 additions & 12 deletions API/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,21 @@ def format(self, record):
formatter = logging.Formatter(log_fmt)
return formatter.format(record)

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

stderr_handler = logging.StreamHandler()
stderr_handler.setLevel(logging.DEBUG)
stderr_handler.setFormatter(CustomFormatter())
logger.addHandler(stderr_handler)

file_handler = logging.FileHandler("app.log", mode="w")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(CustomFormatter(True))
logger.addHandler(file_handler)
try:
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

stderr_handler = logging.StreamHandler()
stderr_handler.setLevel(logging.DEBUG)
stderr_handler.setFormatter(CustomFormatter())
logger.addHandler(stderr_handler)

file_handler = logging.FileHandler("app.log", mode="w")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(CustomFormatter(True))
logger.addHandler(file_handler)

logging.info("Logging configuration initialized successfully.")
except Exception as e:
print(f"Error initializing logging configuration: {e}")
logging.error(f"Error initializing logging configuration: {e}")
Loading