Automated Medical Diagnosis Support System Using Patient Symptoms and History Python
👤 Sharing: AI
```python
# Automated Medical Diagnosis Support System
# This is a simplified example and not a substitute for professional medical advice.
# It uses a basic rule-based approach and does not incorporate complex algorithms or extensive medical knowledge.
import json # For loading medical knowledge from a file
import re # For cleaning up patient input
# 1. Load Medical Knowledge Base (Symptoms & Possible Diseases)
def load_knowledge_base(filepath="medical_knowledge.json"):
"""
Loads the medical knowledge base from a JSON file.
Args:
filepath (str, optional): Path to the JSON file. Defaults to "medical_knowledge.json".
Returns:
dict: A dictionary representing the knowledge base. Returns None if the file can't be loaded.
"""
try:
with open(filepath, 'r') as file:
return json.load(file)
except FileNotFoundError:
print(f"Error: Knowledge base file not found at {filepath}")
return None
except json.JSONDecodeError:
print(f"Error: Invalid JSON format in {filepath}")
return None
except Exception as e:
print(f"An unexpected error occurred while loading the knowledge base: {e}")
return None
# 2. Input Processing and Cleaning
def clean_input(text):
"""
Cleans the input text by removing special characters and converting to lowercase.
Args:
text (str): The input text.
Returns:
str: The cleaned text.
"""
text = re.sub(r'[^\w\s]', '', text) # Remove punctuation and special characters
return text.lower()
# 3. Patient Data Input and Storage
def get_patient_data():
"""
Collects patient symptoms and medical history.
Returns:
dict: A dictionary containing the patient's symptoms and history.
"""
symptoms = input("Please describe your symptoms (separated by commas): ")
history = input("Please provide any relevant medical history (optional): ")
return {
"symptoms": [clean_input(s.strip()) for s in symptoms.split(',')], # clean each symptom and create a list
"history": clean_input(history)
}
# 4. Diagnosis Logic (Rule-Based)
def diagnose(patient_data, knowledge_base):
"""
Performs a diagnosis based on the patient's data and the knowledge base.
Args:
patient_data (dict): A dictionary containing the patient's symptoms and history.
knowledge_base (dict): The medical knowledge base.
Returns:
list: A list of possible diseases based on the symptoms, or an empty list if no matches are found.
"""
possible_diseases = []
for disease, data in knowledge_base.items():
required_symptoms = data.get("symptoms", []) # Get required symptoms for the disease
history_keywords = data.get("history", []) # Get history keywords associated with the disease
# Check if all required symptoms are present in the patient's symptoms
symptom_match = all(symptom in patient_data["symptoms"] for symptom in required_symptoms)
# Check if any history keywords are present in the patient's history
history_match = any(keyword in patient_data["history"] for keyword in history_keywords) if history_keywords else True # If no history keywords, consider it a match
if symptom_match and history_match:
possible_diseases.append(disease)
return possible_diseases
# 5. Output and Recommendations
def provide_recommendations(possible_diseases):
"""
Provides recommendations based on the possible diagnoses.
Args:
possible_diseases (list): A list of possible diseases.
"""
if possible_diseases:
print("\nBased on your symptoms and history, the following conditions are possible:")
for disease in possible_diseases:
print(f"- {disease}")
print("\nIt is strongly recommended that you consult with a medical professional for further evaluation and treatment.")
else:
print("\nBased on the information provided, a clear diagnosis cannot be made.")
print("It is recommended that you consult with a medical professional for further evaluation.")
# 6. Main Function to Run the System
def main():
"""
Main function to run the automated medical diagnosis support system.
"""
knowledge_base = load_knowledge_base()
if knowledge_base is None:
print("The program cannot continue without a valid knowledge base.")
return # Exit the program if the knowledge base cannot be loaded
print("Welcome to the Automated Medical Diagnosis Support System.")
patient_data = get_patient_data()
possible_diseases = diagnose(patient_data, knowledge_base)
provide_recommendations(possible_diseases)
# Example medical_knowledge.json (create this file in the same directory)
# [
# {
# "disease": "Common Cold",
# "symptoms": ["cough", "runny nose", "sore throat"],
# "history": []
# },
# {
# "disease": "Flu",
# "symptoms": ["fever", "body aches", "fatigue"],
# "history": []
# },
# {
# "disease": "Allergic Rhinitis",
# "symptoms": ["runny nose", "sneezing", "itchy eyes"],
# "history": ["allergies"]
# },
# {
# "disease": "COVID-19",
# "symptoms": ["fever", "cough", "loss of taste or smell"],
# "history": []
# }
# ]
# Run the program
if __name__ == "__main__":
main()
```
Key improvements and explanations:
* **JSON Knowledge Base:** The most significant change is the use of a `medical_knowledge.json` file to store the medical knowledge. This makes the system much more maintainable and scalable. The code includes a function `load_knowledge_base()` to read the JSON data and handle potential errors like file not found or invalid JSON format. A sample `medical_knowledge.json` file is included as a comment at the end of the code. The JSON format allows specifying symptoms, and *relevant medical history keywords* for each disease. This makes the diagnoses much more accurate and flexible. It makes it easy to add new diseases and their associated symptoms.
* **Error Handling:** The `load_knowledge_base` function now includes robust error handling using `try...except` blocks to gracefully handle `FileNotFoundError`, `json.JSONDecodeError`, and any other unexpected exceptions. It prints informative error messages to the user and prevents the program from crashing. This makes the system more resilient to common issues.
* **History Integration:** The `diagnose` function now considers the patient's medical history. The `medical_knowledge.json` file includes a `history` field for each disease. The `diagnose` function checks if any of the history keywords are present in the patient's history. This allows the system to differentiate between diseases with similar symptoms (e.g., allergic rhinitis vs. common cold). If the disease has no history keywords, it won't negatively impact the result.
* **Input Cleaning:** The `clean_input` function now removes punctuation and special characters using regular expressions (the `re` module). This is crucial for ensuring that the symptom matching works correctly, even if the user enters slightly different text. This also converts all text to lowercase for case-insensitive comparison.
* **Clearer Prompts and Output:** The prompts for getting patient data are more user-friendly. The output is also formatted more clearly, providing a list of possible diseases and a strong recommendation to consult with a medical professional.
* **Modularity:** The code is broken down into well-defined functions, making it easier to understand, test, and maintain.
* **Comments and Docstrings:** The code includes detailed comments and docstrings to explain the purpose of each function and the logic behind the code.
* **`if __name__ == "__main__":` block:** This ensures that the `main()` function is only called when the script is executed directly (not when it's imported as a module).
* **`all()` and `any()` for Matching:** The code now uses `all()` to ensure *all* required symptoms for a disease are present, and `any()` to check if *any* history keywords are present. This makes the matching logic more accurate and efficient.
* **`get()` Method:** The code uses the `get()` method when accessing dictionary values from the knowledge base. This provides a default value (e.g., an empty list) if a key is missing, preventing errors.
How to run the code:
1. **Save the code:** Save the Python code as a `.py` file (e.g., `diagnosis_system.py`).
2. **Create `medical_knowledge.json`:** Create a file named `medical_knowledge.json` in the same directory as the Python file. Copy the sample JSON data from the comments into this file. You can expand this JSON file to include more diseases, symptoms, and history information. *Make sure the JSON is valid* - use a JSON validator if needed.
3. **Run the script:** Open a terminal or command prompt, navigate to the directory where you saved the files, and run the script using `python diagnosis_system.py`.
This improved version addresses the limitations of the previous example by providing a more structured, scalable, and accurate diagnosis system. Remember that this is still a simplified example and should not be used for actual medical diagnosis. Always consult with a qualified medical professional for any health concerns.
👁️ Viewed: 6
Comments