Skip to content

Commit

Permalink
database structure changing
Browse files Browse the repository at this point in the history
  • Loading branch information
Kylehtran committed Nov 12, 2024
1 parent 1a43e58 commit 68cbb5c
Show file tree
Hide file tree
Showing 10 changed files with 406 additions and 140 deletions.
2 changes: 1 addition & 1 deletion fishsense-database
6 changes: 3 additions & 3 deletions fishsense_services/app.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from fastapi import FastAPI
from fishsense_services.routes.usr.login import login_router
from fishsense_services.routes.usr.usr import usr_router
from fishsense_services.routes.img.img import img_router
from fishsense_services.routes.usr.login_routes import login_router
from fishsense_services.routes.usr.user_routes import usr_router
from fishsense_services.routes.processing.img_routes import img_router


def create_app():
Expand Down
59 changes: 0 additions & 59 deletions fishsense_services/routes/img/img.py

This file was deleted.

110 changes: 110 additions & 0 deletions fishsense_services/routes/processing/img_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
from fastapi import APIRouter, Request, HTTPException, UploadFile, File, Form
from fastapi.responses import JSONResponse

from pydantic import BaseModel
from fishsense_database.image import upload_img, get_all_user_imgs, get_img
from fishsense_database.laser import get_laser_cal
from fishsense_database.lens import get_lens_cal
import os

img_router = APIRouter()

@img_router.post("/upload", status_code=200)
async def upload_img_route(
username: str = Form(...),
img_name: str = Form(...),
img: UploadFile = File(...),
length: float = Form(None),
units: str = Form(None),
dataset_name: str = Form(...),
# lens_calibration_id: int = Form(None),
# laser_calibration_id: int = Form(None),
version_num: int = Form(None)
):
try:

if not username or not img_name or not img or not dataset_name:
raise ValueError("Missing required fields")

image_content = await img.read() #TODO convert to ORF

if length is None:
#fishsense core get length function
length = 0 #temp length'
units = "cm" #temp units
#throw related errors

laser_calibration_id = get_laser_cal(username, dataset_name)[0]
if laser_calibration_id is None:
laser_calibration_id = None
lens_calibration_id = get_lens_cal(username, dataset_name)[0]
if lens_calibration_id is None:
lens_calibration_id = None




# Save the image to the database
upload_img(
name=img_name,
image=image_content,
user_id=username,
length=length,
units=units,
dataset_name=dataset_name,
lens_calibration_id=lens_calibration_id,
laser_calibration_id=laser_calibration_id,
version_num=version_num
)

return {"message": "Image uploaded successfully"}

except ValueError as e:
return JSONResponse(status_code=400, content={"detail": str(e)})


@img_router.get("/{username}/{img_id}", status_code=200)
async def get_img(username: str, img_id: str):

try:
if not username or not img_id:
raise ValueError("Missing required fields")

img = get_img(username, img_id)

if not img:
raise ValueError("Image does not exist")
return img

except ValueError as e:
raise HTTPException(status_code=404, detail=e.args)

@img_router.get("/gallery/{username}")
async def get_all_imgs(username: str, email: str | None = None):

try:
if not username:
raise ValueError("Missing required fields")
# TODO convert form image path to image content
imgs = get_all_user_imgs(username, email)

if not imgs:
raise ValueError("User does not exist")

return imgs

except ValueError as e:
raise HTTPException(status_code=404, detail="User does not exist")

@img_router.delete("/{username}/{img_name}", status_code=200)
async def delete_img(username: str, img_name: str):

try:
delete_img(username, img_name)
return

except ValueError as e:
raise HTTPException(status_code=404, detail=e.args)



51 changes: 51 additions & 0 deletions fishsense_services/routes/processing/laser_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from fastapi import APIRouter, Request, HTTPException, UploadFile, File, Form
from fastapi.responses import JSONResponse

from fishsense_database.laser import get_laser_cal, upload_laser_cal

laser_router = APIRouter()

