::: Rule-based logic (e.g., IF symptoms THEN Dx)
A Rule-Based Logic System (i.e., “IF symptoms THEN diagnosis”) is a classic and transparent way to build a medical diagnosis engine—especially useful for early-stage prototypes or systems that require explainability (such as for doctors, regulators, or patients).
✅ 1. Definition
A rule-based system uses IF–THEN rules to derive conclusions from inputs.
Example:
pythonIF fever AND neck_stiffness AND photophobia
THEN possible diagnosis = "Meningitis"
🧠 2. Core Components
| Component | Description |
|---|---|
| Fact base | Symptoms or patient findings (e.g., “has fever”, “has rash”) |
| Rule base | A collection of IF–THEN rules |
| Inference engine | Logic to match facts with rules and infer results |
| Explanation engine | Explains why a certain rule fired (optional but helpful in medicine) |
🔧 3. How to Build It (Python Example)
A. Define Rules:
pythonrules = [
{
"conditions": ["fever", "neck_stiffness", "photophobia"],
"diagnosis": "Meningitis"
},
{
"conditions": ["fever", "rash", "low_platelets"],
"diagnosis": "Dengue"
},
{
"conditions": ["swelling_face", "pain_maxilla"],
"diagnosis": "Maxillary Sinusitis"
}
]
B. Inference Engine:
pythondef diagnose(symptoms, rules):
for rule in rules:
if all(cond in symptoms for cond in rule["conditions"]):
return rule["diagnosis"]
return "Diagnosis unclear – consider more input"
C. Use it:
pythonuser_symptoms = ["fever", "neck_stiffness", "photophobia"]
print(diagnose(user_symptoms, rules))
# Output: Meningitis
📖 4. Rule-based Medical Systems – Classic Examples
| System | Domain | Type |
|---|---|---|
| MYCIN | Infectious disease | Rule-based expert system |
| CASNET | Glaucoma diagnosis | Rule-based |
| Internist-I | General internal medicine | Rule-based |
📘 5. Best Practice Design Tips
- Use standard terminologies: SNOMED CT, ICD-10, or UMLS codes for conditions
- Add certainty levels (e.g., “IF fever AND neck stiffness THEN 90% meningitis”)
- Use AND, OR, and NOT for logic gates
- Include severity and duration modifiers (e.g., “severe”, “chronic”)
✅ 6. Tools You Can Use
| Tool / Framework | Description |
|---|---|
| CLIPS | C language tool for rule-based systems |
| Drools (Java) | Business rule management system |
| PyKnow / Experta (Python) | Rule engines for Python |
| Prolog | Logic programming language for inference |
| Fuzzy logic systems | For soft rules (e.g., “mild”, “likely”, etc.) |
📂 7. Use Cases in Cosmetic Surgery or Facial Diagnosis
pythonIF "pain" AND "swelling" AND "recent filler injection"
THEN possible_dx = "Delayed inflammatory nodule"
IF "asymmetry" AND "no trauma" AND "onset > 1 week"
THEN possible_dx = "Facial nerve palsy"
Would you like a ready-made Python template with a GUI to test symptom inputs and get rule-based outputs? Or do you want to connect this logic to an image recognition module?Tools
ready-made Python template with a GUI
medical diagnosis system.
🩺🖥️ Python Rule-Based Diagnosis GUI (Tkinter)
pythonimport tkinter as tk
from tkinter import messagebox
# --- Define rule base ---
rules = [
{
"conditions": ["fever", "cough", "shortness of breath"],
"diagnosis": "Possible COVID-19"
},
{
"conditions": ["fever", "neck stiffness", "photophobia"],
"diagnosis": "Possible Meningitis"
},
{
"conditions": ["facial swelling", "maxillary pain", "nasal congestion"],
"diagnosis": "Possible Maxillary Sinusitis"
},
{
"conditions": ["swelling after filler", "pain", "erythema"],
"diagnosis": "Possible Delayed Filler Reaction"
}
]
# --- Diagnosis Engine ---
def diagnose(symptoms, rules):
for rule in rules:
if all(cond in symptoms for cond in rule["conditions"]):
return rule["diagnosis"]
return "Diagnosis unclear – recommend further evaluation"
# --- GUI Logic ---
def get_diagnosis():
input_text = entry.get()
symptoms = [s.strip().lower() for s in input_text.split(",")]
result = diagnose(symptoms, rules)
messagebox.showinfo("Diagnosis Result", result)
# --- GUI Layout ---
window = tk.Tk()
window.title("Rule-Based Symptom Checker")
window.geometry("500x200")
label = tk.Label(window, text="Enter symptoms (comma-separated):", font=("Arial", 12))
label.pack(pady=10)
entry = tk.Entry(window, width=60)
entry.pack()
button = tk.Button(window, text="Diagnose", command=get_diagnosis, bg="lightblue", font=("Arial", 11))
button.pack(pady=20)
window.mainloop()
🧪 How to Use
- Copy this code into a
.pyfile (e.g.,diagnosis_gui.py) - Run the file using Python 3: bashCopy code
python diagnosis_gui.py - Enter symptoms like: Copy code
fever, cough, shortness of breath
✅ You Can Easily Extend It:
- Add weight/confidence score per rule
- Connect it to image input (via
OpenCV,tkinter.filedialog) - Export diagnosis history to CSV
- Add multilanguage support (Thai, Chinese, etc.)
Would you like:
- A version with image upload for face-related conditions?
- A web-based version using
StreamlitorFlask?
Let me know how you’d like to expand this system.
image upload for face-related conditions?
Perfect — here’s an extended Python app using Tkinter + OpenCV + PIL to allow image upload for face-related medical conditions (e.g., swelling, asymmetry, post-filler complications), with basic integration into your rule-based diagnosis engine.
🖼️🧠 GUI: Rule-Based Diagnosis + Image Upload (Face-Related)
pythonimport tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image, ImageTk
import os
# --- Define basic rule base (expand as needed) ---
rules = [
{
"conditions": ["facial swelling", "pain", "post filler"],
"diagnosis": "Possible Delayed Inflammatory Nodule"
},
{
"conditions": ["facial asymmetry", "no trauma", "gradual onset"],
"diagnosis": "Possible Facial Nerve Palsy"
}
]
# --- Diagnosis Engine ---
def diagnose(symptoms, rules):
for rule in rules:
if all(cond in symptoms for cond in rule["conditions"]):
return rule["diagnosis"]
return "Diagnosis unclear – refer for further evaluation"
# --- GUI Logic ---
def select_image():
global img_label
file_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg *.png *.jpeg")])
if file_path:
image = Image.open(file_path)
image.thumbnail((250, 250))
photo = ImageTk.PhotoImage(image)
img_label.config(image=photo)
img_label.image = photo
status.set(f"Loaded image: {os.path.basename(file_path)}")
def run_diagnosis():
input_text = entry.get()
symptoms = [s.strip().lower() for s in input_text.split(",")]
result = diagnose(symptoms, rules)
messagebox.showinfo("Diagnosis Result", result)
# --- GUI Layout ---
window = tk.Tk()
window.title("Facial Diagnosis Assistant")
window.geometry("550x500")
tk.Label(window, text="Upload facial image:", font=("Arial", 12)).pack(pady=5)
tk.Button(window, text="Choose Image", command=select_image, bg="lightgray").pack()
img_label = tk.Label(window)
img_label.pack(pady=5)
status = tk.StringVar()
status.set("No image selected.")
tk.Label(window, textvariable=status, font=("Arial", 9), fg="gray").pack()
tk.Label(window, text="Enter symptoms (comma-separated):", font=("Arial", 12)).pack(pady=10)
entry = tk.Entry(window, width=60)
entry.pack()
tk.Button(window, text="Diagnose", command=run_diagnosis, bg="lightblue", font=("Arial", 11)).pack(pady=20)
window.mainloop()
📦 Requirements
Install required libraries (if not already):
bashpip install pillow opencv-python
🧪 Example Use Case:
- Upload an image of a patient’s face (e.g., post-injection swelling)
- Enter:
facial swelling, pain, post filler - Output:
Possible Delayed Inflammatory Nodule
🚀 Next Step Options
Would you like to:
- Add OpenCV face detection to highlight symmetry zones?
- Use AI (CNN) to pre-analyze the uploaded image?
- Deploy this as a web app (Streamlit or Flask)?
Let me know and I can help build the next layer for you.
