Refine event types and update related models and logic

Standardized event types with stricter validation using `Literal`. Adjusted related data and logic to align with new types, including changes to PGROUP assignments, event timeline increments, and schema updates. Cleaned up unused code and clarified database initialization behavior.
This commit is contained in:
GotthardG
2025-03-14 13:11:05 +01:00
parent f41262575e
commit fbc32474ff
9 changed files with 267 additions and 165 deletions

View File

@ -14,6 +14,8 @@ from app.schemas import (
SampleResult,
ExperimentParametersCreate,
ExperimentParametersRead,
# ResultResponse,
# ResultCreate,
)
from app.models import (
Puck as PuckModel,
@ -22,6 +24,8 @@ from app.models import (
Image as ImageModel,
Dewar as DewarModel,
ExperimentParameters as ExperimentParametersModel,
# ExperimentParameters,
# Results,
)
from app.dependencies import get_db
import logging
@ -132,6 +136,32 @@ async def upload_sample_image(
if not sample:
raise HTTPException(status_code=404, detail="Sample not found")
# Retrieve the most recent sample event for the sample
sample_event = (
db.query(SampleEventModel)
.filter(SampleEventModel.sample_id == sample_id)
.order_by(SampleEventModel.timestamp.desc()) # Sort by most recent event
.first()
)
if not sample_event:
logging.debug(f"No events found for sample with id: {sample_id}")
raise HTTPException(
status_code=404, detail="No events found for the specified sample"
)
# Log the found sample event for debugging
logging.debug(
f"Most recent event found for sample_id {sample_id}: "
f"event_id={sample_event.id}, "
f"type={sample_event.event_type}, "
f"timestamp={sample_event.timestamp}"
)
# Extract event type and timestamp for directory structure
event_type = sample_event.event_type
event_timestamp = sample_event.timestamp.strftime("%Y-%m-%d_%H-%M-%S")
# Define Directory Structure
pgroup = sample.puck.dewar.pgroups # adjust to sample or puck pgroups as needed
today = datetime.now().strftime("%Y-%m-%d")
@ -142,7 +172,12 @@ async def upload_sample_image(
)
puck_name = sample.puck.puck_name if sample.puck else "default_puck"
position = sample.position if sample.position else "default_position"
base_dir = Path(f"images/{pgroup}/{today}/{dewar_name}/{puck_name}/{position}")
# Add 'run/event' specific details to the folder structure
base_dir = Path(
f"images/{pgroup}/{today}/{dewar_name}/{puck_name}/"
f"{position}/{event_type}_{event_timestamp}"
)
base_dir.mkdir(parents=True, exist_ok=True)
# Validate MIME type and Save the File
@ -150,7 +185,7 @@ async def upload_sample_image(
raise HTTPException(
status_code=400,
detail=f"Invalid file type: {uploaded_file.filename}."
f" Only images are accepted.",
f"Only images are accepted.",
)
file_path = base_dir / uploaded_file.filename
@ -164,8 +199,8 @@ async def upload_sample_image(
logging.error(f"Error saving file {uploaded_file.filename}: {str(e)}")
raise HTTPException(
status_code=500,
detail=f"Could not save file {uploaded_file.filename}."
f" Ensure the server has correct permissions.",
detail=f"Could not save file {uploaded_file.filename}. "
f"Ensure the server has correct permissions.",
)
# Create the payload from the Pydantic schema
@ -175,19 +210,20 @@ async def upload_sample_image(
filepath=str(file_path),
status="active",
sample_id=sample_id,
sample_event_id=int(sample_event.id), # Link to the most recent sample event
).dict()
# Convert the payload to your mapped SQLAlchemy model instance.
# Make sure that ImageModel is your mapped model for images.
# Convert the payload to your mapped SQLAlchemy model instance
new_image = ImageModel(**image_payload)
db.add(new_image)
db.commit()
db.refresh(new_image)
logging.info(
f"Uploaded 1 file for sample {sample_id} and"
f" added record {new_image.id} to the database."
f"Uploaded 1 file for sample {sample_id} and event {sample_event.id} and "
f"added record {new_image.id} to the database."
)
# Returning the mapped SQLAlchemy object, which will be converted to the
# Pydantic response model.
return new_image
@ -283,3 +319,42 @@ def create_experiment_parameters_for_sample(
db.refresh(new_exp)
return new_exp
# @router.post("/results", response_model=ResultResponse)
# def create_result(result: ResultCreate, db: Session = Depends(get_db)):
# # Validate sample_id and result_id (optional but recommended)
# sample = db.query(SampleModel).filter_by(id=result.sample_id).first()
# if not sample:
# raise HTTPException(status_code=404, detail="Sample not found")
#
# experiment = db.query(ExperimentParameters).filter_by(id=result.result_id).first()
# if not experiment:
# raise HTTPException(status_code=404, detail="Experiment parameters not found")
#
# # Create a new Results entry
# result_obj = Results(
# sample_id=result.sample_id,
# result_id=result.result_id,
# result=result.result
# )
# db.add(result_obj)
# db.commit()
# db.refresh(result_obj)
#
# return result_obj
#
# @router.get("/results", response_model=list[ResultResponse])
# def get_results(sample_id: int, result_id: int, db: Session = Depends(get_db)):
# query = db.query(Results)
#
# if sample_id:
# query = query.filter(Results.sample_id == sample_id)
# if result_id:
# query = query.filter(Results.result_id == result_id)
#
# results = query.all()
# if not results:
# raise HTTPException(status_code=404, detail="No results found")
#
# return results