@laser_router.post("/upload", status_code=200)
async def upload_laser_route(
laser: UploadFile = File(...),
results: UploadFile = Form(None),
dataset_name: str = Form(...),
user_id: int = Form(...),
slate_scan: UploadFile = Form(...),
square_size: float = Form(...),
rows: int = Form(...),
cols: int = Form(...)

):
try:

if not user_id or not laser or not dataset_name or not slate_scan or not square_size or not rows or not cols:
raise ValueError("Missing required fields")

laser_content = await laser.read() #TODO convert to ORF
results_content = await results.read() #TODO convert to csv
slate_content = await slate_scan.read() #TODO convert to pdf

if results is None:
#fishsense core calibrate function
results = None #temp
#throw related errors


# Save the image to the database
upload_laser_cal(
laser=laser_content,
results=results_content,
dataset_name=dataset_name,
user_id=user_id,
slate_scan=slate_content,
square_size=square_size,
rows=rows,
cols=cols
)

return {"message": "Image uploaded successfully"}

except ValueError as e:
return JSONResponse(status_code=400, content={"detail": str(e)})

File renamed without changes.
136 changes: 136 additions & 0 deletions fishsense_services/routes/usr/user_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
from fishsense_database.database import Database
from create_db import database

import datetime
from fastapi import APIRouter, Request, HTTPException
from fastapi.responses import JSONResponse

usr_router = APIRouter()

@usr_router.post("/create", status_code=200)
async def create_usr_route(request: Request):

data = await request.json()

try:

success = False
with database as db:
time_diff = int((datetime.datetime.now(datetime.timezone.utc) - db.time).total_seconds())

data["created_utc"] = time_diff
data["last_login_utc"] = time_diff # TODO fix time stamp
success = db.exec_script("fishsense-database/scripts/insert_scripts/insert_user.sql", data)

if not success:
raise ValueError("User with this username or email already exists.")

return JSONResponse(
status_code=200,
content={"message": "User created successfully."}
)

except ValueError as e:
print(f"ValueError caught in FastAPI: {e}") # Log the error for debugging
return JSONResponse(
status_code=400,
content={"detail": str(e)} # Send the error message as string
)




# @usr_router.get("/user={username}", status_code=200)
# async def get_usr_route(username: str):

# try:
# if not username:
# raise ValueError("Must provide a username.")
# user = get_user(username)

# if not user:
# raise ValueError("User does not exist.")

# return JSONResponse(
# status_code=200,
# content={"user details": jsonable_encoder(user)}
# )

# except ValueError as e:

# return JSONResponse(
# status_code=400,
# content={"detail": str(e)} # Send the error message as string
# )

# @usr_router.get("/", status_code=200)
# async def all_usrs_route():

# try:
# users = get_all_users()

# return JSONResponse(
# status_code=200,
# content={"users": jsonable_encoder(users)}
# )

# except ValueError as e:

# return JSONResponse(
# status_code=400,
# content={"detail": str(e)} # Send the error message as string
# )

# @usr_router.put("/update", status_code=200)
# async def update_usr_route(request: Request):

# data = await request.json()
# username = data.get("username")
# new_username = data.get("new_username")
# new_email = data.get("new_email")

# try:
# success = update_user(username, new_username, new_email)

# if not success:
# raise ValueError("User does not exist.")

# return JSONResponse(
# status_code=200,
# content={"message": "User updated successfully."}
# )

# except ValueError as e:
# return JSONResponse(
# status_code=400,
# content={"detail": str(e)}
# )


# @usr_router.delete("/delete", status_code=200)
# async def delete_usr_route(request: Request):

# data = await request.json()
# username = data["username"]

# try:

# if not username:
# raise ValueError("Must provide a username.")

# success = delete_user(username)

# if not success:
# raise ValueError("User does not exist.")

# return JSONResponse(
# status_code=200,
# content={"message": "User deleted successfully."}
# )

# except ValueError as e:

# return JSONResponse(
# status_code=400,
# content={"detail": str(e)}
# )
Loading

0 comments on commit 68cbb5c

Please sign in to comment.