File size: 4,718 Bytes
73c6377
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3699d7c
 
 
73c6377
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3699d7c
 
 
73c6377
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""
HBV Patient Assessment Router
API endpoint for HBV treatment eligibility assessment
"""
from fastapi import APIRouter, HTTPException
from api.models import HBVPatientInput, HBVAssessmentResponse, TextAssessmentInput
import logging
from core.hbv_assessment import assess_hbv_eligibility
from core.text_parser import parse_patient_text, validate_extracted_data

logger = logging.getLogger(__name__)

router = APIRouter(
    prefix="",
    tags=["HBV Assessment"]
)


@router.post("/assess", response_model=HBVAssessmentResponse)
async def assess_patient(patient: HBVPatientInput) -> HBVAssessmentResponse:
    """
    Assess HBV patient eligibility for treatment according to SASLT 2021 guidelines
    
    This endpoint:
    1. Validates patient data
    2. Provides SASLT 2021 guideline pages (3, 4, 6, 7, 8, 9, 10) directly as context
    3. Uses LLM to analyze patient against the guidelines
    4. Returns structured assessment with eligibility and comprehensive recommendations
    
    Returns:
        HBVAssessmentResponse containing:
        - eligible: Whether patient is eligible for treatment
        - recommendations: Comprehensive narrative including eligibility determination, 
          specific criteria met, treatment options (ETV, TDF, TAF), and special considerations,
          with inline citations in format [SASLT 2021, Page X]
    """
    try:
        logger.info(f"Assessing HBV patient: Age {patient.age}, Sex {patient.sex}, HBV DNA {patient.hbv_dna_level}")
        
        # Convert Pydantic model to dict for core function
        patient_data = patient.dict()
        
        # Call core assessment function
        result = assess_hbv_eligibility(patient_data)
        
        # Convert dict result back to Pydantic response model
        response = HBVAssessmentResponse(**result)
        
        logger.info(f"Assessment complete: Eligible={response.eligible}")
        return response
        
    except Exception as e:
        logger.error(f"Error assessing patient: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Error assessing patient: {str(e)}")


@router.post("/assess/text", response_model=HBVAssessmentResponse)
async def assess_patient_from_text(text_input: TextAssessmentInput) -> HBVAssessmentResponse:
    """
    Assess HBV patient eligibility from free-form text input
    
    This endpoint:
    1. Parses free-form text to extract structured patient data using LLM
    2. Validates the extracted data
    3. Provides SASLT 2021 guideline pages directly as context
    4. Uses LLM to analyze patient against the guidelines
    5. Returns structured assessment with eligibility and recommendations
    
    Example text input:
    "45-year-old male patient
    HBsAg: Positive for 12 months
    HBV DNA: 5000 IU/mL
    HBeAg: Positive
    ALT: 80 U/L
    Fibrosis stage: F2-F3
    Necroinflammatory activity: A2
    No extrahepatic manifestations
    No immunosuppression
    No coinfections (HIV, HCV, HDV)
    No family history of cirrhosis or HCC"
    
    Returns:
        HBVAssessmentResponse containing:
        - eligible: Whether patient is eligible for treatment
        - recommendations: Comprehensive narrative with inline citations
    """
    try:
        logger.info(f"Received text input for assessment (length: {len(text_input.text_input)} characters)")
        logger.info(f"Text input preview: {text_input.text_input[:200]}...")
        
        # Parse text to extract structured patient data
        logger.info("Parsing text input to extract patient data...")
        patient_data = parse_patient_text(text_input.text_input)
        logger.info(f"Extracted patient data: {patient_data}")
        
        # Validate extracted data
        logger.info("Validating extracted patient data...")
        validated_data = validate_extracted_data(patient_data)
        logger.info("Patient data validated successfully")
        
        # Call core assessment function with extracted data
        logger.info("Performing HBV eligibility assessment...")
        result = assess_hbv_eligibility(validated_data)
        
        # Convert dict result to Pydantic response model
        response = HBVAssessmentResponse(**result)
        
        logger.info(f"Text-based assessment complete: Eligible={response.eligible}")
        return response
        
    except ValueError as e:
        logger.error(f"Validation error in text assessment: {str(e)}")
        raise HTTPException(status_code=400, detail=f"Invalid patient data: {str(e)}")
    except Exception as e:
        logger.error(f"Error in text-based assessment: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Error processing text input: {str(e)}")