File size: 10,514 Bytes
79b0bef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0bfe8ee
 
 
 
79b0bef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4dc0836
79b0bef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4dc0836
 
79b0bef
 
 
 
 
 
4dc0836
 
 
 
79b0bef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4dc0836
79b0bef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4dc0836
79b0bef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4dc0836
 
 
 
 
 
79b0bef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4dc0836
 
 
 
 
 
 
 
 
79b0bef
 
 
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
"""
src/api/schemas.py
────────────────────────────────────────────────────────────────
Pydantic models for API request validation and response shaping.

Every route uses these schemas β€” nothing in the routes builds
or returns raw dicts.  This gives us:
  - Automatic request validation with clear error messages
  - Auto-generated OpenAPI documentation at /docs
  - Type safety between the API and the dashboard client

Naming convention
─────────────────
  *Request  β€” payload coming IN  (POST body, query params)
  *Response β€” payload going OUT  (what the client receives)
  *Summary  β€” a lightweight response used in list endpoints
────────────────────────────────────────────────────────────────
"""

from __future__ import annotations

from datetime import datetime

from pydantic import BaseModel, Field, field_validator

# ════════════════════════════════════════════════════════════════
# SHARED / BASE
# ════════════════════════════════════════════════════════════════

class HealthResponse(BaseModel):
    """Response from the health-check endpoint."""

    status:   str = "ok"
    version:  str
    database: str = Field(description="'connected' or 'unreachable'")
    icd10_embedding_available: bool = Field(
        default=True,
        description=(
            "False if semantic ICD-10 matching has failed to load and "
            "is disabled for this process. Exact/fuzzy ICD-10 matching "
            "is unaffected either way β€” this only flags the fallback "
            "used for entity text that doesn't match any ICD-10 "
            "description lexically."
        ),
    )


# ════════════════════════════════════════════════════════════════
# NOTES
# ════════════════════════════════════════════════════════════════

class AnalyseRequest(BaseModel):
    """Request body for POST /notes/analyse.

    The user pastes or sends a clinical note and receives
    entities, ICD-10 mappings, and a severity prediction
    in one round trip.
    """

    text: str = Field(
        ...,
        min_length  = 10,
        description = "Clinical note text to analyse.",
        examples    = [
            (
                "Patient presents with acute chest pain and shortness "
                "of breath. History of hypertension and diabetes."
            )
        ],
    )
    include_icd10:      bool = Field(
        default     = True,
        description = "Whether to run ICD-10 mapping on extracted entities.",
    )
    include_severity:   bool = Field(
        default     = True,
        description = "Whether to run the severity classifier.",
    )

    @field_validator("text")
    @classmethod
    def text_not_blank(cls, v: str) -> str:
        """Reject payloads that are whitespace-only."""
        if not v.strip():
            raise ValueError("text must not be blank")
        return v


class EntityResponse(BaseModel):
    """A single extracted named entity."""

    text:         str
    label:        str = Field(
        description="DISEASE, MEDICATION, PROCEDURE, SYMPTOM, or ANATOMY"
    )
    start:        int
    end:          int
    confidence:   float | None = None
    icd10_matches: list[ICD10MatchResponse] = Field(default_factory=list)


class ICD10MatchResponse(BaseModel):
    """One ICD-10 code candidate for an entity."""

    icd10_code:   str
    description:  str
    confidence:   float
    match_method: str = Field(
        description="'exact', 'fuzzy', or 'embedding'"
    )
    rank:         int


class SeverityResponse(BaseModel):
    """Severity classification result for a clinical note."""

    label:         str = Field(
        description="'routine', 'urgent', or 'critical'"
    )
    confidence:    float
    probabilities: dict[str, float]
    task:          str


class AnalyseResponse(BaseModel):
    """Full analysis response for a single clinical note.

    Returned by POST /notes/analyse.
    """

    text_length:    int
    word_count:     int
    entities:       list[EntityResponse]
    entity_counts:  dict[str, int] = Field(
        description="Count of entities per label type"
    )
    severity:       SeverityResponse | None = None
    processing_ms:  float | None            = None


