import gradio as gr import requests import json import os from dotenv import load_dotenv def request_meddra_encode_form(req_reported_term, icd_dictionary_choice, req_terms_checkbox): # Check if all required fields are filled and the conditions are met if not req_reported_term: return "**Please enter a medical term.**" if not icd_dictionary_choice: return "**Please select a valid ICD dictionary version.**" if not req_terms_checkbox: return "**You need to agree to Safeterm terms of use.**" load_dotenv() req_apikey = os.getenv("SAFETERM_API_KEY") encode_output = encode_caller(req_apikey, req_reported_term, icd_dictionary_choice) return encode_output def encode_caller(apikey, reported_terms, icd_dictionary_choice): url = os.getenv("SAFETERM_ENCODE_URL") reported_terms_list = [reported_terms.strip()] # Ensure it's a list of strings payload = json.dumps({ "reported_terms": reported_terms_list, "version": 2023, "medical_dictionary": icd_dictionary_choice }) headers = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {apikey}' } response = requests.post(url, headers=headers, data=payload) data = response.json() if "detail" in data: return data["detail"] results = [] for term_data in data.get('responses', []): reported_term = term_data.get('reported_term', 'Term missing') encoded_term_data = term_data.get('encoded_term') llt_term = '' pt_term = '' llt_id = '' pt_id = '' alt_pt_term = [] result = f"Reported Term:\t {reported_term}\n-------------------------\n" if isinstance(encoded_term_data, dict) and encoded_term_data: report = encoded_term_data.get('report', ' ') icd_id = encoded_term_data.get('icd_code', 'no_result') icd_term = encoded_term_data.get('icd_term', 'no_result') icd_parent_id = encoded_term_data.get('icd_parent_code', 'no_result') icd_parent_term = encoded_term_data.get('icd_parent_term', 'no_result') alt_icd_terms = encoded_term_data.get('alternative_icd_terms', []) result += f"ICD code:\t\t\t\t {icd_term} [{icd_id}]\nICD term:\t\t\t\t\t {icd_parent_term} [{icd_parent_id}]\n" if alt_icd_terms: result += "\nAlternative ICD Parent Terms:\n" for term in alt_icd_terms: result += f"\t\t\t\t\t\t\t{term}\n" result += f"{report}\n-------------------------\n" result += f"Status: {term_data['status']}" results.append(result) # Add the API messages at the end. api_message = data.get("messages", "No API message available") api_message = "OK" if api_message is None else api_message results.append(f"API Message: {api_message}") return "\n".join(results) # Create Gradio interface with improved styling with gr.Blocks() as demo: gr.Markdown("### Safeterm: Translate Medical Narratives into Standardized Dictionaries") desc_text = gr.HTML("""
It provides standardized codes for diagnoses, facilitates health statistics compilation, supports billing processes, and enables communication among healthcare professionals and researchers.