-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathxrayvision.py
More file actions
executable file
·6270 lines (5350 loc) · 242 KB
/
xrayvision.py
File metadata and controls
executable file
·6270 lines (5350 loc) · 242 KB
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# XRayVision - Async DICOM processor with AI and WebSocket dashboard.
# Copyright (C) 2025 Costin Stroie <costinstroie@eridu.eu.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
# Standard library imports
import argparse
import asyncio
import base64
import json
import logging
import math
import os
import re
import sqlite3
import random
from datetime import datetime, timedelta
from typing import Optional
# Third-party imports
import aiohttp
import cv2
import numpy as np
from aiohttp import web
from pydicom import dcmread
from pydicom.dataset import Dataset
from pynetdicom import AE, evt, QueryRetrievePresentationContexts, StoragePresentationContexts
from pynetdicom.sop_class import (
Verification,
ComputedRadiographyImageStorage,
DigitalXRayImageStorageForPresentation,
PatientRootQueryRetrieveInformationModelFind,
PatientRootQueryRetrieveInformationModelMove,
PatientRootQueryRetrieveInformationModelGet
)
# Logger config
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s | %(levelname)8s | %(message)s',
handlers=[
logging.FileHandler("xrayvision.log"),
logging.StreamHandler()
]
)
# Filter out noisy module logs
logging.getLogger('aiohttp').setLevel(logging.WARNING)
logging.getLogger('asyncio').setLevel(logging.WARNING)
# DICOM network operations
logging.getLogger('pynetdicom').setLevel(logging.WARNING)
# DICOM file operations
logging.getLogger('pydicom').setLevel(logging.WARNING)
# Set default log level
logging.getLogger().setLevel(logging.INFO)
# Configuration
import configparser
# Default configuration values
DEFAULT_CONFIG = {
'general': {
'XRAYVISION_DB_PATH': 'xrayvision.db',
'XRAYVISION_BACKUP_DIR': 'backup'
},
'dicom': {
'AE_TITLE': 'XRAYVISION',
'AE_PORT': '4010',
'REMOTE_AE_TITLE': 'DICOM_SERVER',
'REMOTE_AE_IP': '192.168.1.1',
'REMOTE_AE_PORT': '104',
'RETRIEVAL_METHOD': 'C-MOVE'
},
'openai': {
'OPENAI_URL_PRIMARY': 'http://127.0.0.1:8080/v1/chat/completions',
'OPENAI_URL_SECONDARY': 'http://127.0.0.1:11434/v1/chat/completions',
'OPENAI_API_KEY': 'sk-your-api-key',
'MODEL_NAME': 'medgemma-4b-it'
},
'dashboard': {
'DASHBOARD_PORT': '8000'
},
'notifications': {
'NTFY_URL': 'https://ntfy.sh/xrayvision-alerts'
},
'processing': {
'PAGE_SIZE': '10',
'KEEP_DICOM': 'False',
'LOAD_DICOM': 'False',
'NO_QUERY': 'False',
'ENABLE_NTFY': 'False',
'QUERY_INTERVAL': '300',
'SEVERITY_THRESHOLD': '5'
}
}
# County names mapping for Romanian CNP validation
county_names = {
1: "Alba", 2: "Arad", 3: "Argeș", 4: "Bacău", 5: "Bihor", 6: "Bistrița-Năsăud",
7: "Botoșani", 8: "Brașov", 9: "Brăila", 10: "Buzău", 11: "Caraș-Severin",
12: "Cluj", 13: "Constanța", 14: "Covasna", 15: "Dâmbovița", 16: "Dolj",
17: "Galați", 18: "Gorj", 19: "Harghita", 20: "Hunedoara", 21: "Ialomița",
22: "Iași", 23: "Ilfov", 24: "Maramureș", 25: "Mehedinți", 26: "Mureș",
27: "Neamț", 28: "Olt", 29: "Prahova", 30: "Satu Mare", 31: "Sălaj",
32: "Sibiu", 33: "Suceava", 34: "Teleorman", 35: "Timiș", 36: "Tulcea",
37: "Vaslui", 38: "Vâlcea", 39: "Vrancea", 40: "București", 41: "București",
42: "București", 43: "București", 44: "București", 45: "București", 46: "București",
51: "Călărași", 52: "Giurgiu",
70: "Diaspora", 71: "Diaspora", 72: "Diaspora", 73: "Diaspora", 74: "Diaspora",
75: "Diaspora", 76: "Diaspora", 77: "Diaspora", 78: "Diaspora", 79: "Diaspora",
90: "Special", 91: "Special", 92: "Special", 93: "Special", 94: "Special",
95: "Special", 96: "Special", 97: "Special", 98: "Special", 99: "Special"
}
# Load configuration from file if it exists, otherwise use defaults
config = configparser.ConfigParser()
config.read_dict(DEFAULT_CONFIG)
try:
config.read('xrayvision.cfg')
logging.info("Configuration loaded from xrayvision.cfg")
# Check for local configuration file to override settings
local_config_files = config.read('local.cfg')
if local_config_files:
logging.debug("Local configuration loaded from local.cfg")
except Exception as e:
logging.debug("Using default configuration values")
# User roles configuration
USERS = {}
if 'users' in config:
for user in config['users']:
password, role = config.get('users', user).split(',', 1)
USERS[user.strip()] = {
'password': password.strip(),
'role': role.strip()
}
# Extract configuration values
OPENAI_URL_PRIMARY = config.get('openai', 'OPENAI_URL_PRIMARY')
OPENAI_URL_SECONDARY = config.get('openai', 'OPENAI_URL_SECONDARY')
OPENAI_API_KEY = config.get('openai', 'OPENAI_API_KEY')
NTFY_URL = config.get('notifications', 'NTFY_URL')
DASHBOARD_PORT = config.getint('dashboard', 'DASHBOARD_PORT')
AE_TITLE = config.get('dicom', 'AE_TITLE')
AE_PORT = config.getint('dicom', 'AE_PORT')
REMOTE_AE_TITLE = config.get('dicom', 'REMOTE_AE_TITLE')
REMOTE_AE_IP = config.get('dicom', 'REMOTE_AE_IP')
REMOTE_AE_PORT = config.getint('dicom', 'REMOTE_AE_PORT')
RETRIEVAL_METHOD = config.get('dicom', 'RETRIEVAL_METHOD')
FHIR_URL = config.get('fhir', 'FHIR_URL')
FHIR_USERNAME = config.get('fhir', 'FHIR_USERNAME')
FHIR_PASSWORD = config.get('fhir', 'FHIR_PASSWORD')
IMAGES_DIR = 'images'
STATIC_DIR = 'static'
DB_FILE = config.get('general', 'XRAYVISION_DB_PATH')
BACKUP_DIR = config.get('general', 'XRAYVISION_BACKUP_DIR')
MODEL_NAME = config.get('openai', 'MODEL_NAME')
SYS_PROMPT = ("""
You are an experienced emergency radiologist analyzing imaging studies.
OUTPUT FORMAT:
You must respond with ONLY valid JSON in this exact format:
{
"short": "yes" or "no",
"report": "detailed findings as a string",
"confidence": integer from 0 to 100,
"severity": integer from 0 to 10,
"summary": "diagnosis in 1-3 words"
}
CRITICAL RULES:
- Output ONLY the JSON object - no additional text, explanations, or apologies before or after
- The "short" field must be exactly "yes" or "no" (lowercase, in quotes)
- "yes" means pathological findings are present
- "no" means no significant findings detected
- The "confidence" field must be a number between 0-100 (no quotes)
- The "severity" field must be a number between 0-10 (no quotes), where 0 is normal and 10 is critical
- The "summary" field must be a brief diagnosis in 1-3 words, focusing on major category classifications (e.g., "pneumonia", "fracture", "normal", "interstitial infiltrate")
- Use double quotes for all keys and string values
- Properly escape special characters in the report string
EXAMPLES:
Example 1 - Chest X-ray with pneumonia:
Input: Chest X-ray, patient with cough and fever
Output: {"short": "yes", "report": "Consolidation in the right lower lobe consistent with pneumonia. No pleural effusion or pneumothorax. Heart size normal.", "confidence": 92, "severity": 6, "summary": "pneumonia"}
Example 2 - Normal chest X-ray:
Input: Chest X-ray, routine screening
Output: {"short": "no", "report": "Clear lung fields bilaterally. No consolidation, pleural effusion, or pneumothorax. Cardiac silhouette within normal limits. No acute bony abnormalities.", "confidence": 95, "severity": 0, "summary": "normal"}
Example 3 - Abdominal X-ray with uncertain findings:
Input: Abdominal X-ray, abdominal pain
Output: {"short": "yes", "report": "Dilated small bowel loops measuring up to 3.5 cm with air-fluid levels, concerning for possible small bowel obstruction. No free air under the diaphragm. Limited assessment of solid organs on plain film.", "confidence": 78, "severity": 7, "summary": "bowel obstruction"}
ANALYSIS APPROACH:
- Systematically examine the entire image for all abnormalities
- Report all identified lesions and pathological findings
- Be factual - if uncertain, describe what you observe without assuming
- Use professional radiological terminology
- Review the image multiple times if findings are ambiguous
REPORT CONTENT:
The "report" field should contain a complete radiological description including:
- Primary findings related to the clinical question
- Additional incidental findings or lesions
- Relevant negative findings if clinically important
SEVERITY SCORING:
- 0: Normal findings
- 1-3: Minimal abnormalities, no immediate clinical concern
- 4-6: Moderate findings requiring clinical correlation
- 7-8: Significant abnormalities requiring prompt attention
- 9-10: Critical findings requiring immediate intervention
CONFIDENCE SCORING:
- 90-100: High confidence in findings
- 70-89: Moderate confidence, some uncertainty
- 50-69: Low confidence, significant uncertainty
- 0-49: Very low confidence, speculative findings
Remember: Output ONLY the JSON object with no other text.
""")
USR_PROMPT = ("""
{question} in this {anatomy} X-ray of a {subject}?
""")
REV_PROMPT = ("""
Your previous report was incorrect. Carefully re-examine the image.
Review checklist:
- Verify each finding you previously reported
- Look for any missed abnormalities
- Reassess systematically from top to bottom
Output ONLY the JSON format. No apologies or explanations.
""")
CHK_PROMPT = ("""
You are a medical assistant analyzing radiology reports.
TASK: Read the report and extract the main pathological information in JSON format.
ANALYZE EACH SENTENCE SEPARATELY and identify any pathological findings, even if other aspects are described as normal.
OUTPUT FORMAT (JSON):
{
"pathologic": "yes/no",
"severity": 1-10,
"summary": "1-3 words"
}
RULES:
- "pathologic": "yes" if ANY pathological finding exists, otherwise "no"
- "severity": 1=minimal, 5=moderate, 10=critical/urgent
- "summary": diagnosis in 1-3 words, focusing on major category classifications (e.g., "fracture", "pneumonia", "interstitial infiltrate")
- If everything is normal: {"pathologic": "no", "severity": 0, "summary": "normal"}
- CRITICAL: Analyze each sentence separately - if ANY sentence describes a pathological finding, mark as pathologic
- Ignore spelling errors
- Note: In Romanian reports, "fără" and "fara" mean "no" or "without"
- Note: In Romanian reports, "SCD" means "costo-diaphragmatic sinuses"
- Note: In Romanian reports, "liber" means "clear" or "free"
- Respond ONLY with the JSON, without additional text
EXAMPLES:
Report: "Hazy opacity in the left mid lung field, possibly representing consolidation or infiltrate."
Response: {"pathologic": "yes", "severity": 6, "summary": "pneumonia"}
Report: "No pathological changes. Heart of normal size."
Response: {"pathologic": "no", "severity": 0, "summary": "normal"}
Report: "Fără semne de fractură sau leziuni osteolitice."
Response: {"pathologic": "no", "severity": 0, "summary": "normal"}
Report: "SCD libere, fără lichid pleural."
Response: {"pathologic": "no", "severity": 0, "summary": "normal"}
Report: "Proces de condensare paracardiac dreapta. SCD libere. Cord normal"
Response: {"pathologic": "yes", "severity": 7, "summary": "pneumonia"}
""")
ANA_PROMPT = ("""
You are a senior radiologist providing detailed analysis of radiology reports.
TASK: Perform a three-pass critical analysis of the radiology report:
FIRST PASS - Overview and Context:
- Identify the main clinical topic and purpose of the report
- Determine the primary findings and overall conclusion
SECOND PASS - Detailed Content Analysis:
- Summarize the main points and key findings
- Identify supporting evidence and clinical observations
- Evaluate if the conclusions logically follow from the findings
THIRD PASS - Critical Evaluation:
- Identify and challenge every statement and assumption
- Point out any implicit assumptions or missing information
- Evaluate potential issues with interpretations or missing citations to standard practices
OUTPUT FORMAT (JSON):
{
"first_pass": {
"topic": "main clinical topic",
"purpose": "purpose of the examination",
"primary_findings": "overall primary findings"
},
"second_pass": {
"main_points": ["key finding 1", "key finding 2"],
"supporting_evidence": ["evidence 1", "evidence 2"],
"conclusions_valid": true/false
},
"third_pass": {
"assumptions": ["assumption 1", "assumption 2"],
"missing_info": ["missing information 1", "missing information 2"],
"critique": "detailed critique of the report"
},
"overall_assessment": "overall quality and completeness assessment"
}
RULES:
- Provide detailed, professional radiological analysis
- Be factual and constructive in your critique
- Focus on clinical relevance and report quality
- Use clear, concise language
- Respond ONLY with the JSON, without additional text
- IMPORTANT: Properly escape all special characters in JSON strings, especially double quotes (") should be escaped as (\")
- Ensure all JSON keys and string values are properly quoted with double quotes
- Do not include any text before or after the JSON object
""")
TRN_PROMPT = ("""
You are a professional medical translator specializing in radiology reports.
TASK: Translate the Romanian radiology report into English.
OUTPUT FORMAT:
{
"translation": "English translation of the report"
}
RULES:
- Translate the entire report text from Romanian to English
- Maintain all medical terminology and anatomical references
- Preserve the original meaning and clinical context
- Use professional medical English terminology
- Keep the same structure and formatting as the original
- Do not add any explanations, comments, or additional text
- Respond ONLY with the JSON object containing the translation
- Ensure proper escaping of special characters in the translation string
EXAMPLES:
Romanian: "SCD libere, fără lichid pleural."
English: "Clear costo-diaphragmatic sinuses, no pleural effusion."
Romanian: "Proces de condensare paracardiac dreapta."
English: "Right paracardiac consolidation process."
Romanian: "Fără semne de fractură sau leziuni osteolitice."
English: "No signs of fracture or osteolytic lesions."
""")
# Images directory
os.makedirs(IMAGES_DIR, exist_ok=True)
# Static directory
os.makedirs(STATIC_DIR, exist_ok=True)
# Global variables
MAIN_LOOP = None # Main asyncio event loop reference
websocket_clients = set() # Set of connected WebSocket clients for dashboard updates
QUEUE_EVENT = asyncio.Event() # Event to signal when items are added to the processing queue
next_query = None # Timestamp for the next scheduled DICOM query operation
# Global variables to store the servers
dicom_server = None # DICOM server instance for receiving studies
web_server = None # Web server instance for dashboard and API
# External API health
active_openai_url = None # Currently active AI API endpoint
health_status = {
OPENAI_URL_PRIMARY: False, # Health status of primary AI endpoint
OPENAI_URL_SECONDARY: False, # Health status of secondary AI endpoint
FHIR_URL: False # Health status of FHIR endpoint
}
# AI timings
timings = {
'total': 0, # Total processing time (milliseconds)
'average': 0 # Average processing time (milliseconds)
}
# Global parameters
PAGE_SIZE = config.getint('processing', 'PAGE_SIZE') # Number of exams to display per page in the dashboard
KEEP_DICOM = config.getboolean('processing', 'KEEP_DICOM') # Whether to keep DICOM files after processing
LOAD_DICOM = config.getboolean('processing', 'LOAD_DICOM') # Whether to load existing DICOM files at startup
NO_QUERY = config.getboolean('processing', 'NO_QUERY') # Whether to disable automatic DICOM query/retrieve
ENABLE_NTFY = config.getboolean('processing', 'ENABLE_NTFY') # Whether to enable ntfy.sh notifications for positive findings
ENABLE_HIS = config.getboolean('processing', 'ENABLE_HIS') # Whether to enable HIS/FHIR integration
QUERY_INTERVAL = config.getint('processing', 'QUERY_INTERVAL') # Base interval for query/retrieve in seconds
SEVERITY_THRESHOLD = config.getint('processing', 'SEVERITY_THRESHOLD') # Severity threshold for correctness calculation
# Load region identification rules from config
REGION_RULES = {}
region_config = config['regions']
for key in region_config:
REGION_RULES[key] = [word.strip() for word in region_config[key].split(',')]
# Load region-specific questions from config
REGION_QUESTIONS = {}
question_config = config['questions']
for key in question_config:
REGION_QUESTIONS[key] = question_config[key]
# Load supported regions from config
REGIONS = []
region_config = config['supported_regions']
for key in region_config:
if config.getboolean('supported_regions', key):
REGIONS.append(key)
# Dashboard state
dashboard = {
'queue_size': 0, # Number of exams waiting in the processing queue (queued + requeue)
'check_queue_size': 0, # Number of exams queued for FHIR report checking
'processing': None, # Currently processing exam patient name
'success_count': 0, # Number of successfully processed exams in the last week
'error_count': 0, # Number of exams that failed processing
'ignore_count': 0 # Number of exams that were ignored (wrong region)
}
# Database operations
def db_init():
"""
Initialize the SQLite database with normalized tables and indexes.
Creates tables for patients, exams, AI reports, and radiologist reports.
Also creates indexes for efficient query operations.
Database Schema:
patients:
- cnp (TEXT, PRIMARY KEY): Romanian personal identification number
- id (TEXT): Patient ID from hospital system
- name (TEXT): Patient full name
- birthdate (TEXT): Patient birth date (YYYY-MM-DD format)
- sex (TEXT): Patient sex ('M', 'F', or 'O')
exams:
- uid (TEXT, PRIMARY KEY): Unique exam identifier (SOP Instance UID)
- cnp (TEXT, FOREIGN KEY): References patients.cnp
- id (TEXT): service request ID from HIS
- created (TIMESTAMP): Exam timestamp from DICOM
- protocol (TEXT): Imaging protocol name from DICOM
- region (TEXT): Anatomic region identified from protocol
- type (TEXT): Exam type/modality
- status (TEXT): Processing status ('none', 'queued', 'processing', 'done', 'error', 'ignore')
- study (TEXT): Study Instance UID
- series (TEXT): Series Instance UID
ai_reports:
- uid (TEXT, PRIMARY KEY, FOREIGN KEY): References exams.uid
- created (TIMESTAMP): Report creation timestamp (default: CURRENT_TIMESTAMP)
- updated (TIMESTAMP): Report last update timestamp (default: CURRENT_TIMESTAMP)
- text (TEXT): AI-generated report content
- positive (INTEGER): Binary indicator (-1=not assessed, 0=no findings, 1=findings)
- confidence (INTEGER): AI self-confidence score (0-100, -1 if not assessed)
- model (TEXT): Name of the model used to analyze the image
- latency (INTEGER): Time in seconds needed to analyze the image by the AI (-1 if not assessed)
rad_reports:
- uid (TEXT, PRIMARY KEY, FOREIGN KEY): References exams.uid
- id (TEXT): Diagnostic report ID from HIS
- created (TIMESTAMP): Report creation timestamp (default: CURRENT_TIMESTAMP)
- updated (TIMESTAMP): Report last update timestamp (default: CURRENT_TIMESTAMP)
- text (TEXT): Radiologist report content
- positive (INTEGER): Binary indicator (-1=not assessed, 0=no findings, 1=findings)
- severity (INTEGER): Severity score (0-10, -1 if not assessed)
- summary (TEXT): Brief summary of findings
- type (TEXT): Exam type
- radiologist (TEXT): Identifier for the radiologist
- justification (TEXT): Clinical diagnostic text
- model (TEXT): Name of the model used to summarize the radiologist report
- latency (INTEGER): Time in seconds needed by the radiologist to fill in the report (-1 if not assessed)
Indexes:
- idx_exams_status: Fast filtering by exam status
- idx_exams_region: Quick regional analysis
- idx_exams_cnp: Efficient patient lookup
- idx_patients_name: Fast patient name searches
"""
with sqlite3.connect(DB_FILE, isolation_level=None) as conn:
# Configure SQLite for concurrent access
conn.execute('PRAGMA journal_mode=WAL')
conn.execute('PRAGMA synchronous=NORMAL')
conn.execute('PRAGMA foreign_keys = ON')
conn.execute('PRAGMA cache_size = 10000')
conn.execute('PRAGMA temp_store = MEMORY')
conn.execute('PRAGMA mmap_size = 268435456') # 256MB
# Create tables within a transaction
try:
conn.execute('BEGIN IMMEDIATE')
# Patients table
conn.execute('''
CREATE TABLE IF NOT EXISTS patients (
cnp TEXT PRIMARY KEY,
id TEXT,
name TEXT,
birthdate TEXT,
sex TEXT CHECK(sex IN ('M', 'F', 'O'))
)
''')
# Exams table
conn.execute('''
CREATE TABLE IF NOT EXISTS exams (
uid TEXT PRIMARY KEY,
cnp TEXT,
id TEXT,
created TIMESTAMP,
protocol TEXT,
region TEXT,
type TEXT,
status TEXT DEFAULT 'none',
study TEXT,
series TEXT,
FOREIGN KEY (cnp) REFERENCES patients(cnp)
)
''')
# AI reports table
conn.execute('''
CREATE TABLE IF NOT EXISTS ai_reports (
uid TEXT PRIMARY KEY,
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
text TEXT,
positive INTEGER DEFAULT -1 CHECK(positive IN (-1, 0, 1)),
confidence INTEGER DEFAULT -1 CHECK(confidence BETWEEN -1 AND 100),
severity INTEGER DEFAULT -1 CHECK(severity BETWEEN -1 AND 10),
summary TEXT,
model TEXT,
latency INTEGER DEFAULT -1,
FOREIGN KEY (uid) REFERENCES exams(uid)
)
''')
# Radiologist reports table
conn.execute('''
CREATE TABLE IF NOT EXISTS rad_reports (
uid TEXT PRIMARY KEY,
id TEXT,
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
text TEXT,
text_en TEXT,
positive INTEGER DEFAULT -1 CHECK(positive IN (-1, 0, 1)),
severity INTEGER DEFAULT -1 CHECK(severity BETWEEN -1 AND 10),
summary TEXT,
type TEXT,
radiologist TEXT,
justification TEXT,
model TEXT,
latency INTEGER DEFAULT -1,
FOREIGN KEY (uid) REFERENCES exams(uid)
)
''')
# Indexes for common query filters
conn.execute('''
CREATE INDEX IF NOT EXISTS idx_exams_status
ON exams(status)
''')
conn.execute('''
CREATE INDEX IF NOT EXISTS idx_exams_region
ON exams(region)
''')
conn.execute('''
CREATE INDEX IF NOT EXISTS idx_exams_cnp
ON exams(cnp)
''')
conn.execute('''
CREATE INDEX IF NOT EXISTS idx_exams_created
ON exams(created)
''')
conn.execute('''
CREATE INDEX IF NOT EXISTS idx_exams_study
ON exams(study)
''')
conn.execute('''
CREATE INDEX IF NOT EXISTS idx_ai_reports_created
ON ai_reports(created)
''')
conn.execute('''
CREATE INDEX IF NOT EXISTS idx_rad_reports_created
ON rad_reports(created)
''')
conn.execute('''
CREATE INDEX IF NOT EXISTS idx_patients_name
ON patients(name)
''')
conn.commit()
logging.info("Initialized SQLite database with normalized schema.")
except Exception as e:
conn.rollback()
logging.error(f"Failed to initialize database: {e}")
raise
def db_execute_query(query: str, params: tuple = (), fetch_mode: str = 'all') -> Optional[list]:
"""Execute a database query and return results.
Executes a parameterized SQL query with proper transaction isolation
for concurrent operations.
Args:
query (str): SQL query to execute
params (tuple): Query parameters
fetch_mode (str): 'all', 'one', or 'none' for fetchall(), fetchone(), or no fetch
Returns:
Query results based on fetch_mode, or None on error
"""
with sqlite3.connect(DB_FILE, isolation_level=None) as conn:
# Configure SQLite for concurrent access
conn.execute('PRAGMA journal_mode=WAL')
conn.execute('PRAGMA synchronous=NORMAL')
conn.execute('PRAGMA foreign_keys = ON')
try:
cursor = conn.cursor()
cursor.execute(query, params)
if fetch_mode == 'all':
return cursor.fetchall()
elif fetch_mode == 'one':
return cursor.fetchone()
elif fetch_mode == 'none':
conn.commit()
return cursor.rowcount
except Exception as e:
conn.rollback()
return handle_error(e, "database query execution", None, raise_on_error=False)
def db_execute_query_retry(query: str, params: tuple = (), max_retries: int = 5) -> Optional[int]:
"""Execute a database query with retry logic.
Executes a database query with exponential backoff retry logic in case
of failures, with proper transaction isolation for concurrent operations.
Args:
query (str): SQL query to execute
params (tuple): Query parameters
max_retries (int): Maximum number of retry attempts
Returns:
Number of affected rows or None on error
"""
with sqlite3.connect(DB_FILE, isolation_level=None) as conn:
# Configure SQLite for concurrent access
conn.execute('PRAGMA journal_mode=WAL')
conn.execute('PRAGMA synchronous=NORMAL')
conn.execute('PRAGMA foreign_keys = ON')
for attempt in range(max_retries):
try:
conn.execute('BEGIN IMMEDIATE')
cursor = conn.cursor()
cursor.execute(query, params)
conn.commit()
return cursor.rowcount
except sqlite3.OperationalError as e:
if "database is locked" in str(e) and attempt < max_retries - 1:
# Use sync sleep for synchronous function
import time
time.sleep(0.1 * (2 ** attempt)) # Exponential backoff
continue
conn.rollback()
return handle_error(e, "database query with retry", None, raise_on_error=False)
except Exception as e:
conn.rollback()
return handle_error(e, "database query with retry", None, raise_on_error=False)
return None
# Cache for db_analyze results
_db_analyze_cache = {}
def db_analyze(table_name):
"""
Analyze a table to get its primary key and columns using PRAGMA table_info.
Args:
table_name: Name of the table to analyze
Returns:
tuple: (primary_key, columns) where primary_key is the name of the
primary key column and columns is a list of all column names
"""
# Check cache first
if table_name in _db_analyze_cache:
return _db_analyze_cache[table_name]
query = f"PRAGMA table_info({table_name})"
rows = db_execute_query(query, fetch_mode='all')
if not rows:
return None, []
primary_key = None
columns = []
for row in rows:
# row format: (cid, name, type, notnull, dflt_value, pk)
cid, name, type, notnull, dflt_value, pk = row
columns.append(name)
if pk: # pk is 1 if this column is part of the primary key
primary_key = name
# Cache the result
result = (primary_key, columns)
_db_analyze_cache[table_name] = result
return result
def db_unpack_result(result: list, keys: list) -> dict:
"""
Unpack a database result list into a dictionary using provided keys.
Args:
result: List of values from a database query result
keys: List of keys to map to the values
Returns:
dict: Dictionary with keys mapped to corresponding values
"""
if not result or not keys:
return {}
return dict(zip(keys, result))
def db_create_insert_query(table_name, *columns):
"""
Convenience function to build INSERT OR REPLACE query strings.
Args:
table_name: Name of the table to insert into
*columns: Variable number of column names
Returns:
str: Formatted SQL query string with placeholders
"""
placeholders = ', '.join(['?'] * len(columns))
columns_str = ', '.join(columns)
return f'INSERT OR REPLACE INTO {table_name} ({columns_str}) VALUES ({placeholders})'
def db_create_select_query(table_name, *columns, where=None, order_by=None, asc=True, limit=None):
"""
Convenience function to build SELECT query strings.
Args:
table_name: Name of the table to select from
*columns: Variable number of column names (use '*' for all columns)
where: Optional WHERE clause (without the WHERE keyword)
order_by: Optional column to order by
asc: Boolean indicating ascending (True) or descending (False) order
limit: Optional limit on number of rows returned
Returns:
str: Formatted SQL query string
"""
if not columns:
columns_str = '*'
else:
columns_str = ', '.join(columns)
query = f'SELECT {columns_str} FROM {table_name}'
if where:
query += f' WHERE {where}'
if order_by:
query += f' ORDER BY {order_by}'
if not asc:
query += ' DESC'
if limit:
query += f' LIMIT {limit}'
return query
def db_select(table_name, columns=None, where_clause=None, where_params=None, limit=None, order_by=None, asc=True):
"""
Convenience function to select records from a table and return as list of dictionaries.
Args:
table_name: Name of the table to select from
columns: List of column names to select (None for all columns)
where_clause: Optional WHERE clause (without the WHERE keyword)
where_params: Parameters for the WHERE clause
limit: Optional limit on number of rows returned
order_by: Optional column to order by
asc: Boolean indicating ascending (True) or descending (False) order
Returns:
list: List of dictionaries representing the selected rows
"""
# Use all columns if none specified
if columns is None:
# Get all columns from table schema
_, all_columns = db_analyze(table_name)
columns = all_columns
# Build query
query = db_create_select_query(table_name, *columns, where=where_clause, order_by=order_by, asc=asc, limit=limit)
# Execute query
params = where_params if where_params else ()
rows = db_execute_query(query, params, fetch_mode='all')
# Convert to list of dictionaries
if rows:
return [db_unpack_result(row, columns) for row in rows]
return []
def db_count(table_name, where_clause=None, where_params=None):
"""
Convenience function to count records in a table.
Args:
table_name: Name of the table to count records in
where_clause: Optional WHERE clause (without the WHERE keyword)
where_params: Parameters for the WHERE clause
Returns:
int: Number of records matching the criteria
"""
query = f"SELECT COUNT(*) FROM {table_name}"
params = ()
if where_clause:
query += f" WHERE {where_clause}"
params = where_params if where_params else ()
result = db_execute_query(query, params, fetch_mode='one')
return result[0] if result else 0
def db_update(table_name, where_clause, where_params, **kwargs):
"""
Convenience function to update records in a table.
Args:
table_name: Name of the table to update
where_clause: WHERE clause (without the WHERE keyword)
where_params: Parameters for the WHERE clause
**kwargs: Column-value pairs to update
Returns:
int: Number of rows affected
"""
if not kwargs:
return 0
# Build SET clause
set_columns = list(kwargs.keys())
set_values = list(kwargs.values())
set_clause = ', '.join([f'{col} = ?' for col in set_columns])
# Build query
query = f'UPDATE {table_name} SET {set_clause} WHERE {where_clause}'
params = set_values + list(where_params)
return db_execute_query_retry(query, tuple(params))
def db_insert(table_name, **kwargs):
"""
Convenience function to insert records into a table.
Args:
table_name: Name of the table to insert into
**kwargs: Column-value pairs to insert
Returns:
int: Number of rows affected
"""
if not kwargs:
return 0
# Build query using db_create_insert_query
columns = list(kwargs.keys())
values = list(kwargs.values())
query = db_create_insert_query(table_name, *columns)
params = tuple(values)
return db_execute_query_retry(query, params)
def db_select_one(table_name, pk_value):
"""
Convenience function to get a single record from a table using its primary key.
Args:
table_name: Name of the table to select from
pk_value: Value of the primary key to search for
Returns:
dict: Record data or None if not found
"""
# Get primary key and all columns for the table
primary_key, columns = db_analyze(table_name)
if not primary_key or not columns:
return None
# Create query using the primary key
where_clause = f"{primary_key} = ?"
query = db_create_select_query(table_name, *columns, where=where_clause)
params = (pk_value,)
result = db_execute_query(query, params, fetch_mode='one')
if result:
return db_unpack_result(result, columns)
return None
def db_add_patient(cnp, id, name, birthdate, sex):
"""
Add a new patient to the database or update existing patient information.
Args:
cnp: Romanian personal identification number (primary key)
id: Patient ID from hospital system
name: Patient full name
birthdate: Patient birth date (YYYY-MM-DD format)
sex: Patient sex ('M', 'F', or 'O')
"""
query = db_create_insert_query('patients', 'cnp', 'id', 'name', 'birthdate', 'sex')
params = (cnp, id, name, birthdate, sex)
return db_execute_query_retry(query, params)
def db_add_ai_report(uid, report_text, positive, confidence, model, latency, severity=None, summary=None):
"""
Add or update an AI report entry in the database.
Args:
uid: Exam unique identifier
report_text: AI-generated report content
positive: AI prediction result (True/False)
confidence: AI confidence score (0-100)
model: Name of the model used
latency: Processing time in seconds
severity: Severity score (0-10, -1 if not assessed)
summary: Brief summary of findings
"""
db_insert('ai_reports',
uid=uid,
text=report_text,
positive=int(positive),
confidence=confidence if confidence is not None else -1,
severity=severity if severity is not None else -1,
summary=summary,
model=model,
latency=latency)
def db_add_rad_report(uid, report_id, report_text, positive, severity, summary, report_type, radiologist, justification, model, latency, text_en=None):
"""
Add or update a radiologist report entry in the database.
Args:
uid: Exam unique identifier
report_id: HIS report ID
report_text: Radiologist report content
positive: Report positivity (-1=not assessed, 0=no findings, 1=findings)
severity: Severity score (0-10, -1 if not assessed)
summary: Brief summary of findings
report_type: Exam type
radiologist: Identifier for the radiologist
justification: Clinical diagnostic text
model: Name of the model used
latency: Processing time in seconds
text_en: English translation of the report (optional)
"""
db_insert('rad_reports',