import gradio as gr import requests import time import re import threading import uvicorn import logging import os import signal import sys from typing import Dict, List, Optional, Tuple from collections import defaultdict # Import your backend modules from service_v2 import app as fastapi_app from chapter_retrieval_system_v2 import MultiCollectionChapterRetrieval # Configure logging for Spaces logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) class ICD10SearchInterface: def __init__(self, api_base_url: str = "http://127.0.0.1:8000"): """Initialize the interface with API base URL""" self.api_base_url = api_base_url.rstrip('/') self.server_ready = False self.max_retries = 30 # Increased for Spaces startup time # ICD-10 code to chapter mapping self.code_to_chapter = self._build_code_to_chapter_mapping() def _build_code_to_chapter_mapping(self) -> Dict[str, Dict[str, str]]: """Build mapping from ICD-10 code ranges to chapters""" return { # Chapter I: Certain infectious and parasitic diseases (A00-B99) "chapter_1_I": { "title": "Certain infectious and parasitic diseases", "code_ranges": ["A", "B"], "description": "Infectious diseases, parasitic diseases, and related conditions" }, # Chapter II: Neoplasms (C00-D49) "chapter_2_II": { "title": "Neoplasms", "code_ranges": ["C", "D"], "description": "Malignant neoplasms, benign neoplasms, and neoplasms of uncertain behavior" }, # Chapter III: Diseases of blood and blood-forming organs (D50-D89) "chapter_3_III": { "title": "Diseases of the blood and blood-forming organs", "code_ranges": ["D5", "D6", "D7", "D8"], "description": "Anemias, coagulation defects, and other blood disorders" }, # Chapter IV: Endocrine, nutritional and metabolic diseases (E00-E89) "chapter_4_IV": { "title": "Endocrine, nutritional and metabolic diseases", "code_ranges": ["E"], "description": "Diabetes, thyroid disorders, nutritional deficiencies, and metabolic disorders" }, # Chapter V: Mental and behavioural disorders (F01-F99) "chapter_5_V": { "title": "Mental and behavioural disorders", "code_ranges": ["F"], "description": "Mental disorders, substance abuse, and behavioral conditions" }, # Chapter VI: Diseases of the nervous system (G00-G99) "chapter_6_VI": { "title": "Diseases of the nervous system", "code_ranges": ["G"], "description": "Neurological disorders, epilepsy, migraines, and nervous system diseases" }, # Chapter VII: Diseases of the eye and adnexa (H00-H59) "chapter_7_VII": { "title": "Diseases of the eye and adnexa", "code_ranges": ["H0", "H1", "H2", "H3", "H4", "H5"], "description": "Eye diseases, visual disorders, and related conditions" }, # Chapter VIII: Diseases of the ear and mastoid process (H60-H95) "chapter_8_VIII": { "title": "Diseases of the ear and mastoid process", "code_ranges": ["H6", "H7", "H8", "H9"], "description": "Hearing disorders, ear infections, and mastoid conditions" }, # Chapter IX: Diseases of the circulatory system (I00-I99) "chapter_9_IX": { "title": "Diseases of the circulatory system", "code_ranges": ["I"], "description": "Heart disease, hypertension, stroke, and vascular disorders" }, # Chapter X: Diseases of the respiratory system (J00-J99) "chapter_10_X": { "title": "Diseases of the respiratory system", "code_ranges": ["J"], "description": "Pneumonia, asthma, COPD, and other respiratory conditions" }, # Chapter XI: Diseases of the digestive system (K00-K95) "chapter_11_XI": { "title": "Diseases of the digestive system", "code_ranges": ["K"], "description": "Gastrointestinal disorders, liver disease, and digestive conditions" }, # Chapter XII: Diseases of the skin and subcutaneous tissue (L00-L99) "chapter_12_XII": { "title": "Diseases of the skin and subcutaneous tissue", "code_ranges": ["L"], "description": "Skin infections, dermatitis, and subcutaneous tissue disorders" }, # Chapter XIII: Diseases of the musculoskeletal system (M00-M99) "chapter_13_XIII": { "title": "Diseases of the musculoskeletal system and connective tissue", "code_ranges": ["M"], "description": "Arthritis, bone disorders, muscle diseases, and connective tissue conditions" }, # Chapter XIV: Diseases of the genitourinary system (N00-N99) "chapter_14_XIV": { "title": "Diseases of the genitourinary system", "code_ranges": ["N"], "description": "Kidney disease, urinary disorders, and reproductive system conditions" }, # Chapter XV: Pregnancy, childbirth and the puerperium (O00-O9A) "chapter_15_XV": { "title": "Pregnancy, childbirth and the puerperium", "code_ranges": ["O"], "description": "Pregnancy complications, delivery issues, and postpartum conditions" }, # Chapter XVI: Certain conditions originating in the perinatal period (P00-P96) "chapter_16_XVI": { "title": "Certain conditions originating in the perinatal period", "code_ranges": ["P"], "description": "Newborn conditions and perinatal complications" }, # Chapter XVII: Congenital malformations (Q00-Q99) "chapter_17_XVII": { "title": "Congenital malformations, deformations and chromosomal abnormalities", "code_ranges": ["Q"], "description": "Birth defects and chromosomal disorders" }, # Chapter XVIII: Symptoms, signs and abnormal findings (R00-R99) "chapter_18_XVIII": { "title": "Symptoms, signs and abnormal clinical and laboratory findings", "code_ranges": ["R"], "description": "Symptoms and signs not elsewhere classified" }, # Chapter XIX: Injury, poisoning and external causes (S00-T88) "chapter_19_XIX": { "title": "Injury, poisoning and certain other consequences of external causes", "code_ranges": ["S", "T"], "description": "Injuries, poisoning, and external cause consequences" }, # Chapter XX: External causes of morbidity (V01-Y99) "chapter_20_XX": { "title": "External causes of morbidity", "code_ranges": ["V", "W", "X", "Y"], "description": "External causes of injury and poisoning" }, # Chapter XXI: Factors influencing health status (Z00-Z99) "chapter_21_XXI": { "title": "Factors influencing health status and contact with health services", "code_ranges": ["Z"], "description": "Health maintenance, screening, and healthcare encounters" } } def wait_for_server(self, max_wait_time=60): """Wait for FastAPI server to be ready with enhanced logging""" logger.info(f"Waiting for FastAPI server at {self.api_base_url}") start_time = time.time() attempt = 0 while time.time() - start_time < max_wait_time: attempt += 1 try: response = requests.get(f"{self.api_base_url}/health", timeout=10) if response.status_code == 200: self.server_ready = True logger.info(f"FastAPI server ready after {attempt} attempts ({time.time() - start_time:.1f}s)") return True else: logger.warning(f"Server returned status {response.status_code}, attempt {attempt}") except requests.exceptions.RequestException as e: if attempt % 10 == 0: # Log every 10 attempts logger.info(f"Waiting for server... attempt {attempt} ({time.time() - start_time:.1f}s)") time.sleep(2) continue logger.error(f"FastAPI server failed to start within {max_wait_time} seconds") return False def get_server_status(self) -> Tuple[bool, str]: """Get current server status for UI display""" if not self.server_ready: return False, "Server starting up..." try: response = requests.get(f"{self.api_base_url}/health", timeout=5) if response.status_code == 200: return True, "Server Ready" else: return False, f"Server Error (Status: {response.status_code})" except requests.exceptions.RequestException as e: return False, f"Connection Error: {str(e)}" def test_connection(self) -> Tuple[bool, str]: """Test if the API is accessible""" return self.get_server_status() # Keep all your existing methods (copy from original code) def extract_category_code(self, icd_code: str) -> str: """Extract the main category code from ICD-10 code (e.g., I21.0 -> I21)""" if not icd_code: return "" code = icd_code.strip().upper() match = re.match(r'^([A-Z]\d{2,3})', code) if match: return match.group(1) return code def group_codes_by_category(self, results: List[Dict]) -> Dict[str, List[Dict]]: """Group ICD-10 codes by their main category""" categories = defaultdict(list) for result in results: code = result.get('code', '') category = self.extract_category_code(code) if category: categories[category].append(result) return dict(categories) def get_category_info(self, category_code: str, codes_in_category: List[Dict]) -> Dict: """Get information about a category from its codes""" category_result = None max_score = 0 for code_info in codes_in_category: if code_info['code'] == category_code: category_result = code_info break if code_info['score'] > max_score: max_score = code_info['score'] category_result = code_info return category_result or codes_in_category[0] def get_chapter_info_for_code(self, icd_code: str) -> Optional[Dict[str, str]]: """Get chapter information for a given ICD-10 code""" if not icd_code: return None code = icd_code.strip().upper() # Check each chapter's code ranges for chapter_id, chapter_data in self.code_to_chapter.items(): for code_prefix in chapter_data["code_ranges"]: if code.startswith(code_prefix): return { "chapter_id": chapter_id, "title": chapter_data["title"], "description": chapter_data["description"] } return None def search_icd10( self, query: str, limit: int = 10, score_threshold: float = 0.3, search_mode: str = "smart", target_chapters: str = "", detailed_analysis: bool = False, chapters_per_sentence: int = 2 ) -> str: """Search ICD-10 codes using the API with enhanced error handling for Spaces""" if not query or not query.strip(): return "Please enter a diagnostic query." if not self.server_ready: return """
The FastAPI server is still initializing. Please wait a moment and try again.
This usually takes 10-30 seconds on first load.
{connection_msg}
Please refresh the page and try again.
{error_data.get('detail', 'Unknown error')}
The search is taking too long. Try reducing the limit or increasing the score threshold.
{str(e)}
{str(e)}
Results are organized by sentence and grouped by ICD-10 categories with chapter context. High-scoring codes are highlighted.
Advanced diagnostic code search with AI-powered sentence analysis
Powered by advanced semantic search and AI-driven sentence analysis
Features: Chapter context • Category descriptions • Score-based prioritization
Note: This tool is for research purposes only and should not replace professional medical diagnosis