class NoteSummary(BaseModel):
    """Lightweight note record for list responses."""

    id:          int
    specialty:   str | None
    note_type:   str | None
    severity:    str | None
    word_count:  int | None
    data_source: str
    created_at:  datetime

    model_config = {"from_attributes": True}


class NoteDetail(NoteSummary):
    """Full note record including transcription text."""

    transcription: str

    model_config = {"from_attributes": True}


class NoteListResponse(BaseModel):
    """Paginated list of notes."""

    total:  int
    limit:  int
    offset: int
    items:  list[NoteSummary]


# ════════════════════════════════════════════════════════════════
# ENTITIES
# ════════════════════════════════════════════════════════════════

class EntitySummary(BaseModel):
    """Lightweight entity record for list responses."""

    id:         int
    text:       str
    label:      str
    confidence: float | None
    note_id:    int

    model_config = {"from_attributes": True}


class TopEntityItem(BaseModel):
    """One item in a top-N entity frequency list."""

    text:  str
    count: int


class TopEntitiesResponse(BaseModel):
    """Top-N most frequent entities, optionally filtered by label."""

    label:   str | None
    limit:   int
    items:   list[TopEntityItem]


# ════════════════════════════════════════════════════════════════
# ICD-10
# ════════════════════════════════════════════════════════════════

class ICD10LookupRequest(BaseModel):
    """Request body for POST /icd/lookup."""

    text: str = Field(
        ...,
        min_length  = 2,
        description = "Entity text to map to ICD-10 codes.",
        examples    = ["hypertension", "type 2 diabetes mellitus"],
    )
    top_k: int = Field(
        default     = 3,
        ge          = 1,
        le          = 10,
        description = "Maximum number of candidate codes to return.",
    )


class ICD10LookupResponse(BaseModel):
    """ICD-10 mapping result for a single entity text."""

    query:   str
    matches: list[ICD10MatchResponse]


# ════════════════════════════════════════════════════════════════
# STATS / DASHBOARD
# ════════════════════════════════════════════════════════════════

class SeverityDistribution(BaseModel):
    """Count of notes per severity label."""

    routine:  int = 0
    urgent:   int = 0
    critical: int = 0
    total:    int = 0


class SpecialtyCount(BaseModel):
    """Note count for one specialty."""

    specialty: str
    count:     int


class StatsResponse(BaseModel):
    """Aggregate statistics for the dashboard overview page."""

    total_notes:          int
    total_entities:       int
    severity_distribution: SeverityDistribution
    top_specialties:      list[SpecialtyCount]
    top_diseases:         list[TopEntityItem]
    top_icd10_codes:      list[ICD10MatchResponse]


# ════════════════════════════════════════════════════════════════
# MODEL RUNS
# ════════════════════════════════════════════════════════════════

class ModelRunSummary(BaseModel):
    """Summary of a classifier training run."""

    id:               int
    model_name:       str
    task:             str
    val_accuracy:     float | None
    val_f1:           float | None
    test_accuracy:    float | None = None
    test_f1:          float | None = None
    training_samples: int | None
    epochs:           int | None
    is_deployed:      bool
    created_at:       datetime

    model_config = {"from_attributes": True}


class ModelMetricsResponse(BaseModel):
    """Full metrics for the currently deployed classifier run.

    Returned by GET /model/metrics. Read by the dashboard's Model
    Metrics page instead of a local file, since the dashboard process
    never has direct access to the classifier or its checkpoint --
    only the API does.
    """

    model_name:       str
    task:             str
    training_samples: int | None                = None
    val_accuracy:     float | None               = None
    val_f1:           float | None               = None
    test_accuracy:    float | None                = None
    test_f1:          float | None                = None
    per_class:        dict[str, dict[str, float]] | None = None
    confusion_matrix: list[list[int]] | None      = None
    history:          list[dict] | None           = None
    run_notes:        str | None                  = None
    created_at:       datetime

    model_config = {"from_attributes": True}