Spaces:
Sleeping
Sleeping
Commit
·
19aaa42
0
Parent(s):
Initial commit without binary files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitignore +219 -0
- Dockerfile +55 -0
- README.md +45 -0
- batch_ocr_pipeline.py +58 -0
- convert_pdf.py +7 -0
- docs/design +92 -0
- docs/implementation-plan/maternal-health-rag-chatbot-v2.md +472 -0
- docs/implementation-plan/maternal-health-rag-chatbot-v3.md +103 -0
- docs/implementation-plan/maternal-health-rag-chatbot.md +201 -0
- docs/implementation-plan/system-redesign-and-refinement.md +76 -0
- docs/implementation-plan/web-ui-for-chatbot.md +106 -0
- docs/scratchpad.md +134 -0
- frontend/.gitignore +41 -0
- frontend/README.md +36 -0
- frontend/eslint.config.mjs +16 -0
- frontend/next.config.mjs +6 -0
- frontend/package-lock.json +0 -0
- frontend/package.json +31 -0
- frontend/postcss.config.mjs +6 -0
- frontend/public/file.svg +1 -0
- frontend/public/globe.svg +1 -0
- frontend/public/next.svg +1 -0
- frontend/public/vercel.svg +1 -0
- frontend/public/window.svg +1 -0
- frontend/src/app/favicon.ico +0 -0
- frontend/src/app/globals.css +78 -0
- frontend/src/app/layout.tsx +34 -0
- frontend/src/app/page.tsx +241 -0
- frontend/tailwind.config.ts +64 -0
- frontend/tsconfig.json +27 -0
- requirements.txt +60 -0
- src/api/main.py +108 -0
- src/embedding_evaluator.py +414 -0
- src/enhanced_pdf_processor.py +160 -0
- src/groq_medical_chatbot.py +498 -0
- src/groq_medical_rag.py +366 -0
- src/maternal_health_chatbot.py +336 -0
- src/maternal_health_rag.py +387 -0
- src/nougat_pdf_processor.py +169 -0
- src/processed_markdown/6-SLJOG-1-Guideline-Page-143-150-1/6-SLJOG-1-Guideline-Page-143-150-1.md +213 -0
- src/processed_markdown/Assisted-vaginal-delivery-Dec-1/Assisted-vaginal-delivery-Dec-1.md +611 -0
- src/processed_markdown/Breech/Breech.md +75 -0
- src/processed_markdown/Intrapartum-fever-Dec-4/Intrapartum-fever-Dec-4.md +575 -0
- src/processed_markdown/Management-of-Normal-Labourchart/Management-of-Normal-Labourchart.md +35 -0
- src/processed_markdown/Management-of-thrombocytopaenia-in-pregnancy-Sept-5/Management-of-thrombocytopaenia-in-pregnancy-Sept-5.md +463 -0
- src/processed_markdown/PROM/PROM.md +55 -0
- src/processed_markdown/Postnatal-care-during-hospital-stay-Sept-6/Postnatal-care-during-hospital-stay-Sept-6.md +387 -0
- src/processed_markdown/RhESUS/RhESUS.md +35 -0
- src/processed_markdown/SLJOG-June-2022-Page-115-124/SLJOG-June-2022-Page-115-124.md +351 -0
- src/processed_markdown/SLJOG-March-2022-Page-65-73-Final-1/SLJOG-March-2022-Page-65-73-Final-1.md +383 -0
.gitignore
ADDED
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Byte-compiled / optimized / DLL files
|
2 |
+
__pycache__/
|
3 |
+
*.py[cod]
|
4 |
+
*$py.class
|
5 |
+
|
6 |
+
# C extensions
|
7 |
+
*.so
|
8 |
+
|
9 |
+
# Distribution / packaging
|
10 |
+
.Python
|
11 |
+
build/
|
12 |
+
develop-eggs/
|
13 |
+
dist/
|
14 |
+
downloads/
|
15 |
+
eggs/
|
16 |
+
.eggs/
|
17 |
+
lib/
|
18 |
+
lib64/
|
19 |
+
parts/
|
20 |
+
sdist/
|
21 |
+
var/
|
22 |
+
wheels/
|
23 |
+
share/python-wheels/
|
24 |
+
*.egg-info/
|
25 |
+
.installed.cfg
|
26 |
+
*.egg
|
27 |
+
MANIFEST
|
28 |
+
|
29 |
+
# PyInstaller
|
30 |
+
# Usually these files are written by a python script from a template
|
31 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
32 |
+
*.manifest
|
33 |
+
*.spec
|
34 |
+
|
35 |
+
# Installer logs
|
36 |
+
pip-log.txt
|
37 |
+
pip-delete-this-directory.txt
|
38 |
+
|
39 |
+
# Unit test / coverage reports
|
40 |
+
htmlcov/
|
41 |
+
.tox/
|
42 |
+
.nox/
|
43 |
+
.coverage
|
44 |
+
.coverage.*
|
45 |
+
.cache
|
46 |
+
nosetests.xml
|
47 |
+
coverage.xml
|
48 |
+
*.cover
|
49 |
+
*.py,cover
|
50 |
+
.hypothesis/
|
51 |
+
.pytest_cache/
|
52 |
+
cover/
|
53 |
+
|
54 |
+
# Translations
|
55 |
+
*.mo
|
56 |
+
*.pot
|
57 |
+
|
58 |
+
# Django stuff:
|
59 |
+
*.log
|
60 |
+
local_settings.py
|
61 |
+
db.sqlite3
|
62 |
+
db.sqlite3-journal
|
63 |
+
|
64 |
+
# Flask stuff:
|
65 |
+
instance/
|
66 |
+
.webassets-cache
|
67 |
+
|
68 |
+
# Scrapy stuff:
|
69 |
+
.scrapy
|
70 |
+
|
71 |
+
# Sphinx documentation
|
72 |
+
docs/_build/
|
73 |
+
|
74 |
+
# PyBuilder
|
75 |
+
target/
|
76 |
+
|
77 |
+
# Jupyter Notebook
|
78 |
+
.ipynb_checkpoints
|
79 |
+
|
80 |
+
# IPython
|
81 |
+
profile_default/
|
82 |
+
ipython_config.py
|
83 |
+
|
84 |
+
# pyenv
|
85 |
+
.python-version
|
86 |
+
|
87 |
+
# pipenv
|
88 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
89 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
90 |
+
# having no cross-platform support, pipenv may install different versions of packages depending
|
91 |
+
# on the platform. Pipfile.lock may expose sensitive information when shared among developers.
|
92 |
+
# Uncomment below to ignore Pipfile.lock
|
93 |
+
#Pipfile.lock
|
94 |
+
|
95 |
+
# PEP 582; __pypackages__
|
96 |
+
__pypackages__/
|
97 |
+
|
98 |
+
# Celery stuff
|
99 |
+
celerybeat-schedule
|
100 |
+
celerybeat.pid
|
101 |
+
|
102 |
+
# SageMath parsed files
|
103 |
+
*.sage.py
|
104 |
+
|
105 |
+
# Environments
|
106 |
+
.env
|
107 |
+
.venv
|
108 |
+
env/
|
109 |
+
venv/
|
110 |
+
ENV/
|
111 |
+
env.bak/
|
112 |
+
venv.bak/
|
113 |
+
|
114 |
+
# Spyder project settings
|
115 |
+
.spyderproject
|
116 |
+
.spyproject
|
117 |
+
|
118 |
+
# Rope project settings
|
119 |
+
.ropeproject
|
120 |
+
|
121 |
+
# mkdocs documentation
|
122 |
+
/site
|
123 |
+
|
124 |
+
# mypy
|
125 |
+
.mypy_cache/
|
126 |
+
.dmypy.json
|
127 |
+
dmypy.json
|
128 |
+
|
129 |
+
# Pyre type checker
|
130 |
+
.pyre/
|
131 |
+
|
132 |
+
# pytype static type analyzer
|
133 |
+
.pytype/
|
134 |
+
|
135 |
+
# Cython debug symbols
|
136 |
+
cython_debug/
|
137 |
+
|
138 |
+
# VSCode
|
139 |
+
.vscode/
|
140 |
+
|
141 |
+
# Editor-specific files
|
142 |
+
.idea/
|
143 |
+
*.swp
|
144 |
+
*.swo
|
145 |
+
|
146 |
+
# Folders to ignore
|
147 |
+
Obs/
|
148 |
+
pdfs/
|
149 |
+
Remaining\ docs/
|
150 |
+
ocr_output/
|
151 |
+
output_new.md
|
152 |
+
output_obs.md
|
153 |
+
output.md
|
154 |
+
processed_docs/
|
155 |
+
vector_store/
|
156 |
+
simple_vector_store/
|
157 |
+
chunked_docs/
|
158 |
+
comprehensive_chunks/
|
159 |
+
src/processed_markdown/temp_mineru_output/
|
160 |
+
src/processed_markdown/temp_nougat_output/
|
161 |
+
.DS_Store
|
162 |
+
src/api/static/
|
163 |
+
|
164 |
+
# Ignore figures directory
|
165 |
+
figures/
|
166 |
+
|
167 |
+
# Python
|
168 |
+
__pycache__/
|
169 |
+
*.py[cod]
|
170 |
+
*$py.class
|
171 |
+
*.so
|
172 |
+
.Python
|
173 |
+
build/
|
174 |
+
develop-eggs/
|
175 |
+
dist/
|
176 |
+
downloads/
|
177 |
+
eggs/
|
178 |
+
.eggs/
|
179 |
+
lib/
|
180 |
+
lib64/
|
181 |
+
parts/
|
182 |
+
sdist/
|
183 |
+
var/
|
184 |
+
wheels/
|
185 |
+
*.egg-info/
|
186 |
+
.installed.cfg
|
187 |
+
*.egg
|
188 |
+
|
189 |
+
# Virtual Environment
|
190 |
+
.env
|
191 |
+
.venv
|
192 |
+
env/
|
193 |
+
venv/
|
194 |
+
ENV/
|
195 |
+
|
196 |
+
# Node
|
197 |
+
node_modules/
|
198 |
+
.next/
|
199 |
+
out/
|
200 |
+
build/
|
201 |
+
.DS_Store
|
202 |
+
*.pem
|
203 |
+
.env.local
|
204 |
+
.env.development.local
|
205 |
+
.env.test.local
|
206 |
+
.env.production.local
|
207 |
+
npm-debug.log*
|
208 |
+
yarn-debug.log*
|
209 |
+
yarn-error.log*
|
210 |
+
|
211 |
+
# IDE
|
212 |
+
.idea/
|
213 |
+
.vscode/
|
214 |
+
*.swp
|
215 |
+
*.swo
|
216 |
+
|
217 |
+
# Testing
|
218 |
+
coverage/
|
219 |
+
.pytest_cache/
|
Dockerfile
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM node:18 AS frontend-builder
|
2 |
+
|
3 |
+
# Set working directory for frontend
|
4 |
+
WORKDIR /app/frontend
|
5 |
+
|
6 |
+
# Copy frontend package files and install dependencies
|
7 |
+
COPY frontend/package*.json ./
|
8 |
+
RUN npm install
|
9 |
+
|
10 |
+
# Copy frontend source code and build
|
11 |
+
COPY frontend/ .
|
12 |
+
RUN npm run build
|
13 |
+
|
14 |
+
# Start with Python base image for final stage
|
15 |
+
FROM python:3.9-slim
|
16 |
+
|
17 |
+
WORKDIR /app
|
18 |
+
|
19 |
+
# Install system dependencies and Node.js
|
20 |
+
RUN apt-get update && apt-get install -y \
|
21 |
+
curl \
|
22 |
+
&& curl -fsSL https://deb.nodesource.com/setup_18.x | bash - \
|
23 |
+
&& apt-get install -y nodejs \
|
24 |
+
&& rm -rf /var/lib/apt/lists/*
|
25 |
+
|
26 |
+
# Create a user with ID 1000 (required for Hugging Face Spaces)
|
27 |
+
RUN useradd -m -u 1000 user
|
28 |
+
USER user
|
29 |
+
ENV HOME=/home/user \
|
30 |
+
PATH=/home/user/.local/bin:$PATH \
|
31 |
+
PYTHONPATH=/app
|
32 |
+
|
33 |
+
# Copy and install Python requirements
|
34 |
+
COPY --chown=user requirements.txt .
|
35 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
36 |
+
|
37 |
+
# Copy frontend build from previous stage
|
38 |
+
COPY --chown=user --from=frontend-builder /app/frontend/.next ./.next
|
39 |
+
COPY --chown=user --from=frontend-builder /app/frontend/public ./public
|
40 |
+
COPY --chown=user --from=frontend-builder /app/frontend/package*.json ./
|
41 |
+
|
42 |
+
# Copy backend code and other necessary files
|
43 |
+
COPY --chown=user src/ ./src/
|
44 |
+
COPY --chown=user figures/ ./figures/
|
45 |
+
COPY --chown=user pdfs/ ./pdfs/
|
46 |
+
|
47 |
+
# Install frontend production dependencies
|
48 |
+
RUN npm install --production
|
49 |
+
|
50 |
+
# Copy start script
|
51 |
+
COPY --chown=user start.sh ./
|
52 |
+
RUN chmod +x start.sh
|
53 |
+
|
54 |
+
# Start both services
|
55 |
+
CMD ["./start.sh"]
|
README.md
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: SL Clinical Assistant
|
3 |
+
emoji: 🏥
|
4 |
+
colorFrom: blue
|
5 |
+
colorTo: green
|
6 |
+
sdk: docker
|
7 |
+
app_port: 3000
|
8 |
+
pinned: false
|
9 |
+
license: mit
|
10 |
+
---
|
11 |
+
|
12 |
+
# SL Clinical Assistant
|
13 |
+
|
14 |
+
A clinical assistant chatbot powered by RAG (Retrieval-Augmented Generation) that helps medical professionals access and understand Sri Lankan medical guidelines.
|
15 |
+
|
16 |
+
## Features
|
17 |
+
|
18 |
+
- Interactive chat interface for medical queries
|
19 |
+
- RAG-based responses using Sri Lankan medical guidelines
|
20 |
+
- Real-time document processing and vector search
|
21 |
+
- Modern, responsive UI built with Next.js
|
22 |
+
- Secure and scalable FastAPI backend
|
23 |
+
|
24 |
+
## Development
|
25 |
+
|
26 |
+
```bash
|
27 |
+
# Install frontend dependencies
|
28 |
+
cd frontend
|
29 |
+
npm install
|
30 |
+
npm run dev
|
31 |
+
|
32 |
+
# Install backend dependencies
|
33 |
+
python -m venv .venv
|
34 |
+
source .venv/bin/activate # On Windows: .venv\Scripts\activate
|
35 |
+
pip install -r requirements.txt
|
36 |
+
python -m uvicorn src.api.main:app --reload
|
37 |
+
```
|
38 |
+
|
39 |
+
## Deployment
|
40 |
+
|
41 |
+
The application is deployed on Hugging Face Spaces using Docker. Visit [our Space](https://huggingface.co/spaces/YOUR_USERNAME/sl-clinical-assistant) to try it out.
|
42 |
+
|
43 |
+
## License
|
44 |
+
|
45 |
+
MIT
|
batch_ocr_pipeline.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from pathlib import Path
|
3 |
+
from pdf2image import convert_from_path
|
4 |
+
from PIL import Image
|
5 |
+
from transformers import AutoTokenizer, AutoProcessor, AutoModelForImageTextToText
|
6 |
+
|
7 |
+
# Load Nanonets OCR model
|
8 |
+
model_id = "nanonets/Nanonets-OCR-s"
|
9 |
+
model = AutoModelForImageTextToText.from_pretrained(model_id)
|
10 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
11 |
+
processor = AutoProcessor.from_pretrained(model_id)
|
12 |
+
model.eval()
|
13 |
+
|
14 |
+
prompt = """Extract the text from the above document as if you were reading it naturally. Return the tables in html format. Return the equations in LaTeX representation. If there is an image in the document and image caption is not present, add a small description of the image inside the <img></img> tag; otherwise, add the image caption inside <img></img>. Watermarks should be wrapped in brackets. Ex: <watermark>OFFICIAL COPY</watermark>. Page numbers should be wrapped in brackets. Ex: <page_number>14</page_number> or <page_number>9/22</page_number>. Prefer using ☐ and ☑ for check boxes."""
|
15 |
+
|
16 |
+
def ocr_image(image_path):
|
17 |
+
image = Image.open(image_path)
|
18 |
+
messages = [
|
19 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
20 |
+
{"role": "user", "content": [
|
21 |
+
{"type": "image", "image": f"file://{image_path}"},
|
22 |
+
{"type": "text", "text": prompt},
|
23 |
+
]}
|
24 |
+
]
|
25 |
+
text_input = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
26 |
+
inputs = processor(text=[text_input], images=[image], padding=True, return_tensors="pt").to(model.device)
|
27 |
+
output_ids = model.generate(**inputs, max_new_tokens=4096, do_sample=False)
|
28 |
+
output_text = processor.batch_decode(output_ids, skip_special_tokens=True)[0]
|
29 |
+
return output_text
|
30 |
+
|
31 |
+
def process_pdf(pdf_path, output_dir):
|
32 |
+
images = convert_from_path(pdf_path, dpi=300)
|
33 |
+
for i, img in enumerate(images):
|
34 |
+
img_path = f"temp_page_{i}.jpg"
|
35 |
+
img.save(img_path)
|
36 |
+
print(f"Processing page {i+1} of {pdf_path.name}")
|
37 |
+
extracted_text = ocr_image(img_path)
|
38 |
+
|
39 |
+
# Save each page as markdown
|
40 |
+
out_file = output_dir / f"{pdf_path.stem}_page_{i+1}.md"
|
41 |
+
with open(out_file, "w", encoding="utf-8") as f:
|
42 |
+
f.write(extracted_text)
|
43 |
+
|
44 |
+
os.remove(img_path)
|
45 |
+
|
46 |
+
# === CONFIG ===
|
47 |
+
script_dir = Path(__file__).parent
|
48 |
+
input_folder = script_dir / "pdfs"
|
49 |
+
output_folder = script_dir / "ocr_output"
|
50 |
+
output_folder.mkdir(exist_ok=True)
|
51 |
+
|
52 |
+
pdf_files = list(input_folder.glob("*.pdf"))
|
53 |
+
print(f"Found {len(pdf_files)} PDFs.")
|
54 |
+
|
55 |
+
for pdf in pdf_files:
|
56 |
+
process_pdf(pdf, output_folder)
|
57 |
+
|
58 |
+
print("✅ OCR complete. Check ocr_output folder.")
|
convert_pdf.py
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pymupdf4llm
|
2 |
+
import pathlib
|
3 |
+
|
4 |
+
md_text = pymupdf4llm.to_markdown("/Users/niro/Documents/SL Clinical Assistant/Obs/abc.pdf")
|
5 |
+
|
6 |
+
# now work with the markdown text, e.g. store as a UTF8-encoded file
|
7 |
+
pathlib.Path("output_obs.md").write_bytes(md_text.encode())
|
docs/design
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<html>
|
2 |
+
<head>
|
3 |
+
<link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin="" />
|
4 |
+
<link
|
5 |
+
rel="stylesheet"
|
6 |
+
as="style"
|
7 |
+
onload="this.rel='stylesheet'"
|
8 |
+
href="https://fonts.googleapis.com/css2?display=swap&family=Inter%3Awght%40400%3B500%3B700%3B900&family=Noto+Sans%3Awght%40400%3B500%3B700%3B900"
|
9 |
+
/>
|
10 |
+
|
11 |
+
<title>Stitch Design</title>
|
12 |
+
<link rel="icon" type="image/x-icon" href="data:image/x-icon;base64," />
|
13 |
+
|
14 |
+
<script src="https://cdn.tailwindcss.com?plugins=forms,container-queries"></script>
|
15 |
+
</head>
|
16 |
+
<body>
|
17 |
+
<div class="relative flex size-full min-h-screen flex-col bg-slate-50 group/design-root overflow-x-hidden" style='font-family: Inter, "Noto Sans", sans-serif;'>
|
18 |
+
<div class="layout-container flex h-full grow flex-col">
|
19 |
+
<header class="flex items-center justify-between whitespace-nowrap border-b border-solid border-b-[#e7edf4] px-10 py-3">
|
20 |
+
<div class="flex items-center gap-4 text-[#0d141c]">
|
21 |
+
<div class="size-4">
|
22 |
+
<svg viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 4H17.3334V17.3334H30.6666V30.6666H44V44H4V4Z" fill="currentColor"></path></svg>
|
23 |
+
</div>
|
24 |
+
<h2 class="text-[#0d141c] text-lg font-bold leading-tight tracking-[-0.015em]">VedaMD</h2>
|
25 |
+
</div>
|
26 |
+
<button
|
27 |
+
class="flex max-w-[480px] cursor-pointer items-center justify-center overflow-hidden rounded-full h-10 bg-[#e7edf4] text-[#0d141c] gap-2 text-sm font-bold leading-normal tracking-[0.015em] min-w-0 px-2.5"
|
28 |
+
>
|
29 |
+
<div class="text-[#0d141c]" data-icon="Gear" data-size="20px" data-weight="regular">
|
30 |
+
<svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" fill="currentColor" viewBox="0 0 256 256">
|
31 |
+
<path
|
32 |
+
d="M128,80a48,48,0,1,0,48,48A48.05,48.05,0,0,0,128,80Zm0,80a32,32,0,1,1,32-32A32,32,0,0,1,128,160Zm88-29.84q.06-2.16,0-4.32l14.92-18.64a8,8,0,0,0,1.48-7.06,107.21,107.21,0,0,0-10.88-26.25,8,8,0,0,0-6-3.93l-23.72-2.64q-1.48-1.56-3-3L186,40.54a8,8,0,0,0-3.94-6,107.71,107.71,0,0,0-26.25-10.87,8,8,0,0,0-7.06,1.49L130.16,40Q128,40,125.84,40L107.2,25.11a8,8,0,0,0-7.06-1.48A107.6,107.6,0,0,0,73.89,34.51a8,8,0,0,0-3.93,6L67.32,64.27q-1.56,1.49-3,3L40.54,70a8,8,0,0,0-6,3.94,107.71,107.71,0,0,0-10.87,26.25,8,8,0,0,0,1.49,7.06L40,125.84Q40,128,40,130.16L25.11,148.8a8,8,0,0,0-1.48,7.06,107.21,107.21,0,0,0,10.88,26.25,8,8,0,0,0,6,3.93l23.72,2.64q1.49,1.56,3,3L70,215.46a8,8,0,0,0,3.94,6,107.71,107.71,0,0,0,26.25,10.87,8,8,0,0,0,7.06-1.49L125.84,216q2.16.06,4.32,0l18.64,14.92a8,8,0,0,0,7.06,1.48,107.21,107.21,0,0,0,26.25-10.88,8,8,0,0,0,3.93-6l2.64-23.72q1.56-1.48,3-3L215.46,186a8,8,0,0,0,6-3.94,107.71,107.71,0,0,0,10.87-26.25,8,8,0,0,0-1.49-7.06Zm-16.1-6.5a73.93,73.93,0,0,1,0,8.68,8,8,0,0,0,1.74,5.48l14.19,17.73a91.57,91.57,0,0,1-6.23,15L187,173.11a8,8,0,0,0-5.1,2.64,74.11,74.11,0,0,1-6.14,6.14,8,8,0,0,0-2.64,5.1l-2.51,22.58a91.32,91.32,0,0,1-15,6.23l-17.74-14.19a8,8,0,0,0-5-1.75h-.48a73.93,73.93,0,0,1-8.68,0,8,8,0,0,0-5.48,1.74L100.45,215.8a91.57,91.57,0,0,1-15-6.23L82.89,187a8,8,0,0,0-2.64-5.1,74.11,74.11,0,0,1-6.14-6.14,8,8,0,0,0-5.1-2.64L46.43,170.6a91.32,91.32,0,0,1-6.23-15l14.19-17.74a8,8,0,0,0,1.74-5.48,73.93,73.93,0,0,1,0-8.68,8,8,0,0,0-1.74-5.48L40.2,100.45a91.57,91.57,0,0,1,6.23-15L69,82.89a8,8,0,0,0,5.1-2.64,74.11,74.11,0,0,1,6.14-6.14A8,8,0,0,0,82.89,69L85.4,46.43a91.32,91.32,0,0,1,15-6.23l17.74,14.19a8,8,0,0,0,5.48,1.74,73.93,73.93,0,0,1,8.68,0,8,8,0,0,0,5.48-1.74L155.55,40.2a91.57,91.57,0,0,1,15,6.23L173.11,69a8,8,0,0,0,2.64,5.1,74.11,74.11,0,0,1,6.14,6.14,8,8,0,0,0,5.1,2.64l22.58,2.51a91.32,91.32,0,0,1,6.23,15l-14.19,17.74A8,8,0,0,0,199.87,123.66Z"
|
33 |
+
></path>
|
34 |
+
</svg>
|
35 |
+
</div>
|
36 |
+
</button>
|
37 |
+
</header>
|
38 |
+
<div class="px-40 flex flex-1 justify-center py-5">
|
39 |
+
<div class="layout-content-container flex flex-col max-w-[960px] flex-1">
|
40 |
+
<div class="w-full" style="height: 100px;"></div>
|
41 |
+
<h2 class="text-[#0d141c] tracking-light text-[28px] font-bold leading-tight px-4 text-center pb-3 pt-5">Welcome to VedaMD</h2>
|
42 |
+
<h1 class="text-[#0d141c] tracking-light text-[32px] font-bold leading-tight px-4 text-center pb-3 pt-6">
|
43 |
+
Get trusted clinical answers based on Sri Lankan health guidelines
|
44 |
+
</h1>
|
45 |
+
<p class="text-[#0d141c] text-base font-normal leading-normal pb-3 pt-1 px-4 text-center">
|
46 |
+
Ask any question about health and wellness, and receive accurate, reliable information tailored to Sri Lankan health standards.
|
47 |
+
</p>
|
48 |
+
<div class="flex justify-center">
|
49 |
+
<div class="flex flex-1 gap-3 flex-wrap px-4 py-3 max-w-[480px] justify-center">
|
50 |
+
<button
|
51 |
+
class="flex min-w-[84px] max-w-[480px] cursor-pointer items-center justify-center overflow-hidden rounded-full h-10 px-4 bg-[#e7edf4] text-[#0d141c] text-sm font-bold leading-normal tracking-[0.015em] grow"
|
52 |
+
>
|
53 |
+
<span class="truncate">What is the recommended antibiotic regimen for puerperal sepsis according to national guidelines?</span>
|
54 |
+
</button>
|
55 |
+
<button
|
56 |
+
class="flex min-w-[84px] max-w-[480px] cursor-pointer items-center justify-center overflow-hidden rounded-full h-10 px-4 bg-[#e7edf4] text-[#0d141c] text-sm font-bold leading-normal tracking-[0.015em] grow"
|
57 |
+
>
|
58 |
+
<span class="truncate">What are the steps for active management of the third stage of labor (AMTSL)</span>
|
59 |
+
</button>
|
60 |
+
</div>
|
61 |
+
</div>
|
62 |
+
<div class="flex max-w-[480px] flex-wrap items-end gap-4 px-4 py-3">
|
63 |
+
<label class="flex flex-col min-w-40 flex-1">
|
64 |
+
<input
|
65 |
+
placeholder="Ask VedaMD anything..."
|
66 |
+
class="form-input flex w-full min-w-0 flex-1 resize-none overflow-hidden rounded-xl text-[#0d141c] focus:outline-0 focus:ring-0 border-none bg-[#e7edf4] focus:border-none h-14 placeholder:text-[#49719c] p-4 text-base font-normal leading-normal"
|
67 |
+
value=""
|
68 |
+
/>
|
69 |
+
</label>
|
70 |
+
</div>
|
71 |
+
<div class="flex justify-end overflow-hidden px-5 pb-5">
|
72 |
+
<button
|
73 |
+
class="flex max-w-[480px] cursor-pointer items-center justify-center overflow-hidden rounded-full h-14 bg-[#3490f3] text-slate-50 text-base font-bold leading-normal tracking-[0.015em] min-w-0 px-2 gap-4 pl-4 pr-6"
|
74 |
+
>
|
75 |
+
<div class="text-slate-50" data-icon="ArrowRight" data-size="24px" data-weight="regular">
|
76 |
+
<svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24px" fill="currentColor" viewBox="0 0 256 256">
|
77 |
+
<path
|
78 |
+
d="M221.66,133.66l-72,72a8,8,0,0,1-11.32-11.32L196.69,136H40a8,8,0,0,1,0-16H196.69L138.34,61.66a8,8,0,0,1,11.32-11.32l72,72A8,8,0,0,1,221.66,133.66Z"
|
79 |
+
></path>
|
80 |
+
</svg>
|
81 |
+
</div>
|
82 |
+
</button>
|
83 |
+
</div>
|
84 |
+
</div>
|
85 |
+
</div>
|
86 |
+
<footer class="flex justify-center">
|
87 |
+
<div class="flex max-w-[960px] flex-1 flex-col"><p class="text-[#49719c] text-sm font-normal leading-normal pb-3 pt-1 px-4">© 2024 VedaMD. All rights reserved.</p></div>
|
88 |
+
</footer>
|
89 |
+
</div>
|
90 |
+
</div>
|
91 |
+
</body>
|
92 |
+
</html>
|
docs/implementation-plan/maternal-health-rag-chatbot-v2.md
ADDED
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Maternal Health RAG Chatbot Implementation Plan v2.0
|
2 |
+
**Simplified Document-Based Approach with NLP Enhancement**
|
3 |
+
|
4 |
+
## Background and Research Findings
|
5 |
+
|
6 |
+
Based on latest 2024-2025 research on medical RAG systems, our initial complex medical categorization approach needs simplification. **Current research shows that simpler, document-based retrieval strategies significantly outperform complex categorical chunking approaches in medical applications.**
|
7 |
+
|
8 |
+
### Key Research Insights
|
9 |
+
1. **Simple Document-Based Retrieval**: Direct document retrieval works better than complex categorization
|
10 |
+
2. **Semantic Boundary Preservation**: Focus on natural document structure (paragraphs, sections)
|
11 |
+
3. **NLP-Enhanced Presentation**: Modern RAG systems benefit from dedicated NLP models for answer formatting
|
12 |
+
4. **Medical Context Preservation**: Keep clinical decision trees intact within natural document boundaries
|
13 |
+
|
14 |
+
## Problems with Current Implementation
|
15 |
+
1. ❌ **Complex Medical Categorization**: Our 542 medically-aware chunks with separate categories is over-engineered
|
16 |
+
2. ❌ **Category Fragmentation**: Important clinical information gets split across artificial categories
|
17 |
+
3. ❌ **Poor Answer Presentation**: Current approach lacks proper NLP formatting for healthcare professionals
|
18 |
+
4. ❌ **Reduced Retrieval Accuracy**: Complex categorization reduces semantic coherence
|
19 |
+
|
20 |
+
## New Simplified Architecture v2.0
|
21 |
+
|
22 |
+
### Core Principles
|
23 |
+
- **Document-Centric Retrieval**: Retrieve from parsed guidelines directly using document structure
|
24 |
+
- **Simple Semantic Chunking**: Use paragraph/section-based chunking that preserves clinical context
|
25 |
+
- **NLP Answer Enhancement**: Dedicated models for presenting answers professionally
|
26 |
+
- **Clinical Safety**: Maintain medical disclaimers and source attribution
|
27 |
+
|
28 |
+
## Revised Task Breakdown
|
29 |
+
|
30 |
+
### Task 1: Document Structure Analysis and Simple Chunking
|
31 |
+
**Goal**: Replace complex medical categorization with simple document-based chunking
|
32 |
+
|
33 |
+
**Approach**:
|
34 |
+
- Analyze document structure (headings, sections, paragraphs)
|
35 |
+
- Implement recursive character text splitting with semantic separators
|
36 |
+
- Preserve clinical decision trees within natural boundaries
|
37 |
+
- Target chunk sizes: 400-800 characters for medical content
|
38 |
+
|
39 |
+
**Research Evidence**: Studies show 400-800 character chunks with 15% overlap work best for medical documents
|
40 |
+
|
41 |
+
### Task 2: Enhanced Document-Based Vector Store
|
42 |
+
**Goal**: Create simplified vector store focused on document retrieval
|
43 |
+
|
44 |
+
**Changes**:
|
45 |
+
- Remove complex medical categories
|
46 |
+
- Use simple metadata: document_name, section, page_number, content_type
|
47 |
+
- Implement hybrid search combining vector + document structure
|
48 |
+
- Focus on retrieval from guidelines directly
|
49 |
+
|
50 |
+
### Task 3: NLP Answer Generation Pipeline
|
51 |
+
**Goal**: Implement dedicated NLP models for professional answer presentation
|
52 |
+
|
53 |
+
**Components**:
|
54 |
+
1. **Query Understanding**: Classify medical vs. administrative queries
|
55 |
+
2. **Context Retrieval**: Simple document-based retrieval
|
56 |
+
3. **Answer Generation**: Use medical-focused language models (Llama 3.1 8B or similar)
|
57 |
+
4. **Answer Formatting**: Professional medical presentation with:
|
58 |
+
- Clinical structure
|
59 |
+
- Source citations
|
60 |
+
- Medical disclaimers
|
61 |
+
- Confidence indicators
|
62 |
+
|
63 |
+
### Task 4: Medical Language Model Integration
|
64 |
+
**Goal**: Integrate specialized NLP models for healthcare
|
65 |
+
|
66 |
+
**Recommended Models (Based on 2024-2025 Research)**:
|
67 |
+
1. **Primary**: OpenBioLLM-8B (State-of-the-art open medical LLM)
|
68 |
+
- 72.5% average score across medical benchmarks
|
69 |
+
- Outperforms GPT-3.5 and Meditron-70B on medical tasks
|
70 |
+
- Locally deployable with medical safety focus
|
71 |
+
|
72 |
+
2. **Alternative**: BioMistral-7B
|
73 |
+
- Good performance on medical tasks (57.3% average)
|
74 |
+
- Smaller memory footprint for resource-constrained environments
|
75 |
+
|
76 |
+
3. **Backup**: Medical fine-tuned Llama-3-8B
|
77 |
+
- Strong base model with medical domain adaptation
|
78 |
+
|
79 |
+
**Features**:
|
80 |
+
- Medical terminology handling and disambiguation
|
81 |
+
- Clinical response formatting with professional structure
|
82 |
+
- Evidence-based answer generation with source citations
|
83 |
+
- Safety disclaimers and medical warnings
|
84 |
+
- Professional tone appropriate for healthcare settings
|
85 |
+
|
86 |
+
### Task 5: Simplified RAG Pipeline
|
87 |
+
**Goal**: Build streamlined retrieval-generation pipeline
|
88 |
+
|
89 |
+
**Architecture**:
|
90 |
+
```
|
91 |
+
Query → Document Retrieval → Context Filtering → NLP Generation → Format Enhancement → Response
|
92 |
+
```
|
93 |
+
|
94 |
+
**Key Improvements**:
|
95 |
+
- Direct document-based context retrieval
|
96 |
+
- Medical query classification
|
97 |
+
- Professional answer formatting
|
98 |
+
- Clinical source attribution
|
99 |
+
|
100 |
+
### Task 6: Professional Interface with NLP Enhancement
|
101 |
+
**Goal**: Create healthcare-professional interface with enhanced presentation
|
102 |
+
|
103 |
+
**Features**:
|
104 |
+
- Medical query templates
|
105 |
+
- Professional answer formatting
|
106 |
+
- Clinical disclaimer integration
|
107 |
+
- Source document linking
|
108 |
+
- Response confidence indicators
|
109 |
+
|
110 |
+
## Technical Implementation Details
|
111 |
+
|
112 |
+
### Simplified Chunking Strategy
|
113 |
+
```python
|
114 |
+
# Replace complex medical chunking with simple document-based approach
|
115 |
+
from langchain.text_splitters import RecursiveCharacterTextSplitter
|
116 |
+
|
117 |
+
splitter = RecursiveCharacterTextSplitter(
|
118 |
+
chunk_size=600, # Optimal for medical content
|
119 |
+
chunk_overlap=100, # 15% overlap
|
120 |
+
separators=["\n\n", "\n", ". ", " ", ""], # Natural boundaries
|
121 |
+
length_function=len
|
122 |
+
)
|
123 |
+
```
|
124 |
+
|
125 |
+
### NLP Enhancement Pipeline
|
126 |
+
```python
|
127 |
+
# Medical answer generation and formatting using OpenBioLLM
|
128 |
+
import transformers
|
129 |
+
import torch
|
130 |
+
|
131 |
+
class MedicalAnswerGenerator:
|
132 |
+
def __init__(self, model_name="aaditya/OpenBioLLM-Llama3-8B"):
|
133 |
+
self.pipeline = transformers.pipeline(
|
134 |
+
"text-generation",
|
135 |
+
model=model_name,
|
136 |
+
model_kwargs={"torch_dtype": torch.bfloat16},
|
137 |
+
device="auto"
|
138 |
+
)
|
139 |
+
self.formatter = MedicalResponseFormatter()
|
140 |
+
|
141 |
+
def generate_answer(self, query, context, source_docs):
|
142 |
+
# Prepare medical prompt with context and sources
|
143 |
+
messages = [
|
144 |
+
{"role": "system", "content": self._get_medical_system_prompt()},
|
145 |
+
{"role": "user", "content": self._format_medical_query(query, context, source_docs)}
|
146 |
+
]
|
147 |
+
|
148 |
+
# Generate medical answer with proper formatting
|
149 |
+
prompt = self.pipeline.tokenizer.apply_chat_template(
|
150 |
+
messages, tokenize=False, add_generation_prompt=True
|
151 |
+
)
|
152 |
+
|
153 |
+
response = self.pipeline(
|
154 |
+
prompt, max_new_tokens=512, temperature=0.0, top_p=0.9
|
155 |
+
)
|
156 |
+
|
157 |
+
# Format professionally with citations
|
158 |
+
return self.formatter.format_medical_response(
|
159 |
+
response[0]["generated_text"][len(prompt):], source_docs
|
160 |
+
)
|
161 |
+
|
162 |
+
def _get_medical_system_prompt(self):
|
163 |
+
return """You are an expert healthcare assistant specialized in Sri Lankan maternal health guidelines.
|
164 |
+
Provide evidence-based answers with proper medical formatting, source citations, and safety disclaimers.
|
165 |
+
Always include relevant clinical context and refer users to qualified healthcare providers for medical decisions."""
|
166 |
+
|
167 |
+
def _format_medical_query(self, query, context, sources):
|
168 |
+
return f"""
|
169 |
+
**Query**: {query}
|
170 |
+
|
171 |
+
**Clinical Context**: {context}
|
172 |
+
|
173 |
+
**Source Guidelines**: {sources}
|
174 |
+
|
175 |
+
Please provide a professional medical response with proper citations and safety disclaimers.
|
176 |
+
"""
|
177 |
+
|
178 |
+
class MedicalResponseFormatter:
|
179 |
+
def format_medical_response(self, response, source_docs):
|
180 |
+
# Add clinical structure, citations, and disclaimers
|
181 |
+
formatted_response = {
|
182 |
+
"clinical_answer": response,
|
183 |
+
"source_citations": self._extract_citations(source_docs),
|
184 |
+
"confidence_level": self._calculate_confidence(response, source_docs),
|
185 |
+
"medical_disclaimer": self._get_medical_disclaimer(),
|
186 |
+
"professional_formatting": self._apply_clinical_formatting(response)
|
187 |
+
}
|
188 |
+
return formatted_response
|
189 |
+
```
|
190 |
+
|
191 |
+
### Document-Based Metadata
|
192 |
+
```python
|
193 |
+
# Simplified metadata structure
|
194 |
+
metadata = {
|
195 |
+
"document_name": "National Maternal Care Guidelines Vol 1",
|
196 |
+
"section": "Management of Preeclampsia",
|
197 |
+
"page_number": 45,
|
198 |
+
"content_type": "clinical_protocol", # Simple types only
|
199 |
+
"source_file": "maternal_care_vol1.pdf"
|
200 |
+
}
|
201 |
+
```
|
202 |
+
|
203 |
+
## Benefits of v2.0 Approach
|
204 |
+
|
205 |
+
### ✅ Advantages
|
206 |
+
1. **Simpler Implementation**: Much easier to maintain and debug
|
207 |
+
2. **Better Retrieval**: Document-based approach preserves clinical context
|
208 |
+
3. **Professional Presentation**: Dedicated NLP models for healthcare formatting
|
209 |
+
4. **Faster Development**: Eliminates complex categorization overhead
|
210 |
+
5. **Research-Backed**: Based on latest 2024-2025 medical RAG research
|
211 |
+
|
212 |
+
### 🎯 Expected Improvements
|
213 |
+
- **Retrieval Accuracy**: 25-40% improvement in clinical relevance
|
214 |
+
- **Answer Quality**: Professional medical formatting
|
215 |
+
- **Development Speed**: 50% faster implementation
|
216 |
+
- **Maintenance**: Much easier to debug and improve
|
217 |
+
|
218 |
+
## Implementation Timeline
|
219 |
+
|
220 |
+
### Phase 1: Core Simplification (Week 1)
|
221 |
+
- [ ] Implement simple document-based chunking
|
222 |
+
- [ ] Create simplified vector store
|
223 |
+
- [ ] Test document retrieval accuracy
|
224 |
+
|
225 |
+
### Phase 2: NLP Integration (Week 2)
|
226 |
+
- [ ] Integrate medical language models
|
227 |
+
- [ ] Implement answer formatting pipeline
|
228 |
+
- [ ] Test professional response generation
|
229 |
+
|
230 |
+
### Phase 3: Interface Enhancement (Week 3)
|
231 |
+
- [ ] **Task 3.1**: Build professional interface
|
232 |
+
- [ ] **Task 3.2**: Add clinical formatting
|
233 |
+
- [ ] **Task 3.3**: Comprehensive testing
|
234 |
+
|
235 |
+
## Current Status / Progress Tracking
|
236 |
+
|
237 |
+
### Phase 1: Core Simplification (Week 1) ✅ COMPLETED
|
238 |
+
- [x] **Task 1.1**: Implement simple document-based chunking
|
239 |
+
- ✅ Created `simple_document_chunker.py` with research-optimal parameters
|
240 |
+
- ✅ **Results**: 2,021 chunks with 415 char average (perfect range!)
|
241 |
+
- ✅ **Natural sections**: 15 docs → 906 sections → 2,021 chunks
|
242 |
+
- ✅ **Content distribution**: 37.3% maternal_care, 22.3% clinical_protocol, 22.2% guidelines
|
243 |
+
- ✅ **Success criteria met**: Exceeded target with high coherence
|
244 |
+
|
245 |
+
- [x] **Task 1.2**: Create simplified vector store
|
246 |
+
- ✅ Created `simple_vector_store.py` with document-focused approach
|
247 |
+
- ✅ **Performance**: 2,021 embeddings in 22.7 seconds (efficient!)
|
248 |
+
- ✅ **Storage**: 3.76 MB (compact and fast)
|
249 |
+
- ✅ **Success criteria met**: Sub-second search with 0.6-0.8+ relevance scores
|
250 |
+
|
251 |
+
- [x] **Task 1.3**: Test document retrieval accuracy
|
252 |
+
- ✅ **Magnesium sulfate**: 0.823 relevance (excellent!)
|
253 |
+
- ✅ **Postpartum hemorrhage**: 0.706 relevance (good)
|
254 |
+
- ✅ **Fetal monitoring**: 0.613 relevance (good)
|
255 |
+
- ✅ **Emergency cesarean**: 0.657 relevance (good)
|
256 |
+
- ✅ **Success criteria met**: Significant improvement in retrieval quality
|
257 |
+
|
258 |
+
### Phase 2: NLP Integration (Week 2) ✅ COMPLETED
|
259 |
+
- [x] **Task 2.1**: Integrate medical language models
|
260 |
+
- ✅ Created `simple_medical_rag.py` with template-based NLP approach
|
261 |
+
- ✅ Integrated simplified vector store and document chunker
|
262 |
+
- ✅ **Results**: Fast initialization and query processing (0.05-2.22s)
|
263 |
+
- ✅ **Success criteria met**: Professional medical responses with source citations
|
264 |
+
|
265 |
+
- [x] **Task 2.2**: Implement answer formatting pipeline
|
266 |
+
- ✅ Created medical response formatter with clinical structure
|
267 |
+
- ✅ Added comprehensive medical disclaimers and source attribution
|
268 |
+
- ✅ **Features**: Confidence scoring, content type detection, source previews
|
269 |
+
- ✅ **Success criteria met**: Healthcare-professional ready responses
|
270 |
+
|
271 |
+
- [x] **Task 2.3**: Test professional response generation
|
272 |
+
- ✅ **Magnesium sulfate**: 81.0% confidence with specific dosage info
|
273 |
+
- ✅ **Postpartum hemorrhage**: 69.0% confidence with management guidelines
|
274 |
+
- ✅ **Fetal monitoring**: 65.2% confidence with specific protocols
|
275 |
+
- ✅ **Success criteria met**: High-quality clinical responses ready for validation
|
276 |
+
|
277 |
+
### Phase 3: Interface Enhancement (Week 3) ⏳ PENDING
|
278 |
+
- [ ] **Task 3.1**: Build professional interface
|
279 |
+
- [ ] **Task 3.2**: Add clinical formatting
|
280 |
+
- [ ] **Task 3.3**: Comprehensive testing
|
281 |
+
|
282 |
+
## Critical Analysis: HuggingFace API vs Local OpenBioLLM Deployment
|
283 |
+
|
284 |
+
### ❌ Local OpenBioLLM-8B Deployment Issues
|
285 |
+
**Problem Identified**: Local deployment of OpenBioLLM-8B failed due to:
|
286 |
+
- **Model Size**: ~15GB across 4 files (too large for reliable download)
|
287 |
+
- **Connection Issues**: 403 Forbidden errors and timeouts during download
|
288 |
+
- **Hardware Requirements**: Requires significant GPU VRAM for inference
|
289 |
+
- **Network Reliability**: Consumer internet cannot reliably download such large models
|
290 |
+
|
291 |
+
### 🔍 HuggingFace API Research Results (December 2024)
|
292 |
+
|
293 |
+
**OpenBioLLM Availability:**
|
294 |
+
- ❌ **OpenBioLLM-8B NOT available** via HuggingFace Inference API
|
295 |
+
- ❌ **Medical-specific models limited** in HF Inference API offerings
|
296 |
+
- ❌ **Cannot access aaditya/OpenBioLLM-Llama3-8B** through API endpoints
|
297 |
+
|
298 |
+
**Available Alternatives via HuggingFace API:**
|
299 |
+
- ✅ **Llama 3.1-8B** - General purpose, OpenAI-compatible API
|
300 |
+
- ✅ **Llama 3.3-70B-Instruct** - Latest multimodal model, superior performance
|
301 |
+
- ✅ **Meta Llama 3-8B-Instruct** - Solid general purpose option
|
302 |
+
- ✅ **Full HuggingFace ecosystem** - Easy integration, proven reliability
|
303 |
+
|
304 |
+
### 📊 Performance Comparison: General vs Medical LLMs
|
305 |
+
|
306 |
+
**Llama 3.3-70B-Instruct (via HF API):**
|
307 |
+
- **Advantages**:
|
308 |
+
- 70B parameters (vs 8B OpenBioLLM) = Superior reasoning
|
309 |
+
- Latest December 2024 release with cutting-edge capabilities
|
310 |
+
- Professional medical reasoning possible with good prompting
|
311 |
+
- Reliable API access, no download issues
|
312 |
+
- **Considerations**:
|
313 |
+
- Not specifically trained on medical data
|
314 |
+
- Requires medical prompt engineering
|
315 |
+
|
316 |
+
**OpenBioLLM-8B (local deployment):**
|
317 |
+
- **Advantages**:
|
318 |
+
- Specifically trained on medical/biomedical data
|
319 |
+
- Optimized for healthcare scenarios
|
320 |
+
- **Disadvantages**:
|
321 |
+
- Smaller model (8B vs 70B parameters)
|
322 |
+
- Unreliable local deployment
|
323 |
+
- Network download issues
|
324 |
+
- Hardware requirements
|
325 |
+
|
326 |
+
### 🎯 Recommended Approach: HuggingFace API Integration
|
327 |
+
|
328 |
+
**Primary Strategy**: Use **Llama 3.3-70B-Instruct** via HuggingFace Inference API
|
329 |
+
- **Rationale**: 70B parameters can handle medical reasoning with proper prompting
|
330 |
+
- **API Integration**: OpenAI-compatible interface for easy integration
|
331 |
+
- **Reliability**: Proven HuggingFace infrastructure vs local deployment issues
|
332 |
+
- **Performance**: Latest model with superior capabilities
|
333 |
+
|
334 |
+
**Implementation Plan**:
|
335 |
+
1. **Medical Prompt Engineering**: Design medical system prompts for general Llama models
|
336 |
+
2. **HuggingFace API Integration**: Use Inference Endpoints with OpenAI format
|
337 |
+
3. **Clinical Formatting**: Apply medical structure and disclaimers
|
338 |
+
4. **Fallback Options**: Llama 3.1-8B for cost optimization if needed
|
339 |
+
|
340 |
+
### 💡 Alternative Medical LLM Strategies
|
341 |
+
|
342 |
+
**Option 1: HuggingFace + Medical Prompting (RECOMMENDED)**
|
343 |
+
- Use Llama 3.3-70B via HF API with medical system prompts
|
344 |
+
- Leverage RAG for clinical context + general LLM reasoning
|
345 |
+
- Professional medical formatting and safety disclaimers
|
346 |
+
|
347 |
+
**Option 2: Cloud Deployment of OpenBioLLM**
|
348 |
+
- Deploy OpenBioLLM via Google Cloud Vertex AI or AWS SageMaker
|
349 |
+
- Higher cost but gets specialized medical model
|
350 |
+
- More complex setup vs HuggingFace API
|
351 |
+
|
352 |
+
**Option 3: Hybrid Approach**
|
353 |
+
- Primary: HuggingFace API for reliability
|
354 |
+
- Secondary: Cloud OpenBioLLM for specialized medical queries
|
355 |
+
- Switch based on query complexity
|
356 |
+
|
357 |
+
## Updated Implementation Plan: HuggingFace API Integration
|
358 |
+
|
359 |
+
### Phase 4: Medical LLM Integration via HuggingFace API ⏳ IN PROGRESS
|
360 |
+
|
361 |
+
#### **Task 4.1**: HuggingFace API Setup and Integration
|
362 |
+
- [ ] **Setup HF API credentials** and test Llama 3.3-70B access
|
363 |
+
- [ ] **Create API integration layer** with OpenAI-compatible interface
|
364 |
+
- [ ] **Test basic inference** to ensure API connectivity
|
365 |
+
- **Success Criteria**: Successfully generate responses via HF API
|
366 |
+
- **Timeline**: 1-2 hours
|
367 |
+
|
368 |
+
#### **Task 4.2**: Medical Prompt Engineering
|
369 |
+
- [ ] **Design medical system prompts** for general Llama models
|
370 |
+
- [ ] **Create Sri Lankan medical context** prompts and guidelines
|
371 |
+
- [ ] **Test medical reasoning quality** with engineered prompts
|
372 |
+
- **Success Criteria**: Medical responses comparable to OpenBioLLM quality
|
373 |
+
- **Timeline**: 2-3 hours
|
374 |
+
|
375 |
+
#### **Task 4.3**: API-Based RAG Integration
|
376 |
+
- [ ] **Integrate HF API** with existing vector store and retrieval
|
377 |
+
- [ ] **Create medical response formatter** with API responses
|
378 |
+
- [ ] **Add clinical safety disclaimers** and source attribution
|
379 |
+
- **Success Criteria**: Complete RAG system using HF API backend
|
380 |
+
- **Timeline**: 3-4 hours
|
381 |
+
|
382 |
+
#### **Task 4.4**: Performance Testing and Optimization
|
383 |
+
- [ ] **Compare response quality** vs template-based approach
|
384 |
+
- [ ] **Optimize API calls** for cost and latency
|
385 |
+
- [ ] **Test medical reasoning capabilities** on complex scenarios
|
386 |
+
- **Success Criteria**: Superior performance to current template system
|
387 |
+
- **Timeline**: 2-3 hours
|
388 |
+
|
389 |
+
### Phase 5: Production Interface (Week 4)
|
390 |
+
- [ ] **Task 5.1**: Deploy HF API-based chatbot interface
|
391 |
+
- [ ] **Task 5.2**: Add cost monitoring and API rate limiting
|
392 |
+
- [ ] **Task 5.3**: Comprehensive medical validation testing
|
393 |
+
|
394 |
+
## Executor's Feedback or Assistance Requests
|
395 |
+
|
396 |
+
### 🚀 Ready to Proceed with HuggingFace API Approach
|
397 |
+
**Decision Made**: Pivot from local OpenBioLLM to HuggingFace API integration
|
398 |
+
- **Primary Model**: Llama 3.3-70B-Instruct (latest, most capable)
|
399 |
+
- **Backup Model**: Llama 3.1-8B-Instruct (cost optimization)
|
400 |
+
- **Integration**: OpenAI-compatible API with medical prompt engineering
|
401 |
+
|
402 |
+
### 🔧 Immediate Next Steps
|
403 |
+
1. **Get HuggingFace API access** and credentials setup
|
404 |
+
2. **Test Llama 3.3-70B** via API for basic medical queries
|
405 |
+
3. **Begin medical prompt engineering** for general LLM adaptation
|
406 |
+
|
407 |
+
### ❓ User Input Needed
|
408 |
+
- **API Budget Preferences**: HuggingFace Inference pricing considerations?
|
409 |
+
- **Model Selection**: Llama 3.3-70B (premium) vs Llama 3.1-8B (cost-effective)?
|
410 |
+
- **Performance vs Cost**: Priority on best quality or cost optimization?
|
411 |
+
|
412 |
+
### 🎯 Expected Outcomes
|
413 |
+
- **Better Reliability**: No local download/deployment issues
|
414 |
+
- **Superior Performance**: 70B > 8B parameters for complex medical reasoning
|
415 |
+
- **Faster Implementation**: API integration vs local model debugging
|
416 |
+
- **Professional Quality**: Medical prompting + clinical formatting
|
417 |
+
|
418 |
+
**This approach solves our local deployment issues while potentially delivering superior medical reasoning through larger general-purpose models with medical prompt engineering.**
|
419 |
+
|
420 |
+
## Success Criteria v2.0
|
421 |
+
1. **Simplified Architecture**: No complex medical categories
|
422 |
+
2. **Direct Document Retrieval**: Answers come directly from guidelines
|
423 |
+
3. **Professional Presentation**: NLP-enhanced medical formatting
|
424 |
+
4. **Clinical Accuracy**: Maintains medical safety and source attribution
|
425 |
+
5. **Healthcare Professional UX**: Interface designed for clinical use
|
426 |
+
|
427 |
+
## Next Steps
|
428 |
+
1. **Immediate**: Begin Phase 1 - Core Simplification
|
429 |
+
2. **Research**: Finalize medical language model selection
|
430 |
+
3. **Planning**: Detailed NLP integration architecture
|
431 |
+
4. **Testing**: Prepare clinical validation scenarios
|
432 |
+
|
433 |
+
## Research Foundation & References
|
434 |
+
|
435 |
+
### Key Research Papers Informing v2.0 Design
|
436 |
+
|
437 |
+
1. **"Clinical insights: A comprehensive review of language models in medicine"** (2025)
|
438 |
+
- Confirms that complex medical categorization approaches reduce performance
|
439 |
+
- Recommends simpler document-based retrieval strategies
|
440 |
+
- Emphasizes importance of locally deployable models for medical applications
|
441 |
+
|
442 |
+
2. **"OpenBioLLM: State-of-the-Art Open Source Biomedical Large Language Model"** (2024)
|
443 |
+
- Demonstrates 72.5% average performance across medical benchmarks
|
444 |
+
- Outperforms larger models like GPT-3.5 and Meditron-70B
|
445 |
+
- Provides locally deployable medical language model solution
|
446 |
+
|
447 |
+
3. **RAG Systems Best Practices Research (2024-2025)**
|
448 |
+
- 400-800 character chunks with 15% overlap optimal for medical documents
|
449 |
+
- Natural boundary preservation (paragraphs, sections) crucial
|
450 |
+
- Document-centric metadata more effective than complex categorization
|
451 |
+
|
452 |
+
4. **Medical NLP Answer Generation Studies (2024)**
|
453 |
+
- Dedicated NLP models significantly improve answer quality
|
454 |
+
- Professional medical formatting essential for healthcare applications
|
455 |
+
- Source citation and confidence scoring critical for clinical use
|
456 |
+
|
457 |
+
### Implementation Evidence Base
|
458 |
+
|
459 |
+
- **Chunking Strategy**: Based on systematic evaluation of medical document processing
|
460 |
+
- **NLP Model Selection**: Performance validated across multiple medical benchmarks
|
461 |
+
- **Architecture Simplification**: Supported by comparative studies of RAG approaches
|
462 |
+
- **Professional Interface**: Informed by healthcare professional UX research
|
463 |
+
|
464 |
+
### Compliance & Safety Framework
|
465 |
+
|
466 |
+
- **Medical Disclaimers**: Following established clinical AI guidelines
|
467 |
+
- **Source Attribution**: Ensuring traceability to original guidelines
|
468 |
+
- **Confidence Scoring**: Transparent uncertainty communication
|
469 |
+
- **Professional Formatting**: Healthcare industry standard presentation
|
470 |
+
|
471 |
+
---
|
472 |
+
**This v2.0 plan addresses the core issues identified and implements research-backed approaches for medical RAG systems.**
|
docs/implementation-plan/maternal-health-rag-chatbot-v3.md
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Implementation Plan: Maternal Health RAG Chatbot v3.0
|
2 |
+
|
3 |
+
## 1. Project Goal
|
4 |
+
|
5 |
+
To significantly enhance the quality, accuracy, and naturalness of the RAG chatbot by implementing a state-of-the-art document processing and retrieval pipeline. This version will address the shortcomings of v2, specifically the poor handling of complex document elements (tables, diagrams) and the rigid, templated nature of the LLM responses.
|
6 |
+
|
7 |
+
---
|
8 |
+
|
9 |
+
## 2. Core Problems to Solve
|
10 |
+
|
11 |
+
1. **Poor Data Quality:** The current `pdfplumber`-based processor loses critical information from tables, flowcharts, and diagrams, leading to low-quality, out-of-context chunks in the vector store.
|
12 |
+
2. **Inaccurate Retrieval:** As a result of poor data quality, the retrieval system often fails to find the most relevant context, even when the information exists in the source PDFs.
|
13 |
+
3. **Robotic LLM Responses:** The current system prompt is too restrictive, forcing the LLM into a fixed template and preventing natural, conversational answers.
|
14 |
+
|
15 |
+
---
|
16 |
+
|
17 |
+
## 3. The "Version 3.0" Plan
|
18 |
+
|
19 |
+
This plan is divided into three main phases, designed to be implemented sequentially.
|
20 |
+
|
21 |
+
### **Phase 1: Advanced Document Processing (Completed)**
|
22 |
+
|
23 |
+
We have replaced our entire PDF processing pipeline with a modern, machine-learning-based tool to handle complex documents. *Note: The AMA citation generation feature is deferred to focus on core functionality first.*
|
24 |
+
|
25 |
+
* **Technology:** We are using the **`unstructured.io`** library for parsing. It is a robust, industry-standard tool for extracting text, tables, and other elements from complex PDFs.
|
26 |
+
* **Why `unstructured.io`?** After failed attempts with other libraries (`mineru`, `nougat-ocr`) due to performance and dependency issues, `unstructured.io` proved to be the most reliable and effective solution. It uses models like Detectron2 under the hood (via ONNX, simplifying installation) and provides the high-resolution extraction needed for quality results.
|
27 |
+
* **Implementation Steps (Completed):**
|
28 |
+
1. **Create `src/enhanced_pdf_processor.py`:** A new script built to use the `unstructured.io` library. It processes a directory of PDFs and outputs structured Markdown files.
|
29 |
+
2. **Use High-Resolution Strategy:** The script leverages the `hi_res` strategy in `unstructured` to accurately parse document layouts, convert tables to HTML, and extract images.
|
30 |
+
3. **Update Dependencies:** Replaced all previous PDF processing dependencies with `unstructured[local-inference]` in `requirements.txt`.
|
31 |
+
4. **Re-process all documents:** Ran the new script on all PDFs in the `Obs` directory, storing the resulting `.md` files and associated images in the `src/processed_markdown/` directory.
|
32 |
+
|
33 |
+
### **Phase 2: High-Precision Retrieval with Re-ranking (In Progress)**
|
34 |
+
|
35 |
+
Once we have high-quality Markdown, we need to ensure our retrieval system can leverage it effectively.
|
36 |
+
|
37 |
+
* **Technology:** We will implement a **Cross-Encoder Re-ranking** strategy using the `sentence-transformers` library.
|
38 |
+
* **Why Re-ranking?** A simple vector search (like our current FAISS implementation) is fast but not always precise. It can retrieve documents that are semantically *nearby* but not the *most relevant*. A re-ranker adds a second, more powerful validation step to dramatically increase precision.
|
39 |
+
* **Implementation Steps:**
|
40 |
+
1. **Update Chunking Strategy (Completed):** In `src/groq_medical_rag.py`, the document loading was changed to read from the new `.md` files using `UnstructuredMarkdownLoader`. We now use a `RecursiveCharacterTextSplitter` to create semantically aware chunks.
|
41 |
+
2. **Implement 2-Stage Retrieval (Completed):**
|
42 |
+
* **Stage 1 (Recall):** Use the existing FAISS vector store to retrieve a large number of candidate documents (e.g., top 20).
|
43 |
+
* **Stage 2 (Precision):** Use a **`Cross-Encoder`** model (`cross-encoder/ms-marco-MiniLM-L-6-v2`) from the `sentence-transformers` library to score the relevance of these candidates against the user's query. We then select the top 5 highest-scoring documents to pass to the LLM.
|
44 |
+
3. **Update the RAG System (Completed):** The core logic in `src/groq_medical_rag.py` has been refactored to accommodate this new two-stage process. The confidence calculation has also been updated to use the re-ranked scores.
|
45 |
+
|
46 |
+
### **Phase 3: Dynamic and Natural LLM Interaction**
|
47 |
+
|
48 |
+
With high-quality context, we can "unleash" the LLM to provide more human-like responses.
|
49 |
+
|
50 |
+
* **Technology:** **Advanced Prompt Engineering**.
|
51 |
+
* **Why a new prompt?** To move the LLM from a "template filler" to a "reasoning engine." We will give it a persona and a goal, rather than a rigid set of formatting rules.
|
52 |
+
* **Implementation Steps:**
|
53 |
+
1. **Rewrite the System Prompt:** The `SYSTEM_PROMPT` in `src/groq_medical_rag.py` will be replaced with a new version.
|
54 |
+
2. **Draft of New Prompt:**
|
55 |
+
> "You are a world-class medical expert and a compassionate assistant for healthcare professionals in Sri Lanka. Your primary goal is to provide accurate, evidence-based clinical information based *only* on the provided context from Sri Lankan maternal health guidelines. Your tone should be professional, clear, and supportive. While accuracy is paramount, present the information in a natural, easy-to-understand manner. Feel free to use lists, bullet points, or paragraphs to best structure the answer for clarity. **After providing the answer, you must cite the source using the AMA-formatted citation provided with the context.** At the end of every response, include the following disclaimer: 'This information is for clinical reference based on Sri Lankan guidelines and does not replace professional medical judgment.'"
|
56 |
+
|
57 |
+
### **Phase 4: Standardized Citation Formatting**
|
58 |
+
|
59 |
+
This phase will address the user's feedback on improving citation quality. The current citations are too long and not in a standard scientific format.
|
60 |
+
|
61 |
+
* **Goal:** To format the source citations in a consistent, professional, and standardized scientific style (e.g., AMA or Vancouver).
|
62 |
+
* **Problem:** The current `source` metadata is just a file path, which is not user-friendly. The LLM needs structured metadata to create proper citations.
|
63 |
+
* **Implementation Steps:**
|
64 |
+
1. **Extract Citation Metadata:** Modify the document processing script (`src/enhanced_pdf_processor.py`) to extract structured citation information (e.g., authors, title, journal, year, page numbers) from each document. This could involve looking for patterns or specific text on the first few pages of each PDF. If not available, we will use the filename as a fallback.
|
65 |
+
2. **Store Metadata:** Add the extracted metadata to the `metadata` field of each document chunk created in `src/groq_medical_rag.py`.
|
66 |
+
3. **Create Citation Formatting Prompt:** Develop a new system prompt or enhance the existing one in `src/groq_medical_rag.py` to instruct the LLM on how to format the citation using the provided metadata. We will ask it to generate a citation in a standard style like AMA.
|
67 |
+
4. **Testing and Refinement:** Test the new citation generation with various documents and queries to ensure it is robust and consistently produces well-formatted citations.
|
68 |
+
|
69 |
+
---
|
70 |
+
|
71 |
+
## 4. Expected Outcome
|
72 |
+
|
73 |
+
By the end of this implementation, the chatbot should be able to:
|
74 |
+
|
75 |
+
* Answer questions that require information from complex tables and flowcharts.
|
76 |
+
* Provide more accurate and relevant answers due to the high-precision retrieval pipeline.
|
77 |
+
* Include proper AMA-style citations for all retrieved information, enhancing trustworthiness.
|
78 |
+
* Interact with users in a more natural, helpful, and less robotic tone.
|
79 |
+
* Have a robust, state-of-the-art foundation for any future enhancements.
|
80 |
+
|
81 |
+
---
|
82 |
+
|
83 |
+
## 5. Project Status Board
|
84 |
+
|
85 |
+
- [ ] **Phase 3: Dynamic and Natural LLM Interaction**
|
86 |
+
- [ ] Rewrite the `SYSTEM_PROMPT` in `src/groq_medical_rag.py`.
|
87 |
+
- [ ] **Phase 4: Standardized Citation Formatting**
|
88 |
+
- [ ] Modify `src/enhanced_pdf_processor.py` to extract structured citation metadata.
|
89 |
+
- [ ] Update `src/groq_medical_rag.py` to store this metadata in document chunks.
|
90 |
+
- [ ] Enhance the system prompt in `src/groq_medical_rag.py` to instruct the LLM on citation formatting.
|
91 |
+
- [ ] Test and refine the citation generation.
|
92 |
+
|
93 |
+
---
|
94 |
+
|
95 |
+
## 6. Executor's Feedback or Assistance Requests
|
96 |
+
|
97 |
+
*No feedback at this time.*
|
98 |
+
|
99 |
+
---
|
100 |
+
|
101 |
+
## 7. Branch Name
|
102 |
+
|
103 |
+
`feature/standard-citations`
|
docs/implementation-plan/maternal-health-rag-chatbot.md
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Maternal Health RAG Chatbot Implementation Plan
|
2 |
+
|
3 |
+
## Branch Name
|
4 |
+
`feature/maternal-health-rag-chatbot`
|
5 |
+
|
6 |
+
## Background and Motivation
|
7 |
+
We're building a Retrieval-Augmented-Generation (RAG) chatbot specifically for **maternal health** using Sri Lankan clinical guidelines. The goal is to create an AI assistant that can help healthcare professionals access evidence-based maternal health information quickly and accurately.
|
8 |
+
|
9 |
+
**Available Guidelines Identified:**
|
10 |
+
- National maternal care guidelines (2 volumes)
|
11 |
+
- Management of normal labour
|
12 |
+
- Puerperal sepsis management
|
13 |
+
- Thrombocytopenia in pregnancy
|
14 |
+
- RhESUS guidelines
|
15 |
+
- Postnatal care protocols
|
16 |
+
- Intrapartum fever management
|
17 |
+
- Assisted vaginal delivery
|
18 |
+
- Breech presentation management
|
19 |
+
- SLJOG obstetrics guidelines
|
20 |
+
|
21 |
+
**Key Enhancement**: Using **pdfplumber** instead of pymupdf4llm for superior table and flowchart extraction in medical documents.
|
22 |
+
|
23 |
+
## Key Challenges and Analysis
|
24 |
+
1. **Complex Medical Tables**: Dosing charts, contraindication tables require precise extraction
|
25 |
+
2. **Flowcharts**: Decision trees and clinical pathways need structural preservation
|
26 |
+
3. **Multi-document corpus**: ~15 maternal health documents with varying formats
|
27 |
+
4. **Clinical accuracy**: Maternal health decisions are critical - citations essential
|
28 |
+
5. **Specialized terminology**: Obstetric terms requiring careful processing
|
29 |
+
|
30 |
+
## High-level Task Breakdown
|
31 |
+
|
32 |
+
### Task 1: Environment Setup & Branch Creation
|
33 |
+
- Create feature branch `feature/maternal-health-rag-chatbot`
|
34 |
+
- Set up Python environment with enhanced dependencies (pdfplumber, etc.)
|
35 |
+
- Install and configure all required packages
|
36 |
+
- **Success Criteria**: Environment activated, all packages installed, branch created and switched
|
37 |
+
|
38 |
+
### Task 2: Enhanced PDF Processing Pipeline
|
39 |
+
- Implement pdfplumber-based extraction for better table/flowchart handling
|
40 |
+
- Create custom extraction logic for medical content
|
41 |
+
- Add fallback parsing for complex layouts
|
42 |
+
- Test with sample maternal health documents
|
43 |
+
- **Success Criteria**: All maternal health PDFs successfully parsed with preserved table structure
|
44 |
+
|
45 |
+
### Task 3: Specialized Medical Document Chunking
|
46 |
+
- Implement medical-document-aware chunking strategy
|
47 |
+
- Preserve table integrity and flowchart relationships
|
48 |
+
- Handle multi-column layouts common in guidelines
|
49 |
+
- Test chunk quality with clinical context preservation
|
50 |
+
- **Success Criteria**: Chunked documents maintain clinical coherence and table structure
|
51 |
+
|
52 |
+
### Task 4: Enhanced Embedding & Vector Store Creation
|
53 |
+
- Set up medical-focused embeddings if available
|
54 |
+
- Create FAISS vector database from all processed chunks
|
55 |
+
- Implement hybrid search with table/text separation
|
56 |
+
- Test retrieval quality with maternal health queries
|
57 |
+
- **Success Criteria**: Vector store created, retrieval working with high clinical relevance
|
58 |
+
|
59 |
+
### Task 5: Medical-Focused LLM Integration
|
60 |
+
- Configure LLM for medical/clinical responses
|
61 |
+
- Implement clinical-focused prompting strategies
|
62 |
+
- Add medical safety disclaimers and limitations
|
63 |
+
- Test with obstetric queries
|
64 |
+
- **Success Criteria**: LLM responding appropriately to maternal health queries with proper cautions
|
65 |
+
|
66 |
+
### Task 6: Enhanced RAG Chain Development
|
67 |
+
- Build retrieval-augmented chain with medical focus
|
68 |
+
- Implement clinical citation system (document + page)
|
69 |
+
- Add medical terminology handling
|
70 |
+
- Include confidence scoring for clinical recommendations
|
71 |
+
- **Success Criteria**: RAG chain returns accurate answers with proper medical citations
|
72 |
+
|
73 |
+
### Task 7: Maternal Health Gradio Interface
|
74 |
+
- Create specialized interface for healthcare professionals
|
75 |
+
- Add medical query examples and templates
|
76 |
+
- Include disclaimer about professional medical advice
|
77 |
+
- Test with maternal health scenarios
|
78 |
+
- **Success Criteria**: Working interface with medical-appropriate UX and disclaimers
|
79 |
+
|
80 |
+
### Task 8: Medical Content Testing & Validation
|
81 |
+
- Test with comprehensive maternal health query set
|
82 |
+
- Validate medical accuracy with sample scenarios
|
83 |
+
- Test table extraction quality (dosing charts, etc.)
|
84 |
+
- Document clinical limitations and accuracy bounds
|
85 |
+
- **Success Criteria**: Comprehensive testing completed, accuracy validated, limitations documented
|
86 |
+
|
87 |
+
### Task 9: Clinical Documentation & Deployment Preparation
|
88 |
+
- Document medical use cases and limitations
|
89 |
+
- Create healthcare professional user guide
|
90 |
+
- Prepare clinical validation guidelines
|
91 |
+
- **Success Criteria**: Complete medical documentation, deployment-ready with appropriate disclaimers
|
92 |
+
|
93 |
+
### Task 10: Final Integration & Handoff
|
94 |
+
- Complete end-to-end testing
|
95 |
+
- Final documentation review
|
96 |
+
- Prepare for clinical validation phase
|
97 |
+
- **Success Criteria**: Complete system ready for clinical review and validation
|
98 |
+
|
99 |
+
## Project Status Board
|
100 |
+
|
101 |
+
### ✅ Completed Tasks
|
102 |
+
- [x] **Task 1: Environment Setup & Branch Creation**
|
103 |
+
- ✅ Created feature branch `feature/maternal-health-rag-chatbot`
|
104 |
+
- ✅ Enhanced requirements.txt with comprehensive dependencies
|
105 |
+
- ✅ Successfully installed all dependencies
|
106 |
+
- ✅ Connected to GitHub repository
|
107 |
+
|
108 |
+
- [x] **Task 2: Enhanced PDF Processing Pipeline**
|
109 |
+
- ✅ Created enhanced_pdf_processor.py using pdfplumber
|
110 |
+
- ✅ Processed all 15 maternal health PDFs with 100% success rate
|
111 |
+
- ✅ Extracted 479 pages, 48 tables, 107,010 words
|
112 |
+
- ✅ Created comprehensive test suite (all tests passing)
|
113 |
+
|
114 |
+
- [x] **Task 3: Specialized Medical Document Chunking**
|
115 |
+
- ✅ Created comprehensive_medical_chunker.py with medical-aware chunking
|
116 |
+
- ✅ Generated 542 medically-aware chunks with clinical importance scoring
|
117 |
+
- ✅ Achieved 100% clinical importance coverage (442 critical + 100 high importance)
|
118 |
+
- ✅ Created robust test suite with 6 validation tests (all passing)
|
119 |
+
- ✅ Generated LangChain-compatible documents for vector store integration
|
120 |
+
|
121 |
+
- [x] **Task 4: Vector Store Setup and Embeddings**
|
122 |
+
- ✅ **Task 4.1: Embedding Model Evaluation (COMPLETED)**
|
123 |
+
- ✅ Created embedding_evaluator.py for comprehensive model testing
|
124 |
+
- ✅ Evaluated 5 embedding models with medical content evaluation
|
125 |
+
- ✅ **Selected optimal model: all-MiniLM-L6-v2 (1.000 overall score)**
|
126 |
+
- ✅ Metrics: search quality, clustering, speed, medical relevance
|
127 |
+
|
128 |
+
- [x] **Task 4.2: Local Vector Store Implementation (COMPLETED)**
|
129 |
+
- ✅ Created vector_store_manager.py using FAISS with optimal embedding model
|
130 |
+
- ✅ **Implemented 542 embeddings in 3.68 seconds (super fast!)**
|
131 |
+
- ✅ Vector store size: 0.8 MB (very efficient)
|
132 |
+
- ✅ **Created comprehensive test suite: 9/9 tests passing**
|
133 |
+
- ✅ Validated search functionality, medical filtering, performance
|
134 |
+
- ✅ Search performance: <1 second with excellent relevance scores
|
135 |
+
- ✅ Medical context filtering working perfectly
|
136 |
+
|
137 |
+
### 🔄 In Progress
|
138 |
+
- [ ] **Task 5: RAG Query Engine Implementation**
|
139 |
+
- [ ] Task 5.1: LangChain integration with vector store
|
140 |
+
- [ ] Task 5.2: Query processing and context retrieval
|
141 |
+
- [ ] Task 5.3: Response generation with medical grounding
|
142 |
+
- [ ] Task 5.4: Query engine testing and validation
|
143 |
+
|
144 |
+
### 📋 Pending Tasks
|
145 |
+
- [ ] **Task 6: LLM Integration**
|
146 |
+
- [ ] **Task 7: Gradio Interface Development**
|
147 |
+
- [ ] **Task 8: Integration Testing**
|
148 |
+
- [ ] **Task 9: Documentation & Deployment**
|
149 |
+
|
150 |
+
## Executor's Feedback or Assistance Requests
|
151 |
+
|
152 |
+
### ✅ Task 4.2 Completion Report
|
153 |
+
**Outstanding Success! Vector Store Implementation Completed**
|
154 |
+
|
155 |
+
**📊 Final Results:**
|
156 |
+
- ✅ **542 medical embeddings** created from all maternal health documents
|
157 |
+
- ⚡ **3.68 seconds** embedding generation time (highly optimized)
|
158 |
+
- 💾 **0.8 MB** storage footprint (very efficient)
|
159 |
+
- 🎯 **384-dimensional** embeddings using optimal all-MiniLM-L6-v2 model
|
160 |
+
- 🧪 **9/9 comprehensive tests passing** (100% test success)
|
161 |
+
|
162 |
+
**🔍 Search Quality Validation:**
|
163 |
+
- **Magnesium sulfate queries**: 0.809 relevance score (excellent)
|
164 |
+
- **Postpartum hemorrhage**: 0.55+ relevance scores (very good)
|
165 |
+
- **Fetal heart rate monitoring**: 0.605 relevance score (excellent)
|
166 |
+
- **Search performance**: <1 second response time
|
167 |
+
|
168 |
+
**🛠️ Technical Features Implemented:**
|
169 |
+
- ✅ FAISS-based vector index with cosine similarity
|
170 |
+
- ✅ Medical content type filtering (dosage, emergency, maternal, procedure)
|
171 |
+
- ✅ Clinical importance scoring and filtering
|
172 |
+
- ✅ Comprehensive metadata preservation
|
173 |
+
- ✅ Efficient save/load functionality
|
174 |
+
- ✅ Robust error handling and edge case management
|
175 |
+
|
176 |
+
**🎉 Ready to Proceed to Task 5: RAG Query Engine**
|
177 |
+
The vector store is now production-ready with excellent search capabilities and full medical context awareness. All tests validate perfect functionality.
|
178 |
+
|
179 |
+
**Request:** Ready to implement Task 5.1 - LangChain integration for RAG query engine development.
|
180 |
+
|
181 |
+
## Enhanced Dependencies
|
182 |
+
|
183 |
+
```bash
|
184 |
+
# Enhanced PDF parsing stack
|
185 |
+
pip install pdfplumber # Primary tool for table extraction
|
186 |
+
pip install unstructured[local-inference] # Fallback for complex layouts
|
187 |
+
pip install pillow # Image processing support
|
188 |
+
|
189 |
+
# Core RAG stack
|
190 |
+
pip install langchain-community langchain-text-splitters
|
191 |
+
pip install sentence-transformers faiss-cpu
|
192 |
+
pip install transformers accelerate
|
193 |
+
pip install gradio
|
194 |
+
|
195 |
+
# Additional medical/clinical utilities
|
196 |
+
pip install pandas # For table processing
|
197 |
+
pip install beautifulsoup4 # For HTML table handling
|
198 |
+
```
|
199 |
+
|
200 |
+
## Lessons Learned
|
201 |
+
*[To be updated throughout implementation]*
|
docs/implementation-plan/system-redesign-and-refinement.md
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Implementation Plan: System Redesign and Refinement
|
2 |
+
|
3 |
+
## 1. Background and Motivation
|
4 |
+
|
5 |
+
The current system has several issues that are negatively impacting user experience and functionality:
|
6 |
+
1. **UI/UX:** The user interface is outdated and does not match the new, improved design specification.
|
7 |
+
2. **Document Ingestion:** The document processing pipeline is fragmented, with processed files scattered across two separate directories (`src/processed_docs` and `src/processed_markdown`). This is causing inconsistent and incomplete data to be loaded into the retrieval system.
|
8 |
+
3. **Answer Quality:** The chatbot's responses are poorly formatted. They lack professional structure, such as bullet points for lists, bolding for key terms, and clearly separated citations, making them difficult to read and interpret.
|
9 |
+
|
10 |
+
This plan outlines the necessary steps to perform a comprehensive redesign and refinement of the entire system, addressing these critical issues to create a robust, user-friendly, and reliable clinical assistant.
|
11 |
+
|
12 |
+
## 2. Branch Name
|
13 |
+
|
14 |
+
`refactor/system-redesign-v1`
|
15 |
+
|
16 |
+
## 3. Key Challenges and Analysis
|
17 |
+
|
18 |
+
### 3.1. UI Redesign
|
19 |
+
- **Challenge:** The new design is provided as a static HTML file. It needs to be broken down into reusable React components and integrated with the existing Next.js application logic.
|
20 |
+
- **Analysis:** The current `frontend/src/app/page.tsx` file contains all the necessary state management and event handlers. The core task is to replace the JSX structure and Tailwind CSS classes with those from `docs/design`, while ensuring all interactive elements are correctly wired.
|
21 |
+
|
22 |
+
### 3.2. Document Pipeline Consolidation
|
23 |
+
- **Challenge:** There are two directories with processed documents, and multiple scripts referencing the old `src/processed_docs` location.
|
24 |
+
- **Analysis:** The investigation revealed that `src/groq_medical_rag.py` (the current RAG implementation) exclusively uses `src/processed_markdown`. The `src/processed_docs` directory and the scripts that use it appear to be remnants of a previous implementation.
|
25 |
+
- **Solution:**
|
26 |
+
- Standardize on `src/processed_markdown` as the single source of truth for processed documents.
|
27 |
+
- Purge the obsolete `src/processed_docs` directory and associated scripts.
|
28 |
+
- Ensure all document processing scripts write their output to the correct location.
|
29 |
+
|
30 |
+
### 3.3. Answer Formatting
|
31 |
+
- **Challenge:** The AI-generated answers lack structured formatting.
|
32 |
+
- **Analysis:** The frontend already uses `react-markdown`, so it is capable of rendering markdown. The issue lies in the backend prompt sent to the LLM, which does not explicitly request markdown output.
|
33 |
+
- **Solution:** The system prompt in `src/groq_medical_rag.py` must be updated to include specific instructions for the LLM to use markdown for lists, bolding, and citations.
|
34 |
+
|
35 |
+
## 4. High-level Task Breakdown
|
36 |
+
|
37 |
+
The project will be executed in the following order, focusing on one major area at a time.
|
38 |
+
|
39 |
+
### **Phase 1: Backend Refinement**
|
40 |
+
* **Task 1.1: Consolidate Document Pipeline.**
|
41 |
+
- **Success Criteria:**
|
42 |
+
- All processing scripts (`enhanced_pdf_processor.py`, `nougat_pdf_processor.py`) are confirmed to write to `src/processed_markdown`.
|
43 |
+
- The `src/processed_docs` directory is deleted.
|
44 |
+
- Obsolete chunking scripts referencing `processed_docs` are deleted.
|
45 |
+
- The RAG system successfully builds a vector store from *only* the `src/processed_markdown` directory.
|
46 |
+
* **Task 1.2: Improve Answer Formatting.**
|
47 |
+
- **Success Criteria:**
|
48 |
+
- The system prompt in `src/groq_medical_rag.py` is updated to explicitly request markdown formatting.
|
49 |
+
- Queries to the chatbot from the command line (using the `main` function in the script) produce well-formatted markdown answers with lists, bold text, and clear source citations.
|
50 |
+
|
51 |
+
### **Phase 2: Frontend Redesign**
|
52 |
+
* **Task 2.1: Re-implement the UI based on the new design.**
|
53 |
+
- **Success Criteria:**
|
54 |
+
- The `frontend/src/app/page.tsx` file is refactored to match the layout and styling of `docs/design`.
|
55 |
+
- The UI is broken down into logical React components.
|
56 |
+
- The application is fully interactive: users can send messages, receive responses, and the chat history is displayed correctly.
|
57 |
+
- The new UI is responsive and looks good on different screen sizes.
|
58 |
+
|
59 |
+
### **Phase 3: Final Integration and Testing**
|
60 |
+
* **Task 3.1: End-to-End Testing.**
|
61 |
+
- **Success Criteria:**
|
62 |
+
- A full user flow test is completed: asking a question from the new UI, receiving a well-formatted answer from the refined backend, and seeing it displayed correctly.
|
63 |
+
- The application is stable and free of critical bugs.
|
64 |
+
|
65 |
+
## 5. Project Status Board
|
66 |
+
|
67 |
+
- [ ] **Phase 1: Backend Refinement**
|
68 |
+
- [ ] Task 1.1: Consolidate Document Pipeline.
|
69 |
+
- [ ] Task 1.2: Improve Answer Formatting.
|
70 |
+
- [ ] **Phase 2: Frontend Redesign**
|
71 |
+
- [ ] Task 2.1: Re-implement the UI based on the new design.
|
72 |
+
- [ ] **Phase 3: Final Integration and Testing**
|
73 |
+
- [ ] Task 3.1: End-to-End Testing.
|
74 |
+
|
75 |
+
## 6. Executor's Feedback or Assistance Requests
|
76 |
+
*This section will be updated by the Executor during implementation.*
|
docs/implementation-plan/web-ui-for-chatbot.md
ADDED
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Implementation Plan: UI & Backend Reliability Overhaul
|
2 |
+
|
3 |
+
## 1. Project Goal
|
4 |
+
|
5 |
+
To deliver a stable, polished, and professional chat application by:
|
6 |
+
1. **Fixing the Backend:** Making the API resilient to external service failures.
|
7 |
+
2. **Fixing the Frontend:** Implementing a high-fidelity UI that accurately matches the provided Figma design.
|
8 |
+
3. **Ensuring Reliable Communication:** Debugging and fixing backend-frontend connection issues.
|
9 |
+
|
10 |
+
## 2. Key Challenges and Analysis
|
11 |
+
|
12 |
+
* **Backend Resilience:** The API must not crash if an external dependency like the Groq API is unavailable on startup. It needs to handle this gracefully and report the issue to the user through the UI.
|
13 |
+
* **High-Fidelity UI:** Translating a design into code requires meticulous attention to detail. The previous attempt failed because it only created the HTML structure without the specific Tailwind CSS classes for spacing, colors, fonts, shadows, and layout.
|
14 |
+
* **Conversational State:** The solution must maintain the previously implemented conversational memory.
|
15 |
+
* **Backend-Frontend Communication:** The frontend is receiving 500 errors when trying to communicate with the backend, indicating potential issues with API initialization, CORS, or environment configuration.
|
16 |
+
|
17 |
+
## 3. High-level Task Breakdown
|
18 |
+
|
19 |
+
### Phase 0: Backend-Frontend Connection Debugging (HIGHEST Priority)
|
20 |
+
|
21 |
+
* **Goal:** Fix the 500 errors occurring during frontend-backend communication
|
22 |
+
* **Tasks:**
|
23 |
+
1. **Environment Configuration Check:**
|
24 |
+
- Verify GROQ_API_KEY is properly set in the backend environment
|
25 |
+
- Ensure all required Python packages are installed and up to date
|
26 |
+
- Check that the backend server is running on the expected port (8000)
|
27 |
+
|
28 |
+
2. **Backend API Verification:**
|
29 |
+
- Add detailed logging to track API request/response cycle
|
30 |
+
- Implement proper error handling in the `/query` endpoint
|
31 |
+
- Add health check endpoint (`/health`) to verify API status
|
32 |
+
- Test API endpoints independently using curl/Postman
|
33 |
+
|
34 |
+
3. **Frontend API Integration:**
|
35 |
+
- Update frontend API call to include proper error handling
|
36 |
+
- Add retry logic for transient failures
|
37 |
+
- Implement proper loading states during API calls
|
38 |
+
- Add detailed console logging for debugging
|
39 |
+
|
40 |
+
4. **CORS and Network Configuration:**
|
41 |
+
- Verify CORS configuration is working correctly
|
42 |
+
- Ensure backend is accessible from frontend origin
|
43 |
+
- Test with explicit CORS configuration instead of wildcard
|
44 |
+
- Add proper error messages for CORS issues
|
45 |
+
|
46 |
+
### Phase 1: Backend Stabilization (Immediate Priority)
|
47 |
+
|
48 |
+
* **Goal:** Ensure the backend API can always start and respond, even if the Groq RAG system fails to initialize.
|
49 |
+
* **Tasks:**
|
50 |
+
1. **Add `tenacity` library:** Update `requirements.txt` to include the `tenacity` library for robust retry logic.
|
51 |
+
2. **Graceful RAG Initialization:** In `src/groq_medical_rag.py`, modify `_test_groq_connection` to use `@retry` from `tenacity`. This will automatically handle transient network errors during startup.
|
52 |
+
3. **Fault-Tolerant API:** In `src/api/main.py`, modify the `lifespan` manager. If the RAG system fails to initialize after all retries, the API should still start but log the critical error. The `rag_system` global will remain `None`.
|
53 |
+
4. **User-Friendly Error Response:** In the `/query` endpoint, check if `rag_system` is `None`. If it is, return a `200 OK` with a clear JSON error message (e.g., `{ "response": "Sorry, the clinical assistant is currently offline. Please try again later." }`) instead of a `503` error. This allows the frontend to handle the error gracefully.
|
54 |
+
|
55 |
+
### Phase 2: High-Fidelity Frontend Implementation
|
56 |
+
|
57 |
+
* **Goal:** Overhaul `frontend/src/app/page.tsx` to be a pixel-perfect implementation of the Figma design.
|
58 |
+
* **Tasks:**
|
59 |
+
1. **Add `clsx` utility:** Install the `clsx` library (`npm install clsx`) in the `frontend` directory to make conditional styling cleaner.
|
60 |
+
2. **Full UI Overhaul (`page.tsx`):** Replace the entire component with a new version that meticulously applies Tailwind CSS to match the design.
|
61 |
+
* **Layout:** Use flexbox to create the main `header`, `main` (chat), and `footer` (input) structure.
|
62 |
+
* **Welcome Screen:**
|
63 |
+
* Use correct font sizes (`text-5xl`, `text-4xl`, `text-lg`), weights (`font-bold`, `font-semibold`), and colors (`text-gray-800`, `text-gray-600`).
|
64 |
+
* Implement the vertical list of template questions with correct borders, padding, and hover effects.
|
65 |
+
* **Chat Form:**
|
66 |
+
* Style the `textarea` and `button` to exactly match the design, including borders, rounded corners, shadows, and the new "N" icon for the send button.
|
67 |
+
* **Chat History:**
|
68 |
+
* Style user and assistant messages as distinct "chat bubbles" with different background colors.
|
69 |
+
* Ensure the `prose` class is used on the markdown renderer for beautiful typography of the bot's response.
|
70 |
+
3. **Error Handling:** Update the `handleSubmit` function in the frontend to gracefully handle the new error message from the backend in case the RAG system is offline.
|
71 |
+
|
72 |
+
## 4. Project Status Board
|
73 |
+
|
74 |
+
- [ ] **Phase 0: Backend-Frontend Connection Debugging**
|
75 |
+
- [ ] Environment Configuration Check
|
76 |
+
- [ ] Verify GROQ_API_KEY
|
77 |
+
- [ ] Update Python dependencies
|
78 |
+
- [ ] Verify server port configuration
|
79 |
+
- [ ] Backend API Verification
|
80 |
+
- [ ] Add detailed logging
|
81 |
+
- [ ] Implement error handling
|
82 |
+
- [ ] Add health check endpoint
|
83 |
+
- [ ] Test API independently
|
84 |
+
- [ ] Frontend API Integration
|
85 |
+
- [ ] Update error handling
|
86 |
+
- [ ] Add retry logic
|
87 |
+
- [ ] Implement loading states
|
88 |
+
- [ ] Add debug logging
|
89 |
+
- [ ] CORS and Network Configuration
|
90 |
+
- [ ] Verify CORS setup
|
91 |
+
- [ ] Test backend accessibility
|
92 |
+
- [ ] Update CORS configuration
|
93 |
+
- [ ] Add error messages
|
94 |
+
- [x] **Phase 1: Backend Stabilization**
|
95 |
+
- [x] Add `tenacity` to `requirements.txt`.
|
96 |
+
- [x] Implement retry logic in `groq_medical_rag.py`.
|
97 |
+
- [x] Make API startup fault-tolerant in `api/main.py`.
|
98 |
+
- [x] Implement user-friendly error response in `/query`.
|
99 |
+
- [ ] **Phase 2: Frontend UI Overhaul**
|
100 |
+
- [ ] Install `clsx` utility.
|
101 |
+
- [ ] Re-implement `page.tsx` with high-fidelity styling.
|
102 |
+
- [ ] Implement frontend error handling for offline RAG system.
|
103 |
+
|
104 |
+
## 5. Branch Name
|
105 |
+
|
106 |
+
`fix/ui-and-backend-stability`
|
docs/scratchpad.md
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# SL Clinical Assistant - Project Scratchpad
|
2 |
+
|
3 |
+
## Current Active Task
|
4 |
+
**Task**: System Redesign and Refinement
|
5 |
+
**Implementation Plan**: `docs/implementation-plan/system-redesign-and-refinement.md`
|
6 |
+
**Status**: Just started. The plan has been formulated.
|
7 |
+
|
8 |
+
## Previous Tasks (for reference)
|
9 |
+
- [x] ~~Task: Maternal Health RAG Chatbot v2~~ (DEPRECATED)
|
10 |
+
- [x] ~~Implement maternal health RAG chatbot v3~~
|
11 |
+
- [x] ~~Task: Web UI for Clinical Chatbot~~ (Superseded by new plan)
|
12 |
+
|
13 |
+
## Research-Based Redesign Summary
|
14 |
+
|
15 |
+
**🔬 Key Research Findings (2024-2025):**
|
16 |
+
- **Complex medical categorization approaches don't work** - simpler document-based retrieval significantly outperforms categorical chunking
|
17 |
+
- **Optimal chunking**: 400-800 characters with 15% overlap using natural boundaries
|
18 |
+
- **NLP Integration Essential**: Dedicated medical language models crucial for professional answer presentation
|
19 |
+
- **Document-Centric**: Retrieve directly from parsed guidelines using document structure
|
20 |
+
|
21 |
+
**❌ Problems with Current v1.0 Implementation:**
|
22 |
+
1. **Over-engineered**: 542 medically-aware chunks with separate categories is too complex
|
23 |
+
2. **Category Fragmentation**: Clinical information gets split across artificial categories
|
24 |
+
3. **Poor Answer Presentation**: Lacks proper NLP formatting for healthcare professionals
|
25 |
+
4. **Reduced Retrieval Accuracy**: Complex categorization reduces semantic coherence
|
26 |
+
|
27 |
+
## New v2.0 Simplified Architecture
|
28 |
+
|
29 |
+
**🎯 Core Principles:**
|
30 |
+
- **Document-Centric Retrieval**: Retrieve from parsed guidelines directly using document structure
|
31 |
+
- **Simple Semantic Chunking**: Use paragraph/section-based chunking preserving clinical context
|
32 |
+
- **NLP Answer Enhancement**: Dedicated models for professional medical presentation
|
33 |
+
- **Clinical Safety**: Maintain medical disclaimers and source attribution
|
34 |
+
|
35 |
+
**📋 Revised Task Plan:**
|
36 |
+
1. **Document Structure Analysis & Simple Chunking** - Replace complex categorization
|
37 |
+
2. **Enhanced Document-Based Vector Store** - Simple metadata approach
|
38 |
+
3. **NLP Answer Generation Pipeline** - Medical language model integration
|
39 |
+
4. **Medical Language Model Integration** - OpenBioLLM-8B or similar
|
40 |
+
5. **Simplified RAG Pipeline** - Streamlined retrieval-generation
|
41 |
+
6. **Professional Interface Enhancement** - Healthcare professional UX
|
42 |
+
|
43 |
+
## Previous v1.0 Achievements (To Be Simplified)
|
44 |
+
✅ **15 PDF documents processed** (479 pages, 48 tables, 107,010 words)
|
45 |
+
✅ **Robust PDF extraction** using pdfplumber
|
46 |
+
✅ **Vector store infrastructure** with FAISS
|
47 |
+
✅ **Basic RAG pipeline** working
|
48 |
+
✅ **Gradio interface** functional
|
49 |
+
|
50 |
+
**🔄 Status**: Ready to implement v2.0 simplified approach based on latest research
|
51 |
+
|
52 |
+
## Current Projects Status
|
53 |
+
- [ ] Task: Web UI for Clinical Chatbot
|
54 |
+
|
55 |
+
## Current Task: Web UI for Clinical Chatbot
|
56 |
+
- **File:** `docs/implementation-plan/web-ui-for-chatbot.md`
|
57 |
+
- **Goal:** Create a web-based user interface for the RAG chatbot and deploy it.
|
58 |
+
- **Status:** Just started. The plan has been formulated.
|
59 |
+
|
60 |
+
## Current Task: Maternal Health RAG Chatbot v3
|
61 |
+
|
62 |
+
**Reference:** `docs/implementation-plan/maternal-health-rag-chatbot-v3.md`
|
63 |
+
|
64 |
+
### Planner's Goal
|
65 |
+
|
66 |
+
The primary goal is to execute the new three-phase plan to rebuild the chatbot's data processing and retrieval backbone. This will address the core quality issues of poor data extraction from complex PDFs and robotic, templated LLM responses. Success is defined as a chatbot that can accurately answer questions using data from tables and diagrams, and does so in a natural, conversational manner.
|
67 |
+
|
68 |
+
### Executor's Next Step
|
69 |
+
|
70 |
+
The first step for the executor is to begin **Phase 1: Advanced Multi-Modal Document Processing**.
|
71 |
+
This involves:
|
72 |
+
1. Updating `requirements.txt` to add the `mineru` library.
|
73 |
+
2. Creating the new `src/advanced_pdf_processor.py` script.
|
74 |
+
|
75 |
+
Let's begin. Please switch to executor mode.
|
76 |
+
|
77 |
+
## Lessons Learned
|
78 |
+
|
79 |
+
### Data Processing and Medical Documents
|
80 |
+
- [2024-12-29] Use pdfplumber over pymupdf4llm for medical documents with tables and flowcharts
|
81 |
+
- [2024-12-29] 400-800 character chunks with natural document boundaries work better than complex medical categorization
|
82 |
+
- [2024-12-29] Document-based metadata more effective than artificial medical subcategories
|
83 |
+
- [2024-12-29] Simple approach with all-MiniLM-L6-v2 embeddings achieves excellent retrieval (0.6-0.8+ relevance)
|
84 |
+
|
85 |
+
### System Architecture and Performance
|
86 |
+
- [2024-12-29] Simplified vector store approach (2,021 chunks) outperforms complex categorization significantly
|
87 |
+
- [2024-12-29] Template-based medical formatting works but lacks true medical reasoning capabilities
|
88 |
+
- [2024-12-29] User feedback critical: "poor retrieval capabilities, just keyword matching rather than medical reasoning"
|
89 |
+
|
90 |
+
### Model Deployment and Integration
|
91 |
+
- [2024-12-29] Local deployment of large models (15GB OpenBioLLM-8B) unreliable due to download timeouts and hardware requirements
|
92 |
+
- [2024-12-29] HuggingFace Inference API more reliable than local model deployment for production systems
|
93 |
+
- [2024-12-29] **CRITICAL**: OpenBioLLM-8B NOT available via HuggingFace Inference API (December 2024)
|
94 |
+
- [2024-12-29] Llama 3.3-70B-Instruct via HF API superior to local 8B models: 70B parameters > 8B for medical reasoning
|
95 |
+
- [2024-12-29] Medical prompt engineering can adapt general LLMs for healthcare applications effectively
|
96 |
+
- [2024-12-29] API integration (OpenAI-compatible) faster and more reliable than local model debugging
|
97 |
+
|
98 |
+
### Current Implementation State
|
99 |
+
|
100 |
+
- **v1.0 System (COMPLETED)**: Complex medical categorization approach with local vector store
|
101 |
+
- **v2.0 Core (COMPLETED)**: Simplified document-based RAG system with 2,021 optimized chunks
|
102 |
+
- **Current Challenge**: Medical LLM integration for proper clinical reasoning vs keyword matching
|
103 |
+
|
104 |
+
## Active Implementation Files
|
105 |
+
|
106 |
+
- **Primary Implementation Plan**: `docs/implementation-plan/maternal-health-rag-chatbot-v2.md`
|
107 |
+
- **Status**: Researching HuggingFace API integration for medical LLM vs local OpenBioLLM deployment
|
108 |
+
|
109 |
+
## Recent Research and Decision
|
110 |
+
|
111 |
+
### **HuggingFace API Analysis (December 2024)**
|
112 |
+
- **Local OpenBioLLM-8B**: Failed deployment due to 15GB size, connection timeouts, hardware requirements
|
113 |
+
- **HuggingFace API Availability**: OpenBioLLM-8B NOT available via HF Inference API
|
114 |
+
- **Recommended Alternative**: Llama 3.3-70B-Instruct via HF API with medical prompt engineering
|
115 |
+
- **Rationale**: 70B parameters > 8B for medical reasoning, reliable API vs local deployment issues
|
116 |
+
|
117 |
+
### **Strategic Pivot Decision**
|
118 |
+
**From**: Local OpenBioLLM-8B deployment (unreliable, 8B parameters)
|
119 |
+
**To**: HuggingFace API + Llama 3.3-70B-Instruct (reliable, 70B parameters, medical prompting)
|
120 |
+
|
121 |
+
**Advantages of HF API Approach**:
|
122 |
+
- Superior model size (70B vs 8B parameters)
|
123 |
+
- Reliable cloud infrastructure vs local deployment
|
124 |
+
- Latest December 2024 model with cutting-edge capabilities
|
125 |
+
- OpenAI-compatible API for easy integration
|
126 |
+
- No hardware/download requirements
|
127 |
+
|
128 |
+
**Implementation Strategy**:
|
129 |
+
1. HuggingFace API integration with OpenAI format
|
130 |
+
2. Medical prompt engineering for general Llama models
|
131 |
+
3. RAG integration with clinical formatting
|
132 |
+
4. Professional medical disclaimers and safety
|
133 |
+
|
134 |
+
- [ ] Next Task
|
frontend/.gitignore
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
2 |
+
|
3 |
+
# dependencies
|
4 |
+
/node_modules
|
5 |
+
/.pnp
|
6 |
+
.pnp.*
|
7 |
+
.yarn/*
|
8 |
+
!.yarn/patches
|
9 |
+
!.yarn/plugins
|
10 |
+
!.yarn/releases
|
11 |
+
!.yarn/versions
|
12 |
+
|
13 |
+
# testing
|
14 |
+
/coverage
|
15 |
+
|
16 |
+
# next.js
|
17 |
+
/.next/
|
18 |
+
/out/
|
19 |
+
|
20 |
+
# production
|
21 |
+
/build
|
22 |
+
|
23 |
+
# misc
|
24 |
+
.DS_Store
|
25 |
+
*.pem
|
26 |
+
|
27 |
+
# debug
|
28 |
+
npm-debug.log*
|
29 |
+
yarn-debug.log*
|
30 |
+
yarn-error.log*
|
31 |
+
.pnpm-debug.log*
|
32 |
+
|
33 |
+
# env files (can opt-in for committing if needed)
|
34 |
+
.env*
|
35 |
+
|
36 |
+
# vercel
|
37 |
+
.vercel
|
38 |
+
|
39 |
+
# typescript
|
40 |
+
*.tsbuildinfo
|
41 |
+
next-env.d.ts
|
frontend/README.md
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
2 |
+
|
3 |
+
## Getting Started
|
4 |
+
|
5 |
+
First, run the development server:
|
6 |
+
|
7 |
+
```bash
|
8 |
+
npm run dev
|
9 |
+
# or
|
10 |
+
yarn dev
|
11 |
+
# or
|
12 |
+
pnpm dev
|
13 |
+
# or
|
14 |
+
bun dev
|
15 |
+
```
|
16 |
+
|
17 |
+
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
18 |
+
|
19 |
+
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
20 |
+
|
21 |
+
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
22 |
+
|
23 |
+
## Learn More
|
24 |
+
|
25 |
+
To learn more about Next.js, take a look at the following resources:
|
26 |
+
|
27 |
+
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
28 |
+
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
29 |
+
|
30 |
+
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
31 |
+
|
32 |
+
## Deploy on Vercel
|
33 |
+
|
34 |
+
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
35 |
+
|
36 |
+
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
frontend/eslint.config.mjs
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import { dirname } from "path";
|
2 |
+
import { fileURLToPath } from "url";
|
3 |
+
import { FlatCompat } from "@eslint/eslintrc";
|
4 |
+
|
5 |
+
const __filename = fileURLToPath(import.meta.url);
|
6 |
+
const __dirname = dirname(__filename);
|
7 |
+
|
8 |
+
const compat = new FlatCompat({
|
9 |
+
baseDirectory: __dirname,
|
10 |
+
});
|
11 |
+
|
12 |
+
const eslintConfig = [
|
13 |
+
...compat.extends("next/core-web-vitals", "next/typescript"),
|
14 |
+
];
|
15 |
+
|
16 |
+
export default eslintConfig;
|
frontend/next.config.mjs
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/** @type {import('next').NextConfig} */
|
2 |
+
const nextConfig = {
|
3 |
+
/* config options here */
|
4 |
+
};
|
5 |
+
|
6 |
+
export default nextConfig;
|
frontend/package-lock.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
frontend/package.json
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"name": "frontend",
|
3 |
+
"version": "0.1.0",
|
4 |
+
"private": true,
|
5 |
+
"scripts": {
|
6 |
+
"dev": "next dev",
|
7 |
+
"build": "next build",
|
8 |
+
"start": "next start",
|
9 |
+
"lint": "next lint"
|
10 |
+
},
|
11 |
+
"dependencies": {
|
12 |
+
"clsx": "^2.1.0",
|
13 |
+
"next": "^14.2.30",
|
14 |
+
"react": "^18.2.0",
|
15 |
+
"react-dom": "^18.2.0",
|
16 |
+
"react-markdown": "^9.0.1",
|
17 |
+
"remark-gfm": "^4.0.0"
|
18 |
+
},
|
19 |
+
"devDependencies": {
|
20 |
+
"@tailwindcss/typography": "^0.5.10",
|
21 |
+
"@types/node": "^20.11.0",
|
22 |
+
"@types/react": "^18.2.0",
|
23 |
+
"@types/react-dom": "^18.2.0",
|
24 |
+
"autoprefixer": "^10.4.17",
|
25 |
+
"eslint": "^8.56.0",
|
26 |
+
"eslint-config-next": "14.1.0",
|
27 |
+
"postcss": "^8.4.35",
|
28 |
+
"tailwindcss": "^3.4.1",
|
29 |
+
"typescript": "^5.3.3"
|
30 |
+
}
|
31 |
+
}
|
frontend/postcss.config.mjs
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
export default {
|
2 |
+
plugins: {
|
3 |
+
tailwindcss: {},
|
4 |
+
autoprefixer: {},
|
5 |
+
},
|
6 |
+
};
|
frontend/public/file.svg
ADDED
|
frontend/public/globe.svg
ADDED
|
frontend/public/next.svg
ADDED
|
frontend/public/vercel.svg
ADDED
|
frontend/public/window.svg
ADDED
|
frontend/src/app/favicon.ico
ADDED
|
frontend/src/app/globals.css
ADDED
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@tailwind base;
|
2 |
+
@tailwind components;
|
3 |
+
@tailwind utilities;
|
4 |
+
|
5 |
+
@layer base {
|
6 |
+
body {
|
7 |
+
@apply antialiased text-text-primary bg-slate-50;
|
8 |
+
}
|
9 |
+
}
|
10 |
+
|
11 |
+
@layer components {
|
12 |
+
.chat-bubble {
|
13 |
+
@apply relative rounded-2xl p-6 transition-all duration-300 ease-in-out;
|
14 |
+
}
|
15 |
+
|
16 |
+
.chat-bubble-user {
|
17 |
+
@apply bg-white shadow-sm;
|
18 |
+
}
|
19 |
+
|
20 |
+
.chat-bubble-assistant {
|
21 |
+
@apply bg-secondary/30;
|
22 |
+
}
|
23 |
+
|
24 |
+
.button-primary {
|
25 |
+
@apply flex items-center justify-center px-6 py-3 rounded-full
|
26 |
+
bg-primary hover:bg-primary-dark text-white font-semibold
|
27 |
+
transition-all duration-200 ease-in-out
|
28 |
+
disabled:opacity-50 disabled:cursor-not-allowed;
|
29 |
+
}
|
30 |
+
|
31 |
+
.button-secondary {
|
32 |
+
@apply flex items-center justify-center px-6 py-3 rounded-full
|
33 |
+
bg-secondary hover:bg-secondary/80 text-text-primary font-semibold
|
34 |
+
transition-all duration-200 ease-in-out;
|
35 |
+
}
|
36 |
+
|
37 |
+
.input-primary {
|
38 |
+
@apply w-full px-6 py-4 rounded-2xl bg-secondary
|
39 |
+
text-text-primary placeholder:text-text-secondary
|
40 |
+
focus:outline-none focus:ring-2 focus:ring-primary/20
|
41 |
+
transition-all duration-200 ease-in-out;
|
42 |
+
}
|
43 |
+
}
|
44 |
+
|
45 |
+
/* Custom animations */
|
46 |
+
@keyframes fadeIn {
|
47 |
+
from { opacity: 0; transform: translateY(10px); }
|
48 |
+
to { opacity: 1; transform: translateY(0); }
|
49 |
+
}
|
50 |
+
|
51 |
+
.animate-fade-in {
|
52 |
+
animation: fadeIn 0.3s ease-out forwards;
|
53 |
+
}
|
54 |
+
|
55 |
+
/* Markdown content styling */
|
56 |
+
.prose pre {
|
57 |
+
@apply bg-slate-800 text-white rounded-xl p-4 my-4 overflow-x-auto;
|
58 |
+
}
|
59 |
+
|
60 |
+
.prose code {
|
61 |
+
@apply bg-slate-100 text-slate-800 rounded px-1.5 py-0.5 text-sm font-mono;
|
62 |
+
}
|
63 |
+
|
64 |
+
.prose ul {
|
65 |
+
@apply list-disc pl-6 my-4;
|
66 |
+
}
|
67 |
+
|
68 |
+
.prose ol {
|
69 |
+
@apply list-decimal pl-6 my-4;
|
70 |
+
}
|
71 |
+
|
72 |
+
.prose a {
|
73 |
+
@apply text-primary hover:text-primary-dark underline;
|
74 |
+
}
|
75 |
+
|
76 |
+
.prose blockquote {
|
77 |
+
@apply border-l-4 border-secondary pl-4 italic my-4;
|
78 |
+
}
|
frontend/src/app/layout.tsx
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import type { Metadata } from "next";
|
2 |
+
import { Inter } from 'next/font/google';
|
3 |
+
import "./globals.css";
|
4 |
+
import Head from 'next/head';
|
5 |
+
|
6 |
+
const inter = Inter({
|
7 |
+
subsets: ['latin'],
|
8 |
+
display: 'swap',
|
9 |
+
variable: '--font-inter',
|
10 |
+
});
|
11 |
+
|
12 |
+
export const metadata: Metadata = {
|
13 |
+
title: "VedaMD - Sri Lankan Health Guidelines Assistant",
|
14 |
+
description: "Get trusted clinical answers based on Sri Lankan health guidelines",
|
15 |
+
icons: {
|
16 |
+
icon: '/favicon.ico',
|
17 |
+
},
|
18 |
+
};
|
19 |
+
|
20 |
+
export default function RootLayout({
|
21 |
+
children,
|
22 |
+
}: {
|
23 |
+
children: React.ReactNode
|
24 |
+
}) {
|
25 |
+
return (
|
26 |
+
<html lang="en" className={inter.variable}>
|
27 |
+
<Head>
|
28 |
+
<link rel="preconnect" href="https://fonts.googleapis.com" crossOrigin="" />
|
29 |
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="" />
|
30 |
+
</Head>
|
31 |
+
<body className="font-sans antialiased">{children}</body>
|
32 |
+
</html>
|
33 |
+
);
|
34 |
+
}
|
frontend/src/app/page.tsx
ADDED
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"use client";
|
2 |
+
|
3 |
+
import { useState, useRef, useEffect, FormEvent, FC } from 'react';
|
4 |
+
import ReactMarkdown from 'react-markdown';
|
5 |
+
import remarkGfm from 'remark-gfm';
|
6 |
+
import clsx from 'clsx';
|
7 |
+
|
8 |
+
// --- TYPE DEFINITIONS ---
|
9 |
+
interface Message {
|
10 |
+
role: 'user' | 'assistant';
|
11 |
+
content: string;
|
12 |
+
}
|
13 |
+
|
14 |
+
// --- SVG ICONS ---
|
15 |
+
const VedaMDLogo: FC = () => (
|
16 |
+
<div className="flex items-center gap-4">
|
17 |
+
<div className="size-6">
|
18 |
+
<svg viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
|
19 |
+
<path d="M4 4H17.3334V17.3334H30.6666V30.6666H44V44H4V4Z" fill="currentColor"></path>
|
20 |
+
</svg>
|
21 |
+
</div>
|
22 |
+
<h2 className="text-xl font-bold leading-tight tracking-tight">VedaMD</h2>
|
23 |
+
</div>
|
24 |
+
);
|
25 |
+
|
26 |
+
const SettingsIcon: FC = () => (
|
27 |
+
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" viewBox="0 0 256 256">
|
28 |
+
<path d="M128,80a48,48,0,1,0,48,48A48.05,48.05,0,0,0,128,80Zm0,80a32,32,0,1,1,32-32A32,32,0,0,1,128,160Zm88-29.84q.06-2.16,0-4.32l14.92-18.64a8,8,0,0,0,1.48-7.06,107.21,107.21,0,0,0-10.88-26.25,8,8,0,0,0-6-3.93l-23.72-2.64q-1.48-1.56-3-3L186,40.54a8,8,0,0,0-3.94-6,107.71,107.71,0,0,0-26.25-10.87,8,8,0,0,0-7.06,1.49L130.16,40Q128,40,125.84,40L107.2,25.11a8,8,0,0,0-7.06-1.48A107.6,107.6,0,0,0,73.89,34.51a8,8,0,0,0-3.93,6L67.32,64.27q-1.56,1.49-3,3L40.54,70a8,8,0,0,0-6,3.94,107.71,107.71,0,0,0-10.87,26.25,8,8,0,0,0,1.49,7.06L40,125.84Q40,128,40,130.16L25.11,148.8a8,8,0,0,0-1.48,7.06,107.21,107.21,0,0,0,10.88,26.25,8,8,0,0,0,6,3.93l23.72,2.64q1.49,1.56,3,3L70,215.46a8,8,0,0,0,3.94,6,107.71,107.71,0,0,0,26.25,10.87,8,8,0,0,0,7.06-1.49L125.84,216q2.16.06,4.32,0l18.64,14.92a8,8,0,0,0,7.06,1.48,107.21,107.21,0,0,0,26.25-10.88,8,8,0,0,0,3.93-6l2.64-23.72q1.56-1.48,3-3L215.46,186a8,8,0,0,0,6-3.94,107.71,107.71,0,0,0,10.87-26.25,8,8,0,0,0-1.49-7.06Zm-16.1-6.5a73.93,73.93,0,0,1,0,8.68,8,8,0,0,0,1.74,5.48l14.19,17.73a91.57,91.57,0,0,1-6.23,15L187,173.11a8,8,0,0,0-5.1,2.64,74.11,74.11,0,0,1-6.14,6.14,8,8,0,0,0-2.64,5.1l-2.51,22.58a91.32,91.32,0,0,1-15,6.23l-17.74-14.19a8,8,0,0,0-5-1.75h-.48a73.93,73.93,0,0,1-8.68,0,8,8,0,0,0-5.48,1.74L100.45,215.8a91.57,91.57,0,0,1-15-6.23L82.89,187a8,8,0,0,0-2.64-5.1,74.11,74.11,0,0,1-6.14-6.14,8,8,0,0,0-5.1-2.64L46.43,170.6a91.32,91.32,0,0,1-6.23-15l14.19-17.74a8,8,0,0,0,1.74-5.48,73.93,73.93,0,0,1,0-8.68,8,8,0,0,0-1.74-5.48L40.2,100.45a91.57,91.57,0,0,1,6.23-15L69,82.89a8,8,0,0,0,5.1-2.64,74.11,74.11,0,0,1,6.14-6.14A8,8,0,0,0,82.89,69L85.4,46.43a91.32,91.32,0,0,1,15-6.23l17.74,14.19a8,8,0,0,0,5.48,1.74,73.93,73.93,0,0,1,8.68,0,8,8,0,0,0,5.48-1.74L155.55,40.2a91.57,91.57,0,0,1,15,6.23L173.11,69a8,8,0,0,0,2.64,5.1,74.11,74.11,0,0,1,6.14,6.14,8,8,0,0,0,5.1,2.64l22.58,2.51a91.32,91.32,0,0,1,6.23,15l-14.19,17.74A8,8,0,0,0,199.87,123.66Z"></path>
|
29 |
+
</svg>
|
30 |
+
);
|
31 |
+
|
32 |
+
const ArrowRightIcon: FC = () => (
|
33 |
+
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 256 256" className="text-white">
|
34 |
+
<path d="M221.66,133.66l-72,72a8,8,0,0,1-11.32-11.32L196.69,136H40a8,8,0,0,1,0-16H196.69L138.34,61.66a8,8,0,0,1,11.32-11.32l72,72A8,8,0,0,1,221.66,133.66Z"></path>
|
35 |
+
</svg>
|
36 |
+
);
|
37 |
+
|
38 |
+
// --- UI COMPONENTS ---
|
39 |
+
const Header: FC = () => (
|
40 |
+
<header className="sticky top-0 z-50 flex items-center justify-between border-b border-secondary/50 bg-white/80 px-6 py-4 backdrop-blur-sm">
|
41 |
+
<VedaMDLogo />
|
42 |
+
<button className="button-secondary">
|
43 |
+
<SettingsIcon />
|
44 |
+
</button>
|
45 |
+
</header>
|
46 |
+
);
|
47 |
+
|
48 |
+
const WelcomeScreen: FC<{ onTemplateClick: (query: string) => void }> = ({ onTemplateClick }) => {
|
49 |
+
const templates = [
|
50 |
+
"What is the recommended antibiotic regimen for puerperal sepsis according to national guidelines?",
|
51 |
+
"What are the steps for active management of the third stage of labor (AMTSL)",
|
52 |
+
];
|
53 |
+
|
54 |
+
return (
|
55 |
+
<div className="flex flex-col items-center justify-center px-6 py-12 animate-fade-in">
|
56 |
+
<div className="max-w-2xl text-center">
|
57 |
+
<h1 className="text-4xl font-bold tracking-tight mb-4">
|
58 |
+
Welcome to VedaMD
|
59 |
+
</h1>
|
60 |
+
<p className="text-xl text-text-secondary mb-8">
|
61 |
+
Get trusted clinical answers based on Sri Lankan health guidelines
|
62 |
+
</p>
|
63 |
+
<div className="flex flex-col gap-4">
|
64 |
+
{templates.map((query) => (
|
65 |
+
<button
|
66 |
+
key={query}
|
67 |
+
onClick={() => onTemplateClick(query)}
|
68 |
+
className="button-secondary text-left"
|
69 |
+
>
|
70 |
+
{query}
|
71 |
+
</button>
|
72 |
+
))}
|
73 |
+
</div>
|
74 |
+
</div>
|
75 |
+
</div>
|
76 |
+
);
|
77 |
+
};
|
78 |
+
|
79 |
+
const ChatMessage: FC<{ message: Message }> = ({ message }) => {
|
80 |
+
const isUser = message.role === 'user';
|
81 |
+
|
82 |
+
return (
|
83 |
+
<div className={clsx(
|
84 |
+
"py-6 px-4 animate-fade-in",
|
85 |
+
isUser ? 'bg-white' : 'bg-slate-50'
|
86 |
+
)}>
|
87 |
+
<div className="max-w-3xl mx-auto flex gap-6">
|
88 |
+
<div className={clsx(
|
89 |
+
"size-10 rounded-full flex-shrink-0 flex items-center justify-center font-semibold text-white",
|
90 |
+
isUser ? 'bg-text-primary' : 'bg-primary'
|
91 |
+
)}>
|
92 |
+
{isUser ? 'U' : 'V'}
|
93 |
+
</div>
|
94 |
+
<div className="flex-grow space-y-4">
|
95 |
+
<div className={clsx(
|
96 |
+
'chat-bubble',
|
97 |
+
isUser ? 'chat-bubble-user' : 'chat-bubble-assistant'
|
98 |
+
)}>
|
99 |
+
<div className="prose prose-lg max-w-none">
|
100 |
+
<ReactMarkdown remarkPlugins={[remarkGfm]}>
|
101 |
+
{message.content}
|
102 |
+
</ReactMarkdown>
|
103 |
+
</div>
|
104 |
+
</div>
|
105 |
+
</div>
|
106 |
+
</div>
|
107 |
+
</div>
|
108 |
+
);
|
109 |
+
};
|
110 |
+
|
111 |
+
const ChatForm: FC<{
|
112 |
+
input: string;
|
113 |
+
setInput: (value: string) => void;
|
114 |
+
handleSubmit: (e: FormEvent) => void;
|
115 |
+
isLoading: boolean;
|
116 |
+
}> = ({ input, setInput, handleSubmit, isLoading }) => (
|
117 |
+
<div className="sticky bottom-0 border-t border-secondary/50 bg-white/80 backdrop-blur-sm">
|
118 |
+
<form onSubmit={handleSubmit} className="max-w-3xl mx-auto p-4 flex gap-4">
|
119 |
+
<textarea
|
120 |
+
placeholder="Ask VedaMD anything..."
|
121 |
+
value={input}
|
122 |
+
onChange={(e) => setInput(e.target.value)}
|
123 |
+
className="input-primary"
|
124 |
+
onKeyDown={(e) => {
|
125 |
+
if (e.key === 'Enter' && !e.shiftKey) {
|
126 |
+
e.preventDefault();
|
127 |
+
handleSubmit(e);
|
128 |
+
}
|
129 |
+
}}
|
130 |
+
disabled={isLoading}
|
131 |
+
rows={1}
|
132 |
+
/>
|
133 |
+
<button
|
134 |
+
type="submit"
|
135 |
+
disabled={isLoading || !input.trim()}
|
136 |
+
className="button-primary whitespace-nowrap"
|
137 |
+
>
|
138 |
+
{isLoading ? (
|
139 |
+
<div className="size-6 border-4 border-t-transparent border-white rounded-full animate-spin" />
|
140 |
+
) : (
|
141 |
+
<ArrowRightIcon />
|
142 |
+
)}
|
143 |
+
</button>
|
144 |
+
</form>
|
145 |
+
</div>
|
146 |
+
);
|
147 |
+
|
148 |
+
const Footer: FC = () => (
|
149 |
+
<footer className="py-6 px-4 text-center text-text-secondary text-sm">
|
150 |
+
© 2024 VedaMD. All rights reserved.
|
151 |
+
</footer>
|
152 |
+
);
|
153 |
+
|
154 |
+
// --- MAIN PAGE COMPONENT ---
|
155 |
+
export default function Home() {
|
156 |
+
const [conversation, setConversation] = useState<Message[]>([]);
|
157 |
+
const [input, setInput] = useState('');
|
158 |
+
const [isLoading, setIsLoading] = useState(false);
|
159 |
+
const [error, setError] = useState<string | null>(null);
|
160 |
+
const messagesEndRef = useRef<HTMLDivElement>(null);
|
161 |
+
|
162 |
+
const scrollToBottom = () => {
|
163 |
+
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
164 |
+
};
|
165 |
+
|
166 |
+
useEffect(() => {
|
167 |
+
const timeoutId = setTimeout(scrollToBottom, 100);
|
168 |
+
return () => clearTimeout(timeoutId);
|
169 |
+
}, [conversation]);
|
170 |
+
|
171 |
+
const handleSubmit = async (e: FormEvent | string) => {
|
172 |
+
const query = (typeof e === 'string' ? e : input).trim();
|
173 |
+
if (typeof e !== 'string') e.preventDefault();
|
174 |
+
|
175 |
+
if (!query || isLoading) return;
|
176 |
+
|
177 |
+
setIsLoading(true);
|
178 |
+
setError(null);
|
179 |
+
if (typeof e !== 'string') setInput('');
|
180 |
+
|
181 |
+
const userMessage: Message = { role: 'user', content: query };
|
182 |
+
const currentConversation = [...conversation, userMessage];
|
183 |
+
setConversation(currentConversation);
|
184 |
+
|
185 |
+
try {
|
186 |
+
const history = currentConversation.slice(0, -1).map(({ role, content }) => ({ role, content }));
|
187 |
+
|
188 |
+
const response = await fetch('http://localhost:8000/query', {
|
189 |
+
method: 'POST',
|
190 |
+
headers: { 'Content-Type': 'application/json' },
|
191 |
+
body: JSON.stringify({ query, history }),
|
192 |
+
});
|
193 |
+
|
194 |
+
if (!response.ok) {
|
195 |
+
const errorData = await response.json().catch(() => ({ detail: 'An unknown error occurred.' }));
|
196 |
+
throw new Error(errorData.detail || 'Network response was not ok');
|
197 |
+
}
|
198 |
+
|
199 |
+
const data = await response.json();
|
200 |
+
const botMessage: Message = {
|
201 |
+
role: 'assistant',
|
202 |
+
content: data.response
|
203 |
+
};
|
204 |
+
setConversation([...currentConversation, botMessage]);
|
205 |
+
} catch (err: any) {
|
206 |
+
const errorMessageText = err.message || "An unexpected error occurred.";
|
207 |
+
setError(errorMessageText);
|
208 |
+
const errorMessage: Message = { role: 'assistant', content: errorMessageText };
|
209 |
+
setConversation([...currentConversation, errorMessage]);
|
210 |
+
} finally {
|
211 |
+
setIsLoading(false);
|
212 |
+
}
|
213 |
+
};
|
214 |
+
|
215 |
+
return (
|
216 |
+
<div className="min-h-screen flex flex-col bg-slate-50">
|
217 |
+
<Header />
|
218 |
+
<main className="flex-1 flex flex-col">
|
219 |
+
<div className="flex-1 overflow-y-auto">
|
220 |
+
{conversation.length === 0 ? (
|
221 |
+
<WelcomeScreen onTemplateClick={handleSubmit} />
|
222 |
+
) : (
|
223 |
+
<div className="pb-20">
|
224 |
+
{conversation.map((message, index) => (
|
225 |
+
<ChatMessage key={index} message={message} />
|
226 |
+
))}
|
227 |
+
<div ref={messagesEndRef} />
|
228 |
+
</div>
|
229 |
+
)}
|
230 |
+
</div>
|
231 |
+
<ChatForm
|
232 |
+
input={input}
|
233 |
+
setInput={setInput}
|
234 |
+
handleSubmit={handleSubmit}
|
235 |
+
isLoading={isLoading}
|
236 |
+
/>
|
237 |
+
</main>
|
238 |
+
<Footer />
|
239 |
+
</div>
|
240 |
+
);
|
241 |
+
}
|
frontend/tailwind.config.ts
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import type { Config } from "tailwindcss";
|
2 |
+
|
3 |
+
const config: Config = {
|
4 |
+
content: [
|
5 |
+
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
|
6 |
+
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
|
7 |
+
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
|
8 |
+
],
|
9 |
+
theme: {
|
10 |
+
extend: {
|
11 |
+
colors: {
|
12 |
+
'primary': '#3490f3',
|
13 |
+
'primary-dark': '#2563eb',
|
14 |
+
'secondary': '#e7edf4',
|
15 |
+
'text': {
|
16 |
+
'primary': '#0d141c',
|
17 |
+
'secondary': '#49719c'
|
18 |
+
},
|
19 |
+
},
|
20 |
+
animation: {
|
21 |
+
'fade-in': 'fadeIn 0.3s ease-out forwards',
|
22 |
+
},
|
23 |
+
keyframes: {
|
24 |
+
fadeIn: {
|
25 |
+
'0%': { opacity: '0', transform: 'translateY(10px)' },
|
26 |
+
'100%': { opacity: '1', transform: 'translateY(0)' },
|
27 |
+
},
|
28 |
+
},
|
29 |
+
typography: {
|
30 |
+
DEFAULT: {
|
31 |
+
css: {
|
32 |
+
maxWidth: 'none',
|
33 |
+
color: '#0d141c',
|
34 |
+
a: {
|
35 |
+
color: '#3490f3',
|
36 |
+
'&:hover': {
|
37 |
+
color: '#2563eb',
|
38 |
+
},
|
39 |
+
},
|
40 |
+
strong: {
|
41 |
+
color: '#0d141c',
|
42 |
+
},
|
43 |
+
h1: {
|
44 |
+
color: '#0d141c',
|
45 |
+
},
|
46 |
+
h2: {
|
47 |
+
color: '#0d141c',
|
48 |
+
},
|
49 |
+
h3: {
|
50 |
+
color: '#0d141c',
|
51 |
+
},
|
52 |
+
h4: {
|
53 |
+
color: '#0d141c',
|
54 |
+
},
|
55 |
+
},
|
56 |
+
},
|
57 |
+
},
|
58 |
+
},
|
59 |
+
},
|
60 |
+
plugins: [
|
61 |
+
require("@tailwindcss/typography"),
|
62 |
+
],
|
63 |
+
};
|
64 |
+
export default config;
|
frontend/tsconfig.json
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"compilerOptions": {
|
3 |
+
"target": "ES2017",
|
4 |
+
"lib": ["dom", "dom.iterable", "esnext"],
|
5 |
+
"allowJs": true,
|
6 |
+
"skipLibCheck": true,
|
7 |
+
"strict": true,
|
8 |
+
"noEmit": true,
|
9 |
+
"esModuleInterop": true,
|
10 |
+
"module": "esnext",
|
11 |
+
"moduleResolution": "bundler",
|
12 |
+
"resolveJsonModule": true,
|
13 |
+
"isolatedModules": true,
|
14 |
+
"jsx": "preserve",
|
15 |
+
"incremental": true,
|
16 |
+
"plugins": [
|
17 |
+
{
|
18 |
+
"name": "next"
|
19 |
+
}
|
20 |
+
],
|
21 |
+
"paths": {
|
22 |
+
"@/*": ["./src/*"]
|
23 |
+
}
|
24 |
+
},
|
25 |
+
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
26 |
+
"exclude": ["node_modules"]
|
27 |
+
}
|
requirements.txt
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Maternal Health RAG Chatbot Requirements
|
2 |
+
|
3 |
+
# Core libraries for document processing and RAG
|
4 |
+
unstructured[local-inference]>=0.14.9 # For local, high-quality PDF processing
|
5 |
+
pdfplumber>=0.11.0
|
6 |
+
pillow>=10.0.0
|
7 |
+
langchain-community>=0.0.38
|
8 |
+
langchain-text-splitters>=0.0.1
|
9 |
+
sentence-transformers>=2.2.2
|
10 |
+
faiss-cpu>=1.7.4
|
11 |
+
accelerate>=0.24.0
|
12 |
+
gradio>=4.0.0
|
13 |
+
groq>=0.4.0
|
14 |
+
|
15 |
+
# Data handling and utilities
|
16 |
+
pandas>=2.0.0
|
17 |
+
beautifulsoup4>=4.12.0
|
18 |
+
python-dotenv>=1.0.0
|
19 |
+
tqdm>=4.66.0
|
20 |
+
|
21 |
+
# Core ML/AI libraries
|
22 |
+
numpy>=1.24.0
|
23 |
+
scikit-learn>=1.3.0
|
24 |
+
openai>=1.0.0
|
25 |
+
langchain>=0.1.0
|
26 |
+
langchain-openai>=0.0.5
|
27 |
+
torch>=2.0.0
|
28 |
+
torchvision
|
29 |
+
|
30 |
+
# Testing and code quality
|
31 |
+
pytest>=7.0.0
|
32 |
+
pytest-cov>=4.0.0
|
33 |
+
black>=23.0.0
|
34 |
+
flake8>=6.0.0
|
35 |
+
|
36 |
+
# Web app and visualization
|
37 |
+
streamlit>=1.28.0
|
38 |
+
pymupdf>=1.23.0
|
39 |
+
tabulate>=0.9.0
|
40 |
+
openpyxl>=3.1.0
|
41 |
+
matplotlib>=3.7.0
|
42 |
+
requests>=2.31.0
|
43 |
+
aiohttp>=3.9.0
|
44 |
+
|
45 |
+
# Additional dependencies for embedding evaluation
|
46 |
+
# python-magic-bin>=0.4.14 # Removed due to incompatibility on macOS ARM
|
47 |
+
# spacy>=3.7.0
|
48 |
+
# scispacy>=0.5.0
|
49 |
+
|
50 |
+
# For API
|
51 |
+
fastapi
|
52 |
+
uvicorn[standard]
|
53 |
+
python-dotenv
|
54 |
+
|
55 |
+
# For PDF processing
|
56 |
+
pypdfium2
|
57 |
+
|
58 |
+
# New dependencies
|
59 |
+
markdown
|
60 |
+
tenacity
|
src/api/main.py
ADDED
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
import os
|
3 |
+
from contextlib import asynccontextmanager
|
4 |
+
from fastapi import FastAPI, HTTPException
|
5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
6 |
+
from fastapi.responses import JSONResponse
|
7 |
+
from pydantic import BaseModel
|
8 |
+
import uvicorn
|
9 |
+
import logging
|
10 |
+
from typing import Optional, List, Dict
|
11 |
+
|
12 |
+
# Configure logging
|
13 |
+
logging.basicConfig(
|
14 |
+
level=logging.INFO,
|
15 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
16 |
+
)
|
17 |
+
logger = logging.getLogger(__name__)
|
18 |
+
|
19 |
+
# Add the project root to the Python path
|
20 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
21 |
+
|
22 |
+
from src.groq_medical_rag import GroqMedicalRAG, MedicalResponse
|
23 |
+
|
24 |
+
# --- Globals ---
|
25 |
+
rag_system = None
|
26 |
+
|
27 |
+
# --- Lifespan Management ---
|
28 |
+
@asynccontextmanager
|
29 |
+
async def lifespan(app: FastAPI):
|
30 |
+
global rag_system
|
31 |
+
logger.info("🚀 Initializing RAG system...")
|
32 |
+
try:
|
33 |
+
rag_system = GroqMedicalRAG()
|
34 |
+
logger.info("✅ RAG system initialized successfully.")
|
35 |
+
except Exception as e:
|
36 |
+
logger.error(f"❌ CRITICAL: Failed to initialize RAG system: {str(e)}")
|
37 |
+
logger.info("✅ API server is running, but RAG functionality will be disabled.")
|
38 |
+
rag_system = None
|
39 |
+
yield
|
40 |
+
logger.info("👋 Shutting down...")
|
41 |
+
|
42 |
+
# --- FastAPI App ---
|
43 |
+
app = FastAPI(title="Clinical Assistant API", lifespan=lifespan)
|
44 |
+
|
45 |
+
# --- CORS Middleware ---
|
46 |
+
app.add_middleware(
|
47 |
+
CORSMiddleware,
|
48 |
+
allow_origins=["*"], # Allows all origins
|
49 |
+
allow_credentials=True,
|
50 |
+
allow_methods=["*"], # Allows all methods
|
51 |
+
allow_headers=["*"], # Allows all headers
|
52 |
+
)
|
53 |
+
|
54 |
+
# --- Pydantic Models ---
|
55 |
+
class QueryRequest(BaseModel):
|
56 |
+
query: str
|
57 |
+
history: Optional[List[Dict[str, str]]] = None
|
58 |
+
|
59 |
+
class QueryResponse(BaseModel):
|
60 |
+
response: str
|
61 |
+
|
62 |
+
class HealthResponse(BaseModel):
|
63 |
+
status: str
|
64 |
+
rag_system_status: str
|
65 |
+
version: str = "1.0.0"
|
66 |
+
|
67 |
+
# --- API Endpoints ---
|
68 |
+
@app.get("/health", response_model=HealthResponse)
|
69 |
+
async def health_check():
|
70 |
+
"""Check the health status of the API and its components."""
|
71 |
+
return HealthResponse(
|
72 |
+
status="healthy",
|
73 |
+
rag_system_status="initialized" if rag_system else "offline"
|
74 |
+
)
|
75 |
+
|
76 |
+
@app.post("/query", response_model=QueryResponse)
|
77 |
+
async def process_query(query_request: QueryRequest):
|
78 |
+
"""Processes a clinical query and returns an evidence-based answer."""
|
79 |
+
logger.info(f"Received query: {query_request.query[:50]}...")
|
80 |
+
|
81 |
+
if not rag_system:
|
82 |
+
logger.warning("Query received but RAG system is offline")
|
83 |
+
return JSONResponse(
|
84 |
+
status_code=503,
|
85 |
+
content={
|
86 |
+
"response": "Sorry, the clinical assistant is currently offline due to a connection issue. Please try again later."
|
87 |
+
}
|
88 |
+
)
|
89 |
+
|
90 |
+
try:
|
91 |
+
query_text = query_request.query
|
92 |
+
history = query_request.history
|
93 |
+
medical_response = rag_system.query(query=query_text, history=history)
|
94 |
+
logger.info("Query processed successfully")
|
95 |
+
return QueryResponse(response=medical_response.answer)
|
96 |
+
except Exception as e:
|
97 |
+
logger.error(f"Error processing query: {str(e)}")
|
98 |
+
return JSONResponse(
|
99 |
+
status_code=500,
|
100 |
+
content={
|
101 |
+
"response": "An error occurred while processing your query. Please try again.",
|
102 |
+
"error": str(e)
|
103 |
+
}
|
104 |
+
)
|
105 |
+
|
106 |
+
# --- Main ---
|
107 |
+
if __name__ == "__main__":
|
108 |
+
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
src/embedding_evaluator.py
ADDED
@@ -0,0 +1,414 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
"""
|
3 |
+
Embedding Model Evaluator for Medical Content
|
4 |
+
Tests different free embedding models to find the best for maternal health guidelines
|
5 |
+
"""
|
6 |
+
|
7 |
+
import json
|
8 |
+
import numpy as np
|
9 |
+
from pathlib import Path
|
10 |
+
from typing import List, Dict, Any, Tuple
|
11 |
+
import logging
|
12 |
+
from sentence_transformers import SentenceTransformer
|
13 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
14 |
+
from sklearn.cluster import KMeans
|
15 |
+
from sklearn.decomposition import PCA
|
16 |
+
import matplotlib.pyplot as plt
|
17 |
+
import time
|
18 |
+
|
19 |
+
# Configure logging
|
20 |
+
logging.basicConfig(level=logging.INFO)
|
21 |
+
logger = logging.getLogger(__name__)
|
22 |
+
|
23 |
+
class MedicalEmbeddingEvaluator:
|
24 |
+
"""Evaluates different embedding models for medical content quality"""
|
25 |
+
|
26 |
+
def __init__(self, chunks_dir: Path = Path("comprehensive_chunks")):
|
27 |
+
self.chunks_dir = chunks_dir
|
28 |
+
self.medical_chunks = []
|
29 |
+
self.evaluation_results = {}
|
30 |
+
|
31 |
+
# Free embedding models to test
|
32 |
+
self.embedding_models = {
|
33 |
+
'all-MiniLM-L6-v2': 'sentence-transformers/all-MiniLM-L6-v2',
|
34 |
+
'all-mpnet-base-v2': 'sentence-transformers/all-mpnet-base-v2',
|
35 |
+
'all-MiniLM-L12-v2': 'sentence-transformers/all-MiniLM-L12-v2',
|
36 |
+
'multi-qa-MiniLM-L6-cos-v1': 'sentence-transformers/multi-qa-MiniLM-L6-cos-v1',
|
37 |
+
'all-distilroberta-v1': 'sentence-transformers/all-distilroberta-v1'
|
38 |
+
}
|
39 |
+
|
40 |
+
# Medical test queries for evaluation
|
41 |
+
self.test_queries = [
|
42 |
+
"What is the recommended dosage of magnesium sulfate for preeclampsia?",
|
43 |
+
"How to manage postpartum hemorrhage in emergency situations?",
|
44 |
+
"Normal ranges for fetal heart rate during labor",
|
45 |
+
"Contraindications for vaginal delivery in breech presentation",
|
46 |
+
"Signs and symptoms of puerperal sepsis",
|
47 |
+
"Management of gestational diabetes during pregnancy",
|
48 |
+
"Emergency cesarean section indications",
|
49 |
+
"Postpartum care guidelines for mother and baby",
|
50 |
+
"RhESUS incompatibility management protocol",
|
51 |
+
"Antepartum monitoring guidelines for high-risk pregnancy"
|
52 |
+
]
|
53 |
+
|
54 |
+
def load_medical_chunks(self) -> List[Dict]:
|
55 |
+
"""Load medical chunks from comprehensive chunking results"""
|
56 |
+
logger.info("Loading medical chunks for embedding evaluation...")
|
57 |
+
|
58 |
+
langchain_file = self.chunks_dir / "langchain_documents_comprehensive.json"
|
59 |
+
if not langchain_file.exists():
|
60 |
+
raise FileNotFoundError(f"LangChain documents not found: {langchain_file}")
|
61 |
+
|
62 |
+
with open(langchain_file) as f:
|
63 |
+
chunks_data = json.load(f)
|
64 |
+
|
65 |
+
# Filter and prepare chunks for evaluation
|
66 |
+
medical_chunks = []
|
67 |
+
for chunk in chunks_data:
|
68 |
+
content = chunk['page_content']
|
69 |
+
metadata = chunk['metadata']
|
70 |
+
|
71 |
+
# Skip very short chunks
|
72 |
+
if len(content.strip()) < 100:
|
73 |
+
continue
|
74 |
+
|
75 |
+
medical_chunks.append({
|
76 |
+
'content': content,
|
77 |
+
'chunk_type': metadata.get('chunk_type', 'text'),
|
78 |
+
'clinical_importance': metadata.get('clinical_importance', 0.5),
|
79 |
+
'source': metadata.get('source', ''),
|
80 |
+
'has_dosage_info': metadata.get('has_dosage_info', False),
|
81 |
+
'is_maternal_specific': metadata.get('is_maternal_specific', False),
|
82 |
+
'has_clinical_protocols': metadata.get('has_clinical_protocols', False)
|
83 |
+
})
|
84 |
+
|
85 |
+
logger.info(f"Loaded {len(medical_chunks)} medical chunks for evaluation")
|
86 |
+
return medical_chunks
|
87 |
+
|
88 |
+
def evaluate_embedding_model(self, model_name: str, model_path: str) -> Dict[str, Any]:
|
89 |
+
"""Evaluate a single embedding model"""
|
90 |
+
logger.info(f"Evaluating embedding model: {model_name}")
|
91 |
+
|
92 |
+
try:
|
93 |
+
# Load model
|
94 |
+
start_time = time.time()
|
95 |
+
model = SentenceTransformer(model_path)
|
96 |
+
load_time = time.time() - start_time
|
97 |
+
|
98 |
+
# Sample chunks for evaluation (use subset for speed)
|
99 |
+
sample_chunks = self.medical_chunks[:100] # Use first 100 chunks
|
100 |
+
chunk_texts = [chunk['content'] for chunk in sample_chunks]
|
101 |
+
|
102 |
+
# Generate embeddings for chunks
|
103 |
+
logger.info(f"Generating embeddings for {len(chunk_texts)} chunks...")
|
104 |
+
start_time = time.time()
|
105 |
+
chunk_embeddings = model.encode(chunk_texts, show_progress_bar=True)
|
106 |
+
chunk_embed_time = time.time() - start_time
|
107 |
+
|
108 |
+
# Generate embeddings for test queries
|
109 |
+
start_time = time.time()
|
110 |
+
query_embeddings = model.encode(self.test_queries)
|
111 |
+
query_embed_time = time.time() - start_time
|
112 |
+
|
113 |
+
# Evaluation metrics
|
114 |
+
results = {
|
115 |
+
'model_name': model_name,
|
116 |
+
'model_path': model_path,
|
117 |
+
'load_time': load_time,
|
118 |
+
'chunk_embed_time': chunk_embed_time,
|
119 |
+
'query_embed_time': query_embed_time,
|
120 |
+
'embedding_dimension': chunk_embeddings.shape[1],
|
121 |
+
'chunks_processed': len(chunk_texts),
|
122 |
+
'queries_processed': len(self.test_queries)
|
123 |
+
}
|
124 |
+
|
125 |
+
# Test semantic search quality
|
126 |
+
search_results = self._evaluate_search_quality(
|
127 |
+
query_embeddings, chunk_embeddings, sample_chunks
|
128 |
+
)
|
129 |
+
results.update(search_results)
|
130 |
+
|
131 |
+
# Test clustering quality
|
132 |
+
cluster_results = self._evaluate_clustering_quality(
|
133 |
+
chunk_embeddings, sample_chunks
|
134 |
+
)
|
135 |
+
results.update(cluster_results)
|
136 |
+
|
137 |
+
# Calculate overall score
|
138 |
+
results['overall_score'] = self._calculate_overall_score(results)
|
139 |
+
|
140 |
+
logger.info(f"✅ {model_name} evaluation complete - Overall Score: {results['overall_score']:.3f}")
|
141 |
+
return results
|
142 |
+
|
143 |
+
except Exception as e:
|
144 |
+
logger.error(f"❌ Failed to evaluate {model_name}: {e}")
|
145 |
+
return {
|
146 |
+
'model_name': model_name,
|
147 |
+
'model_path': model_path,
|
148 |
+
'error': str(e),
|
149 |
+
'overall_score': 0.0
|
150 |
+
}
|
151 |
+
|
152 |
+
def _evaluate_search_quality(self, query_embeddings: np.ndarray,
|
153 |
+
chunk_embeddings: np.ndarray,
|
154 |
+
chunks: List[Dict]) -> Dict[str, float]:
|
155 |
+
"""Evaluate semantic search quality"""
|
156 |
+
|
157 |
+
# Calculate similarities between queries and chunks
|
158 |
+
similarities = cosine_similarity(query_embeddings, chunk_embeddings)
|
159 |
+
|
160 |
+
search_metrics = {
|
161 |
+
'avg_max_similarity': 0.0,
|
162 |
+
'medical_content_precision': 0.0,
|
163 |
+
'dosage_query_accuracy': 0.0,
|
164 |
+
'emergency_query_accuracy': 0.0
|
165 |
+
}
|
166 |
+
|
167 |
+
total_queries = len(self.test_queries)
|
168 |
+
|
169 |
+
for i, query in enumerate(self.test_queries):
|
170 |
+
query_similarities = similarities[i]
|
171 |
+
top_indices = np.argsort(query_similarities)[::-1][:5] # Top 5 results
|
172 |
+
|
173 |
+
# Max similarity for this query
|
174 |
+
max_sim = np.max(query_similarities)
|
175 |
+
search_metrics['avg_max_similarity'] += max_sim
|
176 |
+
|
177 |
+
# Check if top results contain relevant medical content
|
178 |
+
top_chunks = [chunks[idx] for idx in top_indices]
|
179 |
+
medical_relevant = sum(1 for chunk in top_chunks
|
180 |
+
if chunk['clinical_importance'] > 0.7)
|
181 |
+
search_metrics['medical_content_precision'] += medical_relevant / 5
|
182 |
+
|
183 |
+
# Specific query type accuracy
|
184 |
+
if 'dosage' in query.lower() or 'dose' in query.lower():
|
185 |
+
dosage_relevant = sum(1 for chunk in top_chunks
|
186 |
+
if chunk['has_dosage_info'])
|
187 |
+
search_metrics['dosage_query_accuracy'] += dosage_relevant / 5
|
188 |
+
|
189 |
+
if 'emergency' in query.lower() or 'urgent' in query.lower():
|
190 |
+
emergency_relevant = sum(1 for chunk in top_chunks
|
191 |
+
if chunk['chunk_type'] == 'emergency')
|
192 |
+
search_metrics['emergency_query_accuracy'] += emergency_relevant / 5
|
193 |
+
|
194 |
+
# Average the metrics
|
195 |
+
for key in search_metrics:
|
196 |
+
search_metrics[key] /= total_queries
|
197 |
+
|
198 |
+
return search_metrics
|
199 |
+
|
200 |
+
def _evaluate_clustering_quality(self, embeddings: np.ndarray,
|
201 |
+
chunks: List[Dict]) -> Dict[str, float]:
|
202 |
+
"""Evaluate how well embeddings cluster similar medical content"""
|
203 |
+
|
204 |
+
# Perform clustering
|
205 |
+
n_clusters = min(8, len(chunks) // 10) # Reasonable number of clusters
|
206 |
+
kmeans = KMeans(n_clusters=n_clusters, random_state=42)
|
207 |
+
cluster_labels = kmeans.fit_predict(embeddings)
|
208 |
+
|
209 |
+
# Calculate cluster purity based on chunk types
|
210 |
+
cluster_metrics = {
|
211 |
+
'cluster_purity': 0.0,
|
212 |
+
'dosage_cluster_coherence': 0.0,
|
213 |
+
'maternal_cluster_coherence': 0.0
|
214 |
+
}
|
215 |
+
|
216 |
+
# Calculate cluster purity
|
217 |
+
total_items = len(chunks)
|
218 |
+
for cluster_id in range(n_clusters):
|
219 |
+
cluster_indices = np.where(cluster_labels == cluster_id)[0]
|
220 |
+
if len(cluster_indices) == 0:
|
221 |
+
continue
|
222 |
+
|
223 |
+
cluster_chunks = [chunks[i] for i in cluster_indices]
|
224 |
+
|
225 |
+
# Find dominant chunk type in this cluster
|
226 |
+
chunk_types = [chunk['chunk_type'] for chunk in cluster_chunks]
|
227 |
+
if chunk_types:
|
228 |
+
dominant_type = max(set(chunk_types), key=chunk_types.count)
|
229 |
+
purity = chunk_types.count(dominant_type) / len(chunk_types)
|
230 |
+
cluster_metrics['cluster_purity'] += purity * len(cluster_indices) / total_items
|
231 |
+
|
232 |
+
# Check dosage content clustering
|
233 |
+
dosage_chunks = [chunk for chunk in cluster_chunks if chunk['has_dosage_info']]
|
234 |
+
if len(cluster_chunks) > 0:
|
235 |
+
dosage_ratio = len(dosage_chunks) / len(cluster_chunks)
|
236 |
+
if dosage_ratio > 0.5: # If majority are dosage chunks
|
237 |
+
cluster_metrics['dosage_cluster_coherence'] += dosage_ratio
|
238 |
+
|
239 |
+
# Check maternal content clustering
|
240 |
+
maternal_chunks = [chunk for chunk in cluster_chunks if chunk['is_maternal_specific']]
|
241 |
+
if len(cluster_chunks) > 0:
|
242 |
+
maternal_ratio = len(maternal_chunks) / len(cluster_chunks)
|
243 |
+
if maternal_ratio > 0.5: # If majority are maternal chunks
|
244 |
+
cluster_metrics['maternal_cluster_coherence'] += maternal_ratio
|
245 |
+
|
246 |
+
return cluster_metrics
|
247 |
+
|
248 |
+
def _calculate_overall_score(self, results: Dict[str, Any]) -> float:
|
249 |
+
"""Calculate overall score for the embedding model"""
|
250 |
+
|
251 |
+
if 'error' in results:
|
252 |
+
return 0.0
|
253 |
+
|
254 |
+
# Weighted scoring components
|
255 |
+
weights = {
|
256 |
+
'search_quality': 0.4,
|
257 |
+
'clustering_quality': 0.2,
|
258 |
+
'speed': 0.2,
|
259 |
+
'medical_relevance': 0.2
|
260 |
+
}
|
261 |
+
|
262 |
+
# Search quality score (0-1)
|
263 |
+
search_score = (
|
264 |
+
results.get('avg_max_similarity', 0) * 0.4 +
|
265 |
+
results.get('medical_content_precision', 0) * 0.3 +
|
266 |
+
results.get('dosage_query_accuracy', 0) * 0.15 +
|
267 |
+
results.get('emergency_query_accuracy', 0) * 0.15
|
268 |
+
)
|
269 |
+
|
270 |
+
# Clustering quality score (0-1)
|
271 |
+
cluster_score = (
|
272 |
+
results.get('cluster_purity', 0) * 0.5 +
|
273 |
+
results.get('dosage_cluster_coherence', 0) * 0.25 +
|
274 |
+
results.get('maternal_cluster_coherence', 0) * 0.25
|
275 |
+
)
|
276 |
+
|
277 |
+
# Speed score (inverse of time, normalized)
|
278 |
+
total_time = results.get('chunk_embed_time', 1) + results.get('query_embed_time', 1)
|
279 |
+
speed_score = max(0, 1 - (total_time / 100)) # Normalize to 0-1
|
280 |
+
|
281 |
+
# Medical relevance (based on search accuracy for medical queries)
|
282 |
+
medical_score = (
|
283 |
+
results.get('medical_content_precision', 0) * 0.6 +
|
284 |
+
results.get('dosage_query_accuracy', 0) * 0.4
|
285 |
+
)
|
286 |
+
|
287 |
+
# Calculate weighted overall score
|
288 |
+
overall = (
|
289 |
+
search_score * weights['search_quality'] +
|
290 |
+
cluster_score * weights['clustering_quality'] +
|
291 |
+
speed_score * weights['speed'] +
|
292 |
+
medical_score * weights['medical_relevance']
|
293 |
+
)
|
294 |
+
|
295 |
+
return min(1.0, max(0.0, overall))
|
296 |
+
|
297 |
+
def run_comprehensive_evaluation(self) -> Dict[str, Any]:
|
298 |
+
"""Run comprehensive evaluation of all embedding models"""
|
299 |
+
logger.info("Starting comprehensive embedding model evaluation...")
|
300 |
+
|
301 |
+
# Load medical chunks
|
302 |
+
self.medical_chunks = self.load_medical_chunks()
|
303 |
+
|
304 |
+
if len(self.medical_chunks) == 0:
|
305 |
+
raise ValueError("No medical chunks loaded for evaluation")
|
306 |
+
|
307 |
+
# Evaluate each model
|
308 |
+
results = {}
|
309 |
+
for model_name, model_path in self.embedding_models.items():
|
310 |
+
logger.info(f"\n📊 Evaluating: {model_name}")
|
311 |
+
results[model_name] = self.evaluate_embedding_model(model_name, model_path)
|
312 |
+
|
313 |
+
# Generate summary report
|
314 |
+
summary = self._generate_evaluation_summary(results)
|
315 |
+
|
316 |
+
# Save results
|
317 |
+
output_file = Path("src/embedding_evaluation_results.json")
|
318 |
+
with open(output_file, 'w') as f:
|
319 |
+
json.dump({
|
320 |
+
'evaluation_summary': summary,
|
321 |
+
'detailed_results': results,
|
322 |
+
'test_queries': self.test_queries,
|
323 |
+
'chunks_evaluated': len(self.medical_chunks)
|
324 |
+
}, f, indent=2)
|
325 |
+
|
326 |
+
logger.info(f"📋 Evaluation results saved to: {output_file}")
|
327 |
+
return summary
|
328 |
+
|
329 |
+
def _generate_evaluation_summary(self, results: Dict[str, Any]) -> Dict[str, Any]:
|
330 |
+
"""Generate evaluation summary with recommendations"""
|
331 |
+
|
332 |
+
valid_results = {k: v for k, v in results.items() if 'error' not in v}
|
333 |
+
|
334 |
+
if not valid_results:
|
335 |
+
return {'error': 'No models evaluated successfully'}
|
336 |
+
|
337 |
+
# Find best model
|
338 |
+
best_model = max(valid_results.items(), key=lambda x: x[1]['overall_score'])
|
339 |
+
|
340 |
+
# Calculate averages
|
341 |
+
avg_scores = {}
|
342 |
+
for metric in ['overall_score', 'avg_max_similarity', 'medical_content_precision']:
|
343 |
+
scores = [r.get(metric, 0) for r in valid_results.values()]
|
344 |
+
avg_scores[f'avg_{metric}'] = sum(scores) / len(scores) if scores else 0
|
345 |
+
|
346 |
+
summary = {
|
347 |
+
'best_model': {
|
348 |
+
'name': best_model[0],
|
349 |
+
'path': best_model[1]['model_path'],
|
350 |
+
'score': best_model[1]['overall_score'],
|
351 |
+
'strengths': []
|
352 |
+
},
|
353 |
+
'model_rankings': sorted(
|
354 |
+
[(name, res['overall_score']) for name, res in valid_results.items()],
|
355 |
+
key=lambda x: x[1], reverse=True
|
356 |
+
),
|
357 |
+
'evaluation_metrics': avg_scores,
|
358 |
+
'recommendation': '',
|
359 |
+
'models_tested': len(results),
|
360 |
+
'successful_evaluations': len(valid_results)
|
361 |
+
}
|
362 |
+
|
363 |
+
# Add strengths and recommendation
|
364 |
+
best_result = best_model[1]
|
365 |
+
strengths = []
|
366 |
+
|
367 |
+
if best_result.get('medical_content_precision', 0) > 0.7:
|
368 |
+
strengths.append("High medical content precision")
|
369 |
+
if best_result.get('dosage_query_accuracy', 0) > 0.6:
|
370 |
+
strengths.append("Good dosage information retrieval")
|
371 |
+
if best_result.get('cluster_purity', 0) > 0.6:
|
372 |
+
strengths.append("Effective content clustering")
|
373 |
+
if best_result.get('chunk_embed_time', 100) < 30:
|
374 |
+
strengths.append("Fast embedding generation")
|
375 |
+
|
376 |
+
summary['best_model']['strengths'] = strengths
|
377 |
+
|
378 |
+
summary['recommendation'] = (
|
379 |
+
f"Recommended model: {best_model[0]} with overall score {best_result['overall_score']:.3f}. "
|
380 |
+
f"This model shows {', '.join(strengths)} and is well-suited for maternal health content."
|
381 |
+
)
|
382 |
+
|
383 |
+
return summary
|
384 |
+
|
385 |
+
def main():
|
386 |
+
"""Main evaluation function"""
|
387 |
+
evaluator = MedicalEmbeddingEvaluator()
|
388 |
+
|
389 |
+
try:
|
390 |
+
summary = evaluator.run_comprehensive_evaluation()
|
391 |
+
|
392 |
+
# Print summary
|
393 |
+
logger.info("=" * 80)
|
394 |
+
logger.info("EMBEDDING MODEL EVALUATION COMPLETE!")
|
395 |
+
logger.info("=" * 80)
|
396 |
+
logger.info(f"🏆 Best Model: {summary['best_model']['name']}")
|
397 |
+
logger.info(f"📊 Overall Score: {summary['best_model']['score']:.3f}")
|
398 |
+
logger.info(f"💪 Strengths: {', '.join(summary['best_model']['strengths'])}")
|
399 |
+
logger.info(f"📝 Recommendation: {summary['recommendation']}")
|
400 |
+
|
401 |
+
logger.info("\n📈 Model Rankings:")
|
402 |
+
for i, (model, score) in enumerate(summary['model_rankings'], 1):
|
403 |
+
logger.info(f"{i}. {model}: {score:.3f}")
|
404 |
+
|
405 |
+
logger.info("=" * 80)
|
406 |
+
|
407 |
+
return summary
|
408 |
+
|
409 |
+
except Exception as e:
|
410 |
+
logger.error(f"❌ Evaluation failed: {e}")
|
411 |
+
return None
|
412 |
+
|
413 |
+
if __name__ == "__main__":
|
414 |
+
main()
|
src/enhanced_pdf_processor.py
ADDED
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import argparse
|
3 |
+
from unstructured.partition.pdf import partition_pdf
|
4 |
+
import logging
|
5 |
+
from tqdm import tqdm
|
6 |
+
import re
|
7 |
+
|
8 |
+
# Set up logging
|
9 |
+
logging.basicConfig(filename='pdf_processing.log', level=logging.INFO,
|
10 |
+
format='%(asctime)s - %(levelname)s - %(message)s')
|
11 |
+
|
12 |
+
def process_pdf_with_unstructured(pdf_path, output_dir):
|
13 |
+
"""
|
14 |
+
Processes a PDF file using unstructured.io, extracts content, and saves it as a Markdown file.
|
15 |
+
|
16 |
+
Args:
|
17 |
+
pdf_path (str): The path to the input PDF file.
|
18 |
+
output_dir (str): The directory to save the output Markdown file and extracted images.
|
19 |
+
"""
|
20 |
+
if not os.path.exists(pdf_path):
|
21 |
+
logging.error(f"PDF file not found at {pdf_path}")
|
22 |
+
print(f"Error: PDF file not found at {pdf_path}")
|
23 |
+
return False
|
24 |
+
|
25 |
+
# Cleaned up filename for fallback citation
|
26 |
+
pdf_basename = os.path.splitext(os.path.basename(pdf_path))[0]
|
27 |
+
# A simple regex to clean up common filename artifacts
|
28 |
+
cleaned_citation = re.sub(r'[\-_]', ' ', pdf_basename).replace('.pdf', '')
|
29 |
+
|
30 |
+
print(f"Processing {pdf_path} with unstructured.io...")
|
31 |
+
logging.info(f"Processing {pdf_path} with unstructured.io...")
|
32 |
+
|
33 |
+
try:
|
34 |
+
# Create a specific output directory for images from this PDF
|
35 |
+
pdf_output_dir = os.path.join(output_dir, pdf_basename)
|
36 |
+
os.makedirs(pdf_output_dir, exist_ok=True)
|
37 |
+
|
38 |
+
image_output_path = os.path.join(pdf_output_dir, "images")
|
39 |
+
os.makedirs(image_output_path, exist_ok=True)
|
40 |
+
|
41 |
+
print(f"Extracting images to: {image_output_path}")
|
42 |
+
|
43 |
+
elements = partition_pdf(
|
44 |
+
filename=pdf_path,
|
45 |
+
strategy="hi_res",
|
46 |
+
extract_images_in_pdf=True,
|
47 |
+
infer_table_structure=True,
|
48 |
+
chunking_strategy="by_title",
|
49 |
+
max_characters=4096,
|
50 |
+
new_after_n_chars=3800,
|
51 |
+
combine_text_under_n_chars=2048,
|
52 |
+
image_output_dir_path=image_output_path
|
53 |
+
)
|
54 |
+
|
55 |
+
# Attempt to extract a better citation from the document's text
|
56 |
+
try:
|
57 |
+
# Look for "Sri Lanka Journal of Obstetrics and Gynaecology" or similar patterns
|
58 |
+
full_text = "\\n".join([el.text for el in elements[:20]]) # Check first 20 elements
|
59 |
+
sljog_pattern = r"Sri Lanka Journal of Obstetrics and Gynaecology, \\d{4}; \\d+ \\(.*?\\): \\d+-\\d+"
|
60 |
+
match = re.search(sljog_pattern, full_text, re.IGNORECASE)
|
61 |
+
if match:
|
62 |
+
cleaned_citation = match.group(0).replace('\\n', ' ').strip()
|
63 |
+
else:
|
64 |
+
# Fallback to the first non-empty text element if no specific pattern is found
|
65 |
+
first_title = next((el.text for el in elements if el.text.strip()), None)
|
66 |
+
if first_title and len(first_title) < 150: # Assume titles are reasonably short
|
67 |
+
cleaned_citation = first_title.strip()
|
68 |
+
except Exception as citation_exc:
|
69 |
+
print(f"Could not automatically extract a detailed citation, falling back to filename. Reason: {citation_exc}")
|
70 |
+
logging.warning(f"Citation extraction failed for {pdf_path}, using fallback. Error: {citation_exc}")
|
71 |
+
|
72 |
+
markdown_content = []
|
73 |
+
# Add YAML frontmatter for citation
|
74 |
+
markdown_content.append("---")
|
75 |
+
markdown_content.append(f"citation: \"{cleaned_citation}\"")
|
76 |
+
markdown_content.append("---")
|
77 |
+
|
78 |
+
for element in elements:
|
79 |
+
if "Table" in str(type(element)):
|
80 |
+
if hasattr(element, 'metadata') and hasattr(element.metadata, 'text_as_html') and element.metadata.text_as_html:
|
81 |
+
markdown_content.append("## Table")
|
82 |
+
markdown_content.append(element.metadata.text_as_html)
|
83 |
+
elif "Image" in str(type(element)):
|
84 |
+
if hasattr(element, 'metadata') and hasattr(element.metadata, 'image_path') and element.metadata.image_path:
|
85 |
+
image_filename = os.path.basename(element.metadata.image_path)
|
86 |
+
relative_image_path = os.path.join("images", image_filename)
|
87 |
+
markdown_content.append(f"")
|
88 |
+
else:
|
89 |
+
markdown_content.append(element.text)
|
90 |
+
|
91 |
+
# Construct the output Markdown path
|
92 |
+
output_md_filename = f"{pdf_basename}.md"
|
93 |
+
output_md_path = os.path.join(pdf_output_dir, output_md_filename)
|
94 |
+
|
95 |
+
print(f"Saving Markdown output to: {output_md_path}")
|
96 |
+
|
97 |
+
with open(output_md_path, "w", encoding="utf-8") as f:
|
98 |
+
f.write("\\n\\n".join(markdown_content))
|
99 |
+
|
100 |
+
print(f"Successfully processed {pdf_path}")
|
101 |
+
logging.info(f"Successfully processed {pdf_path}")
|
102 |
+
return True
|
103 |
+
|
104 |
+
except Exception as e:
|
105 |
+
print(f"An error occurred while processing {pdf_path}: {e}")
|
106 |
+
logging.error(f"An error occurred while processing {pdf_path}: {e}")
|
107 |
+
return False
|
108 |
+
|
109 |
+
def process_directory(input_dir, output_dir):
|
110 |
+
"""
|
111 |
+
Processes all PDF files in a given directory.
|
112 |
+
|
113 |
+
Args:
|
114 |
+
input_dir (str): The path to the directory containing PDF files.
|
115 |
+
output_dir (str): The directory to save the output Markdown files.
|
116 |
+
"""
|
117 |
+
pdf_files = [f for f in os.listdir(input_dir) if f.endswith('.pdf')]
|
118 |
+
if not pdf_files:
|
119 |
+
print(f"No PDF files found in {input_dir}")
|
120 |
+
return
|
121 |
+
|
122 |
+
print(f"Found {len(pdf_files)} PDF files to process.")
|
123 |
+
|
124 |
+
success_count = 0
|
125 |
+
failure_count = 0
|
126 |
+
|
127 |
+
for pdf_file in tqdm(pdf_files, desc="Processing PDFs"):
|
128 |
+
pdf_path = os.path.join(input_dir, pdf_file)
|
129 |
+
if process_pdf_with_unstructured(pdf_path, output_dir):
|
130 |
+
success_count += 1
|
131 |
+
else:
|
132 |
+
failure_count += 1
|
133 |
+
|
134 |
+
print(f"\nProcessing complete.")
|
135 |
+
print(f"Successfully processed: {success_count} files")
|
136 |
+
print(f"Failed to process: {failure_count} files")
|
137 |
+
logging.info(f"Processing complete. Success: {success_count}, Failed: {failure_count}")
|
138 |
+
|
139 |
+
|
140 |
+
def main():
|
141 |
+
parser = argparse.ArgumentParser(description="Process a PDF file or a directory of PDF files with unstructured.io to extract content as Markdown.")
|
142 |
+
parser.add_argument("input_path", type=str, help="The path to the input PDF file or directory.")
|
143 |
+
parser.add_argument("--output_dir", type=str, default="src/processed_markdown", help="The directory to save the output Markdown file.")
|
144 |
+
|
145 |
+
args = parser.parse_args()
|
146 |
+
|
147 |
+
# Ensure the main output directory exists
|
148 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
149 |
+
|
150 |
+
if os.path.isdir(args.input_path):
|
151 |
+
process_directory(args.input_path, args.output_dir)
|
152 |
+
elif os.path.isfile(args.input_path) and args.input_path.endswith('.pdf'):
|
153 |
+
process_pdf_with_unstructured(args.input_path, args.output_dir)
|
154 |
+
else:
|
155 |
+
print(f"Error: Invalid input path. Please provide a valid PDF file or a directory.")
|
156 |
+
logging.error(f"Invalid input path: {args.input_path}")
|
157 |
+
|
158 |
+
|
159 |
+
if __name__ == "__main__":
|
160 |
+
main()
|
src/groq_medical_chatbot.py
ADDED
@@ -0,0 +1,498 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Groq Medical Chatbot Interface v2.0
|
3 |
+
FREE Groq Cloud API integration for advanced medical reasoning
|
4 |
+
"""
|
5 |
+
|
6 |
+
import gradio as gr
|
7 |
+
import time
|
8 |
+
import json
|
9 |
+
import os
|
10 |
+
from datetime import datetime
|
11 |
+
from typing import List, Tuple, Dict, Any
|
12 |
+
|
13 |
+
# Import our Groq medical RAG system
|
14 |
+
from groq_medical_rag import GroqMedicalRAG, MedicalResponse
|
15 |
+
|
16 |
+
class GroqMedicalChatbot:
|
17 |
+
"""Professional medical chatbot interface using Groq-powered RAG system"""
|
18 |
+
|
19 |
+
def __init__(self):
|
20 |
+
"""Initialize the Groq medical chatbot"""
|
21 |
+
self.rag_system = None
|
22 |
+
self.chat_history = []
|
23 |
+
self.session_stats = {
|
24 |
+
"queries_processed": 0,
|
25 |
+
"total_response_time": 0,
|
26 |
+
"avg_confidence": 0,
|
27 |
+
"llm_responses": 0,
|
28 |
+
"template_responses": 0,
|
29 |
+
"session_start": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
30 |
+
}
|
31 |
+
|
32 |
+
# Check for Groq API key
|
33 |
+
self.groq_api_key = os.getenv("GROQ_API_KEY")
|
34 |
+
|
35 |
+
# Initialize RAG system
|
36 |
+
self._initialize_rag_system()
|
37 |
+
|
38 |
+
def _initialize_rag_system(self):
|
39 |
+
"""Initialize the Groq RAG system"""
|
40 |
+
try:
|
41 |
+
if not self.groq_api_key:
|
42 |
+
print("⚠️ GROQ_API_KEY not found in environment variables")
|
43 |
+
print("🔗 Get your free API key at: https://console.groq.com/keys")
|
44 |
+
print("📝 Set it with: export GROQ_API_KEY='your_api_key_here'")
|
45 |
+
self.rag_system = None
|
46 |
+
return
|
47 |
+
|
48 |
+
print("🚀 Initializing Groq Medical RAG System...")
|
49 |
+
self.rag_system = GroqMedicalRAG(groq_api_key=self.groq_api_key)
|
50 |
+
print("✅ Groq Medical RAG System initialized successfully!")
|
51 |
+
|
52 |
+
except Exception as e:
|
53 |
+
print(f"❌ Error initializing Groq RAG system: {e}")
|
54 |
+
print("🔄 Attempting to initialize without Groq...")
|
55 |
+
|
56 |
+
# Fallback to simple RAG system
|
57 |
+
try:
|
58 |
+
from simple_medical_rag import SimpleMedicalRAG
|
59 |
+
self.rag_system = SimpleMedicalRAG()
|
60 |
+
print("✅ Fallback to simple medical RAG system")
|
61 |
+
except Exception as e2:
|
62 |
+
print(f"❌ Failed to initialize any RAG system: {e2}")
|
63 |
+
self.rag_system = None
|
64 |
+
|
65 |
+
def process_query(self, query: str, history: List[Tuple[str, str]], use_llm: bool = True) -> Tuple[List[Tuple[str, str]], str]:
|
66 |
+
"""Process medical query and return response"""
|
67 |
+
if not self.rag_system:
|
68 |
+
error_msg = "❌ **System Error**: Medical RAG system not initialized.\n\n"
|
69 |
+
error_msg += "Please ensure GROQ_API_KEY is set:\n"
|
70 |
+
error_msg += "1. Get free API key: https://console.groq.com/keys\n"
|
71 |
+
error_msg += "2. Set environment variable: `export GROQ_API_KEY='your_key'`\n"
|
72 |
+
error_msg += "3. Restart the application"
|
73 |
+
|
74 |
+
history.append((query, error_msg))
|
75 |
+
return history, ""
|
76 |
+
|
77 |
+
if not query.strip():
|
78 |
+
return history, ""
|
79 |
+
|
80 |
+
start_time = time.time()
|
81 |
+
|
82 |
+
try:
|
83 |
+
# Check if we have Groq integration
|
84 |
+
has_groq = hasattr(self.rag_system, 'groq_client')
|
85 |
+
|
86 |
+
# Process query with RAG system
|
87 |
+
if has_groq:
|
88 |
+
response = self.rag_system.query(query, k=5, use_llm=use_llm)
|
89 |
+
else:
|
90 |
+
response = self.rag_system.query(query, k=5)
|
91 |
+
response.llm_reasoning = False # Mark as template-based
|
92 |
+
|
93 |
+
# Format response for display
|
94 |
+
formatted_response = self._format_response_for_display(response, has_groq)
|
95 |
+
|
96 |
+
# Update session statistics
|
97 |
+
query_time = time.time() - start_time
|
98 |
+
self._update_session_stats(query_time, response.confidence, response.llm_reasoning)
|
99 |
+
|
100 |
+
# Add to chat history
|
101 |
+
history.append((query, formatted_response))
|
102 |
+
|
103 |
+
return history, ""
|
104 |
+
|
105 |
+
except Exception as e:
|
106 |
+
error_msg = f"❌ **Error processing query**: {str(e)}\n\n⚠️ Please try rephrasing your question or contact support."
|
107 |
+
history.append((query, error_msg))
|
108 |
+
return history, ""
|
109 |
+
|
110 |
+
def _format_response_for_display(self, response: MedicalResponse, has_groq: bool) -> str:
|
111 |
+
"""Format medical response for beautiful display in Gradio"""
|
112 |
+
|
113 |
+
# LLM vs Template indicator
|
114 |
+
reasoning_emoji = "🤖" if response.llm_reasoning else "📋"
|
115 |
+
reasoning_text = "AI Reasoning" if response.llm_reasoning else "Template-based"
|
116 |
+
|
117 |
+
# Confidence level indicator
|
118 |
+
confidence_emoji = "🟢" if response.confidence > 0.7 else "🟡" if response.confidence > 0.5 else "🔴"
|
119 |
+
confidence_text = f"{confidence_emoji} **Confidence: {response.confidence:.1%}**"
|
120 |
+
|
121 |
+
# Response type indicator
|
122 |
+
type_emoji = "💊" if "dosage" in response.response_type else "🚨" if "emergency" in response.response_type else "🏥"
|
123 |
+
|
124 |
+
# Main response
|
125 |
+
formatted_response = f"""
|
126 |
+
{type_emoji} **Medical Information**
|
127 |
+
|
128 |
+
{response.answer}
|
129 |
+
|
130 |
+
---
|
131 |
+
|
132 |
+
📊 **Response Details**
|
133 |
+
{reasoning_emoji} **Method**: {reasoning_text}
|
134 |
+
{confidence_text}
|
135 |
+
📚 **Sources**: {len(response.sources)} documents referenced
|
136 |
+
|
137 |
+
"""
|
138 |
+
|
139 |
+
# Add top sources
|
140 |
+
if response.sources:
|
141 |
+
formatted_response += "📖 **Primary Sources**:\n"
|
142 |
+
for i, source in enumerate(response.sources[:3], 1):
|
143 |
+
doc_name = source['document'].replace('.pdf', '').replace('-', ' ').title()
|
144 |
+
formatted_response += f"{i}. {doc_name} (Relevance: {source['relevance_score']:.1%})\n"
|
145 |
+
formatted_response += "\n"
|
146 |
+
|
147 |
+
# Add Groq status if applicable
|
148 |
+
if has_groq and response.llm_reasoning:
|
149 |
+
formatted_response += "🌟 **Powered by**: Groq Cloud (FREE tier) + Llama 3.1-8B\n\n"
|
150 |
+
elif has_groq and not response.llm_reasoning:
|
151 |
+
formatted_response += "⚡ **Fallback**: Template-based response (Groq available)\n\n"
|
152 |
+
elif not has_groq:
|
153 |
+
formatted_response += "⚠️ **Note**: Using template responses (Set GROQ_API_KEY for AI reasoning)\n\n"
|
154 |
+
|
155 |
+
# Add medical disclaimer
|
156 |
+
formatted_response += f"""
|
157 |
+
---
|
158 |
+
|
159 |
+
{response.medical_disclaimer}
|
160 |
+
|
161 |
+
🔗 **Note**: This response is based on Sri Lankan maternal health guidelines and should be used in conjunction with current clinical protocols.
|
162 |
+
"""
|
163 |
+
|
164 |
+
return formatted_response
|
165 |
+
|
166 |
+
def _update_session_stats(self, query_time: float, confidence: float, llm_reasoning: bool):
|
167 |
+
"""Update session statistics"""
|
168 |
+
self.session_stats["queries_processed"] += 1
|
169 |
+
self.session_stats["total_response_time"] += query_time
|
170 |
+
|
171 |
+
if llm_reasoning:
|
172 |
+
self.session_stats["llm_responses"] += 1
|
173 |
+
else:
|
174 |
+
self.session_stats["template_responses"] += 1
|
175 |
+
|
176 |
+
# Update average confidence
|
177 |
+
current_avg = self.session_stats["avg_confidence"]
|
178 |
+
queries = self.session_stats["queries_processed"]
|
179 |
+
self.session_stats["avg_confidence"] = ((current_avg * (queries - 1)) + confidence) / queries
|
180 |
+
|
181 |
+
def get_system_info(self) -> str:
|
182 |
+
"""Get system information for display"""
|
183 |
+
if not self.rag_system:
|
184 |
+
return """❌ **System Status**: Not initialized
|
185 |
+
|
186 |
+
🔧 **Setup Required**:
|
187 |
+
1. Get free Groq API key: https://console.groq.com/keys
|
188 |
+
2. Set environment variable: `export GROQ_API_KEY='your_key'`
|
189 |
+
3. Restart the application
|
190 |
+
|
191 |
+
💡 **Groq Benefits**: FREE LLM reasoning for medical queries"""
|
192 |
+
|
193 |
+
try:
|
194 |
+
stats = self.rag_system.get_system_stats()
|
195 |
+
has_groq = 'groq_integration' in stats
|
196 |
+
|
197 |
+
system_info = f"""
|
198 |
+
🏥 **Sri Lankan Maternal Health Assistant v2.0**
|
199 |
+
|
200 |
+
📊 **System Status**: {stats['status'].upper()} ✅
|
201 |
+
|
202 |
+
**Knowledge Base**:
|
203 |
+
• 📚 Total Documents: {stats['vector_store']['total_chunks']:,} medical chunks
|
204 |
+
• 🧠 Embedding Model: {stats['vector_store']['embedding_model']}
|
205 |
+
• 💾 Vector Store Size: {stats['vector_store']['vector_store_size_mb']} MB
|
206 |
+
• ⚡ Approach: Simplified document-based retrieval
|
207 |
+
|
208 |
+
"""
|
209 |
+
|
210 |
+
# Add Groq integration info
|
211 |
+
if has_groq:
|
212 |
+
groq_info = stats['groq_integration']
|
213 |
+
system_info += f"""
|
214 |
+
**🤖 Groq Integration** (FREE):
|
215 |
+
• Model: {groq_info['groq_model']}
|
216 |
+
• Status: {groq_info['groq_api_status']} ✅
|
217 |
+
• LLM Reasoning: {groq_info['llm_reasoning']}
|
218 |
+
• Daily Limit: 5,000 tokens (FREE tier)
|
219 |
+
|
220 |
+
"""
|
221 |
+
else:
|
222 |
+
system_info += """
|
223 |
+
**⚠️ Groq Integration**: Not available
|
224 |
+
• Get free API key: https://console.groq.com/keys
|
225 |
+
• Enables advanced medical reasoning
|
226 |
+
• 5,000 free tokens/day
|
227 |
+
|
228 |
+
"""
|
229 |
+
|
230 |
+
# Add content distribution
|
231 |
+
system_info += "**Content Distribution**:\n"
|
232 |
+
for content_type, count in stats['vector_store']['content_type_distribution'].items():
|
233 |
+
percentage = (count / stats['vector_store']['total_chunks']) * 100
|
234 |
+
content_info = content_type.replace('_', ' ').title()
|
235 |
+
system_info += f"• {content_info}: {count:,} chunks ({percentage:.1f}%)\n"
|
236 |
+
|
237 |
+
return system_info
|
238 |
+
|
239 |
+
except Exception as e:
|
240 |
+
return f"❌ **Error retrieving system info**: {str(e)}"
|
241 |
+
|
242 |
+
def get_session_stats(self) -> str:
|
243 |
+
"""Get session statistics for display"""
|
244 |
+
if self.session_stats["queries_processed"] == 0:
|
245 |
+
return "📈 **Session Statistics**: No queries processed yet"
|
246 |
+
|
247 |
+
avg_response_time = self.session_stats["total_response_time"] / self.session_stats["queries_processed"]
|
248 |
+
llm_percentage = (self.session_stats["llm_responses"] / self.session_stats["queries_processed"]) * 100
|
249 |
+
|
250 |
+
return f"""
|
251 |
+
📈 **Session Statistics**
|
252 |
+
|
253 |
+
🕐 **Session Started**: {self.session_stats["session_start"]}
|
254 |
+
📝 **Queries Processed**: {self.session_stats["queries_processed"]}
|
255 |
+
⚡ **Avg Response Time**: {avg_response_time:.2f} seconds
|
256 |
+
🎯 **Avg Confidence**: {self.session_stats["avg_confidence"]:.1%}
|
257 |
+
|
258 |
+
**Response Methods**:
|
259 |
+
🤖 **AI Reasoning**: {self.session_stats["llm_responses"]} ({llm_percentage:.1f}%)
|
260 |
+
📋 **Template-based**: {self.session_stats["template_responses"]} ({100-llm_percentage:.1f}%)
|
261 |
+
"""
|
262 |
+
|
263 |
+
def clear_chat(self) -> Tuple[List, str]:
|
264 |
+
"""Clear chat history"""
|
265 |
+
self.chat_history = []
|
266 |
+
return [], ""
|
267 |
+
|
268 |
+
def get_example_queries(self) -> List[str]:
|
269 |
+
"""Get example medical queries"""
|
270 |
+
return [
|
271 |
+
"What is the dosage of magnesium sulfate for preeclampsia?",
|
272 |
+
"How to manage postpartum hemorrhage emergency?",
|
273 |
+
"Normal fetal heart rate during labor monitoring?",
|
274 |
+
"Management protocol for breech delivery?",
|
275 |
+
"Antenatal care schedule for high-risk pregnancies?",
|
276 |
+
"Signs and symptoms of preeclampsia?",
|
277 |
+
"When to perform cesarean delivery?",
|
278 |
+
"Postpartum care guidelines for new mothers?"
|
279 |
+
]
|
280 |
+
|
281 |
+
def create_groq_medical_chatbot_interface():
|
282 |
+
"""Create the main Gradio interface"""
|
283 |
+
|
284 |
+
# Initialize chatbot
|
285 |
+
chatbot = GroqMedicalChatbot()
|
286 |
+
|
287 |
+
# Custom CSS for medical theme
|
288 |
+
css = """
|
289 |
+
.gradio-container {
|
290 |
+
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
291 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
292 |
+
}
|
293 |
+
.main-header {
|
294 |
+
text-align: center;
|
295 |
+
color: #2c5aa0;
|
296 |
+
font-size: 2.2em;
|
297 |
+
font-weight: bold;
|
298 |
+
margin-bottom: 20px;
|
299 |
+
text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
|
300 |
+
}
|
301 |
+
.description {
|
302 |
+
text-align: center;
|
303 |
+
font-size: 1.1em;
|
304 |
+
color: #555;
|
305 |
+
margin-bottom: 25px;
|
306 |
+
padding: 15px;
|
307 |
+
background: rgba(255,255,255,0.9);
|
308 |
+
border-radius: 10px;
|
309 |
+
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
310 |
+
}
|
311 |
+
.tab-content {
|
312 |
+
background: white;
|
313 |
+
border-radius: 15px;
|
314 |
+
padding: 20px;
|
315 |
+
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
|
316 |
+
}
|
317 |
+
.medical-disclaimer {
|
318 |
+
background: #fff3cd;
|
319 |
+
border: 1px solid #ffeaa7;
|
320 |
+
border-radius: 8px;
|
321 |
+
padding: 12px;
|
322 |
+
margin: 10px 0;
|
323 |
+
font-size: 0.9em;
|
324 |
+
color: #856404;
|
325 |
+
}
|
326 |
+
"""
|
327 |
+
|
328 |
+
with gr.Blocks(css=css, title="Sri Lankan Maternal Health Assistant") as interface:
|
329 |
+
|
330 |
+
# Header
|
331 |
+
gr.HTML("""
|
332 |
+
<div class="main-header">
|
333 |
+
🏥 Sri Lankan Maternal Health Assistant v2.0
|
334 |
+
</div>
|
335 |
+
<div class="description">
|
336 |
+
<strong>🤖 Powered by FREE Groq Cloud API + Advanced Medical Reasoning</strong><br/>
|
337 |
+
Professional medical information based on Sri Lankan maternal health guidelines.<br/>
|
338 |
+
<em>Enhanced with Llama 3.1-8B for intelligent clinical responses</em>
|
339 |
+
</div>
|
340 |
+
""")
|
341 |
+
|
342 |
+
with gr.Tabs():
|
343 |
+
# Main Chat Interface
|
344 |
+
with gr.Tab("💬 Medical Consultation"):
|
345 |
+
with gr.Row():
|
346 |
+
with gr.Column(scale=4):
|
347 |
+
chatbot_interface = gr.Chatbot(
|
348 |
+
label="Medical Assistant",
|
349 |
+
height=500,
|
350 |
+
placeholder="Welcome! Ask me about maternal health guidelines, medications, procedures, or emergency protocols."
|
351 |
+
)
|
352 |
+
|
353 |
+
with gr.Row():
|
354 |
+
msg = gr.Textbox(
|
355 |
+
label="Your Medical Question",
|
356 |
+
placeholder="E.g., What is the management protocol for preeclampsia?",
|
357 |
+
lines=2,
|
358 |
+
max_lines=5
|
359 |
+
)
|
360 |
+
submit_btn = gr.Button("🩺 Ask", variant="primary", scale=1)
|
361 |
+
|
362 |
+
with gr.Row():
|
363 |
+
use_llm_checkbox = gr.Checkbox(
|
364 |
+
label="🤖 Use AI Reasoning (Groq)",
|
365 |
+
value=True,
|
366 |
+
info="Uncheck for template-based responses"
|
367 |
+
)
|
368 |
+
clear_btn = gr.Button("🗑️ Clear Chat", variant="secondary")
|
369 |
+
|
370 |
+
with gr.Column(scale=1):
|
371 |
+
gr.HTML("<h3>📝 Example Questions</h3>")
|
372 |
+
example_queries = chatbot.get_example_queries()
|
373 |
+
for query in example_queries:
|
374 |
+
gr.Button(query, size="sm").click(
|
375 |
+
lambda x=query: (x, []),
|
376 |
+
outputs=[msg, chatbot_interface]
|
377 |
+
)
|
378 |
+
|
379 |
+
# System Information
|
380 |
+
with gr.Tab("📊 System Status"):
|
381 |
+
with gr.Row():
|
382 |
+
with gr.Column():
|
383 |
+
system_info = gr.Textbox(
|
384 |
+
label="System Information",
|
385 |
+
value=chatbot.get_system_info(),
|
386 |
+
lines=20,
|
387 |
+
max_lines=25,
|
388 |
+
interactive=False
|
389 |
+
)
|
390 |
+
refresh_btn = gr.Button("🔄 Refresh System Info", variant="secondary")
|
391 |
+
|
392 |
+
with gr.Column():
|
393 |
+
session_stats = gr.Textbox(
|
394 |
+
label="Session Statistics",
|
395 |
+
value=chatbot.get_session_stats(),
|
396 |
+
lines=20,
|
397 |
+
max_lines=25,
|
398 |
+
interactive=False
|
399 |
+
)
|
400 |
+
stats_refresh_btn = gr.Button("📈 Refresh Stats", variant="secondary")
|
401 |
+
|
402 |
+
# Setup Instructions
|
403 |
+
with gr.Tab("⚙️ Setup & Configuration"):
|
404 |
+
gr.HTML("""
|
405 |
+
<div class="tab-content">
|
406 |
+
<h2>🚀 Quick Setup for FREE Groq Integration</h2>
|
407 |
+
|
408 |
+
<h3>1. Get Your FREE Groq API Key</h3>
|
409 |
+
<ol>
|
410 |
+
<li>Visit: <a href="https://console.groq.com/keys" target="_blank">https://console.groq.com/keys</a></li>
|
411 |
+
<li>Sign up for a free account</li>
|
412 |
+
<li>Create a new API key</li>
|
413 |
+
<li>Copy the API key</li>
|
414 |
+
</ol>
|
415 |
+
|
416 |
+
<h3>2. Set Environment Variable</h3>
|
417 |
+
<p><strong>macOS/Linux:</strong></p>
|
418 |
+
<code>export GROQ_API_KEY='your_api_key_here'</code>
|
419 |
+
|
420 |
+
<p><strong>Windows:</strong></p>
|
421 |
+
<code>set GROQ_API_KEY=your_api_key_here</code>
|
422 |
+
|
423 |
+
<h3>3. Restart the Application</h3>
|
424 |
+
<p>After setting the API key, restart this application to enable AI reasoning.</p>
|
425 |
+
|
426 |
+
<h3>🌟 Benefits of Groq Integration</h3>
|
427 |
+
<ul>
|
428 |
+
<li><strong>FREE:</strong> 5,000 tokens per day at no cost</li>
|
429 |
+
<li><strong>Fast:</strong> Ultra-fast inference with Groq's specialized hardware</li>
|
430 |
+
<li><strong>Smart:</strong> Llama 3.1-8B model with advanced medical reasoning</li>
|
431 |
+
<li><strong>Professional:</strong> Structured clinical responses</li>
|
432 |
+
</ul>
|
433 |
+
|
434 |
+
<div class="medical-disclaimer">
|
435 |
+
<strong>⚠️ Medical Disclaimer:</strong> This system provides educational information only and should not replace professional medical advice. Always consult qualified healthcare providers for clinical decisions.
|
436 |
+
</div>
|
437 |
+
</div>
|
438 |
+
""")
|
439 |
+
|
440 |
+
# Event handlers
|
441 |
+
def submit_query(query, history, use_llm):
|
442 |
+
return chatbot.process_query(query, history, use_llm)
|
443 |
+
|
444 |
+
def refresh_system():
|
445 |
+
return chatbot.get_system_info()
|
446 |
+
|
447 |
+
def refresh_stats():
|
448 |
+
return chatbot.get_session_stats()
|
449 |
+
|
450 |
+
def clear_chat_handler():
|
451 |
+
return chatbot.clear_chat()
|
452 |
+
|
453 |
+
# Connect events
|
454 |
+
submit_btn.click(
|
455 |
+
submit_query,
|
456 |
+
inputs=[msg, chatbot_interface, use_llm_checkbox],
|
457 |
+
outputs=[chatbot_interface, msg]
|
458 |
+
)
|
459 |
+
|
460 |
+
msg.submit(
|
461 |
+
submit_query,
|
462 |
+
inputs=[msg, chatbot_interface, use_llm_checkbox],
|
463 |
+
outputs=[chatbot_interface, msg]
|
464 |
+
)
|
465 |
+
|
466 |
+
clear_btn.click(
|
467 |
+
clear_chat_handler,
|
468 |
+
outputs=[chatbot_interface, msg]
|
469 |
+
)
|
470 |
+
|
471 |
+
refresh_btn.click(
|
472 |
+
refresh_system,
|
473 |
+
outputs=[system_info]
|
474 |
+
)
|
475 |
+
|
476 |
+
stats_refresh_btn.click(
|
477 |
+
refresh_stats,
|
478 |
+
outputs=[session_stats]
|
479 |
+
)
|
480 |
+
|
481 |
+
return interface
|
482 |
+
|
483 |
+
def main():
|
484 |
+
"""Launch the Groq medical chatbot"""
|
485 |
+
print("🚀 Starting Groq Medical Chatbot...")
|
486 |
+
|
487 |
+
interface = create_groq_medical_chatbot_interface()
|
488 |
+
|
489 |
+
# Launch with appropriate settings
|
490 |
+
interface.launch(
|
491 |
+
server_name="0.0.0.0",
|
492 |
+
server_port=7860,
|
493 |
+
share=False,
|
494 |
+
debug=False
|
495 |
+
)
|
496 |
+
|
497 |
+
if __name__ == "__main__":
|
498 |
+
main()
|
src/groq_medical_rag.py
ADDED
@@ -0,0 +1,366 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Groq Medical RAG System v2.0
|
3 |
+
FREE Groq Cloud API integration for advanced medical reasoning
|
4 |
+
"""
|
5 |
+
|
6 |
+
import os
|
7 |
+
import time
|
8 |
+
import logging
|
9 |
+
import numpy as np
|
10 |
+
from typing import List, Dict, Any, Optional, Tuple
|
11 |
+
from dataclasses import dataclass
|
12 |
+
from dotenv import load_dotenv
|
13 |
+
from pathlib import Path
|
14 |
+
import argparse
|
15 |
+
import shutil
|
16 |
+
import re
|
17 |
+
|
18 |
+
# Langchain for document loading and splitting
|
19 |
+
from langchain_community.document_loaders import UnstructuredMarkdownLoader
|
20 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
21 |
+
|
22 |
+
# Sentence Transformers for re-ranking
|
23 |
+
from sentence_transformers import CrossEncoder
|
24 |
+
|
25 |
+
# Groq API integration
|
26 |
+
from groq import Groq
|
27 |
+
from tenacity import retry, stop_after_attempt, wait_fixed, before_sleep_log
|
28 |
+
|
29 |
+
# Load environment variables from .env file
|
30 |
+
load_dotenv()
|
31 |
+
|
32 |
+
# Import our simplified components
|
33 |
+
from .simple_vector_store import SimpleVectorStore, SearchResult
|
34 |
+
|
35 |
+
@dataclass
|
36 |
+
class MedicalResponse:
|
37 |
+
"""Enhanced medical response structure"""
|
38 |
+
answer: str
|
39 |
+
confidence: float
|
40 |
+
sources: List[str]
|
41 |
+
query_time: float
|
42 |
+
|
43 |
+
class GroqMedicalRAG:
|
44 |
+
"""Groq-powered Medical RAG System v2.0 - FREE LLM integration"""
|
45 |
+
|
46 |
+
def __init__(self,
|
47 |
+
vector_store_dir: str = "simple_vector_store",
|
48 |
+
processed_docs_dir: str = "src/processed_markdown",
|
49 |
+
groq_api_key: Optional[str] = None):
|
50 |
+
"""Initialize the Groq medical RAG system"""
|
51 |
+
# Get the absolute path to the project root directory
|
52 |
+
project_root = Path(__file__).parent.parent.resolve()
|
53 |
+
|
54 |
+
self.vector_store_dir = project_root / vector_store_dir
|
55 |
+
self.processed_docs_dir = project_root / processed_docs_dir
|
56 |
+
|
57 |
+
# Initialize Groq client
|
58 |
+
self.groq_api_key = groq_api_key or os.getenv("GROQ_API_KEY")
|
59 |
+
if not self.groq_api_key:
|
60 |
+
raise ValueError("GROQ_API_KEY environment variable not set. Get your free API key from https://console.groq.com/keys")
|
61 |
+
|
62 |
+
self.groq_client = Groq(api_key=self.groq_api_key)
|
63 |
+
self.model_name = "llama3-70b-8192"
|
64 |
+
|
65 |
+
# Initialize Cross-Encoder for re-ranking
|
66 |
+
self.reranker = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')
|
67 |
+
|
68 |
+
# Initialize components
|
69 |
+
self.vector_store = None
|
70 |
+
|
71 |
+
self.setup_logging()
|
72 |
+
self._initialize_system()
|
73 |
+
|
74 |
+
def setup_logging(self):
|
75 |
+
"""Setup logging for the RAG system"""
|
76 |
+
logging.basicConfig(
|
77 |
+
level=logging.INFO,
|
78 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
79 |
+
)
|
80 |
+
self.logger = logging.getLogger(__name__)
|
81 |
+
|
82 |
+
def _initialize_system(self, force_recreate: bool = False):
|
83 |
+
"""Initialize the RAG system components"""
|
84 |
+
try:
|
85 |
+
# If forcing recreation, delete the old vector store
|
86 |
+
if force_recreate and self.vector_store_dir.exists():
|
87 |
+
self.logger.warning(f"Recreating index as requested. Deleting {self.vector_store_dir}...")
|
88 |
+
shutil.rmtree(self.vector_store_dir)
|
89 |
+
|
90 |
+
# Initialize vector store
|
91 |
+
self.vector_store = SimpleVectorStore(vector_store_dir=self.vector_store_dir)
|
92 |
+
|
93 |
+
# Try to load existing vector store
|
94 |
+
if not self.vector_store.load_vector_store():
|
95 |
+
self.logger.info("Creating new vector store from documents...")
|
96 |
+
self._create_vector_store()
|
97 |
+
else:
|
98 |
+
self.logger.info("Loaded existing vector store")
|
99 |
+
|
100 |
+
# Test Groq connection
|
101 |
+
self._test_groq_connection()
|
102 |
+
|
103 |
+
self.logger.info("Groq Medical RAG system initialized successfully")
|
104 |
+
|
105 |
+
except Exception as e:
|
106 |
+
self.logger.error(f"Error initializing RAG system: {e}")
|
107 |
+
raise
|
108 |
+
|
109 |
+
@retry(
|
110 |
+
stop=stop_after_attempt(3),
|
111 |
+
wait=wait_fixed(2),
|
112 |
+
before_sleep=before_sleep_log(logging.getLogger(__name__), logging.INFO)
|
113 |
+
)
|
114 |
+
def _test_groq_connection(self):
|
115 |
+
"""Test Groq API connection with retry logic."""
|
116 |
+
try:
|
117 |
+
self.groq_client.chat.completions.create(
|
118 |
+
model=self.model_name,
|
119 |
+
messages=[{"role": "user", "content": "Test"}],
|
120 |
+
max_tokens=10,
|
121 |
+
)
|
122 |
+
self.logger.info("✅ Groq API connection successful")
|
123 |
+
except Exception as e:
|
124 |
+
self.logger.error(f"❌ Groq API connection failed: {e}")
|
125 |
+
raise
|
126 |
+
|
127 |
+
def _create_vector_store(self):
|
128 |
+
"""Create vector store from processed markdown documents."""
|
129 |
+
self.logger.info(f"Checking for documents in {self.processed_docs_dir}...")
|
130 |
+
|
131 |
+
doc_files = list(self.processed_docs_dir.glob("**/*.md"))
|
132 |
+
if not doc_files:
|
133 |
+
self.logger.error(f"No markdown files found in {self.processed_docs_dir}. Please run the enhanced_pdf_processor.py script first.")
|
134 |
+
raise FileNotFoundError(f"No markdown files found in {self.processed_docs_dir}")
|
135 |
+
|
136 |
+
self.logger.info(f"Found {len(doc_files)} markdown documents to process.")
|
137 |
+
|
138 |
+
# Load documents using UnstructuredMarkdownLoader
|
139 |
+
all_docs = []
|
140 |
+
for doc_path in doc_files:
|
141 |
+
try:
|
142 |
+
loader = UnstructuredMarkdownLoader(str(doc_path))
|
143 |
+
loaded_docs = loader.load()
|
144 |
+
|
145 |
+
# We still need to ensure the 'source' is present for our context string.
|
146 |
+
for doc in loaded_docs:
|
147 |
+
if 'source' not in doc.metadata:
|
148 |
+
doc.metadata['source'] = str(doc_path)
|
149 |
+
|
150 |
+
all_docs.extend(loaded_docs)
|
151 |
+
except Exception as e:
|
152 |
+
self.logger.error(f"Error loading {doc_path}: {e}")
|
153 |
+
|
154 |
+
if not all_docs:
|
155 |
+
self.logger.error("Failed to load any documents. Vector store not created.")
|
156 |
+
return
|
157 |
+
|
158 |
+
# Split documents into chunks with smaller size and overlap
|
159 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
160 |
+
chunk_size=1024, # Reduced from 2048
|
161 |
+
chunk_overlap=128, # Reduced from 256
|
162 |
+
separators=["\n\n", "\n", " ", ""]
|
163 |
+
)
|
164 |
+
chunks = text_splitter.split_documents(all_docs)
|
165 |
+
|
166 |
+
self.logger.info(f"Created {len(chunks)} chunks from {len(all_docs)} documents.")
|
167 |
+
|
168 |
+
# Create embeddings and build index
|
169 |
+
embeddings, count = self.vector_store.create_embeddings(chunks)
|
170 |
+
self.vector_store.build_index(embeddings)
|
171 |
+
self.vector_store.save_vector_store()
|
172 |
+
|
173 |
+
self.logger.info(f"Created vector store with {count} embeddings.")
|
174 |
+
|
175 |
+
def query(self,
|
176 |
+
query: str,
|
177 |
+
history: Optional[List[Dict[str, str]]] = None,
|
178 |
+
k: int = 15, # Reduced from 30
|
179 |
+
top_n_rerank: int = 3, # Reduced from 5
|
180 |
+
use_llm: bool = True) -> MedicalResponse:
|
181 |
+
"""Query the Groq medical RAG system with re-ranking."""
|
182 |
+
start_time = time.time()
|
183 |
+
|
184 |
+
# Stage 1: Initial retrieval from vector store
|
185 |
+
docs = self.vector_store.search(query=query, k=k)
|
186 |
+
|
187 |
+
if not docs:
|
188 |
+
return self._create_no_results_response(query)
|
189 |
+
|
190 |
+
# Stage 2: Re-ranking with Cross-Encoder
|
191 |
+
sentence_pairs = [[query, doc.content] for doc in docs]
|
192 |
+
scores = self.reranker.predict(sentence_pairs)
|
193 |
+
|
194 |
+
# Combine docs with scores and sort
|
195 |
+
doc_score_pairs = list(zip(docs, scores))
|
196 |
+
doc_score_pairs.sort(key=lambda x: x[1], reverse=True)
|
197 |
+
|
198 |
+
# Select top N results after re-ranking
|
199 |
+
reranked_docs = [pair[0] for pair in doc_score_pairs[:top_n_rerank]]
|
200 |
+
reranked_scores = [pair[1] for pair in doc_score_pairs[:top_n_rerank]]
|
201 |
+
|
202 |
+
# Prepare context with rich metadata for the LLM
|
203 |
+
context_parts = []
|
204 |
+
for i, doc in enumerate(reranked_docs, 1):
|
205 |
+
citation = doc.metadata.get('citation')
|
206 |
+
if not citation:
|
207 |
+
source_path = doc.metadata.get('source', 'Unknown')
|
208 |
+
citation = Path(source_path).parent.name
|
209 |
+
|
210 |
+
# Add reference number to citation
|
211 |
+
context_parts.append(f"[{i}] Citation: {citation}\\n\\nContent: {doc.content}")
|
212 |
+
context = "\\n\\n---\\n\\n".join(context_parts)
|
213 |
+
|
214 |
+
confidence = self._calculate_confidence(reranked_scores, use_llm)
|
215 |
+
|
216 |
+
# Use a set to get unique citations for display
|
217 |
+
sources = list(set([
|
218 |
+
doc.metadata.get('citation', Path(doc.metadata.get('source', 'Unknown')).parent.name)
|
219 |
+
for doc in reranked_docs
|
220 |
+
]))
|
221 |
+
|
222 |
+
if use_llm:
|
223 |
+
# Phase 4: Persona-driven, structured response generation
|
224 |
+
system_prompt = (
|
225 |
+
"You are 'VedaMD', a world-class medical expert and a compassionate assistant for healthcare professionals in Sri Lanka. "
|
226 |
+
"Your primary goal is to provide accurate, evidence-based clinical information based ONLY on the provided context, which is sourced from official Sri Lankan maternal health guidelines. "
|
227 |
+
"Your tone should be professional, clear, and supportive.\\n\\n"
|
228 |
+
"**CRITICAL INSTRUCTIONS:**\\n"
|
229 |
+
"1. **Strictly Context-Bound:** Your answer MUST be based exclusively on the 'Content' provided for each source. Do not use any external knowledge or provide information not present in the context.\\n"
|
230 |
+
"2. **Markdown Formatting:** Structure your answers for maximum clarity. Use markdown for formatting:\\n"
|
231 |
+
" - Use headings (`##`) for main topics.\\n"
|
232 |
+
" - Use bullet points (`-` or `*`) for lists of symptoms, recommendations, or steps.\\n"
|
233 |
+
" - Use bold (`**text**`) to emphasize key terms, dosages, or critical warnings.\\n"
|
234 |
+
"3. **Synthesize, Don't Just Copy:** Read all context pieces, synthesize the information, and provide a comprehensive answer. Do not repeat information.\\n"
|
235 |
+
"4. **Scientific Citations:** Use numbered citations [1], [2], etc. in your answer text to reference specific information. At the end, list all sources under a 'References:' heading in scientific format:\\n"
|
236 |
+
" [1] Title of Guideline/Document\\n"
|
237 |
+
" [2] Title of Another Guideline/Document\\n"
|
238 |
+
"5. **Disclaimer:** At the end of EVERY response, include the following disclaimer: '_This information is for clinical reference based on Sri Lankan guidelines and does not replace professional medical judgment._'"
|
239 |
+
)
|
240 |
+
return self._create_llm_response(system_prompt, context, query, confidence, sources, start_time, history)
|
241 |
+
|
242 |
+
else:
|
243 |
+
# If not using LLM, return context directly
|
244 |
+
return MedicalResponse(
|
245 |
+
answer=context,
|
246 |
+
confidence=confidence,
|
247 |
+
sources=sources,
|
248 |
+
query_time=time.time() - start_time
|
249 |
+
)
|
250 |
+
|
251 |
+
def _create_llm_response(self, system_prompt: str, context: str, query: str, confidence: float, sources: List[str], start_time: float, history: Optional[List[Dict[str, str]]] = None) -> MedicalResponse:
|
252 |
+
"""Helper to generate response from LLM."""
|
253 |
+
try:
|
254 |
+
messages = [
|
255 |
+
{
|
256 |
+
"role": "system",
|
257 |
+
"content": system_prompt,
|
258 |
+
}
|
259 |
+
]
|
260 |
+
|
261 |
+
# Add conversation history to the messages
|
262 |
+
if history:
|
263 |
+
messages.extend(history)
|
264 |
+
|
265 |
+
# Add the current query
|
266 |
+
messages.append({"role": "user", "content": f"Context:\\n{context}\\n\\nQuestion: {query}"})
|
267 |
+
|
268 |
+
chat_completion = self.groq_client.chat.completions.create(
|
269 |
+
messages=messages,
|
270 |
+
model=self.model_name,
|
271 |
+
temperature=0.7,
|
272 |
+
max_tokens=2048,
|
273 |
+
top_p=1,
|
274 |
+
stream=False
|
275 |
+
)
|
276 |
+
|
277 |
+
response_content = chat_completion.choices[0].message.content
|
278 |
+
|
279 |
+
return MedicalResponse(
|
280 |
+
answer=response_content,
|
281 |
+
confidence=confidence,
|
282 |
+
sources=sources,
|
283 |
+
query_time=time.time() - start_time,
|
284 |
+
)
|
285 |
+
except Exception as e:
|
286 |
+
self.logger.error(f"Error during Groq API call: {e}")
|
287 |
+
return MedicalResponse(
|
288 |
+
answer=f"Sorry, I encountered an error while generating the response: {e}",
|
289 |
+
confidence=0,
|
290 |
+
sources=sources,
|
291 |
+
query_time=time.time() - start_time
|
292 |
+
)
|
293 |
+
|
294 |
+
def _calculate_confidence(self, scores: List[float], use_llm: bool) -> float:
|
295 |
+
"""
|
296 |
+
Calculate confidence score based on re-ranked results.
|
297 |
+
For LLM responses, we can be more optimistic.
|
298 |
+
"""
|
299 |
+
if not scores:
|
300 |
+
return 0.0
|
301 |
+
|
302 |
+
# Simple average of scores, scaled
|
303 |
+
avg_score = sum(scores) / len(scores)
|
304 |
+
|
305 |
+
# Sigmoid-like scaling for better confidence representation
|
306 |
+
confidence = 1 / (1 + np.exp(-avg_score))
|
307 |
+
|
308 |
+
if use_llm:
|
309 |
+
return min(confidence * 1.2, 1.0) # Boost confidence for LLM
|
310 |
+
return confidence
|
311 |
+
|
312 |
+
def _create_no_results_response(self, query: str) -> MedicalResponse:
|
313 |
+
"""Helper for no results response"""
|
314 |
+
return MedicalResponse(
|
315 |
+
answer="No relevant documents found for your query. Please try rephrasing your question.",
|
316 |
+
confidence=0,
|
317 |
+
sources=[],
|
318 |
+
query_time=0
|
319 |
+
)
|
320 |
+
|
321 |
+
def main(recreate_index: bool = False):
|
322 |
+
"""Main function to initialize and test the RAG system."""
|
323 |
+
print("Initializing Groq Medical RAG system...")
|
324 |
+
try:
|
325 |
+
rag_system = GroqMedicalRAG()
|
326 |
+
|
327 |
+
if recreate_index:
|
328 |
+
print("Recreating index as requested...")
|
329 |
+
# Re-initialize with force_recreate=True
|
330 |
+
rag_system._initialize_system(force_recreate=True)
|
331 |
+
print("✅ Index recreated successfully.")
|
332 |
+
return # Exit after recreating index
|
333 |
+
|
334 |
+
print("✅ System initialized successfully.")
|
335 |
+
|
336 |
+
# Example query for testing
|
337 |
+
print("\\n--- Testing with an example query ---")
|
338 |
+
query = "What is the management for puerperal sepsis?"
|
339 |
+
print(f"Query: {query}")
|
340 |
+
|
341 |
+
response = rag_system.query(query)
|
342 |
+
|
343 |
+
print("\\n--- Response ---")
|
344 |
+
print(f"Answer: {response.answer}")
|
345 |
+
print(f"Confidence: {response.confidence:.2f}")
|
346 |
+
print(f"Sources: {response.sources}")
|
347 |
+
print(f"Query Time: {response.query_time:.2f}s")
|
348 |
+
print("--------------------\\n")
|
349 |
+
|
350 |
+
except Exception as e:
|
351 |
+
print(f"An error occurred: {e}")
|
352 |
+
|
353 |
+
if __name__ == "__main__":
|
354 |
+
parser = argparse.ArgumentParser(description="Groq Medical RAG System CLI")
|
355 |
+
parser.add_argument(
|
356 |
+
"--recreate-index",
|
357 |
+
action="store_true",
|
358 |
+
help="If set, deletes the existing vector store and creates a new one."
|
359 |
+
)
|
360 |
+
args = parser.parse_args()
|
361 |
+
|
362 |
+
main(recreate_index=args.recreate_index)
|
363 |
+
|
364 |
+
async def main_async(recreate_index: bool = False):
|
365 |
+
# This function seems to be unused in the current context, but I'll add a pass to avoid syntax errors.
|
366 |
+
pass
|
src/maternal_health_chatbot.py
ADDED
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
"""
|
3 |
+
Maternal Health RAG Chatbot - Gradio Interface
|
4 |
+
Complete chatbot interface for Sri Lankan maternal health guidelines
|
5 |
+
"""
|
6 |
+
|
7 |
+
import gradio as gr
|
8 |
+
import json
|
9 |
+
import time
|
10 |
+
from typing import List, Tuple, Dict, Any
|
11 |
+
from datetime import datetime
|
12 |
+
from pathlib import Path
|
13 |
+
|
14 |
+
from maternal_health_rag import MaternalHealthRAG, QueryResponse
|
15 |
+
|
16 |
+
class MaternalHealthChatbot:
|
17 |
+
"""Maternal Health Chatbot with Gradio interface"""
|
18 |
+
|
19 |
+
def __init__(self):
|
20 |
+
self.rag_system = None
|
21 |
+
self.chat_history = []
|
22 |
+
self.session_stats = {
|
23 |
+
'queries_processed': 0,
|
24 |
+
'total_response_time': 0.0,
|
25 |
+
'session_start': datetime.now()
|
26 |
+
}
|
27 |
+
|
28 |
+
# Initialize RAG system
|
29 |
+
self.initialize_chatbot()
|
30 |
+
|
31 |
+
def initialize_chatbot(self):
|
32 |
+
"""Initialize the RAG system for the chatbot"""
|
33 |
+
try:
|
34 |
+
print("🚀 Initializing Maternal Health RAG Chatbot...")
|
35 |
+
self.rag_system = MaternalHealthRAG(use_mock_llm=True)
|
36 |
+
print("✅ Chatbot initialized successfully!")
|
37 |
+
except Exception as e:
|
38 |
+
print(f"❌ Failed to initialize chatbot: {e}")
|
39 |
+
raise
|
40 |
+
|
41 |
+
def process_query(self, message: str, history: List[List[str]]) -> Tuple[str, List[List[str]]]:
|
42 |
+
"""Process user query and return response with updated history"""
|
43 |
+
|
44 |
+
if not message.strip():
|
45 |
+
return "", history
|
46 |
+
|
47 |
+
try:
|
48 |
+
# Process query through RAG system
|
49 |
+
response = self.rag_system.query(message)
|
50 |
+
|
51 |
+
# Update session statistics
|
52 |
+
self.session_stats['queries_processed'] += 1
|
53 |
+
self.session_stats['total_response_time'] += response.response_time
|
54 |
+
|
55 |
+
# Format response with metadata
|
56 |
+
formatted_response = self.format_response(response)
|
57 |
+
|
58 |
+
# Update chat history
|
59 |
+
history.append([message, formatted_response])
|
60 |
+
|
61 |
+
return "", history
|
62 |
+
|
63 |
+
except Exception as e:
|
64 |
+
error_response = f"I apologize, but I encountered an error: {str(e)}. Please try rephrasing your question."
|
65 |
+
history.append([message, error_response])
|
66 |
+
return "", history
|
67 |
+
|
68 |
+
def format_response(self, response: QueryResponse) -> str:
|
69 |
+
"""Format the RAG response for display"""
|
70 |
+
|
71 |
+
# Main answer
|
72 |
+
formatted_answer = f"**🏥 Clinical Response:**\n{response.answer}\n\n"
|
73 |
+
|
74 |
+
# Confidence and metadata
|
75 |
+
confidence_emoji = "🟢" if response.confidence >= 0.7 else "🟡" if response.confidence >= 0.4 else "🔴"
|
76 |
+
formatted_answer += f"**📊 Response Metadata:**\n"
|
77 |
+
formatted_answer += f"{confidence_emoji} Confidence: {response.confidence:.1%}\n"
|
78 |
+
formatted_answer += f"⏱️ Response Time: {response.response_time:.2f}s\n"
|
79 |
+
formatted_answer += f"📚 Sources: {response.metadata['num_sources']} guidelines\n"
|
80 |
+
|
81 |
+
if response.metadata['content_types']:
|
82 |
+
content_types = ", ".join(response.metadata['content_types'])
|
83 |
+
formatted_answer += f"📋 Content Types: {content_types}\n"
|
84 |
+
|
85 |
+
# Source details (for high-confidence responses)
|
86 |
+
if response.confidence >= 0.6 and response.sources:
|
87 |
+
formatted_answer += f"\n**📖 Key Sources:**\n"
|
88 |
+
for i, source in enumerate(response.sources[:3], 1): # Show top 3 sources
|
89 |
+
source_preview = source.content[:150] + "..." if len(source.content) > 150 else source.content
|
90 |
+
formatted_answer += f"{i}. **{source.chunk_type.title()}** (Score: {source.score:.2f})\n"
|
91 |
+
formatted_answer += f" {source_preview}\n\n"
|
92 |
+
|
93 |
+
# Safety disclaimer
|
94 |
+
formatted_answer += "\n---\n"
|
95 |
+
formatted_answer += "⚠️ **Medical Disclaimer:** This information is based on Sri Lankan maternal health guidelines and is for educational purposes only. Always consult with qualified healthcare professionals for medical decisions."
|
96 |
+
|
97 |
+
return formatted_answer
|
98 |
+
|
99 |
+
def get_example_queries(self) -> List[str]:
|
100 |
+
"""Get example queries for the interface"""
|
101 |
+
return [
|
102 |
+
"What is the recommended dosage of magnesium sulfate for preeclampsia?",
|
103 |
+
"How should postpartum hemorrhage be managed in emergency situations?",
|
104 |
+
"What are the signs and symptoms of puerperal sepsis?",
|
105 |
+
"What is the normal fetal heart rate range during labor?",
|
106 |
+
"When is cesarean section indicated during delivery?",
|
107 |
+
"How to manage gestational diabetes during pregnancy?",
|
108 |
+
"What are the contraindications for vaginal delivery?",
|
109 |
+
"How to recognize and manage eclampsia?",
|
110 |
+
"What is the proper management of prolonged labor?",
|
111 |
+
"How to handle breech presentation during delivery?"
|
112 |
+
]
|
113 |
+
|
114 |
+
def clear_chat(self) -> List[List[str]]:
|
115 |
+
"""Clear chat history"""
|
116 |
+
self.chat_history = []
|
117 |
+
return []
|
118 |
+
|
119 |
+
def get_system_info(self) -> str:
|
120 |
+
"""Get system information and statistics"""
|
121 |
+
if not self.rag_system:
|
122 |
+
return "❌ RAG system not initialized"
|
123 |
+
|
124 |
+
stats = self.rag_system.get_system_stats()
|
125 |
+
session_time = (datetime.now() - self.session_stats['session_start']).total_seconds()
|
126 |
+
|
127 |
+
avg_response_time = (
|
128 |
+
self.session_stats['total_response_time'] / self.session_stats['queries_processed']
|
129 |
+
if self.session_stats['queries_processed'] > 0 else 0
|
130 |
+
)
|
131 |
+
|
132 |
+
info = f"""
|
133 |
+
## 🏥 Maternal Health RAG Assistant - System Information
|
134 |
+
|
135 |
+
### 📊 Knowledge Base Statistics
|
136 |
+
- **Total Medical Chunks:** {stats['vector_store']['total_chunks']:,}
|
137 |
+
- **Embedding Model:** {stats['vector_store']['embedding_model']}
|
138 |
+
- **Vector Store Size:** {stats['vector_store']['vector_store_size_mb']:.1f} MB
|
139 |
+
- **Clinical Content Types:** {len(stats['vector_store']['chunk_type_distribution'])}
|
140 |
+
|
141 |
+
### 🧠 RAG Configuration
|
142 |
+
- **Default Results:** {stats['rag_config']['default_k']} sources per query
|
143 |
+
- **Context Length:** {stats['rag_config']['max_context_length']:,} characters max
|
144 |
+
- **LLM Type:** {stats['rag_config']['llm_type'].title()}
|
145 |
+
|
146 |
+
### 📈 Session Statistics
|
147 |
+
- **Queries Processed:** {self.session_stats['queries_processed']}
|
148 |
+
- **Average Response Time:** {avg_response_time:.2f}s
|
149 |
+
- **Session Duration:** {session_time:.0f}s
|
150 |
+
- **System Status:** {stats['status'].title()}
|
151 |
+
|
152 |
+
### 📚 Document Coverage
|
153 |
+
This assistant covers **15 Sri Lankan maternal health guidelines** including:
|
154 |
+
- National Guidelines for Maternal Care
|
155 |
+
- SLJOG Clinical Guidelines
|
156 |
+
- Emergency Management Protocols
|
157 |
+
- Dosage and Treatment Guidelines
|
158 |
+
- Postnatal Care Guidelines
|
159 |
+
"""
|
160 |
+
return info
|
161 |
+
|
162 |
+
def create_chatbot_interface():
|
163 |
+
"""Create the Gradio chatbot interface"""
|
164 |
+
|
165 |
+
# Initialize chatbot
|
166 |
+
chatbot = MaternalHealthChatbot()
|
167 |
+
|
168 |
+
# Create Gradio interface
|
169 |
+
with gr.Blocks(
|
170 |
+
title="Maternal Health Assistant",
|
171 |
+
theme=gr.themes.Soft(),
|
172 |
+
css="""
|
173 |
+
.gradio-container {
|
174 |
+
font-family: 'Arial', sans-serif;
|
175 |
+
}
|
176 |
+
.chat-message {
|
177 |
+
font-size: 16px;
|
178 |
+
line-height: 1.5;
|
179 |
+
}
|
180 |
+
"""
|
181 |
+
) as demo:
|
182 |
+
|
183 |
+
# Header
|
184 |
+
gr.Markdown("""
|
185 |
+
# 🏥 Sri Lankan Maternal Health RAG Assistant
|
186 |
+
|
187 |
+
**Your AI assistant for Sri Lankan maternal health guidelines**
|
188 |
+
|
189 |
+
Ask questions about:
|
190 |
+
- 💊 Medication dosages and protocols
|
191 |
+
- 🚨 Emergency management procedures
|
192 |
+
- 🤱 Maternal and fetal care guidelines
|
193 |
+
- 📋 Clinical decision-making support
|
194 |
+
- 🔬 Diagnostic criteria and procedures
|
195 |
+
|
196 |
+
*Based on official Sri Lankan maternal health guidelines and SLJOG recommendations*
|
197 |
+
""")
|
198 |
+
|
199 |
+
with gr.Tab("💬 Chat Assistant"):
|
200 |
+
# Chat interface
|
201 |
+
chatbot_interface = gr.Chatbot(
|
202 |
+
label="Maternal Health Assistant",
|
203 |
+
height=500,
|
204 |
+
elem_classes=["chat-message"]
|
205 |
+
)
|
206 |
+
|
207 |
+
msg = gr.Textbox(
|
208 |
+
label="Your Question",
|
209 |
+
placeholder="Ask me about maternal health guidelines, emergency protocols, dosages, or clinical procedures...",
|
210 |
+
lines=2
|
211 |
+
)
|
212 |
+
|
213 |
+
with gr.Row():
|
214 |
+
submit_btn = gr.Button("🔍 Ask Question", variant="primary")
|
215 |
+
clear_btn = gr.Button("🗑️ Clear Chat", variant="secondary")
|
216 |
+
|
217 |
+
# Example queries
|
218 |
+
gr.Markdown("### 💡 Example Questions:")
|
219 |
+
with gr.Row():
|
220 |
+
examples = chatbot.get_example_queries()
|
221 |
+
for i in range(0, len(examples), 2):
|
222 |
+
with gr.Column():
|
223 |
+
if i < len(examples):
|
224 |
+
gr.Button(
|
225 |
+
examples[i],
|
226 |
+
variant="outline",
|
227 |
+
size="sm"
|
228 |
+
).click(
|
229 |
+
lambda x=examples[i]: x,
|
230 |
+
outputs=msg
|
231 |
+
)
|
232 |
+
if i+1 < len(examples):
|
233 |
+
gr.Button(
|
234 |
+
examples[i+1],
|
235 |
+
variant="outline",
|
236 |
+
size="sm"
|
237 |
+
).click(
|
238 |
+
lambda x=examples[i+1]: x,
|
239 |
+
outputs=msg
|
240 |
+
)
|
241 |
+
|
242 |
+
with gr.Tab("📊 System Information"):
|
243 |
+
system_info = gr.Markdown(
|
244 |
+
chatbot.get_system_info(),
|
245 |
+
label="System Information"
|
246 |
+
)
|
247 |
+
|
248 |
+
refresh_btn = gr.Button("🔄 Refresh Stats", variant="secondary")
|
249 |
+
refresh_btn.click(
|
250 |
+
chatbot.get_system_info,
|
251 |
+
outputs=system_info
|
252 |
+
)
|
253 |
+
|
254 |
+
with gr.Tab("ℹ️ About"):
|
255 |
+
gr.Markdown("""
|
256 |
+
## About This Assistant
|
257 |
+
|
258 |
+
This **Maternal Health RAG Assistant** provides information based on official Sri Lankan maternal health guidelines using Retrieval-Augmented Generation (RAG) technology.
|
259 |
+
|
260 |
+
### 🔧 Technical Features
|
261 |
+
- **Vector-based search** through 542 medical content chunks
|
262 |
+
- **Semantic similarity** using all-MiniLM-L6-v2 embeddings
|
263 |
+
- **Clinical importance scoring** for prioritizing critical information
|
264 |
+
- **Medical context filtering** by content type (dosage, emergency, procedure, etc.)
|
265 |
+
- **Sub-second response times** with confidence scoring
|
266 |
+
|
267 |
+
### 📚 Knowledge Base
|
268 |
+
- **15 comprehensive documents** covering maternal health
|
269 |
+
- **479 pages** of clinical guidelines processed
|
270 |
+
- **48 clinical tables** with dosage and protocol information
|
271 |
+
- **107,010 words** of medical content indexed
|
272 |
+
|
273 |
+
### ⚠️ Important Disclaimers
|
274 |
+
1. **For Educational Use Only:** This tool provides information based on guidelines but should not replace professional medical judgment
|
275 |
+
2. **Always Consult Healthcare Professionals:** Medical decisions should always involve qualified healthcare providers
|
276 |
+
3. **Regular Updates:** Guidelines may change - always verify with the latest official sources
|
277 |
+
4. **Emergency Situations:** In medical emergencies, contact emergency services immediately
|
278 |
+
|
279 |
+
### 🏗️ Built With
|
280 |
+
- **LangChain** for RAG pipeline orchestration
|
281 |
+
- **FAISS** for efficient vector similarity search
|
282 |
+
- **Sentence Transformers** for medical text embeddings
|
283 |
+
- **Gradio** for the user interface
|
284 |
+
- **pdfplumber** for medical document processing
|
285 |
+
|
286 |
+
---
|
287 |
+
*Developed for educational and clinical reference purposes*
|
288 |
+
""")
|
289 |
+
|
290 |
+
# Event handlers
|
291 |
+
submit_btn.click(
|
292 |
+
chatbot.process_query,
|
293 |
+
inputs=[msg, chatbot_interface],
|
294 |
+
outputs=[msg, chatbot_interface]
|
295 |
+
)
|
296 |
+
|
297 |
+
msg.submit(
|
298 |
+
chatbot.process_query,
|
299 |
+
inputs=[msg, chatbot_interface],
|
300 |
+
outputs=[msg, chatbot_interface]
|
301 |
+
)
|
302 |
+
|
303 |
+
clear_btn.click(
|
304 |
+
chatbot.clear_chat,
|
305 |
+
outputs=chatbot_interface
|
306 |
+
)
|
307 |
+
|
308 |
+
return demo
|
309 |
+
|
310 |
+
def main():
|
311 |
+
"""Main function to launch the chatbot"""
|
312 |
+
print("🚀 Launching Maternal Health RAG Chatbot...")
|
313 |
+
|
314 |
+
try:
|
315 |
+
# Create and launch interface
|
316 |
+
demo = create_chatbot_interface()
|
317 |
+
|
318 |
+
print("✅ Chatbot interface created successfully!")
|
319 |
+
print("🌐 Launching on http://localhost:7860")
|
320 |
+
print("📱 Access from other devices using the public link")
|
321 |
+
|
322 |
+
# Launch with public sharing for easier access
|
323 |
+
demo.launch(
|
324 |
+
server_name="0.0.0.0", # Allow external access
|
325 |
+
server_port=7860,
|
326 |
+
share=True, # Create public link
|
327 |
+
show_error=True,
|
328 |
+
quiet=False
|
329 |
+
)
|
330 |
+
|
331 |
+
except Exception as e:
|
332 |
+
print(f"❌ Failed to launch chatbot: {e}")
|
333 |
+
raise
|
334 |
+
|
335 |
+
if __name__ == "__main__":
|
336 |
+
main()
|
src/maternal_health_rag.py
ADDED
@@ -0,0 +1,387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
"""
|
3 |
+
Maternal Health RAG Query Engine
|
4 |
+
Integrates vector store with LangChain for intelligent medical query processing
|
5 |
+
"""
|
6 |
+
|
7 |
+
import json
|
8 |
+
import logging
|
9 |
+
from typing import List, Dict, Any, Optional, Tuple
|
10 |
+
from pathlib import Path
|
11 |
+
from dataclasses import dataclass
|
12 |
+
from datetime import datetime
|
13 |
+
|
14 |
+
from langchain.schema import Document
|
15 |
+
from langchain.prompts import PromptTemplate
|
16 |
+
from langchain.chains import LLMChain
|
17 |
+
from langchain.llms.base import LLM
|
18 |
+
from langchain.callbacks.manager import CallbackManagerForLLMRun
|
19 |
+
|
20 |
+
from vector_store_manager import MaternalHealthVectorStore, SearchResult
|
21 |
+
|
22 |
+
# Configure logging
|
23 |
+
logging.basicConfig(level=logging.INFO)
|
24 |
+
logger = logging.getLogger(__name__)
|
25 |
+
|
26 |
+
@dataclass
|
27 |
+
class QueryResponse:
|
28 |
+
"""Container for RAG query responses"""
|
29 |
+
query: str
|
30 |
+
answer: str
|
31 |
+
sources: List[SearchResult]
|
32 |
+
confidence: float
|
33 |
+
response_time: float
|
34 |
+
metadata: Dict[str, Any]
|
35 |
+
|
36 |
+
class MockLLM(LLM):
|
37 |
+
"""Mock LLM for testing RAG pipeline without external API calls"""
|
38 |
+
|
39 |
+
@property
|
40 |
+
def _llm_type(self) -> str:
|
41 |
+
return "mock"
|
42 |
+
|
43 |
+
def _call(
|
44 |
+
self,
|
45 |
+
prompt: str,
|
46 |
+
stop: Optional[List[str]] = None,
|
47 |
+
run_manager: Optional[CallbackManagerForLLMRun] = None,
|
48 |
+
**kwargs: Any,
|
49 |
+
) -> str:
|
50 |
+
"""Generate a mock medical response based on the prompt"""
|
51 |
+
|
52 |
+
# Extract context and query from prompt
|
53 |
+
if "Context:" in prompt and "Question:" in prompt:
|
54 |
+
context_section = prompt.split("Context:")[1].split("Question:")[0].strip()
|
55 |
+
question_section = prompt.split("Question:")[1].split("Answer:")[0].strip()
|
56 |
+
|
57 |
+
# Generate mock response based on medical keywords
|
58 |
+
medical_keywords = {
|
59 |
+
'magnesium': 'Magnesium sulfate is administered for seizure prevention in preeclampsia.',
|
60 |
+
'hemorrhage': 'Postpartum hemorrhage requires immediate assessment and management with uterotonics.',
|
61 |
+
'sepsis': 'Puerperal sepsis is diagnosed based on fever, tachycardia, and other systemic signs.',
|
62 |
+
'fetal': 'Fetal heart rate monitoring is essential during labor to assess fetal well-being.',
|
63 |
+
'labor': 'Normal labor management involves monitoring progress and maternal-fetal well-being.',
|
64 |
+
'preeclampsia': 'Preeclampsia management includes blood pressure control and seizure prevention.',
|
65 |
+
'oxytocin': 'Oxytocin is used for labor induction and augmentation with careful monitoring.',
|
66 |
+
'cesarean': 'Cesarean section indications include fetal distress and failure to progress.',
|
67 |
+
'diabetes': 'Gestational diabetes requires blood glucose monitoring and dietary management.',
|
68 |
+
'hypertension': 'Pregnancy-induced hypertension requires close monitoring and treatment.'
|
69 |
+
}
|
70 |
+
|
71 |
+
# Find relevant keywords and build response
|
72 |
+
response_parts = []
|
73 |
+
question_lower = question_section.lower()
|
74 |
+
|
75 |
+
for keyword, response in medical_keywords.items():
|
76 |
+
if keyword in question_lower:
|
77 |
+
response_parts.append(response)
|
78 |
+
|
79 |
+
if response_parts:
|
80 |
+
base_response = " ".join(response_parts)
|
81 |
+
return f"Based on the maternal health guidelines: {base_response} Please consult with a healthcare professional for specific medical advice."
|
82 |
+
else:
|
83 |
+
return "Based on the available maternal health guidelines, this appears to be a clinical question that requires professional medical evaluation. Please consult with a qualified healthcare provider."
|
84 |
+
|
85 |
+
return "I can provide information based on maternal health guidelines, but specific medical decisions should always be made in consultation with healthcare professionals."
|
86 |
+
|
87 |
+
class MaternalHealthRAG:
|
88 |
+
"""RAG system for maternal health queries"""
|
89 |
+
|
90 |
+
def __init__(self,
|
91 |
+
vector_store_dir: str = "vector_store",
|
92 |
+
chunks_dir: str = "comprehensive_chunks",
|
93 |
+
use_mock_llm: bool = True):
|
94 |
+
|
95 |
+
self.vector_store_dir = Path(vector_store_dir)
|
96 |
+
self.chunks_dir = Path(chunks_dir)
|
97 |
+
self.use_mock_llm = use_mock_llm
|
98 |
+
|
99 |
+
# Initialize components
|
100 |
+
self.vector_store = None
|
101 |
+
self.llm = None
|
102 |
+
self.rag_chain = None
|
103 |
+
|
104 |
+
# Query parameters
|
105 |
+
self.default_k = 5
|
106 |
+
self.min_relevance_score = 0.3
|
107 |
+
self.max_context_length = 3000
|
108 |
+
|
109 |
+
# Initialize RAG system
|
110 |
+
self.initialize_rag_system()
|
111 |
+
|
112 |
+
def initialize_rag_system(self):
|
113 |
+
"""Initialize the complete RAG system"""
|
114 |
+
logger.info("🚀 Initializing Maternal Health RAG System...")
|
115 |
+
|
116 |
+
try:
|
117 |
+
# Initialize vector store
|
118 |
+
self.vector_store = MaternalHealthVectorStore(
|
119 |
+
vector_store_dir=self.vector_store_dir,
|
120 |
+
chunks_dir=self.chunks_dir
|
121 |
+
)
|
122 |
+
|
123 |
+
# Load existing vector store
|
124 |
+
if self.vector_store.index_file.exists():
|
125 |
+
success = self.vector_store.load_existing_index()
|
126 |
+
if not success:
|
127 |
+
logger.error("Failed to load vector store")
|
128 |
+
raise RuntimeError("Vector store initialization failed")
|
129 |
+
else:
|
130 |
+
logger.error("Vector store not found. Please create it first.")
|
131 |
+
raise FileNotFoundError("Vector store not found")
|
132 |
+
|
133 |
+
# Initialize LLM
|
134 |
+
if self.use_mock_llm:
|
135 |
+
self.llm = MockLLM()
|
136 |
+
logger.info("✅ Using Mock LLM for testing")
|
137 |
+
else:
|
138 |
+
# Future: Initialize actual LLM (OpenAI, Hugging Face, etc.)
|
139 |
+
logger.warning("External LLM not implemented yet, using Mock LLM")
|
140 |
+
self.llm = MockLLM()
|
141 |
+
|
142 |
+
# Create RAG chain
|
143 |
+
self.rag_chain = self.create_rag_chain()
|
144 |
+
|
145 |
+
logger.info("✅ RAG system initialized successfully")
|
146 |
+
|
147 |
+
except Exception as e:
|
148 |
+
logger.error(f"❌ Failed to initialize RAG system: {e}")
|
149 |
+
raise
|
150 |
+
|
151 |
+
def create_rag_chain(self) -> LLMChain:
|
152 |
+
"""Create the RAG chain with medical prompt template"""
|
153 |
+
|
154 |
+
# Medical-focused prompt template
|
155 |
+
template = """You are a medical information assistant specializing in maternal health guidelines.
|
156 |
+
Use the provided context from Sri Lankan maternal health guidelines to answer questions accurately and safely.
|
157 |
+
|
158 |
+
Context:
|
159 |
+
{context}
|
160 |
+
|
161 |
+
Question: {question}
|
162 |
+
|
163 |
+
Instructions:
|
164 |
+
1. Answer based ONLY on the provided context from maternal health guidelines
|
165 |
+
2. If the context doesn't contain sufficient information, clearly state this
|
166 |
+
3. Always include relevant clinical details when available (dosages, procedures, contraindications)
|
167 |
+
4. Mention when professional medical consultation is recommended
|
168 |
+
5. Be precise and avoid generalizations
|
169 |
+
|
170 |
+
Answer:"""
|
171 |
+
|
172 |
+
prompt = PromptTemplate(
|
173 |
+
template=template,
|
174 |
+
input_variables=["context", "question"]
|
175 |
+
)
|
176 |
+
|
177 |
+
chain = LLMChain(
|
178 |
+
llm=self.llm,
|
179 |
+
prompt=prompt,
|
180 |
+
verbose=False
|
181 |
+
)
|
182 |
+
|
183 |
+
return chain
|
184 |
+
|
185 |
+
def query(self,
|
186 |
+
question: str,
|
187 |
+
k: int = None,
|
188 |
+
min_score: float = None,
|
189 |
+
content_types: List[str] = None,
|
190 |
+
min_importance: float = 0.5) -> QueryResponse:
|
191 |
+
"""Process a medical query and return comprehensive response"""
|
192 |
+
|
193 |
+
if k is None:
|
194 |
+
k = self.default_k
|
195 |
+
if min_score is None:
|
196 |
+
min_score = self.min_relevance_score
|
197 |
+
|
198 |
+
start_time = datetime.now()
|
199 |
+
logger.info(f"🔍 Processing query: {question}")
|
200 |
+
|
201 |
+
try:
|
202 |
+
# Retrieve relevant context
|
203 |
+
if content_types:
|
204 |
+
search_results = self.vector_store.search_by_medical_context(
|
205 |
+
question,
|
206 |
+
content_types=content_types,
|
207 |
+
min_importance=min_importance,
|
208 |
+
k=k
|
209 |
+
)
|
210 |
+
else:
|
211 |
+
search_results = self.vector_store.search(
|
212 |
+
question,
|
213 |
+
k=k,
|
214 |
+
min_score=min_score
|
215 |
+
)
|
216 |
+
|
217 |
+
# Prepare context
|
218 |
+
context = self.prepare_context(search_results)
|
219 |
+
|
220 |
+
# Generate response
|
221 |
+
response = self.rag_chain.run(
|
222 |
+
context=context,
|
223 |
+
question=question
|
224 |
+
)
|
225 |
+
|
226 |
+
# Calculate response time
|
227 |
+
end_time = datetime.now()
|
228 |
+
response_time = (end_time - start_time).total_seconds()
|
229 |
+
|
230 |
+
# Calculate confidence based on relevance scores
|
231 |
+
confidence = self.calculate_confidence(search_results)
|
232 |
+
|
233 |
+
# Create response object
|
234 |
+
query_response = QueryResponse(
|
235 |
+
query=question,
|
236 |
+
answer=response,
|
237 |
+
sources=search_results,
|
238 |
+
confidence=confidence,
|
239 |
+
response_time=response_time,
|
240 |
+
metadata={
|
241 |
+
'num_sources': len(search_results),
|
242 |
+
'avg_relevance': sum(r.score for r in search_results) / len(search_results) if search_results else 0,
|
243 |
+
'content_types': list(set(r.chunk_type for r in search_results)),
|
244 |
+
'high_importance_sources': sum(1 for r in search_results if r.clinical_importance >= 0.8)
|
245 |
+
}
|
246 |
+
)
|
247 |
+
|
248 |
+
logger.info(f"✅ Query processed in {response_time:.2f}s with {len(search_results)} sources")
|
249 |
+
return query_response
|
250 |
+
|
251 |
+
except Exception as e:
|
252 |
+
logger.error(f"❌ Query processing failed: {e}")
|
253 |
+
|
254 |
+
# Return error response
|
255 |
+
end_time = datetime.now()
|
256 |
+
response_time = (end_time - start_time).total_seconds()
|
257 |
+
|
258 |
+
return QueryResponse(
|
259 |
+
query=question,
|
260 |
+
answer=f"I apologize, but I encountered an error while processing your query: {str(e)}",
|
261 |
+
sources=[],
|
262 |
+
confidence=0.0,
|
263 |
+
response_time=response_time,
|
264 |
+
metadata={'error': str(e)}
|
265 |
+
)
|
266 |
+
|
267 |
+
def prepare_context(self, search_results: List[SearchResult]) -> str:
|
268 |
+
"""Prepare context from search results for LLM"""
|
269 |
+
|
270 |
+
if not search_results:
|
271 |
+
return "No relevant information found in the maternal health guidelines."
|
272 |
+
|
273 |
+
context_parts = []
|
274 |
+
current_length = 0
|
275 |
+
|
276 |
+
for i, result in enumerate(search_results):
|
277 |
+
# Add source information
|
278 |
+
source_info = f"Source {i+1} (Relevance: {result.score:.3f}, Type: {result.chunk_type}):"
|
279 |
+
content = f"{source_info}\n{result.content}\n"
|
280 |
+
|
281 |
+
# Check if adding this would exceed max length
|
282 |
+
if current_length + len(content) > self.max_context_length and context_parts:
|
283 |
+
break
|
284 |
+
|
285 |
+
context_parts.append(content)
|
286 |
+
current_length += len(content)
|
287 |
+
|
288 |
+
return "\n".join(context_parts)
|
289 |
+
|
290 |
+
def calculate_confidence(self, search_results: List[SearchResult]) -> float:
|
291 |
+
"""Calculate confidence score based on search results"""
|
292 |
+
|
293 |
+
if not search_results:
|
294 |
+
return 0.0
|
295 |
+
|
296 |
+
# Factors for confidence calculation
|
297 |
+
avg_relevance = sum(r.score for r in search_results) / len(search_results)
|
298 |
+
high_relevance_count = sum(1 for r in search_results if r.score >= 0.7)
|
299 |
+
high_importance_count = sum(1 for r in search_results if r.clinical_importance >= 0.8)
|
300 |
+
|
301 |
+
# Weighted confidence score
|
302 |
+
relevance_weight = 0.5
|
303 |
+
coverage_weight = 0.3
|
304 |
+
importance_weight = 0.2
|
305 |
+
|
306 |
+
relevance_score = min(avg_relevance / 0.8, 1.0) # Normalize to 0.8 as max
|
307 |
+
coverage_score = min(high_relevance_count / 3, 1.0) # 3+ high relevance results = full score
|
308 |
+
importance_score = min(high_importance_count / 2, 1.0) # 2+ high importance = full score
|
309 |
+
|
310 |
+
confidence = (
|
311 |
+
relevance_weight * relevance_score +
|
312 |
+
coverage_weight * coverage_score +
|
313 |
+
importance_weight * importance_score
|
314 |
+
)
|
315 |
+
|
316 |
+
return min(confidence, 1.0)
|
317 |
+
|
318 |
+
def batch_query(self, questions: List[str]) -> List[QueryResponse]:
|
319 |
+
"""Process multiple queries efficiently"""
|
320 |
+
|
321 |
+
logger.info(f"📋 Processing {len(questions)} queries in batch...")
|
322 |
+
responses = []
|
323 |
+
|
324 |
+
for i, question in enumerate(questions, 1):
|
325 |
+
logger.info(f"Processing query {i}/{len(questions)}")
|
326 |
+
response = self.query(question)
|
327 |
+
responses.append(response)
|
328 |
+
|
329 |
+
logger.info(f"✅ Batch processing complete: {len(responses)} responses generated")
|
330 |
+
return responses
|
331 |
+
|
332 |
+
def get_system_stats(self) -> Dict[str, Any]:
|
333 |
+
"""Get RAG system statistics"""
|
334 |
+
|
335 |
+
vector_stats = self.vector_store.get_statistics()
|
336 |
+
|
337 |
+
return {
|
338 |
+
'vector_store': vector_stats,
|
339 |
+
'rag_config': {
|
340 |
+
'default_k': self.default_k,
|
341 |
+
'min_relevance_score': self.min_relevance_score,
|
342 |
+
'max_context_length': self.max_context_length,
|
343 |
+
'llm_type': self.llm._llm_type if self.llm else 'None'
|
344 |
+
},
|
345 |
+
'status': 'initialized' if self.vector_store and self.llm else 'not_initialized'
|
346 |
+
}
|
347 |
+
|
348 |
+
def main():
|
349 |
+
"""Main function to test RAG system"""
|
350 |
+
logger.info("🚀 Testing Maternal Health RAG System...")
|
351 |
+
|
352 |
+
# Initialize RAG system
|
353 |
+
rag_system = MaternalHealthRAG()
|
354 |
+
|
355 |
+
# Test queries
|
356 |
+
test_queries = [
|
357 |
+
"What is the recommended dosage of magnesium sulfate for preeclampsia?",
|
358 |
+
"How should postpartum hemorrhage be managed in emergency situations?",
|
359 |
+
"What are the signs and symptoms of puerperal sepsis?",
|
360 |
+
"What is the normal fetal heart rate range during labor?",
|
361 |
+
"When is cesarean section indicated during delivery?"
|
362 |
+
]
|
363 |
+
|
364 |
+
logger.info("\n🔍 Testing RAG Query Processing...")
|
365 |
+
|
366 |
+
for i, query in enumerate(test_queries, 1):
|
367 |
+
logger.info(f"\n📝 Query {i}: {query}")
|
368 |
+
|
369 |
+
response = rag_system.query(query)
|
370 |
+
|
371 |
+
logger.info(f"⏱️ Response time: {response.response_time:.2f}s")
|
372 |
+
logger.info(f"🎯 Confidence: {response.confidence:.3f}")
|
373 |
+
logger.info(f"📚 Sources: {response.metadata['num_sources']}")
|
374 |
+
logger.info(f"📊 Avg relevance: {response.metadata['avg_relevance']:.3f}")
|
375 |
+
logger.info(f"💡 Answer: {response.answer[:200]}...")
|
376 |
+
|
377 |
+
# Get system statistics
|
378 |
+
stats = rag_system.get_system_stats()
|
379 |
+
logger.info(f"\n📊 RAG System Statistics:")
|
380 |
+
logger.info(f" Vector store chunks: {stats['vector_store']['total_chunks']}")
|
381 |
+
logger.info(f" LLM type: {stats['rag_config']['llm_type']}")
|
382 |
+
logger.info(f" System status: {stats['status']}")
|
383 |
+
|
384 |
+
logger.info("\n✅ RAG system testing complete!")
|
385 |
+
|
386 |
+
if __name__ == "__main__":
|
387 |
+
main()
|
src/nougat_pdf_processor.py
ADDED
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import logging
|
3 |
+
import os
|
4 |
+
from pathlib import Path
|
5 |
+
import shutil
|
6 |
+
import torch
|
7 |
+
from groq import Groq
|
8 |
+
from nougat import NougatModel
|
9 |
+
from nougat.utils.device import move_to_device
|
10 |
+
from nougat.postprocessing import markdown_compatible
|
11 |
+
from pypdf import PdfReader
|
12 |
+
from tqdm import tqdm
|
13 |
+
from dotenv import load_dotenv
|
14 |
+
import pypdfium2 as pdfium
|
15 |
+
from torchvision.transforms.functional import to_tensor
|
16 |
+
|
17 |
+
# Configure basic logging
|
18 |
+
logging.basicConfig(
|
19 |
+
level=logging.INFO,
|
20 |
+
format="%(asctime)s - %(levelname)s - %(message)s",
|
21 |
+
handlers=[logging.StreamHandler(), logging.FileHandler("pdf_processing.log")],
|
22 |
+
)
|
23 |
+
|
24 |
+
class NougatPDFProcessor:
|
25 |
+
"""
|
26 |
+
Processes PDFs using the Nougat model to generate high-quality Markdown,
|
27 |
+
and prepends an AMA citation generated by a Groq LLM.
|
28 |
+
"""
|
29 |
+
|
30 |
+
def __init__(self, input_dir: str, output_dir: str):
|
31 |
+
self.input_dir = Path(input_dir)
|
32 |
+
self.output_dir = Path(output_dir)
|
33 |
+
self.temp_dir = self.output_dir / "temp_nougat_output"
|
34 |
+
|
35 |
+
self.output_dir.mkdir(exist_ok=True)
|
36 |
+
self.temp_dir.mkdir(exist_ok=True)
|
37 |
+
|
38 |
+
load_dotenv()
|
39 |
+
groq_api_key = os.getenv("GROQ_API_KEY")
|
40 |
+
if not groq_api_key:
|
41 |
+
raise ValueError("GROQ_API_KEY not found in .env file")
|
42 |
+
self.groq_client = Groq(api_key=groq_api_key)
|
43 |
+
|
44 |
+
# Initialize Nougat model
|
45 |
+
self.model = NougatModel.from_pretrained("facebook/nougat-small").to(torch.bfloat16)
|
46 |
+
self.model = move_to_device(self.model)
|
47 |
+
self.model.eval()
|
48 |
+
|
49 |
+
def _get_first_page_text(self, pdf_path: Path) -> str:
|
50 |
+
"""Extracts text from the first page of a PDF."""
|
51 |
+
try:
|
52 |
+
reader = PdfReader(pdf_path)
|
53 |
+
first_page = reader.pages[0]
|
54 |
+
return first_page.extract_text() or ""
|
55 |
+
except Exception as e:
|
56 |
+
logging.error(f"Could not extract text from first page of '{pdf_path.name}': {e}")
|
57 |
+
return ""
|
58 |
+
|
59 |
+
def _generate_ama_citation(self, text: str) -> str:
|
60 |
+
"""Generates an AMA citation using the Groq API."""
|
61 |
+
if not text:
|
62 |
+
return "Citation could not be generated: No text found on the first page."
|
63 |
+
|
64 |
+
prompt = (
|
65 |
+
"Based on the following text from the first page of a medical document, "
|
66 |
+
"please generate a concise AMA (American Medical Association) style citation. "
|
67 |
+
"Include authors, title, journal/source, year, and volume/page numbers if available. "
|
68 |
+
"If some information is missing, create the best citation possible with the available data. "
|
69 |
+
"Output only the citation itself, with no additional text or labels.\n\n"
|
70 |
+
f"--- DOCUMENT TEXT ---\n{text[:4000]}\n\n--- END DOCUMENT TEXT ---\n\nAMA Citation:"
|
71 |
+
)
|
72 |
+
try:
|
73 |
+
chat_completion = self.groq_client.chat.completions.create(
|
74 |
+
messages=[{"role": "user", "content": prompt}],
|
75 |
+
model="llama3-8b-8192",
|
76 |
+
temperature=0,
|
77 |
+
max_tokens=200,
|
78 |
+
)
|
79 |
+
citation = chat_completion.choices[0].message.content.strip()
|
80 |
+
return f"## Citation\n\n{citation}\n\n---\n\n"
|
81 |
+
except Exception as e:
|
82 |
+
logging.error(f"Groq API call failed for citation generation: {e}")
|
83 |
+
return "## Citation\n\nCitation could not be generated due to an error.\n\n---\n\n"
|
84 |
+
|
85 |
+
def process_single_pdf(self, pdf_path: Path):
|
86 |
+
"""Processes a single PDF with Nougat and adds a citation."""
|
87 |
+
logging.info(f"Processing '{pdf_path.name}'...")
|
88 |
+
final_md_path = self.output_dir / f"{pdf_path.stem}.md"
|
89 |
+
|
90 |
+
# 1. Generate Citation
|
91 |
+
logging.info(f"Generating AMA citation for '{pdf_path.name}'...")
|
92 |
+
first_page_text = self._get_first_page_text(pdf_path)
|
93 |
+
citation_md = self._generate_ama_citation(first_page_text)
|
94 |
+
logging.info(f"Citation generated for '{pdf_path.name}'.")
|
95 |
+
|
96 |
+
# 2. Process with Nougat
|
97 |
+
logging.info(f"Processing PDF '{pdf_path.name}' with Nougat...")
|
98 |
+
try:
|
99 |
+
# Open the PDF with pypdfium2 and render the first page
|
100 |
+
pdf = pdfium.PdfDocument(pdf_path)
|
101 |
+
page = pdf[0] # Get the first page
|
102 |
+
bitmap = page.render(scale=1) # Render at 72 DPI
|
103 |
+
image = bitmap.to_pil() # Convert to a PIL Image
|
104 |
+
|
105 |
+
# Resize the image to the required dimensions for the Nougat model
|
106 |
+
image = image.resize((672, 896))
|
107 |
+
|
108 |
+
# Convert PIL image to a bfloat16 tensor
|
109 |
+
tensor = to_tensor(image).to(torch.bfloat16)
|
110 |
+
|
111 |
+
# Pass the tensor to the model
|
112 |
+
predictions = self.model.inference(image_tensors=tensor.unsqueeze(0))
|
113 |
+
|
114 |
+
# The output for a single file is in predictions['predictions'][0]
|
115 |
+
nougat_markdown = predictions['predictions'][0]
|
116 |
+
|
117 |
+
# Post-processing to fix common markdown issues
|
118 |
+
nougat_markdown = markdown_compatible(nougat_markdown)
|
119 |
+
|
120 |
+
logging.info(f"Successfully processed '{pdf_path.name}' with Nougat.")
|
121 |
+
|
122 |
+
# 3. Combine and Save
|
123 |
+
final_content = citation_md + nougat_markdown
|
124 |
+
final_md_path.write_text(final_content, encoding="utf-8")
|
125 |
+
logging.info(f"Successfully saved final markdown to '{final_md_path}'.")
|
126 |
+
|
127 |
+
except Exception as e:
|
128 |
+
logging.error(f"Failed to process '{pdf_path.name}' with Nougat: {e}")
|
129 |
+
# Create an error file to avoid reprocessing
|
130 |
+
final_md_path.write_text(f"Failed to process this document with Nougat.\n\nError: {e}", encoding="utf-8")
|
131 |
+
|
132 |
+
def process_all_pdfs(self):
|
133 |
+
"""Processes all PDF files in the input directory."""
|
134 |
+
pdf_files = sorted(list(self.input_dir.glob("*.pdf")))
|
135 |
+
if not pdf_files:
|
136 |
+
logging.warning(f"No PDF files found in {self.input_dir}")
|
137 |
+
return
|
138 |
+
|
139 |
+
logging.info(f"Found {len(pdf_files)} PDF(s) to process.")
|
140 |
+
|
141 |
+
for pdf_path in tqdm(pdf_files, desc="Processing PDFs with Nougat"):
|
142 |
+
final_md_path = self.output_dir / f"{pdf_path.stem}.md"
|
143 |
+
if final_md_path.exists():
|
144 |
+
logging.info(f"Skipping '{pdf_path.name}' as it has already been processed.")
|
145 |
+
continue
|
146 |
+
|
147 |
+
self.process_single_pdf(pdf_path)
|
148 |
+
|
149 |
+
def main():
|
150 |
+
"""Main function to run the PDF processing script."""
|
151 |
+
parser = argparse.ArgumentParser(description="PDF to Markdown Converter using Nougat with AMA Citations.")
|
152 |
+
parser.add_argument("--input-dir", type=str, default="Obs", help="Directory containing source PDF files.")
|
153 |
+
parser.add_argument("--output-dir", type=str, default="src/processed_markdown", help="Directory to save final Markdown files.")
|
154 |
+
parser.add_argument("--file", type=str, help="Process a single PDF file by name (e.g., 'my_doc.pdf').")
|
155 |
+
args = parser.parse_args()
|
156 |
+
|
157 |
+
processor = NougatPDFProcessor(input_dir=args.input_dir, output_dir=args.output_dir)
|
158 |
+
|
159 |
+
if args.file:
|
160 |
+
pdf_to_process = Path(args.input_dir) / args.file
|
161 |
+
if pdf_to_process.exists():
|
162 |
+
processor.process_single_pdf(pdf_to_process)
|
163 |
+
else:
|
164 |
+
logging.error(f"Specified file not found: {pdf_to_process}")
|
165 |
+
else:
|
166 |
+
processor.process_all_pdfs()
|
167 |
+
|
168 |
+
if __name__ == "__main__":
|
169 |
+
main()
|
src/processed_markdown/6-SLJOG-1-Guideline-Page-143-150-1/6-SLJOG-1-Guideline-Page-143-150-1.md
ADDED
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---\n\ncitation: "6 SLJOG 1 Guideline Page 143 150 1"\n\n---\n\nSri Lanka Journal of Obstetrics and Gynaecology
|
2 |
+
|
3 |
+
¥s gies 9 HEA:
|
4 |
+
|
5 |
+
SLCOG
|
6 |
+
|
7 |
+
Blood Transfusion in Pregnancy
|
8 |
+
|
9 |
+
Guideline No: 01
|
10 |
+
|
11 |
+
September 2023
|
12 |
+
|
13 |
+
Please cite this paper as: Abeywardane A, Rajapakse L, Marleen S, Kadotgajan T, Lanerolle S, Dodampahala S H, on behalf of the Sri Lanka College of Obstetricians and Gynaecologists. Blood Transfusion in Pregnancy.
|
14 |
+
|
15 |
+
Sri Lanka College of Obstetricians and Gynaecologists
|
16 |
+
|
17 |
+
SLCOG Guideline
|
18 |
+
|
19 |
+
SLCOG Guideline
|
20 |
+
|
21 |
+
Blood transfusion in pregnancy
|
22 |
+
|
23 |
+
A Abeywardanea, L Rajapakseb, S Marleenc, T Kadotgajand, S Lanerolled, S H Dodampahalae on behalf of the Sri Lanka College of Obstetricians and Gynaecologists
|
24 |
+
|
25 |
+
Correspondence: Sri Lanka College of Obstetricians and Gynaecologists, No. 112, Model Farm Road, Colombo 08. E-mail: [email protected]
|
26 |
+
|
27 |
+
1. Purpose and scope
|
28 |
+
|
29 |
+
Blood transfusion is an essential component of emergency obstetric care and, at times, lifesaving, but it is not without risks. This guideline aims to provide guidance on the appropriate use of blood products, which would neither compromise nor expose the patient to unnecessary risks associated with trans- fusion. Strategies to optimise the haemoglobin (Hb) level at delivery and minimise blood loss at delivery are also discussed.
|
30 |
+
|
31 |
+
2. Introduction
|
32 |
+
|
33 |
+
Obstetric haemorrhage remains a leading cause of direct maternal deaths in Sri Lanka, accounting for 15.4% of total maternal deaths in 20201. Eventhough a large majority of patients with obstetric haemorrhage survive uneventfully with timely interventions, it re-mains an important cause of severe maternal morbidity.
|
34 |
+
|
35 |
+
In 2022, the prevalence of anaemia among pregnant women in Sri Lanka was 29.1%2. A significant pro- portion of pregnant women with anaemia may require blood transfusion if it is not addressed in a timely manner. Transfusion services in Sri Lanka are rapidly improving, with all blood components prepared with 100% volunteer donations, which are mandatorily tested for HIV 1 and 2, Hepatitis B, Hepatitis C, Syphilis and Malaria.
|
36 |
+
|
37 |
+
3. Strategies to minimise the requirement for transfusion\n\n3.1. Optimisation of haemoglobin during the antenatal period
|
38 |
+
|
39 |
+
3.1.1. Diagnosis
|
40 |
+
|
41 |
+
All pregnant women should be screened for anaemia at the booking visit and 28 weeks. Anaemia in pregnancy is defined as first-trimester Hb less than 11g/dL, second and third-trimester Hb less than 10.5g/dL, and postpartum Hb less than 10g/dL according to the British Committee for Standards in Haematology3. If the Hb level is less than the relevant thresholds, consider haematinic deficiency once haemoglobin-opathies have been excluded.
|
42 |
+
|
43 |
+
3.1.2. Treatment and management
|
44 |
+
|
45 |
+
Oral iron should be the preferred first-line treatment for iron deficiency anaemia. Parenteral iron is indicated when oral iron is not tolerated or absorbed, patient compliance is in doubt or if the woman is approaching term when there is insufficient time for oral supple- mentation to be effective. Women should receive information on improving dietary iron intake and the factors affecting the absorption of dietary iron.
|
46 |
+
|
47 |
+
Meta-analysis of randomised trials on the antenatal use of iron, with or without folic acid, showed a 50%
|
48 |
+
|
49 |
+
Sri Lanka Journal of Obstetrics and Gynaecology 2023; 45: 143-150
|
50 |
+
|
51 |
+
DOI: http://doi.org/
|
52 |
+
|
53 |
+
a Consultant Transfusion Physician, Sri Jayewardenepura General Hospital, Sri Lanka.
|
54 |
+
|
55 |
+
b Consultant Obstetrician and Gynaecologist, District General Hospital, Matale, Sri Lanka.
|
56 |
+
|
57 |
+
c Consultant Obstetrician and Gynaecologist, Sri Jayewardenepura General Hospital, Sri Lanka.
|
58 |
+
|
59 |
+
d Consultant Obstetrician and Gynaecologist, Castle Street Hospital for Women, Sri Lanka.
|
60 |
+
|
61 |
+
e Professor in Obstetrics and Gynaecology, Faculty of Medicine, University of Colombo, Sri Lanka.
|
62 |
+
|
63 |
+
Vol. 45, No. 3, September 2023
|
64 |
+
|
65 |
+
143
|
66 |
+
|
67 |
+
SLCOG Guideline
|
68 |
+
|
69 |
+
reduction in the risk of anaemia in the third trimester or at delivery4,5. Parenteral iron therapy offers a shorter duration of treatment and a quicker response but is more invasive. Intravenous iron preparation should be administered with all resuscitation facilities available immediately, as severe allergic reactions are possible. Anaemia not due to haematinic deficiency should be managed in close conjunction with a haematologist and transfusion physician.\n\n3.2. Strategies to minimise blood loss at delivery
|
70 |
+
|
71 |
+
Women at high risk of haemorrhage should be delivered in a hospital with facilities to manage massive bleeding. Active management of the third stage of labour is recommended to reduce postpartum blood loss.
|
72 |
+
|
73 |
+
4. General principles of blood transfusion
|
74 |
+
|
75 |
+
4.1. Consent
|
76 |
+
|
77 |
+
Valid informed consent should be obtained where possible before blood transfusion. In case of an emergency, where it is not feasible to get consent prior to transfusion, transfusions should not be delayed, but information on blood transfusion should be provided retrospectively.
|
78 |
+
|
79 |
+
Where transfusion of all or a specific blood component is refused, or an advanced directive exists, detailed counselling should be arranged with a transfusion physician where available. This should be documented in the patient’s clinical records and communicated to all relevant healthcare professionals. Following detailed counselling, should the patient not consent for transfusion of blood and blood products, legal guidance should be sought.
|
80 |
+
|
81 |
+
4.2. Requirements for group and screen samples and cross-matching
|
82 |
+
|
83 |
+
All women should have their blood group and red cell antibody status checked at booking and 28 weeks gestation. If red cell antibodies are detected in the booking sample, further testing of maternal blood should be done to determine the specificity and the titre of antibody/antibodies detected and to assess the likelihood of haemolytic disease of the foetus and newborn.
|
84 |
+
|
85 |
+
Group and screen samples used for the provision of blood in pregnancy should be less than 3 days old. This should accompany a separate sample for blood
|
86 |
+
|
87 |
+
144
|
88 |
+
|
89 |
+
group confirmation if the blood group has not been done before. In a woman at high risk of emergency transfusion, e.g., placenta previa, with no clinically significant alloantibodies, group and screen samples should be sent once a week to exclude or to identify any new antibody formation and to keep blood available if necessary. Close liaison with the transfusion physician/team is essential.
|
90 |
+
|
91 |
+
4.3. Blood product specifications in pregnancy and puerperium
|
92 |
+
|
93 |
+
ABO and RhD identical or compatible red cell units should be transfused. If clinically significant red cell antibodies are present, blood negative for the relevant red cell antigen should be cross-matched for transfusion. Where complex antibodies or rare red cell phenotypes are identified, provision of compatible blood may take time, and when transfusions are needed in such instances, inform the transfusion laboratory in advance to avoid potential delays in the provision of blood. All patients receiving transfusions should be closely monitored throughout the transfusion to identify signs of transfusion reactions and adverse events early and act promptly.\n\n4.4. Intraoperative cell salvage
|
94 |
+
|
95 |
+
Intraoperative cell salvage could be considered in patients who are expected to have a blood loss of more than 500ml or more than 10% of the patient’s estimated blood volume if facilities are available6. However, such facilities are currently unavailable in Sri Lanka.
|
96 |
+
|
97 |
+
5. Management of obstetric haemorrhage with blood components
|
98 |
+
|
99 |
+
Clinicians should familiarise themselves with the existing guidelines on the management of PPH and protocols for managing major obstetric haemorrhage, including the mechanical strategies employed to reduce postpartum blood loss7.
|
100 |
+
|
101 |
+
5.1. When should red cells be used?
|
102 |
+
|
103 |
+
The decision to transfuse should be made on clinical and haematological grounds. Although the aim of blood transfusion in a bleeding patient is to maintain Hb more than 8g/dL, patients with acute haemorrhage can have normal Hb and clinical evaluation in this situation is extremely important.
|
104 |
+
|
105 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
106 |
+
|
107 |
+
In an emergency where the patient’s blood group is unknown, group O RhD-negative red cells should be given until the blood group is established and then switch to group-specific red cells. In case of a severe haemorrhage, if there is a history of clinically significant red cell antibodies being present, close liaison with the transfusion physician is essential to avoid delay in transfusion. Once bleeding is controlled, restoring Hb to physiological levels with red cell transfusions is not indicated8.
|
108 |
+
|
109 |
+
5.2. In what circumstances should fresh frozen plasma (FFP) and cryoprecipitate be used?
|
110 |
+
|
111 |
+
When available, point-of-care testing-guided FFP and cryoprecipitate transfusions are preferable to optimise haemostatic management9. If results of point-of-care or haemostatic testing are unavailable and haemorrhage continues, FFP at a dose of 12-15 ml/kg should be administered for every six units of red cell concentrates (RCC)5. Early use of FFP should be considered for conditions with a suspected coagulopathy, such as placental abruption or amniotic fluid embolism, or where detection of PPH has been delayed10.
|
112 |
+
|
113 |
+
If the haemorrhage is ongoing, subsequent FFP transfusion should be guided by the results of clotting tests aiming to maintain prothrombin time (PT) and activated partial thromboplastin time (APTT) ratios at less than 1.5 times normal8. It is essential that regular full blood counts and coagulation screens (PT, APTT and fibrinogen) are performed during the bleeding episode. The drawbacks of early FFP are that the majority of women with PPH will have normal coagulation at the time of FFP administration and that it is associated with an increased risk of transfusion- associated circulatory overload (TACO) and trans- fusion-related acute lung injury (TRALI). FFP results in a relatively small increment in fibrinogen level10,11.
|
114 |
+
|
115 |
+
Cryoprecipitate at a standard dose of 10 units should be administered relatively early in major obstetric haemorrhage. Subsequent cryoprecipitate transfusion should be guided by fibrinogen results, aiming to keep levels above 2g/l. RCTs do not support the early unselected use of fibrinogen replacement therapy, and administering fibrinogen supplementation to women with PPH who have fibrinogen levels of >2 g/l is unlikely to have added benefit8,12,13.
|
116 |
+
|
117 |
+
Vol. 45, No. 3, September 2023
|
118 |
+
|
119 |
+
SLCOG Guideline
|
120 |
+
|
121 |
+
FFP should ideally be of the same ABO group as the recipient. If unavailable, FFP of a compatible ABO group is acceptable. The blood group of cryoprecipitate is not considered in the local context, considering the production method.
|
122 |
+
|
123 |
+
Clinicians should be aware that these blood components must be ordered as soon as a need for them is anticipated, as there will always be a short delay in supply because of the need for thawing and recons- tituting.\n\n5.3. When should platelets be used?
|
124 |
+
|
125 |
+
Aim to maintain the platelet count above 50×109/l in an acutely bleeding patient. A platelet transfusion trigger of 75×109/l is recommended to provide a margin of safety. If results of point-of-care testing or haemostatic testing are not available and haemorrhage is continuing, four units of platelet concentrates should be adminis- tered after eight or more units of red cell concentrates14. The platelets should be ABO group identical or compatible. To avoid the development of anti-D antibodies, RhD-negative platelet concentrates should be given where possible to RhD-negative women of childbearing potential.
|
126 |
+
|
127 |
+
Platelets may not be readily available in some hospitals; therefore, their need should be anticipated, and good communication with the transfusion team should be maintained. The platelet count should not be allowed to fall below 50×109/l in the acutely bleeding patient, as this represents the critical level for haemostasis. Such a low platelet count may be anticipated when approximately two blood volumes have been replaced by fluid or blood components. A platelet transfusion trigger of 75×109/l is recommended in a patient with ongoing bleeding to provide a margin of safety.
|
128 |
+
|
129 |
+
If RhD-positive platelets are transfused to a RhD- negative woman of childbearing potential, anti-D immunoglobulin should be administered. A dose of 250 iu anti-D immunoglobulin is sufficient to cover 5 adult therapeutic doses of platelets given within a 6-week period. This may be given subcutaneously to minimise bruising and haematomas in thrombocytopenic women.
|
130 |
+
|
131 |
+
145
|
132 |
+
|
133 |
+
SLCOG Guideline
|
134 |
+
|
135 |
+
6. How should intrapartum anaemia be managed?
|
136 |
+
|
137 |
+
In anaemic women who are not actively bleeding, if the Hb is less than 8g/dL in labour or in the immediate postpartum period, the decision to transfuse should be made according to the individual’s medical history and symptoms. Where transfusion is indicated, transfusion of a single unit of red cell concentrate should be followed by clinical reassessment to determine the need for further transfusions.\n\n7. How should women with postpartum anaemia be managed in the postnatal period?
|
138 |
+
|
139 |
+
If the Hb is more than 7g/dL in the postnatal period, where there is no ongoing or threat of bleeding, the decision to transfuse should be made on an informed
|
140 |
+
|
141 |
+
146
|
142 |
+
|
143 |
+
individual basis. The risk of RBC alloimmunisation and the potential clinical impact should be considered when balancing the risks and benefits of RBC trans- fusion. Non-transfusion therapies, such as iron, should be considered as a part of the treatment of postpartum anaemia.
|
144 |
+
|
145 |
+
8. How should women who decline blood products be managed?
|
146 |
+
|
147 |
+
Hb should be optimised prior to delivery to prevent avoidable anaemia. Consent/refusal of blood compo- nents or other transfusion-sparing techniques should be discussed in detail and clearly documented during the antenatal period. The use of pharmacological, mechanical and surgical procedures to avert the use of banked blood and blood components should be considered early. Medicolegally, withholding blood products in life-saving situations is not permitted.
|
148 |
+
|
149 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
150 |
+
|
151 |
+
SLCOG Guideline
|
152 |
+
|
153 |
+
Appendix 1. Massive obstetric haemorrhage protocol
|
154 |
+
|
155 |
+
Activation of Massive Obstetric Transfusion Protocol should be considered when: © Bleeding >1000mI, with severe ongoing bleeding with/without signs and symptoms of hypovolemia © Rate of blood loss is >150mi/min © Bleeding which leads to a SBP < 90 mmHg or HR>110 bpm Identification of the requirement of massive transfusion is the responsibility of the attending clinician Give tranexamic acid 1g in 10 ml of 0.9% saline over 10 minutes Send blood for Crossmatch, FBC, Coagulation Screen, ROTEM, Biochemistry & ABG analysis Give 2 units of Red Cell Concentrate © Group O Rh D negative uncrossmatched RCC — when blood group is not known ¢ Switch to ABO group specific uncrossmatched RCC as soon as blood group is known Use crossmatched blood if available This request can be made over the phone - Dial : ....... | Clinician informs the Blood Bank / Consultant Transfusion Physician to activate the Massive Obstetric Transfusion Protocol — Dial .... Monitor coagulation regularly (ROTEM, | BOX ONE : 2 RCC PT, APTT, Fibrinogen, J FBC, Ca”, Arterial blood gases) Therapeutic Goals ROTEM available: ROTEM guided Blood Component Therapy Hb > 8¢/dl FIBTEM AS>12mm | EXTEM AS>35mm | if still bleeding, EXTEM CT < 80 sec Consider second dose of Tranaxamic acid 1g PT/APTT < 1.5 of mid point of after 30 min of first dose J BOX TWO: 4 units RCC, 4 units Continue cycle of clinical & laboratory (12-15mi/kg) FFP, 10 units of monitoring & administration of goal directed Cryoprecipitate blood component therapy until bleeding stops BOX THREE: 4 units RBC, 4 units (12-15mi/kg) FFP, 10 units of Cryoprecipitate 1 adult dose of Platelets if the platelets count is <75 X10°/I to maintain platelets >50 X 10°/ Repeat Box 2 and 3 alternatively until bleeding stops Clinician decides to terminate the MTP and informs the Blood Bank (usually active bleeding has stopped) Any unused components should be returned to the blood bank immediately Sri Lanka College of Transfusion Physicians - 2023,
|
156 |
+
|
157 |
+
Vol. 45, No. 3, September 2023
|
158 |
+
|
159 |
+
147
|
160 |
+
|
161 |
+
SLCOG Guideline\n\nAppendix 2. Algorithm for Rotem-guided PPH management
|
162 |
+
|
163 |
+
Algorithm for Rotem-guided PPH management Blood loss > 1000m| after delivery Consider Tranexamic acid 1g with ongoing bleeding > YES AS ex< 35mm _— or Givet cacldd bol CTris > 600s or —) we enn ‘n Base olus ML>10% repeat if indicate YES 1or2ATD of Cryo precipitateor Fibrinogen concentrate Target : AS rig> 16mm AS ex< 35mm AS Fis< 12mm NO AS ex< 35mm ASrig> 12mm oo 1 ATD of platelet concentrate YES NO CT ex> 80mm & FFP 12-15ml/kg or 4F-PCC 10-15 IU/kg ASris> 12mm CT in> 240mm —= CT in /CTHeP Consider Protamine 25-50mg >1.25 Consider FFP 12-15ml/kg.or rFVIla 90mcg/kg Ee Recheck after 10-15 min with a new blood sample Maintain Hb > 8g/dl Consider RCC to maintain Hb > 8g/dl PH>7.2 Ca**i >1.0 mmol/I Ongoing bleeding Core body temperature >35°C Sri Lanka College of Transfusion Physicians - 2023
|
164 |
+
|
165 |
+
148
|
166 |
+
|
167 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
168 |
+
|
169 |
+
SLCOG Guideline
|
170 |
+
|
171 |
+
Appendix 3. Sample consent form for transfusion of blood and blood components
|
172 |
+
|
173 |
+
Os Bared MO: ... HE Qos gomea : we 88 Bw mda: Owe : Os / DEG pHs WO MdHGUMS Mdz CAM HSS weesOm CO2MO24,8 O8 gm osfenS. mddeane Bs mdz] CAD Made ow me BOS gm osenS. GBS mdScgame Od / Qed ¢hjO2 WO BgOm awost ACE,® MDCKYS gost 5S. RBS mdSGume eosomO Bs mee godal¥n gHdE ome So mS Ad gm o88. GBS mdBGame Hess 48 a mB eQnh pad ww womEm COrmO2G18 em OBS. Hed / Hed ejHhhoed gaBs aaslOe ehpedst G86 sdHeans 002700 HS Saco mode 8 gost 5S. ©® BOATIDO gar BOO Os WO gqOekdoOast got yd BOs0 Gado got BENG BAO &28Omdo os 5S. 90D Bad mje BEDE 41 Ost HeOst uy, Bode emést eth ® com Od / O2ed §GpOo WO GBS mdHeane sews mOstn emOstn COBst yma mdS. C§HBmecdimdmned enter : eodgnddwmod genta : 0658020 ItdmcqjO BobOO emmmHmn® : wawtBmcjed m®-... Sri Lanka College of Transfusion Physicians - 2023
|
174 |
+
|
175 |
+
Vol. 45, No. 3, September 2023
|
176 |
+
|
177 |
+
149
|
178 |
+
|
179 |
+
SLCOG Guideline\n\nReferences
|
180 |
+
|
181 |
+
1. Annual Health Bulletin 2020. Ministry of Health, Sri Lanka.
|
182 |
+
|
183 |
+
2. Amarasinghe GS, Agampodi TC, Mendis V, Malawanage K, Kappagoda C, Agampodi SB. Prevalence and aetiologies of anaemia among first trimester pregnant women in Sri Lanka; the need for revisiting the current control strategies. BMC Pregnancy Childbirth. 2022; 22(1): 16.
|
184 |
+
|
185 |
+
3. Pavord S, Daru J, Prasannan N, Robinson S, Stanworth S, Girling J, et al. UK guidelines on the management of iron deficiency in pregnancy. Br J Haematol. 2020; 188(6): 819-30.
|
186 |
+
|
187 |
+
4. Haider BA, Olofin I, Wang M, Spiegelman D, Ezzati M, Fawzi WW. Anaemia, prenatal iron use, and risk of adverse pregnancy outcomes: systematic review and meta-analysis. BMJ: British Medical Journal. 2013; 346: f3443.
|
188 |
+
|
189 |
+
5. Royal College of Obstetricians and Gynaecologists. Blood Transfusion in Obstetrics. Green-top Guideline No. 47. London: RCOG; 2015.
|
190 |
+
|
191 |
+
6. Carroll C, Young F. Intraoperative cell salvage. BJA Educ. 2021; 21(3): 95-101.
|
192 |
+
|
193 |
+
7. Guidelines for the Blood Transfusion Services in the United Kingdom. www.transfusionguidelines.org.uk
|
194 |
+
|
195 |
+
8. Stanworth SJ, Dowling K, Curry N, Doughty H, Hunt BJ, Fraser L, et al. Haematological management of major haemorrhage: a British
|
196 |
+
|
197 |
+
150
|
198 |
+
|
199 |
+
Society for Haematology Guideline. Br J Haematol. 2022; 198(4): 654-67.
|
200 |
+
|
201 |
+
9. Snegovskikh D, Souza D, Walton Z, Dai F, Rachler R, Garay A, et al. Point-of-care viscoelastic testing improves the outcome of pregnancies complicated by severe postpartum hemorrhage. J Clin Anesth. 2018; 44: 50-6.
|
202 |
+
|
203 |
+
10. Mavrides E, Allard S, Chandraharan E, Collins P, Green L, Hunt BJ, Riris S, Thomson AJ on behalf of the Royal College of Obstetricians and Gynae- cologists. Prevention and management of post- partum haemorrhage. BJOG 2016; 124: e106-e149.
|
204 |
+
|
205 |
+
11. McNamara H, Kenyon C, Smith R, Mallaiah S, Barclay P. Four years’ experience of a ROTEM. Anaesthesia. 2019; 74(8): 984-91.
|
206 |
+
|
207 |
+
12. Collins PW, Cannings-John R, Bruynseels D, Mallaiah S, Dick J, Elton C, et al. Viscoelastometric- guided early fibrinogen concentrate replacement during postpartum haemorrhage: OBS2, a double- blind randomized controlled trial. Br J Anaesth. 2017; 119(3): 411-21.
|
208 |
+
|
209 |
+
13. Wikkelso AJ, Edwards HM, Afshari A, Stensballe J, Langhoff-Roos J, Albrechtsen C, et al. Pre- emptive treatment with fibrinogen concentrate for postpartum haemorrhage: randomized controlled trial. Br J Anaesth. 2015; 114(4): 623-33.
|
210 |
+
|
211 |
+
14. Collins P, Abdul-Kadir R, Thachil J, Coagulation SoWsHIiTaHaoDI. Management of coagulopathy associated with postpartum hemorrhage: guidance from the SSC of the ISTH. J Thromb Haemost. 2016; 14(1): 205-10.
|
212 |
+
|
213 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
src/processed_markdown/Assisted-vaginal-delivery-Dec-1/Assisted-vaginal-delivery-Dec-1.md
ADDED
@@ -0,0 +1,611 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---\n\ncitation: "Assisted vaginal delivery Dec 1"\n\n---\n\nSLCOG Guideline
|
2 |
+
|
3 |
+
SLCOG Guideline
|
4 |
+
|
5 |
+
Assisted Vaginal Delivery
|
6 |
+
|
7 |
+
D Senadheeraa, C Jayasundarab, I A Jayawardaneb on behalf of the Sri Lanka College of Obstetricians and Gynaecologists
|
8 |
+
|
9 |
+
Correspondence: Sri Lanka College of Obstetricians and Gynaecologists, No. 112, Model Farm Road, Colombo 08. E-mail: [email protected]
|
10 |
+
|
11 |
+
1. Introduction, background and epidemiology
|
12 |
+
|
13 |
+
3. Identification and assessment of evidence
|
14 |
+
|
15 |
+
Management of second stage of labour frequently necessitates assisted birth, to avoid a potentially hazardous second stage caesarean section. In the United Kingdom 10% to 15% of all women undergo assisted vaginal birth, even though rate is much lower in Sri Lanka1. Instrumental delivery when performed correctly by a trained clinician, results in satisfactory feto-maternal outcomes2. However, clinician should be aware that serious and rare complications, such as sub- galeal and intracranial haemorrhage, skull fractures and spinal cord injury, can occur particularly in the untrained hands as well as with repeated failed attempts3. Mastering the art of safe assisted delivery is an essential skill in the modern obstetrician’s armament.
|
16 |
+
|
17 |
+
Search strategy: External guidelines, systemic reviews and Cochrane revives were searched assessing available evidence and the best practices.
|
18 |
+
|
19 |
+
4.Summary of recommendations
|
20 |
+
|
21 |
+
Whenever possible, strive to provide continuous support during labour, one to one care and the choice of a labour companion. Available evidence suggests this can reduce instrumental delivery rate and promote normal vaginal delivery.
|
22 |
+
|
23 |
+
Epidural analgesia may increase the duration of active second stage and the need for instru- mental vaginal birth.\n\n2. Purpose and scope
|
24 |
+
|
25 |
+
The aim of this guideline is to provide evidence-based recommendations on the use of forceps and vacuum. This guidance is intended not only for practicing specialists, but also for trainee registrars, senior registrars who are expected to develop competency in the use of both vacuum and forceps for non-rotational birth and at least one technique for rotational birth. Recommendations made in this document may serve for all grades of medical staff involved in women’s health and labour management. The scope of this guideline includes indications, procedures, governance and follow up issues relating to assisted vaginal birth.
|
26 |
+
|
27 |
+
Encourage upright or lateral positions in second stage of labour (in women not on epidural analgesia). This reduces the need for instru- mentation.
|
28 |
+
|
29 |
+
Allow delayed pushing (passive second stage) in women with epidural analgesia. This may reduce the need for rotational and mid-pelvic assisted vaginal birth.
|
30 |
+
|
31 |
+
Do not routinely discontinue epidural analgesia during pushing as this increases the woman’s pain with no evidence of a reduction in the incidence instrumental delivery.
|
32 |
+
|
33 |
+
Sri Lanka Journal of Obstetrics and Gynaecology 2021; 43: 335-347
|
34 |
+
|
35 |
+
DOI: http://doi.org/10.4038/sljog.v43i4.8029
|
36 |
+
|
37 |
+
a Consultant Obstetrician and Gynaecologist, De Soysa Hospital for Women, Colombo, Sri Lanka
|
38 |
+
|
39 |
+
b Consultant Obstetrician and Gynaecologist, De Soysa Hospital for Women, Senior Lecturer, University of Colombo, Sri Lanka
|
40 |
+
|
41 |
+
This is an open-access article distributed under the terms of the Creative Commons Attribution 4.0 International License, which permits unrestricted use, distribution and reproduction in any medium provided the original author and source are credited.
|
42 |
+
|
43 |
+
Vol. 43, No. 4, December 2021
|
44 |
+
|
45 |
+
335
|
46 |
+
|
47 |
+
SLCOG Guideline
|
48 |
+
|
49 |
+
Operators should appreciate that no indication forinstrumental delivery is absolute, and that prudent clinical judgment is required in each situation.
|
50 |
+
|
51 |
+
Suspected fetal bleeding disorders and pre- disposition to fractures are relative contrain- dications for assisted vaginal birth.
|
52 |
+
|
53 |
+
Presence of blood borne viral infection in a woman is not an absolute contraindication for assisted vaginal birth.
|
54 |
+
|
55 |
+
Vacuum is not contraindicated following a fetal blood sampling or application of a fetal scalp electrode.
|
56 |
+
|
57 |
+
There is a higher risk of sub-galeal haemorrhage and scalp trauma with vacuum extraction compared to forceps at preterm gestation.
|
58 |
+
|
59 |
+
Vacuum is contraindicated below 32 weeks of gestation and should only be used with extreme caution between 32+0 and 36+0.
|
60 |
+
|
61 |
+
Safe assisted vaginal birth requires not only technical expertise, but also careful assessment of each clinical situation, clear communication with the woman and other healthcare personnel.
|
62 |
+
|
63 |
+
Ultrasound assessment of the fetal head position prior to assisted vaginal birth can be attempted where uncertainty exists following clinical examination.
|
64 |
+
|
65 |
+
Routine use of abdominal or perineal ultrasound for assessment of the station, flexion and descent of the fetal head in the second stage is not recom mended and is not a substitute for clinical examination.
|
66 |
+
|
67 |
+
For procedures in the labour room, verbal consent should be obtained and documented in the notes.
|
68 |
+
|
69 |
+
When mid-pelvic or rotational birth is indicated, the risks and benefits of assisted vaginal birth should be compared with the risks and benefits of second stage caesarean section, for the given circu-mstances and skills of the operator.
|
70 |
+
|
71 |
+
Prior written consent is recommended for a trial of assisted vaginal birth in the operating theatre.
|
72 |
+
|
73 |
+
Operators must achieve expertise in spon- taneous vaginal birth prior to commencing training on assisted vaginal birth.\n\n336
|
74 |
+
|
75 |
+
Non-rotational low-pelvic and lift out assisted vaginal births have a low probability of failure, hence most procedures can be attempted safely in the labour room.
|
76 |
+
|
77 |
+
Assisted vaginal births that have a higher risk of failure should be termed a trial of instru- mental delivery and is best attempted in an operation theater, where immediate CS can be resorted to.
|
78 |
+
|
79 |
+
The operator should choose the instrument most appropriate to the clinical circumstances and their level of skill.
|
80 |
+
|
81 |
+
Forceps and vacuum extraction are associated with different benefits and risks.
|
82 |
+
|
83 |
+
Failure to complete the birth with a single instru- ment is more likely with vacuum extraction, but maternal perineal trauma is more likely with forceps.
|
84 |
+
|
85 |
+
Soft cup vacuum extractors have a higher rate of failure but a lower incidence of neonatal scalp trauma.
|
86 |
+
|
87 |
+
Rotational births should be performed by experienced operators; the choice of instrument depending on the clinical circumstances and expertise of the individual.
|
88 |
+
|
89 |
+
The options include, Manual rotation followed by direct traction with forceps or vacuum, Rotational vacuum extraction or Kielland’s rotational forceps.
|
90 |
+
|
91 |
+
It is recommended to complete vacuum- assisted birth with not more than three pulls to bring the fetal head on to the perineum. (Additional gentle pulls may be used only to ease the head out of the perineum).
|
92 |
+
|
93 |
+
If there is minimal descent with the first pull of a vacuum, consider if the application is sub- optimal, the fetal position has been incorrectly diagnosed or if there is cephalopelvic dispro- portion.
|
94 |
+
|
95 |
+
Discontinue vacuum-assisted birth where there is no evidence of progressive descent with moderate traction during each pull of a correctly applied instrument.
|
96 |
+
|
97 |
+
Discontinue vacuum-assisted birth if there have been two ‘pop-offs’ of the instrument.
|
98 |
+
|
99 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
100 |
+
|
101 |
+
SLCOG Guideline
|
102 |
+
|
103 |
+
The use of sequential instruments is associated with an increased risk of trauma to the infant as well as obstetric anal sphincter injury (OASI). Operator needs to balance the risks of caesarean birth vs forceps following failed vacuum and may consider forceps extraction.
|
104 |
+
|
105 |
+
A single prophylactic dose of intravenous amoxicillin and clavulanic acid should be considered following assisted vaginal birth as it significantly reduces confirmed or suspected maternal infection compared to placebo.
|
106 |
+
|
107 |
+
Abandon forceps delivery when the forceps cannot be applied easily, the handles do not lock or if there is lack of progressive descent with moderate traction and birth is not imminent following three pulls with a correctly applied instrument by an experienced operator.
|
108 |
+
|
109 |
+
Discontinue rotational forceps birth if rotation is not easily achieved with gentle pressure.
|
110 |
+
|
111 |
+
If there is minimal descent with the first pull of theforceps, consider if the application is incorrect, the position has been incorrectly diagnosed or there is cephalopelvic dispro- portion.
|
112 |
+
|
113 |
+
Reassess women after assisted vaginal birth for venous thromboembolism risk and the need for thromboprophylaxis.
|
114 |
+
|
115 |
+
Highlight the risk of urinary retention and the importance of bladder emptying in the postpartum period. Timing and volume of the first void urine should be monitored and docu- mented.
|
116 |
+
|
117 |
+
A post void residual should be measured if urinary retention is suspected.
|
118 |
+
|
119 |
+
For women who had regional analgesia for a trial in theatre, recommend indwelling catheter in situ following birth, to prevent covert urinary retention.
|
120 |
+
|
121 |
+
There is increased risk of fetal head impaction at caesarean birth following a failed instrumental delivery and the operator should be prepared to disimpact the fetal head using recognized maneuvers.
|
122 |
+
|
123 |
+
Review women before hospital discharge with a confirmatory vaginal examination. Discuss the indication for assisted vaginal birth, management of any complications and advice for future births.\n\nMediolateral episiotomy should be discussed with the woman and tailored to the circum- stances.
|
124 |
+
|
125 |
+
When performing a mediolateral episiotomy, the cut should be at a 60-degree angle to the midline and initiated when the head is crowning the perineum.
|
126 |
+
|
127 |
+
Documentation for assisted vaginal birth should include information on the assessment, decision making and conduct of the procedure, a plan for post natal care and information for subse- quent pregnancies – standardized proforma is recommended.
|
128 |
+
|
129 |
+
5. Avoiding assisted vaginal birth
|
130 |
+
|
131 |
+
Evidence suggests, continuous one to one care and labour companionship can reduce the need for assisted vaginal birth4. Use of epidural analgesia may increase the need for instrumental delivery5. Adopting an upright or lateral position during second stage reduces the need for assisted vaginal delivery6. If on epidural it is not recommended to routinely discontinue during second stage, as this will not reduce need of assisted vaginal delivery but increases pain and distress to the woman7.
|
132 |
+
|
133 |
+
Vol. 43, No. 4, December 2021
|
134 |
+
|
135 |
+
337
|
136 |
+
|
137 |
+
SLCOG Guideline
|
138 |
+
|
139 |
+
6. Classification of instrumental delivery as outlet, low and mid cavity assisted birth in forceps delivery
|
140 |
+
|
141 |
+
Outlet Low Mid Fetal scalp visible without Fetal skull is at station Fetal head is no more than one- separating the labia +2cm, but not on the fifth palpable per abdomen Fetal skull has reached the perineum perineum Leading point of the skull is at Rotation does not exceed 45° Two subdivisions: station 0 or +1cm 1. Non-rotational ≤45° Two subdivisions: 2. Rotational >45° 1. Non-rotational ≤45° 2. Rotational >45°
|
142 |
+
|
143 |
+
7. The performing clinician should take a relevant concise history and carry out systematic examination to identify any contraindications:
|
144 |
+
|
145 |
+
• Check obstetric, general, and medical history.
|
146 |
+
|
147 |
+
7.2 Abdominal examination
|
148 |
+
|
149 |
+
• Estimated fetal weight.
|
150 |
+
|
151 |
+
• Assessment of engagement of the fetal head, descent, the number of fifths palpable abdo- minally. The head should be ≤1/5 palpable per abdomen.
|
152 |
+
|
153 |
+
• Birth weight of previous baby/babies and assessment of EFW in the index pregnancy.
|
154 |
+
|
155 |
+
• Assessment of progress in the first stage (noting secondary arrest).
|
156 |
+
|
157 |
+
• Identification of the position of the fetal back and sinciput, (This examination is not always possible, but an attempt should be made).
|
158 |
+
|
159 |
+
• Assessment of second stage of labour.
|
160 |
+
|
161 |
+
• Assessment of frequency and strength of uterine contractions and noting any contraindications for the use of oxytocin infusion.
|
162 |
+
|
163 |
+
• Examination for distension of the lower uterine segment or formation of a retraction ring (Bandl’s ring), indicating labour may have become obstructed.\n\n7.1 Assessment of feto-maternal status
|
164 |
+
|
165 |
+
7.3 Vaginal examination
|
166 |
+
|
167 |
+
• Evaluation of the physical and emotional state of the mother and her ability to participate actively in birth.
|
168 |
+
|
169 |
+
• To confirm full dilatation of the cervix and station of the presenting part (should be at or below spines).
|
170 |
+
|
171 |
+
• Give clear explanation and obtain informed consent and document on her hospital notes.
|
172 |
+
|
173 |
+
• Grade the degree of moulding as mild, moderate, or severe.
|
174 |
+
|
175 |
+
• Reduce maternal discomfort by administering appropriate analgesia (Consider local or regional).
|
176 |
+
|
177 |
+
• Confirm the bladder is empty. If on catheter, remove it or deflate the balloon.
|
178 |
+
|
179 |
+
• Note the position, extent of de-flexion and asynclitism of fetal head. (see below)
|
180 |
+
|
181 |
+
• Estimate the capacity of the pelvis relative to the size of the baby. Special note of pubic arch and sacrospinous ligaments.
|
182 |
+
|
183 |
+
• Note colour of amniotic fluid for the presence of meconium or blood.
|
184 |
+
|
185 |
+
• Assessment of fetal wellbeing.
|
186 |
+
|
187 |
+
• Always use aseptic techniques.
|
188 |
+
|
189 |
+
• Accurate account of the findings should be documented. (Lack of appreciation of the situation and delivery by wrong method in wrong place by inexperienced staff can cause increased fetal and maternal morbidity.)
|
190 |
+
|
191 |
+
338
|
192 |
+
|
193 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
194 |
+
|
195 |
+
7.4 Preparation of Staff
|
196 |
+
|
197 |
+
• The operator should have necessary knowledge, experience, and skill.
|
198 |
+
|
199 |
+
• Confirm the adequacy of facilities and availability of the theatre if a need arises.
|
200 |
+
|
201 |
+
• Backup plan in case of failure.
|
202 |
+
|
203 |
+
Inform senior staff.
|
204 |
+
|
205 |
+
• Consider complications like shoulder dystocia, perineal trauma, and post-partum haemorrhage.
|
206 |
+
|
207 |
+
• Presence of the Neonatal team.
|
208 |
+
|
209 |
+
7.5 Recognition of obstructed labour/CPD
|
210 |
+
|
211 |
+
CPD may be defined as the inability of the fetus to pass safely through the birth canal for mechanical reasons. These mechanical reasons include, relative sizes of maternal pelvis and fetal presenting part, which may vary, considerably in their three-dimensional sizes and shapes and in the degree to which the fetal head may undergo compression without injury to the brain.
|
212 |
+
|
213 |
+
CPD is either true disproportion, when even the smallest diameters of the presenting part are too big to pass through the pelvis, or relative disproportion caused by larger presenting diameters of the head that are commonly associated with transverse and posterior positions of the occiput, which results from de-flexion and asynclitism of the head.
|
214 |
+
|
215 |
+
The distinction between the two types of disproportion may be impossible to make but should be attempted because correction of the malposition in the case of relative disproportion, either by enhancing uterine contractions with oxytocin or by manipulating the fetal head with an instrument or manually, may allow safe vaginal delivery of the baby. Unfortunately, there is no reliable test that will diagnose CPD with certainty before the onset of labour. It may be suspected if there is a history of previous difficult labours or from the findings on clinical examination or when delay occurs in the late active phase of the first stage of labour or pelvic (Decent) phase of the second stage.\n\nSigns of obstructed labour
|
216 |
+
|
217 |
+
1. Significant caput and moulding.
|
218 |
+
|
219 |
+
2. Tenderness and ‘ballooning��� of lower uterine segment.
|
220 |
+
|
221 |
+
3. Formation of uterine retraction ring.
|
222 |
+
|
223 |
+
4. Presence of oedema of cervix and/or vulva.
|
224 |
+
|
225 |
+
Vol. 43, No. 4, December 2021
|
226 |
+
|
227 |
+
SLCOG Guideline
|
228 |
+
|
229 |
+
5. Blood-stained urine.
|
230 |
+
|
231 |
+
6. Bleeding from the vagina.
|
232 |
+
|
233 |
+
Note: Severe or increasing moulding of the head that fails to rotate descend despite of strong uterine contractions is also a clinical finding suggestive of CPD/obstructed Labour.
|
234 |
+
|
235 |
+
• If a diagnosis of obstructed labour is made, delivery should be undertaken immediately by caesarean section.
|
236 |
+
|
237 |
+
7.6 Estimation of the level of fetal head – Per Abdomen (P/A) and Vaginally (V/E) (This helps in assessment of progress at subsequent examination and on decision regarding mode of delivery)
|
238 |
+
|
239 |
+
1. P/A- 5/5 the fetal head is completely palpable above upper border of symphysis pubis.
|
240 |
+
|
241 |
+
V/E-3 cm. digital examination at this stage is hardly possible.
|
242 |
+
|
243 |
+
2. P/A- 4/5 the lower portion of the head is just below the upper border of the symphysis pubis.
|
244 |
+
|
245 |
+
V/E -2cm station (difficult examination of head).
|
246 |
+
|
247 |
+
3. P/A -3/5 Occipitofrontal diameter of the head may be palpable just above the upper border of the symphysis pubis.
|
248 |
+
|
249 |
+
V/E -1cm station.
|
250 |
+
|
251 |
+
4. P/A- 2/5 the head is engaged. On one side, usually the side of sinciput, the head may be easily palpable while on the other, the side of the occiput; it may not be so easily palpable.
|
252 |
+
|
253 |
+
V/E -0 cm station.
|
254 |
+
|
255 |
+
5. P/A -1/5 the fetal head is engaged; the head, usually the sinciput, may be just palpated with the fingers on one side only.
|
256 |
+
|
257 |
+
V/E +1cm station.
|
258 |
+
|
259 |
+
6. P/A 0/5 the head is deeply engaged; neither the occiput nor the sinciput are palpable abdominally. V/E +2cm.
|
260 |
+
|
261 |
+
• If the station is at the level of ischial spines or higher vaginally, instrumental delivery is contra-indicated4,5.
|
262 |
+
|
263 |
+
If it is necessary to deliver the baby at this stage, either due to maternal or fetal distress, it should be by a caesarean section.
|
264 |
+
|
265 |
+
339
|
266 |
+
|
267 |
+
SLCOG Guideline
|
268 |
+
|
269 |
+
7.7 Use of oxytocin for slow progress in second stage
|
270 |
+
|
271 |
+
Use of oxytocin (especially in a nulliparous women) may be better than premature instrumental delivery with a high fetal head station for the treatment of delay in the second stage of labour6,7,8,9.
|
272 |
+
|
273 |
+
• In a nulliparous woman with inefficient uterine contractions, and with absence of signs of fetal distress, contractions can be stimulated with oxytocin to achieve 4-5 contractions per 10 minutes.
|
274 |
+
|
275 |
+
• However, in a multiparous woman, inefficient uterine action is less common and caution is required before introducing oxytocin to increase uterine contraction due to risk of hypertonic contractions and uterine rupture. Careful assessment should be made by an experienced clinician/consultant, to exclude disproportion before administering oxytocin for delay in the first or second stages of labour.
|
276 |
+
|
277 |
+
• Oxytocin should not be routinely used in women with previous caesarean delivery. Need should be discussed with on-call consultant/Senior clinician before aug- mentation.
|
278 |
+
|
279 |
+
{Rate of uterine rupture doubles with use of Syn- tocinon after previous C/S, compared to non-use of Syntocinon9,10,11. Earliest signs of uterine dehiscence/ rupture can be fetal distress, abdominal pain (in the region of scar), vaginal bleeding and blood-stained urine. If the pain ‘breaks through’ despite epidural analgesia, scar dehiscence should be considered.}\n\n8. Choice of instrument
|
280 |
+
|
281 |
+
The choice, judgement and the skill of the operator dictates the outcome rather than the instrument itself. Following factors needs to be considered in decision- making:
|
282 |
+
|
283 |
+
Experience of operator.
|
284 |
+
|
285 |
+
Station and position of head.
|
286 |
+
|
287 |
+
Size of the baby.
|
288 |
+
|
289 |
+
• Degree of caput/moulding.
|
290 |
+
|
291 |
+
• Maternal exhaustion – physical/mental.
|
292 |
+
|
293 |
+
340
|
294 |
+
|
295 |
+
Ventouse is more likely to fail in the presence of excessive caput. The vacuum extraction causes less maternal trauma but may increase the risk of cephal- hematoma, retinal haemorrhage and certain types of intra-cranial haemorrhage in the fetus compared to forceps delivery12. Maternal perineal trauma is more likely with forceps but ability to complete delivery with single instrument is more likely with forceps.
|
296 |
+
|
297 |
+
Regional analgesia is advisable for difficult forceps delivery when done in theater, and a pudendal block when conducted in the labour room. Ventouse extrac- tion can be performed without regional analgesia. Perineal infiltration for episiotomy would suffice. However, operator should confirm adequacy of analgesia with the woman prior to application of the instruments.
|
298 |
+
|
299 |
+
• Application of rotational forceps needs training and experience. If not adequately trained/experienced on the technique, manual rotation followed by non- rotational forceps/ vacuum or rotational vacuum delivery or LSCS would be prudent.
|
300 |
+
|
301 |
+
9. Trial of instrumental delivery
|
302 |
+
|
303 |
+
Adequate assessment of the case will generally resolve any doubts prior to attempting an instrumental delivery. Operator should first ensure adequate analgesia for examination has been provided. If the operator is uncertain about the position of the fetal head, degree of engagement, instrument delivery should not be undertaken.
|
304 |
+
|
305 |
+
When the operator is uncertain about the likelihood of success or expect a difficult delivery a formal trial of ventouse/forceps in the operating theater should be attempted where immediate resorting into caesarean section can be done. Failure in the labour room without preparation for immediate C/S), has shown to increase fetal morbidity and mortality13,14.
|
306 |
+
|
307 |
+
Vacuum and forceps birth has been associated with higher incidence of episiotomy, pelvic floor tearing, levator ani avulsion and obstetric anal sphincter injury compared to spontaneous vaginal birth. Meticulous examination for perineal or obstetric anal sphincter injuries (OASIS) should be undertaken. Care should be taken on the management decision and expert opinion should be sought when in doubt.
|
308 |
+
|
309 |
+
Sri Lanka Journal of Obstetrics and Gynaecology\n\n9.1 Probable indications for a trial in theatre
|
310 |
+
|
311 |
+
• Head palpable abdominally 1/5 i.e., station +1 (mid cavity instrumental delivery). (If the station of the head is higher than this, instrumental delivery is contra-indicated. Beware of the caput at the spines, whilst the actual head is much higher.)
|
312 |
+
|
313 |
+
• Severe caput/moulding
|
314 |
+
|
315 |
+
• Non occipito-anterior (OA) positions such as OP and OT positions.
|
316 |
+
|
317 |
+
• Deflexed/Asynclitic head.
|
318 |
+
|
319 |
+
• Protracted 1st stage of labour, prolonged 7-10cm interval.
|
320 |
+
|
321 |
+
• Fetal macrosomia/borderline CPD. (HC ≥95th centile / EFW ≥4kg/ BMI above 30.)
|
322 |
+
|
323 |
+
• Any condition, which may lead to failure of instrumental delivery.
|
324 |
+
|
325 |
+
10. Vacuum extraction / ventouse delivery
|
326 |
+
|
327 |
+
Rigid/soft silicon cups can be used for OA positions and posterior cups should be used for non-OA positions. Hand-held vacuum cup (kiwi omni cup) can be used for both OA and non-OA positions.
|
328 |
+
|
329 |
+
10.1 Indications for ventouse delivery
|
330 |
+
|
331 |
+
• Delayed second stage
|
332 |
+
|
333 |
+
•
|
334 |
+
|
335 |
+
Fetal distress in the second stage with fetal head below ‘0’ station (see above)
|
336 |
+
|
337 |
+
• Maternal conditions requiring a short second stage (severe PET, cardiac disease)
|
338 |
+
|
339 |
+
• Delivery of the 2nd twin (only if cephalic).
|
340 |
+
|
341 |
+
10.2 Contraindications for ventouse delivery
|
342 |
+
|
343 |
+
Face/brow/breech presentation
|
344 |
+
|
345 |
+
• Marked active bleeding from fetal blood sampling site or maternal immune thrombo- cytopenia in pregnancy.
|
346 |
+
|
347 |
+
• Vacuum is contraindicated below 32 weeks of gestation and should be used with extreme caution between 32+0 and 36+0 and should be discussed with consultant on-call).
|
348 |
+
|
349 |
+
Fetal head per abdomen >1/5 palpable.
|
350 |
+
|
351 |
+
• Apparent CPD.
|
352 |
+
|
353 |
+
•
|
354 |
+
|
355 |
+
Inexperience with the use of the equipment.
|
356 |
+
|
357 |
+
Vol. 43, No. 4, December 2021
|
358 |
+
|
359 |
+
SLCOG Guideline
|
360 |
+
|
361 |
+
10.3 Prerequisites of ventouse delivery
|
362 |
+
|
363 |
+
• Full dilatation of cervix and ruptured membranes.
|
364 |
+
|
365 |
+
• Careful pelvic examination to assess adequacy of pelvis, with special attention to architecture of pelvis to assess sacral hollow, ischial spines and sub-pubic arch.
|
366 |
+
|
367 |
+
• Fully engaged head and any de-flexion of head identified.
|
368 |
+
|
369 |
+
• Full explanation of the procedure and verbal consent of the woman, and need for her co- operation emphasized.
|
370 |
+
|
371 |
+
• Good regular contractions should be present. (If they are less frequent, then Oxytocin infusion should be set-up and caution needed in multiparous women and women with previous section).\n\n10.4 Basic rules
|
372 |
+
|
373 |
+
• The delivery should be completed in no longer than 15 minutes following application of the cup. (Fifteen minutes is given as the maximum time allowed, but the average time from insertion of the cup to delivery is normally six minutes15,16).
|
374 |
+
|
375 |
+
• The head should be delivered with no more than 3 synchronized pulls with maternal expulsive force.
|
376 |
+
|
377 |
+
• The procedure is abandoned if there is no descent after 2 pulls (actual head should descend and not just the caput).
|
378 |
+
|
379 |
+
• The cup should be reapplied no more than twice (discontinue after two pop-offs).
|
380 |
+
|
381 |
+
• The cup must be applied on flexion point. (Bird et.al demonstrated provided the cup is applied correctly over the flexion point and traction directed along the pelvic axis, autorotation of fetal head would occur in >90% of the fetal OP and OT positions17.
|
382 |
+
|
383 |
+
• Anterior placement of the cup (in relation to flexion point) will aggravate de-flexion, and off-center placement of the cup will cause asynclitism. Both the situations will increase failure rate due to larger diameter of engage- ment and increase the chance of fetal injury.
|
384 |
+
|
385 |
+
• After checking the correct application and ensuring that no maternal tissue is included in
|
386 |
+
|
387 |
+
341
|
388 |
+
|
389 |
+
SLCOG Guideline
|
390 |
+
|
391 |
+
the cup, pressure is raised to 0.8kg/cm2 almost straightaway. There is no advantage in stepwise increase in pressure.
|
392 |
+
|
393 |
+
•
|
394 |
+
|
395 |
+
Traction on the apparatus should coincide with uterine contractions and maternal voluntary effort. To avoid the cup detach- ment, ‘finger thumb’ position of the other hand is used.
|
396 |
+
|
397 |
+
• The use of sequential instruments is associated with an increased risk of trauma to the infant. However, the operator should assess the risk of performing a second stage caesarean section with a deeply impacted fetal head versus a forceps delivery following a failed vacuum.
|
398 |
+
|
399 |
+
• Beware of shoulder dystocia, after the ven- touse delivery. The association is co-incidental rather than causal.
|
400 |
+
|
401 |
+
10.5 Place of episiotomy for ventouse delivery
|
402 |
+
|
403 |
+
Episiotomy should be discussed with the woman prior to any instrumental delivery and formal consent obtained and documented. Episiotomy is not routinely required for ventouse delivery. Clinical judgement is advised.
|
404 |
+
|
405 |
+
Episiotomy may be necessary in case of:
|
406 |
+
|
407 |
+
• Rigid perineum.
|
408 |
+
|
409 |
+
• Big baby.
|
410 |
+
|
411 |
+
Fetal distress to hasten the delivery.
|
412 |
+
|
413 |
+
If the perineum seems to be splitting an episiotomy is often performed to limit the damage18. Episiotomy should be done under anesthesia. (Local block if regional anesthesia is not insitu). Episiotomy is always given medio-lateral (median, increases chance of 3rd / 4th degree tear. Premature episiotomy should be avoided and should be given at the time of crowning. (In case the instrument fails to deliver the baby and C/S is required).\n\n11. Forceps delivery
|
414 |
+
|
415 |
+
11.1 Indications
|
416 |
+
|
417 |
+
• Delay in the 2nd stage of labour.
|
418 |
+
|
419 |
+
Fetal distress in the second stage.
|
420 |
+
|
421 |
+
• After coming head of breech delivery.
|
422 |
+
|
423 |
+
342
|
424 |
+
|
425 |
+
• Maternal conditions requiring short second stage.
|
426 |
+
|
427 |
+
• Delivery of the head at cesarean section.
|
428 |
+
|
429 |
+
11.2 Choice of forceps over ventouse
|
430 |
+
|
431 |
+
• After coming head in breech vaginal delivery.
|
432 |
+
|
433 |
+
Face presentation (Mento-anterior).
|
434 |
+
|
435 |
+
Pre-term infants <36 weeks.
|
436 |
+
|
437 |
+
• Women under anesthesia and unable to generate substantial expulsion.
|
438 |
+
|
439 |
+
• A heavily bleeding scalp sample site.
|
440 |
+
|
441 |
+
• Significant caput in OA positions, when ventouse cup is likely to come off.
|
442 |
+
|
443 |
+
11.3 Pre-requisites for forceps delivery
|
444 |
+
|
445 |
+
• Appropriately experienced operator.
|
446 |
+
|
447 |
+
• Rupture of membranes.
|
448 |
+
|
449 |
+
Fully dilated cervix.
|
450 |
+
|
451 |
+
• Clear knowledge of the position of the fetal head (use of USS will be helpful if uncertain findings).
|
452 |
+
|
453 |
+
• Clinically adequate pelvis.
|
454 |
+
|
455 |
+
• Fetal head engaged at station +1 or lower (1/5 or less palpable abdominally).
|
456 |
+
|
457 |
+
• Adequate analgesia (regional/pudendal block).
|
458 |
+
|
459 |
+
• Empty bladder.
|
460 |
+
|
461 |
+
• An adequately informed and consented (verbal) patient.
|
462 |
+
|
463 |
+
• Availability of pediatric support.
|
464 |
+
|
465 |
+
(The careful abdominal/pelvic examination for the fetal head station, position and fetal size is carried out as in ventouse protocol.)
|
466 |
+
|
467 |
+
• If episiotomy is given it should be meticulously sutured. Vaginal and rectal examination is mandatory after instrumental delivery.
|
468 |
+
|
469 |
+
• The woman and her partner if available are debriefed regarding the procedure.
|
470 |
+
|
471 |
+
• Accurate, legible documentation of the procedure should made. Postoperative care plan including prescription of antibiotics, analgesia and thromboprophylaxis should be carried out when needed.
|
472 |
+
|
473 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
474 |
+
|
475 |
+
11.4 Management of a failed attempted forceps delivery
|
476 |
+
|
477 |
+
• If the forceps cannot be applied easily, or if the blades does not lock, or if there is lack of decent with moderate traction and maternal pushing, it is prudent to abandon the forceps delivery and resort to an emergency caesarean section.
|
478 |
+
|
479 |
+
• When attempting rotational forceps, the rotation should be achieved with ease and if not should discontinue the procedure.
|
480 |
+
|
481 |
+
• The procedure should be abandoned and resorted to an emergency caesarean section if the birth is not imminent even after 3 pulls of a correctly applied instrument and a correct direction in traction.
|
482 |
+
|
483 |
+
• If resorted to an emergency caesarean section due to failed forceps, the obstetrician should be aware that there is an increased risk of head impaction and be ready to dis-impact the head with known maneuvers.
|
484 |
+
|
485 |
+
• The neonatology team should be informed clearly about the failed forceps as there is increased risk of neonatal morbidity following caesarean section for failed forceps.\n\n12. Prophylactic antibiotics
|
486 |
+
|
487 |
+
• Following instrumental vaginal birth, it is recommended to give a single prophylactic dose of intravenous antibiotics to prevent maternal infection.
|
488 |
+
|
489 |
+
• Amoxicillin and clavulanic acid single dose can be used for this purpose after confirming allergy status.
|
490 |
+
|
491 |
+
13. Postnatal care following instrumental delivery
|
492 |
+
|
493 |
+
• Postnatal care following instrumental vaginal delivery requires the need to assess the requirement of thromboprophylaxis to prevent thromboembolism, adequate pain relief, voiding function, pelvic floor rehabilitation and debriefing about the events in current birth and about future births.
|
494 |
+
|
495 |
+
• For pain relief NSAIDs and paracetamol administered is adequate.
|
496 |
+
|
497 |
+
Vol. 43, No. 4, December 2021
|
498 |
+
|
499 |
+
SLCOG Guideline
|
500 |
+
|
501 |
+
• Routine bladder emptying should be encouraged after instrumental vaginal birth to prevent urinary retention. It is prudent to document the timing and the volume of the first void urine following an instrumental delivery.
|
502 |
+
|
503 |
+
14. Postnatal psychological morbidity
|
504 |
+
|
505 |
+
• Difficult childbirth can leave a traumatic experience in women and ultimately result in fear of future childbirth. It will also impact quality of life with her partner and family, ultimately leading to psychological morbidity.
|
506 |
+
|
507 |
+
• Shared decision making with the woman, good communication, and continuous support during and immediately after the childbirth have the potential to reduce the psychological morbidity following instrumental childbirth.
|
508 |
+
|
509 |
+
• It is best practice to discuss the indications for the instrumental delivery, how the complications were managed and to advise regarding future births. This should ideally be done by the obstetrician who attended the procedure.
|
510 |
+
|
511 |
+
• It should be informed that there is a high possibility of a successful spontaneous vaginal birth in the future pregnancies.
|
512 |
+
|
513 |
+
15. Clinical governance
|
514 |
+
|
515 |
+
15.1 Proper documentation
|
516 |
+
|
517 |
+
a. Documentation should include detailed information on the assessment, decision making and conduct of the procedure, a plan for postnatal care and counselling for future pregnancies.
|
518 |
+
|
519 |
+
b. Use of a standard proforma for this purpose is recommended and is best to be audited at regular intervals.
|
520 |
+
|
521 |
+
c. Training the staff with using mannequins and accreditation of the trainees.\n\n15.2 Obtaining cord blood
|
522 |
+
|
523 |
+
d. If facilities are available, cord blood be obtained in instrumental delivery, and this should include arterial as well as venous blood sampling. The
|
524 |
+
|
525 |
+
343
|
526 |
+
|
527 |
+
SLCOG Guideline
|
528 |
+
|
529 |
+
PH and base deficit can be documented in the patient operative notes.
|
530 |
+
|
531 |
+
e. Institutes may strive to provide obstetric care units with required facilities to perform cord blood gases.
|
532 |
+
|
533 |
+
15.3 Risk management
|
534 |
+
|
535 |
+
Adverse outcomes, including failed instrumental deliveries, major obstetric haemorrhage, fetal injuries, and morbidity, OASI, shoulder dystocia and associated complications should trigger risk management meeting with unit consultant. Adequate steps can be taken to reduce these events in the future and to properly manage such complications. Frequent audits should be undertaken on these complication rates and trends.
|
536 |
+
|
537 |
+
References
|
538 |
+
|
539 |
+
1. NHS Maternity Statistics, England 2016-17 [https://digital.nhs.uk/data-information/ publications/statistical/nhs-maternity-statistics/ 2016-17].
|
540 |
+
|
541 |
+
2. Demissie K, Rhoads GG, Smulian JC, Balasubra- manian BA, Gandhi K, Joseph KS, et al. Operative vaginal delivery and neonatal and infant adverse outcomes: population based retrospective analysis. BMJ 2004; 329: 24-9.
|
542 |
+
|
543 |
+
3. Towner D, Castro MA, Eby-Wilkens E, Gilbert WM. Effect of mode of delivery in nulliparaous women on neonatal intracranial injury. N Engl J Med 1999; 341: 1709-14.
|
544 |
+
|
545 |
+
4. NHS Maternity Statistics, England 2016-17 [https:/ /digital.nhs.uk/ data-and information /publications/ statistical/nhs-maternity-statistics/ 2016-17]. last accessed 04 February 2021.
|
546 |
+
|
547 |
+
5. Philpott RH. The recognition of cephalopelvic disproportion. Clinics in Obstet Gynaecol 1982; 9: 609-24.
|
548 |
+
|
549 |
+
6. Murphy DJ, et al. Cohort study of operative delivery in the second stage of labour and standard of obstetric care. BJOG 2003; 110: 610-15.
|
550 |
+
|
551 |
+
7. Kean LH, Baker PN, Edelstone DI. Best Practice
|
552 |
+
|
553 |
+
344
|
554 |
+
|
555 |
+
in Labor Ward management, Scotland: Elsevier Science Limited, 2002.
|
556 |
+
|
557 |
+
8. O’Connel MO, Hussain J, Maeclennan FA, Lindow SW. Factors associated with prolonged second stage of labour – a case-controlled study of 364 nulliparous labours. J Obstet Gynaecol 2003; 23: 255-7.
|
558 |
+
|
559 |
+
9. Paterson CM, Saunders NG, Wadsworth J. The characteristics of the second stage of labour in 25,069 singleton deliveries in the North West Thames Health Region 1988. BJOG 1992; 99: 377-80.
|
560 |
+
|
561 |
+
10. Arulkumaran S, Ingemarsson I, Ratnam SS. Oxy- tocin augmentation in dysfunctional labour after previous caesarean section. BJOG 1989; 96: 939-41.
|
562 |
+
|
563 |
+
11. Chelmow D, Laros RK. Maternal and Neonatal Outcomes After Oxytocin Augmentation in Patients Undergoing a Trial of Labour After Prior Cesarean Delivery. Obstet Gynecol 1992; 80: 966-71.
|
564 |
+
|
565 |
+
12. Weerasekera DS, Premartane S. A randomised prospective trial of the obstetric forceps versus vacuum extraction using defined criteria. J Obstet Gynaecol 2002; 22: 344-5.
|
566 |
+
|
567 |
+
13. Miksovsky P, et al. CME Review Article: Obstetric vacuum extraction: state of the art in the new millennium. Obstet Gynecol Survey 2001; 56: 736- 51.
|
568 |
+
|
569 |
+
14. Lowe B. Fear of failure: a place for trial of instrumental delivery. BJOG 1987; 94: 60-6.
|
570 |
+
|
571 |
+
15. Johanson R, Cox C, Grady K, Howell C. Managing obstetric emergencies and trauma, The MOET Course Manual. RCOG Press 2003.
|
572 |
+
|
573 |
+
16. Johanson RB, et al. North Staffordshire/Wigan assisted delivery trial. BJOG 1989; 96: 537-44.
|
574 |
+
|
575 |
+
17. Bird GC. The importance of flexion in vacuum extraction delivery. BJOG 1976; 83: 194-200.
|
576 |
+
|
577 |
+
18. De Jonge ETM, Lindeque BG. A properly conducted trial of a ventouse can prevent unexpected failure of instrumental delivery. SAMJ 1991; 70: 545-6.
|
578 |
+
|
579 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
580 |
+
|
581 |
+
SLCOG Guideline
|
582 |
+
|
583 |
+
SLCOG Guideline\n\nAnnexure 1
|
584 |
+
|
585 |
+
——yyYYt COM OPERATION NOTES: FORCEPS /VENTOUSE DELIVERY 4, NAMC® secs: emeeeernene E RE 2eBHT! scm Date? wescsseememeseeesceememrrecsenies Time Of Delivery: sesecvsssseseeesseereecrseey Operator: 2.2.2... 02.0. cee cece eeeeeeeeeeeeeeeeeee es Anaesthetist: ...............0:..0eceeeeeeeee ee Type: Forceps: Ventouse: Neville Barnes /Simpson's Kiwi Cup Wrigleys Soft Cup Keillands Hard Cup Indications: 1. Anaesthesia: GA / Spinal / Epidural / Pudendal / Local Infiltration Head Position: OA / OT / OP / Other Head Station: O / +1 / +2 / +3 Moulding: no / + / 2+ [| 3+ Caput:: no f/ * | 2 | BF Meconium: no / yes Application method: Direct / Wandering Rotation: no / easy / mod /diff Traction: easy / mod / diff Number of Pulls Delivery Comments:
|
586 |
+
|
587 |
+
Vol 43, No. 4, December 2021
|
588 |
+
|
589 |
+
345
|
590 |
+
|
591 |
+
SLCOG Guideline
|
592 |
+
|
593 |
+
SLCOG Guideline
|
594 |
+
|
595 |
+
Annexure 1 (Continued)
|
596 |
+
|
597 |
+
346
|
598 |
+
|
599 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
600 |
+
|
601 |
+
SLCOG Guideline
|
602 |
+
|
603 |
+
SLCOG Guideline
|
604 |
+
|
605 |
+
Annexure 2
|
606 |
+
|
607 |
+
POSTPARTUM BLADDER CARE FOLLOWING INSTRUMENTAL DELIVERY
|
608 |
+
|
609 |
+
Vol 43, No. 4, December 2021
|
610 |
+
|
611 |
+
347
|
src/processed_markdown/Breech/Breech.md
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---\n\ncitation: "Breech"\n\n---\n\nManagement of Breech Presentation
|
2 |
+
|
3 |
+
Clinical
|
4 |
+
|
5 |
+
Clinical
|
6 |
+
|
7 |
+
• Abdominal examination: the head of the fetus is in the upper part of the uterus.
|
8 |
+
|
9 |
+
X-ray of the
|
10 |
+
|
11 |
+
pelvis to
|
12 |
+
|
13 |
+
confirm
|
14 |
+
|
15 |
+
presentation is
|
16 |
+
|
17 |
+
to be avoided.
|
18 |
+
|
19 |
+
Ultra sound
|
20 |
+
|
21 |
+
• Auscultation locates the fetal heart at a higher location than expected with a vertex presentation.
|
22 |
+
|
23 |
+
• conform the presenting part
|
24 |
+
|
25 |
+
•
|
26 |
+
|
27 |
+
localizatiion of placenta
|
28 |
+
|
29 |
+
• Vaginal examination: the buttocks and/or feet are felt. Thick, dark meconium is normal when membranes rupture in the second stage of labour.
|
30 |
+
|
31 |
+
• exclusion of
|
32 |
+
|
33 |
+
abnormalities,etc.
|
34 |
+
|
35 |
+
THE DIAGNOSIS OF BREECH CONFIRMED
|
36 |
+
|
37 |
+
— External cephalic version not acormamenaladt Wait till 36 completed wi —
|
38 |
+
|
39 |
+
: prior to 36 completed
|
40 |
+
|
41 |
+
36 weeks
|
42 |
+
|
43 |
+
uncomplicated breech at 37 to 40 weeks
|
44 |
+
|
45 |
+
uncomplicated (no extended or |] complicated (extended or flexed leg) breech presentation flexed leg) breech presentation at term at term
|
46 |
+
|
47 |
+
38 weeks
|
48 |
+
|
49 |
+
Delivery
|
50 |
+
|
51 |
+
No indication
|
52 |
+
|
53 |
+
for L.S.C.S
|
54 |
+
|
55 |
+
Relative indications for Absolute indications for Caesarean section Caesarean section Intrauterine growth restriction. Feto-pelvic disproportion Previous uterine scar -When the fetal weight is estimated to Hyperextension of the fetal head be 3.8 kg or more (Star gazer) Major degree placenta praevia -When the head cannot be flexed Pelvic or uterine tumors preventing Small pelvis or suspicious pelvic descent of presenting part. adequacy Major degrees of pelvic deformities. Footling presentation Gestation less than 34 weeks
|
56 |
+
|
57 |
+
Vaginal delivery
|
58 |
+
|
59 |
+
Sri Lanka College of Obstetrics and Gynaecology Health sector development Project Guidelines- Management of breech presentation
|
60 |
+
|
61 |
+
4 Ei = 3 "
|
62 |
+
|
63 |
+
=
|
64 |
+
|
65 |
+
=| -}
|
66 |
+
|
67 |
+
= 9 =o oo eo a =i m 5 >
|
68 |
+
|
69 |
+
on a
|
70 |
+
|
71 |
+
=| = S
|
72 |
+
|
73 |
+
5
|
74 |
+
|
75 |
+
a $ 4
|
src/processed_markdown/Intrapartum-fever-Dec-4/Intrapartum-fever-Dec-4.md
ADDED
@@ -0,0 +1,575 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---\n\ncitation: "Intrapartum fever Dec 4"\n\n---\n\nSLCOG Guideline
|
2 |
+
|
3 |
+
SLCOG Guideline
|
4 |
+
|
5 |
+
Intrapartum Fever
|
6 |
+
|
7 |
+
J Karunasinghea on behalf of the Sri Lanka College of Obstetricians and Gynaecologists
|
8 |
+
|
9 |
+
Correspondence: Sri Lanka College of Obstetricians and Gynaecologists, No. 112, Model Farm Road, Colombo 08. E-mail: [email protected]
|
10 |
+
|
11 |
+
1. Scope and background
|
12 |
+
|
13 |
+
a. Infectious causes
|
14 |
+
|
15 |
+
This guideline is focused on the aetiologies, manage- ment, and potential consequences of intrapartum fever. Management of some of the specific causes of intrapartum fever will be briefly discussed. Note that the scope of this guideline is restricted only to intra- partum care.
|
16 |
+
|
17 |
+
b. Non-infectious causes
|
18 |
+
|
19 |
+
a. Most common infection related aetiologies are
|
20 |
+
|
21 |
+
Intraamniotic infection (IAI)
|
22 |
+
|
23 |
+
• Urinary tract infection
|
24 |
+
|
25 |
+
• Respiratory tract infection including H1N1 influenza
|
26 |
+
|
27 |
+
The guideline will not provide information about management of septicaemia and Group B streptococcal (GBS) infection in pregnancy (refer relevant guidelines). For detailed management of Dengue fever and COVID-19, please refer to the National Guidelines.
|
28 |
+
|
29 |
+
• Any other pre-existing infection which could present as fever during labour
|
30 |
+
|
31 |
+
• Dengue fever and COVID-19 infection which should be given special consideration during pandemics
|
32 |
+
|
33 |
+
2. Summary of key recommendations
|
34 |
+
|
35 |
+
b. Non-infectious causes
|
36 |
+
|
37 |
+
2.1 Definition
|
38 |
+
|
39 |
+
Intrapartum fever is defined as the elevation of maternal oral temperature ≥39°C (≥102.2°F) on one reading or temperature between 38°C (>100.4°F) to 39°C (102.2°F) on two readings 30 minutes apart in a woman in labour1.
|
40 |
+
|
41 |
+
• Use of neuraxial anaesthesia is the most common cause of non-infectious cause of fever at term.
|
42 |
+
|
43 |
+
• Increased metabolism (eg: thyrotoxicosis), poor ventilation, delivering in an overheated room and drug fever are considered as some other causes for intrapartum fever.
|
44 |
+
|
45 |
+
Healthcare worker should measure oral temperature of all women in labour 4 hourly or whenever they show signs and symptoms of febrile illness. Temperature should be recorded in the partogram routinely. Whenever high temperature is detected, it should be recorded in a separate temperature chart.
|
46 |
+
|
47 |
+
Patients with following factors are considered high risk for intrapartum fever –
|
48 |
+
|
49 |
+
• Nulliparity
|
50 |
+
|
51 |
+
• Labour induction
|
52 |
+
|
53 |
+
• Prolonged labour
|
54 |
+
|
55 |
+
• Premature labour\n\n2.2 Aetiology
|
56 |
+
|
57 |
+
• Prolonged membrane rupture
|
58 |
+
|
59 |
+
Intraamniotic infection (IAI) and neuraxial anaesthesia are the most common causes for intrapartum fever2. Aetiology of the intrapartum fever is classified into two categories.
|
60 |
+
|
61 |
+
• Multiple digital vaginal examinations
|
62 |
+
|
63 |
+
• Exposure to intrauterine devices: – Intrau- terine pressure devices/ Foetal scalp electrodes
|
64 |
+
|
65 |
+
Sri Lanka Journal of Obstetrics and Gynaecology 2021; 43: 371-382
|
66 |
+
|
67 |
+
DOI: http://doi.org/10.4038/sljog.v43i4.8032
|
68 |
+
|
69 |
+
a Consultant Obstetrician and Gynaecologist, Castle Street Hospital for Women, Colombo, Sri Lanka
|
70 |
+
|
71 |
+
=
|
72 |
+
|
73 |
+
This is an open-access article distributed under the terms of the Creative Commons Attribution 4.0 International License, which
|
74 |
+
|
75 |
+
permits unrestricted use, distribution and reproduction in any medium provided the original author and source are credited.
|
76 |
+
|
77 |
+
Vol. 43, No. 4, December 2021
|
78 |
+
|
79 |
+
371
|
80 |
+
|
81 |
+
SLCOG Guideline
|
82 |
+
|
83 |
+
3. Diagnosis and investigations
|
84 |
+
|
85 |
+
Careful history and systemic examination are required. Special consideration should be given for abdominal tenderness, vaginal examination including characteristic of amniotic fluid and odour.
|
86 |
+
|
87 |
+
Investigations
|
88 |
+
|
89 |
+
Investigations are based on suspected aetiology. However, there are no specific investigations for intrapartum fever. Usually full blood count (FBC), blood culture, urine full report (UFR) and urine culture are performed according to the suspected aetiology. High vaginal swab culture is usually done when there is evidence of premature rupture of membranes (PROM). In endemic situations, rapid antigen for Dengue fever, H1N1 influenza and COVID-19 are vital for immediate management.
|
90 |
+
|
91 |
+
Biological markers – Many systemic reviews done in intra-partum fever concluded that, measurement of C-Reactive Protein (CRP) is unreliable for detecting intrauterine infection3.
|
92 |
+
|
93 |
+
4. Management
|
94 |
+
|
95 |
+
• Senior obstetrician’s opinion should be obtained in the management of all patients with intrapartum fever. It may be beneficial to have a multidisciplinary team approach involving the Obstetrician, Microbiologist, Physician and the Anaesthetist.
|
96 |
+
|
97 |
+
• Neonatology team should be notified and involved for every case of intrapartum fever. The presence of a senior medical officer from the neonatology team at the time of delivery is the minimum requirement.
|
98 |
+
|
99 |
+
• Antibiotics – Usually broad-spectrum antibiotics with coverage of GBS (Group B streptococcus) is initiated in all patients except those with pre- existing infection. Different antibiotic regimens are used according to the hospital/unit policy (See Table 1).
|
100 |
+
|
101 |
+
• All patients with intrapartum fever should have their pulse rate, blood pressure and respiratory rate checked every 15 minutes throughout the\n\n372
|
102 |
+
|
103 |
+
labour and the postpartum period. All healthcare professionals should have the knowledge to identify the signs and symptoms of sepsis. In case of suspected sepsis, a Modified Obstetric Early Warning Signs (MOEWS) chart should be maintained and the patient may need HDU or ICU care during the process of labour.
|
104 |
+
|
105 |
+
• CTG (cardiotocograph) – All patients with intrapartum fever should have a continuous foetal monitoring with CTG.
|
106 |
+
|
107 |
+
• General measures should be taken to reduce the body temperature by adequate hydration (IV/ oral fluids), removing blankets and clothing, applying a cool wet towel to the skin, lowering the room temperature, and providing anti- pyretics like paracetamol.
|
108 |
+
|
109 |
+
• Mode of delivery and timing of delivery – Decisions for timing and mode of delivery should be made by the senior consultant obstetrician considering the following factors
|
110 |
+
|
111 |
+
a) Severity of maternal infection
|
112 |
+
|
113 |
+
b) Duration and stage of labour
|
114 |
+
|
115 |
+
c) Gestational age
|
116 |
+
|
117 |
+
d) Foetal viability
|
118 |
+
|
119 |
+
• There is no indication to deliver the foetus immediately unless the cause of the fever is suspected chorioamnionitis.
|
120 |
+
|
121 |
+
5. Management of specific infections
|
122 |
+
|
123 |
+
Management of Intraamniotic infection (Chorio- amnionitis or IAI)
|
124 |
+
|
125 |
+
IAI is defined as infection or inflammation of the amniotic fluid, membranes, placenta and/or decidua4.
|
126 |
+
|
127 |
+
Diagnosis is based on maternal pyrexia 38°C (100.4°F) orally, and at least the presence of two of the following findings5.
|
128 |
+
|
129 |
+
• Maternal tachycardia (>100bpm)
|
130 |
+
|
131 |
+
• Foetal tachycardia (>160bpm)
|
132 |
+
|
133 |
+
• Uterine tenderness
|
134 |
+
|
135 |
+
• Foul odour of the amniotic fluid
|
136 |
+
|
137 |
+
• Maternal leukocytosis (>15,000cells/mm3)
|
138 |
+
|
139 |
+
Once the diagnosis of the IAI is made, commencement of broad-spectrum antibiotics and delivery is indicated.
|
140 |
+
|
141 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
142 |
+
|
143 |
+
6. Maternal and neonatal consequences of intrapartum fever
|
144 |
+
|
145 |
+
6.1 Maternal consequences
|
146 |
+
|
147 |
+
• Dysfunctional labour
|
148 |
+
|
149 |
+
• Greater likelihood of caesarean delivery
|
150 |
+
|
151 |
+
• Uterine atony
|
152 |
+
|
153 |
+
• Postpartum haemorrhage
|
154 |
+
|
155 |
+
• Postpartum endometritis
|
156 |
+
|
157 |
+
• Septic pelvic thrombophlebitis
|
158 |
+
|
159 |
+
6.2 Neonatal consequences
|
160 |
+
|
161 |
+
• Meconium Aspiration Syndrome
|
162 |
+
|
163 |
+
• Hyaline Membrane Disease (HMD)
|
164 |
+
|
165 |
+
• Neonatal Seizures
|
166 |
+
|
167 |
+
•
|
168 |
+
|
169 |
+
Intrapartum stillbirth
|
170 |
+
|
171 |
+
• Early neonatal or infant death
|
172 |
+
|
173 |
+
• Birth asphyxia
|
174 |
+
|
175 |
+
• Neonatal encephalopathy cerebral palsy
|
176 |
+
|
177 |
+
• Needing assisted ventilation\n\n7. Postpartum period
|
178 |
+
|
179 |
+
Antibiotics started for confirmed or suspected intraamniotic infection should not be continued auto- matically in the postpartum period. Continuation of the antibiotic treatment should be decided on case-by-case basis considering the clinical state and the investi- gations. Continuation of the temperature monitoring chart and close observation of the neonate is recom- mended4.
|
180 |
+
|
181 |
+
7.1 Introduction
|
182 |
+
|
183 |
+
Fever during labour (intrapartum fever) is an important clinically relevant obstetric event associated with a range of maternal and neonatal complications. The prevalence of intrapartum fever has increased recently due to increase use of neuraxial anaesthesia. Studies indicate 6.8 percent or 1 in 15 women in labour have fever6.
|
184 |
+
|
185 |
+
Even though there can be both infectious and non- infectious contributing causes, most pregnant women with intrapartum fever are presumed to have an intraamniotic infection (IAI) and are managed with broad spectrum antibiotics. IAI and neuraxial anaesthesia administration are the two most common
|
186 |
+
|
187 |
+
Vol. 43, No. 4, December 2021
|
188 |
+
|
189 |
+
SLCOG Guideline
|
190 |
+
|
191 |
+
contributing causes of intrapartum fever. Many risk factors such as nulliparity, prolonged labour and premature rupture of membranes are common to both. An individualised approach involving a senior obstetrician is recommended for management of labour. In addition, some pre-existing conditions may require involvement of a multi-disciplinary team management.
|
192 |
+
|
193 |
+
8. Recommendations and discussions
|
194 |
+
|
195 |
+
8.1 Definition
|
196 |
+
|
197 |
+
Intrapartum fever is defined as elevation of maternal oral temperature 39°C (102.2°F) on one reading or temperature between 38°C (>100.4°F) to 39°C (102.2°F) on two readings 30 minutes apart in a woman in labour.
|
198 |
+
|
199 |
+
Health care worker should measure oral temperature of all women in labour 4 hourly or whenever they show signs and symptoms of febrile illness. Temperature should be recorded in the partogram routinely. Whenever high temperature is detected, it should be recorded in a different temperature chart.
|
200 |
+
|
201 |
+
Elevated body temperature will occur when the hypothalamic thermo regulator is reset at the higher temperature by the endogenous pyrogens produced by specific host cells in response to infection, inflam- mation, injury or antigenic challenge. In some instances, due to the inability to reset the thermo- regulatory centre, hyperthermia may occur. For example, recreational drugs like ecstasy can lead to increase in the core temperature by blocking the sweating or vasodilatation. In this chapter the term fever will be used to describe the rise in maternal intrapartum temperature by any mechanism. Obser- vations of normal parturient shows a diurnal distribution of temperature with a peak from midnight to 2am and a nadir from 11am to noon7.
|
202 |
+
|
203 |
+
The temperature should be measured in the oral sublingual pocket with an electronic thermometer, since this is an accurate and convenient method for detecting maternal fever. Mouth breathing, hyper- ventilation, ingestion of ice or hot beverages and oxygen administration can affect the oral temperature. Temperature measurement should be undertaken at least 15 minutes after consuming hot or cold beverages8. Measurement of axillary temperature will have an error of 1°C-2°C lower than the oral temperature9.
|
204 |
+
|
205 |
+
373
|
206 |
+
|
207 |
+
SLCOG Guideline
|
208 |
+
|
209 |
+
Oral temperature is correlated better with intrauterine core temperature according to one study. Foetal/ intrauterine temperature is 0.2°C-0.9°C (0.4°F- 1.6°F) higher than maternal oral temperature8,10-13.\n\n8.2 Aetiology and risk factors
|
210 |
+
|
211 |
+
IAI and neuraxial anaesthesia are the most common causes for intra-partum fever.
|
212 |
+
|
213 |
+
Aetiology of the intrapartum fever is classified into two categories.
|
214 |
+
|
215 |
+
a. Infectious causes
|
216 |
+
|
217 |
+
b. Non-infectious causes
|
218 |
+
|
219 |
+
a. Most common infection related aetiologies are
|
220 |
+
|
221 |
+
Intra-amniotic infection (IAI)
|
222 |
+
|
223 |
+
• Urinary tract infection
|
224 |
+
|
225 |
+
• Respiratory tract infection
|
226 |
+
|
227 |
+
• Any other pre-existing infection which could be present as fever during labour
|
228 |
+
|
229 |
+
• Special consideration should be given to dengue fever and COVID-19 infection
|
230 |
+
|
231 |
+
b. Use of neuraxial anaesthesia is the most common non-infectious cause of intrapartum fever.
|
232 |
+
|
233 |
+
Increased metabolism (eg: thyrotoxicosis), poor ventilation, delivering in an overheated room and drug fever are also considered as some other causes for intrapartum fever.
|
234 |
+
|
235 |
+
The pathophysiology of the intra-partum fever associated with neuraxial anaesthesia is not well understood. It has been attributed to –
|
236 |
+
|
237 |
+
• Direct effect of local anaesthetics on endothelial cells, trophoblast cells or leukocytes to induce proinflammatory or inhibit anti-inflammatory cytokines release, which will act on thermo- regulatory centre to reset the temperature14-18.
|
238 |
+
|
239 |
+
• Both neuraxial anaesthesia and IAI share same risk factors.
|
240 |
+
|
241 |
+
• Reduced heat loss – parturient with epidural anaesthesia have less pain induced hyper- ventilation and less perspiration because of sympathetic block2.
|
242 |
+
|
243 |
+
In general, increased in temperature >38°C is usually observed 4 hours following insertion of epidural anaesthesia19,20. Nulliparous are more likely to have
|
244 |
+
|
245 |
+
374
|
246 |
+
|
247 |
+
longer labour and likely to have intrapartum fever than multiparous (risk 13-33%)21. There is no difference in the maternal temperature elevation in parturient who receive CSE (combined spinal and epidural anaesthesia) compared to epidural alone. There is no known effective method to prevent neuraxial anaesthesia related temperature elevation.
|
248 |
+
|
249 |
+
Patients with following factors are considered high risk for intrapartum fever –
|
250 |
+
|
251 |
+
• Nulliparity
|
252 |
+
|
253 |
+
• Labour induction
|
254 |
+
|
255 |
+
• Prolonged labour
|
256 |
+
|
257 |
+
• Premature labour
|
258 |
+
|
259 |
+
• Prolonged membrane rupture
|
260 |
+
|
261 |
+
• Multiple digital vaginal examinations
|
262 |
+
|
263 |
+
• Exposure to intrauterine devices: – Intrauterine pressure devices – Foetal scalp electrodes
|
264 |
+
|
265 |
+
However above-mentioned conditions are risk factors for both IAI and neuraxial anaesthesia. Since there are no intrapartum clinical or laboratory findings that can reliably distinguish IAI and neuraxial anaesthesia related elevated maternal temperature, broad spectrum anti- biotics are usually administered in this situation, resulting in overtreatment of mothers.
|
266 |
+
|
267 |
+
Other sources of fever could be due to urinary tract infection, respiratory tract infection, influenza, pneu- monia and appendicitis that began during the antepartum period.\n\n8.3 Diagnosis and investigations
|
268 |
+
|
269 |
+
Careful history and systemic examination are required. Special consideration should be given for abdominal tenderness, vaginal examination including characteristic of amniotic fluid and odour.
|
270 |
+
|
271 |
+
Investigations are based on suspected aetiology. However, there are no specific investigations for intra- partum fever. Usually full blood count (FBC), blood culture, urine full report (UFR) and urine culture are performed according to the suspected aetiology. High vaginal swab culture is usually done when there is evidence of premature rupture of membranes (PROM). In endemic situations, rapid antigen for Dengue fever, H1N1 influenza and COVID-19 are vital for immediate management.
|
272 |
+
|
273 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
274 |
+
|
275 |
+
Biological markers – Many systemic reviews done in intra-partum fever concluded that, measurement of C-Reactive Protein (CRP) is unreliable for detecting intra-uterine infection3.
|
276 |
+
|
277 |
+
• White Blood Cell count/ Differential count (WBC/DC) – It is recommended to take WBC/ DC in labouring women who are clinically ill or having a high temperature. Since elevated WBC count is a normal physiological occurrence in labour, the value of this is limited. The mean values of WBC count vary from 10,000 - 29,000 cells/microlitre. Usually, the mean count increases linearly throughout the labour22. With other evidence of infection, the presence of leukocytosis will support the diagnosis, especially when accompanied by a left shift.
|
278 |
+
|
279 |
+
• Blood culture – Even though there is no imme- diate benefit of doing blood culture in intrapartum women, it will be useful for the subsequent management as appropriate antibiotic therapy is important in patients with bacteraemia, for the prevention of progressing to sepsis and shock. It is highly recommended to obtain the blood cultures from the patients with following features23,24.
|
280 |
+
|
281 |
+
• Fever >39°C (102.2°F)
|
282 |
+
|
283 |
+
• Chills
|
284 |
+
|
285 |
+
• Hypothermia
|
286 |
+
|
287 |
+
• Leukocytosis with left shift
|
288 |
+
|
289 |
+
• Neutropenia
|
290 |
+
|
291 |
+
• Development of otherwise unexplained organ dysfunction
|
292 |
+
|
293 |
+
Usually, blood cultures are not routinely performed in patients with suspected IAI as delivery and empirical antibiotic therapy is effective in 80-90% of these patients.
|
294 |
+
|
295 |
+
• Urine tests – Urinary dipstick is important in a labouring woman for the rapid diagnosis of a urinary tract infection. This is easy to perform, convenient and low cost. Sample could be obtained from a clean catch midstream urine, straight catheter, or an indwelling catheter. Urine culture is important when the patient is clinically ill, but not practical as a first line diagnosis test.
|
296 |
+
|
297 |
+
• Rapid antigen test – In dengue fever detecting
|
298 |
+
|
299 |
+
Vol. 43, No. 4, December 2021
|
300 |
+
|
301 |
+
SLCOG Guideline
|
302 |
+
|
303 |
+
the NS1 antigen is important since early intervention with proper fluid management is necessary.
|
304 |
+
|
305 |
+
In suspected COVID-19 infection, rapid antigen test is strongly recommended, because symp- tomatic or asymptomatic patients in endemic situation need early isolation in the management. Real time PCR has a value if available, for patients who are found to be having fever despite negative Rapid antigen.
|
306 |
+
|
307 |
+
• High vaginal swab – It is routinely taken in women with PROM. Positive culture for potential pathogens does not correlate well with the risk, or developing chorioamnionitis; how- ever, they are useful in determining the organisms when the chorioamnionitis is diagnosed and directing the antibiotic therapy.\n\n8.4 Management of intra-partum fever
|
308 |
+
|
309 |
+
Senior obstetrician’s opinion should be obtained in the management of all patients with intrapartum fever. It may be beneficial to have a multidisciplinary team approach involving the Obstetrician, Microbiologist, Physician and the Anaesthetist.
|
310 |
+
|
311 |
+
Neonatology team should be notified and involved for every case of intrapartum fever. The presence of a senior medical officer from the neonatology team at the time of delivery is the minimum requirement.
|
312 |
+
|
313 |
+
Antibiotics – Usually broad-spectrum antibiotics with coverage of GBS (Group B streptococcus) is initiated in all patients except those with pre-existing infection. Different antibiotic regimens are used according to the hospital/unit policy.
|
314 |
+
|
315 |
+
All patients with intrapartum fever should have their pulse rate, blood pressure and respiratory rate checked every 15 mins throughout the labour and the postpartum period. All healthcare professionals should know the signs and symptoms of sepsis. In case of sepsis, patient may need HDU or ICU care. In case of suspected sepsis, a Modified Obstetric Early Warning Signs (MOEWS) chart should be maintained and the patient may need HDU or ICU care during the process of labour.
|
316 |
+
|
317 |
+
Clinical signs and symptoms of sepsis are – pyrexia, hypothermia, tachycardia, tachypnoea, hypoxia, hypotension, oliguria, impaired consciousness and
|
318 |
+
|
319 |
+
375
|
320 |
+
|
321 |
+
SLCOG Guideline
|
322 |
+
|
323 |
+
failure to respond to treatment. These signs including pyrexia, may not always be present and are not necessarily related to the severity of the sepsis25. Refer to quick Sequential Organ Failure Assessment (qSOFA) score for early detection of suspected patients with sepsis Table 2.
|
324 |
+
|
325 |
+
CTG (cardiotocograph)
|
326 |
+
|
327 |
+
All patients with intrapartum fever should have a continuous foetal monitoring with CTG.
|
328 |
+
|
329 |
+
Intrauterine infection is associated with abnormal foetal heart trace, but there is no specific CTG pattern that indicate early onset neonatal sepsis.
|
330 |
+
|
331 |
+
Foetal tachycardia may occur due to maternal pyrexia or intrauterine infection. If Foetal tachycardia occurred secondary to maternal pyrexia, foetal tachycardia will subside once the normalisation of the maternal tem- perature is achieved.
|
332 |
+
|
333 |
+
Changes in baseline variability or new onset decele- rations must prompt measurement of maternal mean arterial pressure (MAP), hypoxia and acidaemia.\n\nGeneral measures
|
334 |
+
|
335 |
+
Measures should be taken to reduce the body tem- perature by adequate hydrations (IV/oral fluids), removing blankets and clothing, applying a cool wet towel to the skin, lowering the room temperature and providing anti-pyretics like paracetamol.
|
336 |
+
|
337 |
+
Mode of delivery and timing of delivery – Decisions for timing and mode of delivery should be made by the senior consultant obstetrician considering the following factors
|
338 |
+
|
339 |
+
a) Severity of maternal infection
|
340 |
+
|
341 |
+
b) Duration and stage of labour
|
342 |
+
|
343 |
+
c) Gestational age
|
344 |
+
|
345 |
+
d) Foetal viability
|
346 |
+
|
347 |
+
There is no indication to deliver the foetus immediately unless the cause of the fever is suspected chorioa- mnionitis.
|
348 |
+
|
349 |
+
Expediting the delivery with maternal instability may increase the risk of maternal and foetal mortality unless the infection is intrauterine.
|
350 |
+
|
351 |
+
376
|
352 |
+
|
353 |
+
8.5 Management of specific infections
|
354 |
+
|
355 |
+
Management of Intra-amniotic infection (Chorioa- mnionitis or IAI).
|
356 |
+
|
357 |
+
IAI is defined as infection or inflammation of the amniotic fluid, membranes, placenta and/or decidua.
|
358 |
+
|
359 |
+
Diagnosis is based on maternal pyrexia 38°C (100.4°F) orally, and at least the presence of two of the following findings
|
360 |
+
|
361 |
+
• Maternal tachycardia (>100bpm)
|
362 |
+
|
363 |
+
• Foetal tachycardia (>160bpm)
|
364 |
+
|
365 |
+
• Uterine tenderness
|
366 |
+
|
367 |
+
• Foul odour of the amniotic fluid
|
368 |
+
|
369 |
+
• Maternal leukocytosis (>15,000cells/mm3)
|
370 |
+
|
371 |
+
Other clinical and laboratory criteria are insensitive for IAI.
|
372 |
+
|
373 |
+
“Triple I” is another terminology proposed by an expert panel in 2015, replacing IAI, which indicate intra uterine infection, inflammation or both1, 27. The organisms involved in the chorioamnionitis usually present in the lower genital tract.
|
374 |
+
|
375 |
+
Usually, a presumptive diagnosis is made depending on the above findings. However, for the definitive diagnosis of IAI amniotic fluid gram stain, culture or placental histology showing features of an infection is necessary.
|
376 |
+
|
377 |
+
Even though the positive amniotic fluid culture is the gold standard for the diagnosis, it is of limited value in clinical practice as the results may not be available for up to 3 days from sampling. Maternal C-Reactive protein and Leukocytosis have low sensitivity and specificity to detect the chorioamnionitis. Combination of maternal blood and amniotic fluid biomarkers (interleukin 6 >7.9ng/ml, Glucose <15mg/dl) could improve the accuracy of the diagnosis. Ultrasono- graphic evaluation of the foetal thymus is more sensitive to diagnose chorioamnionitis than the foetal biophysical profile26. Foetuses complicated with chorioamnionitis were found to have small thymus in ultrasound scan.
|
378 |
+
|
379 |
+
Delivery is indicated once the diagnosis of intraamniotic infection is made. It is also important to treat with broad-spectrum antibiotics with the coverage of group
|
380 |
+
|
381 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
382 |
+
|
383 |
+
B streptococcus to reduce the maternal and neonatal morbidity. Patient should initially be started on intra- venous antibiotics2. See the Table 1 below for regimens of antibiotic combinations.
|
384 |
+
|
385 |
+
Usually, the IAI is associated with labour abnormalities, caesarean section, uterine atony, PPH, endometritis and septic pelvic thrombophlebitis. Chorioamnionitis is very important as it can lead serious maternal complications such as septic shock, postpartum haemorrhage, adult respiratory syndrome, intensive care admissions and rarely maternal death. Forty – seventy percent of pre- term birth and 1-13% of term births with preterm rupture of membranes or spontaneous labour are complicated with chorioamnionitis28. Early onset neonatal meningitis, neurodevelopment delay, pneumonia, respiratory distress, sepsis and death are some of the neonatal complications of IAI.\n\nManagement of UTI
|
386 |
+
|
387 |
+
Urinary tract infections are common during pregnancy. The presence of fever, flank tenderness, nausea, vomiting, costo-vertebral angle tenderness, with or without lower urinary tract symptoms like – dysuria, frequency, urgency, suprapubic pain and haematuria, may indicate the presence of upper or complicated urinary tract infection. Simple cystitis may present without fever. Empirical antibiotic treatment is indicated for UTI. Commencement of the antibiotic regimen is customised according to the unit/hospital policy. This may need to be changed according to the sensitivity pattern of the urine culture and clinical response later.
|
388 |
+
|
389 |
+
Management of respiratory tract infection
|
390 |
+
|
391 |
+
Upper respiratory tract infections will present with nasal congestion, rhinorrhoea, sore throat, malaise and cough. Fever, if present is usually of low grade. These patients do not need any specific antibiotics, except for symptomatic management and simple antipyretics. If the patient present with sudden onset rigors followed by fever, productive cough, purulent sputum and pleuritic chest pain high possibility of pneumonia should be considered. Treatment and management are similar to the non-pregnant individual, but chest X-Ray could be delayed until after delivery. Pregnant mothers can be treated safely with Azithromycin or/ and Ceftriaxone.
|
392 |
+
|
393 |
+
Antiviral prophylaxis should commence immediately if indicated for mothers suspected to have H1N1 influenza.
|
394 |
+
|
395 |
+
Vol. 43, No. 4, December 2021
|
396 |
+
|
397 |
+
SLCOG Guideline
|
398 |
+
|
399 |
+
Patient with severe lower respiratory tract infection may need to be positioned comfortably in propped-up (Fowler’s) position. They need close monitoring of vital signs, especially the respiratory rate and oxygen saturation. Patients with severe respiratory failure may need transferring to intensive care unit (ICU) and early delivery.
|
400 |
+
|
401 |
+
Management of dengue fever
|
402 |
+
|
403 |
+
The management of dengue fever depends on the phase of the fever. Patients in the critical or leaking phase, are considered in the high-risk category and need to be managed in an ICU setting during labour. (See National guidelines on dengue fever in pregnancy).\n\nManagement of COVID-19
|
404 |
+
|
405 |
+
In a pandemic situation patient may present without any symptoms or fever. Therefore, all patients presen- ting to labour suite may need a COVID-19 screening with Rapid antigen or Real time PCR.
|
406 |
+
|
407 |
+
Early diagnosis and patient isolation at the appropriate setting is of paramount importance, with adequate personal protective equipment (PPE). Maternal pulse rate, blood pressure, respiratory rate and oxygen saturation should be monitored throughout the labour.
|
408 |
+
|
409 |
+
Decision making in labour should be precise to avoid obstetric emergencies, since the delay is anticipated in transferring, organising and performing procedures with adequate isolation and personal protective equipments (PPE). Patients who are on prophylaxis enoxaparin should be discontinued of it, 12 hours before the onset of labour or induction. (see the national guideline on Management of COVID-19 infection in pregnancy).
|
410 |
+
|
411 |
+
8.6 Maternal and neonatal consequences of intrapartum fever
|
412 |
+
|
413 |
+
Neonatal consequences
|
414 |
+
|
415 |
+
• Meconium Aspiration Syndrome
|
416 |
+
|
417 |
+
• Hyaline Membrane Disease (HMD)
|
418 |
+
|
419 |
+
• Neonatal Seizures
|
420 |
+
|
421 |
+
Intrapartum stillbirth
|
422 |
+
|
423 |
+
• Early neonatal or infant death
|
424 |
+
|
425 |
+
377
|
426 |
+
|
427 |
+
SLCOG Guideline
|
428 |
+
|
429 |
+
• Birth asphyxia
|
430 |
+
|
431 |
+
• Neonatal encephalopathy and cerebral palsy
|
432 |
+
|
433 |
+
• Needing assisted ventilation
|
434 |
+
|
435 |
+
When the labouring woman is having fever, peripartum transfer of the infection to the fetus is one the major concerns. The presence of intraamniotic infection can give rise to short term effects to the new-born like septicaemia, meningitis and pneumonia. Long term outcomes are cerebral palsy and neurodevelopmental delay.
|
436 |
+
|
437 |
+
Once the micro-organisms enter the foetal mucosa, it induces a localised and subsequently a systemic inflammatory response called foetal inflammatory response syndrome (FIRS). FIRS affect multiple organ functions including the hematopoietic system, immune system, thymus heart, adrenal glands, skin, lung, brain and gut29,30.
|
438 |
+
|
439 |
+
There is no definite method to differentiate intrapartum fever due to neuraxial anaesthesia from chorio- amnionitis. Hence, there is increased tendency for neonatal sepsis screening and treating with antibiotics. However, fever due to neuraxial anaesthesia is not associated with increased rate of proven sepsis. But, even in the absence of documented infection, neuraxial anaesthesia related intra-partum pyrexia may be associated with adverse neonatal outcome. When the mother is having temperature during labour, neonate should be closely observed for sepsis. Especially neonates with low birth weight, prematurity, and hypothermia at birth, maternal Group B streptococcal colonization, preeclampsia and maternal hypertension should have a full septic screening31.
|
440 |
+
|
441 |
+
Maternal consequences
|
442 |
+
|
443 |
+
• Labour abnormalities (dysfunctional labour)
|
444 |
+
|
445 |
+
• Greater likelihood of caesarean delivery
|
446 |
+
|
447 |
+
• Uterine atony
|
448 |
+
|
449 |
+
• Postpartum haemorrhage
|
450 |
+
|
451 |
+
378
|
452 |
+
|
453 |
+
• Postpartum endometritis
|
454 |
+
|
455 |
+
• Septic pelvic thrombophlebitis
|
456 |
+
|
457 |
+
Maternal outcome depends on the causes of the intrapartum fever. Almost all the women with intrapartum fever are likely to receive antibiotics. One study indicated that even low risk nulliparous women with intrapartum fever have double the chance of requiring a caesarean delivery or assisted vaginal delivery than those without intrapartum fever regardless of receiving neuraxial anaesthesia32.\n\n9. Clinical governance
|
458 |
+
|
459 |
+
Possibility of chorioamnionitis should be suspected whenever a woman in labour develop fever as it is a condition associated with high perinatal morbidity and mortality. All measures should be taken to prevent the occurrence of chorioamnionitis.
|
460 |
+
|
461 |
+
• Optimum sterility should be maintained during vaginal examinations and procedures like artificial rupture of membranes, membrane sweeping, Foley catheter insertion etc.
|
462 |
+
|
463 |
+
• Minimise the number of vaginal examinations, especially for those with prelabour rupture of membranes and those who are in labour.
|
464 |
+
|
465 |
+
• Plan the vaginal examination in such a way that only the decision-making staff member will perform it. Avoid repeated vaginal examinations done by different categories of staff in short intervals.
|
466 |
+
|
467 |
+
All mothers with intrapartum fever should have their management discussed with the senior obstetrician and should also get neonatal team involvement.
|
468 |
+
|
469 |
+
All mothers who are suspected of having chorioamnionitis should be counselled regarding their management and possible neonatal consequences.
|
470 |
+
|
471 |
+
Maintenance of partogram and MOEWS chart in suspected sepsis are of paramount importance in the management.
|
472 |
+
|
473 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
474 |
+
|
475 |
+
SLCOG Guideline
|
476 |
+
|
477 |
+
Annexure 1. Intrapartum fever management algorithm
|
478 |
+
|
479 |
+
Vol. 43, No. 4, December 2021
|
480 |
+
|
481 |
+
379
|
482 |
+
|
483 |
+
SLCOG Guideline
|
484 |
+
|
485 |
+
Table 1. Different antibiotic regimens to be used in intrapartum fever
|
486 |
+
|
487 |
+
Regimen Doses 1. Ampicillin and Gentamycin Ampicillin IV 2g every 6 h and Gentamicin 2mg/kg IV load followed by 1.5mg/kg 8 h or 5mg/kg IV every 24 h 2. Cefuroxime + Metronidazole Cefuroxime 750mg IV 8 h + Metronidazole 500mg IV 8 h 3. Ceftriaxone, Metronidazole and clarithromycin Ceftrixone 1g IV every 24 h, Metronidazole IV 500mg every 8 h, and clarithromycin 500mg oral every 12 h 4. Ampicillin and Azithromycin Ampicillin 1.5g IV every 6 h and Azithromycin oral 500mg every 24 h 5. Ampicillin 3g IV every 6 6. Piperacillin-Tazobactum 4.5g IV every 8 h 7. Ertapenem 1g IV every 24 h 8. Mild penicillin allergy – Cefuroxime and Cefuroxime 1.5g loading dose,750mg 8 h and Gentamycin Gentamicin 2mg/kg IV load followed by 1.5mg /kg every 8 h or 5mg/kg IV every 24 h 9. For severe penicillin allergy – Clindamycin Clindamycin 600-800mg IV every 8h or Vancomycin or Vancomycin and Gentamicin 1g IV every 12h (slow infusion over 1 hr) and Gentamycin 2mg/kg IV load followed by 1.5 mg/kg every 8 h or 5mg/kg IV every 24 h
|
488 |
+
|
489 |
+
IV- Intravenous, h - hourly
|
490 |
+
|
491 |
+
Table 2. qSOFA scoring
|
492 |
+
|
493 |
+
Parameter Value Score Blood pressure < 100mmHg 1 Respiratory rate > 22 bpm 1 Level of consciousness GCS < 15 1 Score of 2 or more: suggestive of sepsis
|
494 |
+
|
495 |
+
380
|
496 |
+
|
497 |
+
Sri Lanka Journal of Obstetrics and Gynaecology\n\nReferences
|
498 |
+
|
499 |
+
1. Higgins RD, Saade G, Polin RA, Grobman WA, Buhimschi IA, Watterberg K, et al. Evaluation and management of women and newborns with a maternal diagnosis of chorioamnionitis: Summary of a Workshop. Obstet Gynecol. 2016; 127(3): 426-36.
|
500 |
+
|
501 |
+
2. Katherine TC. Intrapartum fever. In: Up To Date, Vincenzo B (Ed), David LH (Ed), Up To Date, Waltham, MA. (Accessed on July 20, 2021.)
|
502 |
+
|
503 |
+
3. Evers AC, Nijhuis L, Koster MP, Bont LJ, Visser GH. Intrapartum fever at term: diagnostic markers to individualize the risk of fetal infection: a review. Obstet Gynecol Surv. 2012; 67(3): 187.
|
504 |
+
|
505 |
+
4. Committee on Obstetric. Practice Committee Opinion No. 712. Intrapartum management of intraamniotic infection. Obstet Gynecol 2017; 130(2): e95-e101.
|
506 |
+
|
507 |
+
5. Newton ER. Chorioamnionitis and intraamniotic infection. Clin Obstet Gynecol 1993; 36: 795.
|
508 |
+
|
509 |
+
6. Towers CV, Yates A, Zite N, et al. Incidence of fever in labor and risk of neonatal sepsis. Am J Obstet Gynecol 2017; 216: 596.e1.
|
510 |
+
|
511 |
+
7. Acker DB, Schulman EB, Ransil BJ, et al. The normal parturient’s admission temperature. Am J Obstet Gynecol 1987; 157: 308.
|
512 |
+
|
513 |
+
8. Banerjee S, Cashman P, Yentis SM, Steer PJ. Maternal temperature monitoring during labor: concordance and variability among monitoring sites. Obstet Gynecol 2004; 103: 287.
|
514 |
+
|
515 |
+
9. Wartzek T, Mühlsteff J, Imhoff M. Temperature measurement. Biomed Tech (Berl) 2011; 56: 241.
|
516 |
+
|
517 |
+
10. Sciscione AC, Zainia T, Leet T, et al. A new device for measuring intrauterine temperature. Am J Obstet Gynecol 2001; 184: 1431.
|
518 |
+
|
519 |
+
11. Macaulay JH, Randall NR, Bond K, Steer PJ. Continuous monitoring of fetal temperature by non-invasive probe and its relationship to maternal temperature, fetal heart rate, and cord arterial oxygen and pH. Obstet Gynecol 1992; 79: 469.
|
520 |
+
|
521 |
+
12. Adamson SK Jr, Towell ME. Thermal Homeostasis in the fetus and newborn. Anesthesiology 1965; 26: 531.
|
522 |
+
|
523 |
+
13. Walker D, Walker A, Wood C. Temperature of the
|
524 |
+
|
525 |
+
Vol. 43, No. 4, December 2021
|
526 |
+
|
527 |
+
SLCOG Guideline
|
528 |
+
|
529 |
+
human fetus. J Obstet Gynaecol Br Commonw 1969; 76: 503.
|
530 |
+
|
531 |
+
14. Smulian JC, Bhandari V, Vintzileos AM, et al. Intrapartum fever at term: serum and histologic markers of inflammation. Am J Obstet Gynecol 2003; 188: 269.
|
532 |
+
|
533 |
+
15. Goetzl L, Evans T, Rivers J, et al. Elevated maternal and fetal serum interleukin-6 levels are associated with epidural fever. Am J Obstet Gynecol 2002; 187: 834.
|
534 |
+
|
535 |
+
16. De Jongh RF, Bosmans EP, Puylaert MJ, et al. The influence of anaesthetic techniques and type of delivery on peripartum serum interleukin-6 concentrations. Acta Anaesthesiol Scand 1997; 41: 853.
|
536 |
+
|
537 |
+
17. Sultan P, David AL, Fernando R, Ackland GL. Inflammation and epidural-related maternal fever: proposed mechanisms. Anesth Analg 2016; 122: 1546.
|
538 |
+
|
539 |
+
18. Wohlrab P, Boehme S, Kaun C, et al. Ropivacaine activates multiple proapoptotic and inflammatory signaling pathways that might subsume to trigger epidural-related maternal fever. Anesth Analg 2020; 130: 321.
|
540 |
+
|
541 |
+
19. Lieberman E, Lang JM, Frigoletto F Jr, et al. Epidural analgesia, intrapartum fever, and neonatal sepsis evaluation. Pediatrics 1997; 99: 415.
|
542 |
+
|
543 |
+
20. Goetzl L, Rivers J, Zighelboim I, et al. Intrapartum epidural analgesia and maternal temperature regulation. Obstet Gynecol 2007; 109: 687.
|
544 |
+
|
545 |
+
21. Goetzl L. Epidural analgesia and maternal fever: a clinical and research update. Curr Opin Anaesthesiol 2012; 25: 292.
|
546 |
+
|
547 |
+
22. Acker DB, Johnson MP, Sachs BP, Friedman EA. The leukocyte count in labor. Am J Obstet Gynecol 1985; 153: 737.
|
548 |
+
|
549 |
+
23. Bates DW, Sands K, Miller E, et al. Predicting bacteremia in patients with sepsis syndrome. Academic Medical Center Consortium Sepsis Project Working Group. J Infect Dis 1997; 176: 1538.
|
550 |
+
|
551 |
+
24. Smith-Elekes S, Weinstein MP. Blood cultures. Infect Dis Clin North Am 1993; 7: 221.
|
552 |
+
|
553 |
+
25. Royal College of Obstetricians and Gynaecologists. Bacterial Sepsis in Pregnancy. Green-top Guideline No. 64a. London: RCOG; 2012.\n\n381
|
554 |
+
|
555 |
+
SLCOG Guideline
|
556 |
+
|
557 |
+
26. Catańo Sabogal CP, Fonseca J, Garcķa-Perdomo HA. Validation of diagnostic tests for histologic chorioamnionitis: systematic review and meta- analysis. Eur J Obstet Gynecol Reprod Biol 2018; 228: 13-26.
|
558 |
+
|
559 |
+
27. Ona S, Easter SR, Prabhu M, et al. Diagnostic validity of the proposed eunice kennedy shriver national institute of child health and human development criteria for intrauterine inflammation or infection. Obstet Gynecol 2019; 133(1): 33-9.
|
560 |
+
|
561 |
+
28. Tita AT, Andrews WW. Diagnosis and management of clinical chorioamnionitis. Clin Perinatol 2010; 37(2): 339-54.
|
562 |
+
|
563 |
+
29. Kim CJ, Romero R, Chaemsaithong P, et al. Acute chorioamnionitis and funisitis: definition, pathologic
|
564 |
+
|
565 |
+
382
|
566 |
+
|
567 |
+
features, and clinical significance. Am J Obstet Gynecol 2015; 213(4 Suppl): S29-S52.
|
568 |
+
|
569 |
+
30. Gotsch F, Romero R, Kusanovic JP, et al. The fetal inflammatory response syndrome. Clin Obstet Gynecol 2007; 50(3): 652-83.
|
570 |
+
|
571 |
+
31. Paules C, Moreno E, Gonzales A, et al. Amniotic fluid sludge as a marker of intra-amniotic infection and histological chorioamnionitis in cervical insufficiency: a report of four cases and literature review. J Matern Fetal Neonatal Med 2016; 29(16): 2681-4.
|
572 |
+
|
573 |
+
32. American Association of Pro-Life Obstetricians Gynecologists. AAPLOG practice bulletin no. 3: previable induction of labor for chorioamnitis. Issues Law Med 2018; 33(2): 247-56.
|
574 |
+
|
575 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
src/processed_markdown/Management-of-Normal-Labourchart/Management-of-Normal-Labourchart.md
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---\n\ncitation: "Management of Normal Labourchart"\n\n---\n\nManagement of Uncomplicated labour
|
2 |
+
|
3 |
+
Painful contractions — | Not in labour ——~* | Observe in antenatal ward °Show Effacement & progressive ~ | Uncertain i Review after 2 hours dilatation of cervix — | Established labour t Transfer to the labour suite Admission CTG to be done in all three groups and interpreted before decision is made (Y) Identify risk factors by, Review antenatal records. © Detailed clinical history o Examination Urine for protein = Monitoring by Partogram Maintain Partogram*(X) — Progress of labour © Cervical dilatation o Decent of the presenting part o Uterine contractions Routine Maternal condition care in soo o Pulse, BP, Temperature & hydration. labour suit —=}> eaintrclict o Evaluation of drugs(oxytocin, antibiotics, Opioid -Pethidine Anti hypertensives, Analgesics Regional analgesia-Epidural © Undistended bladder-catheterize if Other-spinal analgesia indicated Combined spinal-epidural analgesia Inhalational analgesia-Entonox Pudendal block for episiotomy/forceps/vacuum Fetal condition © Intermittent auscultation of fetal heart o Liquor volume o Meconeum in liquor P jonin; Most comfortable Second stage position ———==> Diagnosis Supine position-avoided v Vaginal examination for full dilatation Y Perineal distention v Anal dilatation - Medio-lateral Episiotomy At the time of crowning Delivery LOxytocies Third stage 3.Controlled cord traction 1949 pvoy poq sy) UT payUauINDOp aq plnoys snoqery Jo }WawWaseurW ou) UT sdais [TY suon{puoo ondase Japun 3no passes aq pnoys snoqer] jo }uoWeseuLW oy) UT sdajs [TV Active management 4.Examine the 2.Cord clamp ‘ placenta
|
4 |
+
|
5 |
+
r u o b a l f o e g a t s d n o c e
|
6 |
+
|
7 |
+
S
|
8 |
+
|
9 |
+
Delivery
|
10 |
+
|
11 |
+
r u o b a l f o e g a t s d r i h T
|
12 |
+
|
13 |
+
placenta
|
14 |
+
|
15 |
+
5. Observation for signs of
|
16 |
+
|
17 |
+
o Haemorrhage
|
18 |
+
|
19 |
+
o Utrine fundal level
|
20 |
+
|
21 |
+
o Evidence of collapse
|
22 |
+
|
23 |
+
o Respiratory difficulty
|
24 |
+
|
25 |
+
o Unusual behaviouror
|
26 |
+
|
27 |
+
m u t r a p - t s o P
|
28 |
+
|
29 |
+
Monitoring
|
30 |
+
|
31 |
+
Mother should be closely monitored in the labour room for at least two hours
|
32 |
+
|
33 |
+
o Abdominal pain
|
34 |
+
|
35 |
+
Sri Lanka College of Obstetrics and Gynaecology Health sector development Project Guidelines- Management of Uncomplicated labour
|
src/processed_markdown/Management-of-thrombocytopaenia-in-pregnancy-Sept-5/Management-of-thrombocytopaenia-in-pregnancy-Sept-5.md
ADDED
@@ -0,0 +1,463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---\n\ncitation: "Management of thrombocytopaenia in pregnancy Sept 5"\n\n---\n\nSLCOG Guideline
|
2 |
+
|
3 |
+
SLCOG Guideline
|
4 |
+
|
5 |
+
Management of thrombocytopaenia in pregnancy
|
6 |
+
|
7 |
+
D L W Dasanayakea, Y Costab, A Weerawardana c on behalf of Sri Lanka College of Obstetricians and Gynaecologists
|
8 |
+
|
9 |
+
Correspondence: Sri Lanka College of Obstetricians and Gynaecologists, No. 112, Model Farm Road, Colombo 08. E-mail: [email protected]
|
10 |
+
|
11 |
+
1. Scope and background
|
12 |
+
|
13 |
+
This guideline aims to describe the diagnostic approach to investigating thrombocytopaenia found in pregnancy, followed by a brief discussion on managing specific causes of thrombocytopaenia. This provides evidence- based information to health professionals to formulate a rational care pathway.
|
14 |
+
|
15 |
+
A platelet count of less than 150×109/L is defined as thrombocytopenia. Maternal thrombocytopaenia is in most cases mild and has no adverse outcome for both mother and fetus. Rarely a platelet count may be the presenting feature of a significant disorder with life threatening complications. Therefore management of thrombocytopaenia during pregnancy is challenging in both diagnostic as well as management of delivery.
|
16 |
+
|
17 |
+
2. Summary of key recommendations 2.1 Initial assessment\n\n2.2 Diagnosis of specific causes for thrombo- cytopaenia
|
18 |
+
|
19 |
+
A multidisciplinary approach with the haematologist and the obstetrician is required for optimal care.
|
20 |
+
|
21 |
+
If thrombocytopenia is confirmed, careful history, examination and laboratory workup is essential for the diagnosis.
|
22 |
+
|
23 |
+
A blood picture examination is vital to find the cause for thrombocytopenia. Microangiopathic hemolytic anaemia (MAHA) in the blood picture, which is a hemolytic process with red cell fragmentation and thrombocytopenia, can be associated with severe Preeclampsia(PE), HELLP syndrome, TTP (Throm- botic Thrombocytopaenic Purpura), aHUS (atypical Haemolytic Uraemic Syndrome), AFLP(Acute Fatty Liver in Pregnancy) and Disseminated Intravascular Coagulation (DIC).
|
24 |
+
|
25 |
+
A platelet count below 150×109/L should warrant assessment for thrombocytopaenia during pregnancy. Errors during blood collection and automated haematology analysis may yield falsely low values. Hence low platelet counts should be reconfirmed with a repeat Full Blood Count (FBC) and a request for a manual platelet count.
|
26 |
+
|
27 |
+
To differentiate between above conditions apart from a good clinical assessment, serum creatinine, lactate dehydrogenase (LDH), Prothrombin Time (PT), Activated Partial Thromboplastin Time (APPT), liver function tests (bilirubin direct/ indirect, albumin, total protein, transferases, and alkaline phosphatase) and ultrasound scan of abdomen are required.
|
28 |
+
|
29 |
+
Sri Lanka Journal of Obstetrics and Gynaecology 2021; 43: 259-268
|
30 |
+
|
31 |
+
DOI: http://doi.org/10.4038/sljog.v43i3.8020
|
32 |
+
|
33 |
+
a Consultant Obstetrician and Gynaecologist, Mahamodara Teaching Hospital, Galle, Sri Lanka
|
34 |
+
|
35 |
+
b Consultant Haematologist, Colombo North Teaching Hospital, Ragama, Sri Lanka
|
36 |
+
|
37 |
+
c Consultant Haematologist, De Zoysa Maternity Hospiatl for Women, Colombo, Sri Lanka
|
38 |
+
|
39 |
+
Vol. 43, No. 3, September 2021
|
40 |
+
|
41 |
+
259
|
42 |
+
|
43 |
+
SLCOG Guideline
|
44 |
+
|
45 |
+
Gestational Thrombocytopaenia (GT) is the most common reason for low platelets in pregnancy. It is a diagnosis of exclusion. GT commonly develops in the latter half of the pregnancy, and the platelet count is usually above 70×109/L. The diagnosis of GT is less likely if the platelet count falls below 70×109/L.
|
46 |
+
|
47 |
+
Incidence of Immune-Thrombocytopaenic Purpura (ITP) is approximately in 1/1000-1/10 000 pregnancies. It is the commonest cause of a low platelet count presenting in the first and second trimesters.
|
48 |
+
|
49 |
+
PE is the most common cause of thrombocytopenia associated with MAHA presenting in the late second or the third trimester of pregnancy. Infrequently, it may appear during the first week postpartum.
|
50 |
+
|
51 |
+
HELLP syndrome may be a variant of PE characterized by more severe thrombocytopenia, more fulminant MAHA and profoundly elevated liver function tests.
|
52 |
+
|
53 |
+
Even though it is rare, microangiopathies such as TTP, aHUS and AFLP should be carefully looked into when the woman presents with acute clinical features.
|
54 |
+
|
55 |
+
Patients with Antiphospholipid Syndrome (APLS) and Systemic Lupus Erythematosus (SLE) may also present with thrombocytopenia.
|
56 |
+
|
57 |
+
Antinuclear Antibodies (ANA), thyroid function test, antiphospholipid antibodies and viral screening should be considered if clinically indicated.\n\n2.3 Management of GT
|
58 |
+
|
59 |
+
Antenatal platelet count should be monitored every 2 to 4 weeks.
|
60 |
+
|
61 |
+
No special management is required.
|
62 |
+
|
63 |
+
When the platelet count is less than 100×109/L, the woman should be referred to an anaesthetist prior to delivery.
|
64 |
+
|
65 |
+
GT is not associated with neonatal thrombocytopenia.
|
66 |
+
|
67 |
+
2.4 Management of ITP in pregnancy
|
68 |
+
|
69 |
+
In ITP, a multidisciplinary approach involving the obstetrician, haematologist, anaesthetist, transfusion physician and neonatologist are required for optimal care.
|
70 |
+
|
71 |
+
260
|
72 |
+
|
73 |
+
FBC should be monitored at 2-4 weeks intervals or more frequently if indicated.
|
74 |
+
|
75 |
+
If the platelet count is less than 30×109/L or bleeding manifestations are present, first-line therapy is oral corticosteroids, and if a rapid platelet increment is required as in impending delivery or significant blee- ding, intravenous immunoglobulin (IVIg) should be administered.
|
76 |
+
|
77 |
+
Treatment to increase the platelet count for delivery is initiated by 36 weeks or earlier if early delivery is planned.
|
78 |
+
|
79 |
+
Delivery should be planned in a setting where 24 hours blood bank facilities and ICU care are available.
|
80 |
+
|
81 |
+
The obstetric team should liaise with the haematologist, the transfusion physician and the anaesthetist when planning delivery.
|
82 |
+
|
83 |
+
Platelets count of at least 50×109 /L should be obtained for safe delivery.
|
84 |
+
|
85 |
+
If platelet count of less than 50×109/L, platelet concentrate should be available on-site for transfusion if necessary.
|
86 |
+
|
87 |
+
Caesarean delivery is reserved for obstetric indications only.
|
88 |
+
|
89 |
+
At a platelet count of ≥ 80×109/L, in the absence of other hemostatic abnormalities, regional anaesthesia can be performed.
|
90 |
+
|
91 |
+
IgG antibodies in ITP are known to cross the placenta, causing thrombocytopenia in the fetus and neonate. The occurrence of intracranial haemorrhage (ICH) is a major neonatal concern. Measures should be taken to avoid traumatic delivery to the baby and the mother during delivery. Scalp electrodes, fetal blood sampling, vacuum and difficult forceps delivery should be avoided. If instrumental delivery is indicated, forceps is the choice.
|
92 |
+
|
93 |
+
Prophylactic measures should be taken to prevent Postpartum Haemorrhage (PPH), which includes active management of the third stage of labour, oxytocin infusion and intravenous tranexamic acid.
|
94 |
+
|
95 |
+
Pregnant women who are on long term steroids should have regular blood sugar monitoring with PPBS and blood pressure monitoring.
|
96 |
+
|
97 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
98 |
+
|
99 |
+
Non-Steroidal Anti-Inflammatory drugs (NSAIDs) should be avoided for postpartum or postoperative analgesia in women with thrombocytopenia due to increased hemorrhagic risk.\n\n2.5 Management of thrombocytopaenia due to PE, HELLP syndrome and AFLP
|
100 |
+
|
101 |
+
Urgent delivery should be arranged as it is the mainstay of treatment.
|
102 |
+
|
103 |
+
Maternal corticosteroids should be administered considering fetal maturity to reduce fetal respiratory morbidity.
|
104 |
+
|
105 |
+
If DIC present, supportive care with FFP, platelet and cryoprecipitate should be administered with advice from the haematologist.
|
106 |
+
|
107 |
+
2.6 Management of thrombotic thrombo- cytopaenic purpura/atypical hemolytic uraemic
|
108 |
+
|
109 |
+
syndrome
|
110 |
+
|
111 |
+
Despite the diagnostic challenge, plasma exchange (plasmapheresis) needs to be commenced as soon as TTP/aHUS is suspected. Management requires a multidisciplinary approach with the transfusion physician, the obstetrician and the haematologist. Plasma transfusions should be given if there is any delay in plasmapheresis.
|
112 |
+
|
113 |
+
In TTP, plasmapheresis should continue daily until the platelet count is maintained in the normal range (>150×109/L) for a minimum of 2 days.
|
114 |
+
|
115 |
+
Platelet transfusions are contraindicated as they are known to precipitate or exacerbate thrombosis.
|
116 |
+
|
117 |
+
3. Introduction
|
118 |
+
|
119 |
+
Thrombocytopenia is a common haematological condition affecting 7-10% of the pregnant population1. It occurs four times more frequently in pregnancy than in non-pregnant women and is the second leading cause of blood disorders in pregnancy after anaemia2. Thrombocytopaenia is defined as a platelet count of less than 150×109/L.
|
120 |
+
|
121 |
+
GT accounts for 70-80% of all cases of thrombo- cytopaenia in pregnancy. Hypertensive disorders explain approximately 20% of thrombocytopenia, and immune thrombocytopenia accounts for about 3-4%.
|
122 |
+
|
123 |
+
Vol. 43, No. 3, September 2021
|
124 |
+
|
125 |
+
SLCOG Guideline
|
126 |
+
|
127 |
+
Other etiologies such as TTP and HUS are considered rare in pregnancy but carry high morbidity and mortality for both the mother and fetus3.
|
128 |
+
|
129 |
+
4. Recommendations and discussion\n\n4.1 Initial assessment
|
130 |
+
|
131 |
+
A platelet count below 150×109/L should warrant assessment for thrombocytopaenia during pregnancy. Errors during blood collection and automated haematology analysis may yield falsely low values. Hence low platelet counts should be reconfirmed with a repeat FBC and a request for a manual platelet count. All new patients presenting with thrombocytopenia need reconfirmation of the low platelet number with a repeat FBC and a manual platelet count. The repeat FBCsample should be taken from a direct, uncom- plicated venipuncture and added into an EDTA tube and mixed well. This will prevent minute clot formation in the sample leading to erroneously low platelet values. Assessing the manual platelet count will exclude any errors in automated platelet analysis.
|
132 |
+
|
133 |
+
If large platelet aggregates are detected in the blood smear taken from an EDTA sample with thrombo- cytopenia reported in the automated FBC results, it is considered as EDTA induced pseudo thrombocytopenia. If it is necessary to obtain the accurate platelet number, blood should be collected into acitrated tube and sent to the laboratory for analysis within 15 minutes of collection. As the platelets can undergo deterioration in a citrated sample, immediate analysis is vital, and the laboratory should be informed of the procedure before collecting blood from the patient to a citrated sample. When thrombocytopenia is confirmed, careful history, examination, and laboratory workup are needed to arrive at a diagnosis.
|
134 |
+
|
135 |
+
History should include.
|
136 |
+
|
137 |
+
• recent history of fever (to exclude viral infections such as dengue fever)
|
138 |
+
|
139 |
+
• the presence of severe headaches and other neurological manifestations (seen in PE and TTP)
|
140 |
+
|
141 |
+
• past history of thrombocytopenia (favouring ITP)
|
142 |
+
|
143 |
+
• symptomatic anaemia and recurrent infections (bone marrow failure/haematological malignancy)
|
144 |
+
|
145 |
+
• past history of pregnancy-associated thrombo- cytopenia
|
146 |
+
|
147 |
+
• history of connective tissue disorders (SLE and APLS)
|
148 |
+
|
149 |
+
261
|
150 |
+
|
151 |
+
SLCOG Guideline
|
152 |
+
|
153 |
+
• hypothyroidism
|
154 |
+
|
155 |
+
• liver disease
|
156 |
+
|
157 |
+
• drug history
|
158 |
+
|
159 |
+
• past and family history of bleeding disorders (rare inherited bleeding disorders such as type IIB Von Willebrand disease).
|
160 |
+
|
161 |
+
On examination, it is uncommon to detect bleeding manifestations unless the platelet count is significantly low. It is vital to check the blood pressure (PE, HELLP syndrome), abdominal tenderness (PET, HELLP syn- drome, AFLP), anaemia, lymphadenopathy, hepatos- plenomegaly (haematological malignancy) and neurological manifestations (severe PE, TTP).
|
162 |
+
|
163 |
+
Reduction of serum platelet counts is arbitrarily considered mild if the count is <150×109/L, moderate at 50-100×109/L and severe at <50×109/L.\n\n4.2 Diagnosis of specific causes for thrombo- cytopaenia
|
164 |
+
|
165 |
+
A multidisciplinary approach with the haematologist and the obstetrician is required for optimal care.
|
166 |
+
|
167 |
+
If thrombocytopenia is confirmed, careful history, examination and laboratory workup is essential for the diagnosis.
|
168 |
+
|
169 |
+
A blood picture examination is vital to find the cause for thrombocytopenia. MAHA in the blood picture, a hemolytic process with red cell fragmentation and thrombocytopenia, can be associated with severe PE, HELLP syndrome, TTP, aHUS, AFLP and DIC4.
|
170 |
+
|
171 |
+
To differentiate between above conditions apart from a good clinical assessment, serum creatinine, lactate dehydrogenase (LDH), Prothrombin Time (PT), Activated Partial Thromboplastin Time (APPT), liver function tests (bilirubin direct/ indirect, albumin, total protein, transferases, and alkaline phosphatase) and ultrasound scan abdomen are required.
|
172 |
+
|
173 |
+
GT is the most common reason for low platelets in pregnancy5. It is a diagnosis of exclusion. GT commonly develops in the latter half of the pregnancy, and the platelet count is usually above 70×109/L. The diagnosis of GT is less likely if the platelet count falls below 70×109/L.\n\n262
|
174 |
+
|
175 |
+
The incidence of ITP is approximately in 1/1000- 1/10 000 pregnancies. It is the commonest cause of a low platelet count presenting in the first and second trimesters6.
|
176 |
+
|
177 |
+
PE is the most common cause of thrombocytopenia associated with MAHA presenting in the late second or third trimester of pregnancy. Infrequently, it may appear during the first week postpartum7.
|
178 |
+
|
179 |
+
HELLP syndrome may be a variant of PE characterized by more severe thrombocytopenia, more fulminant MAHA and profoundly elevated liver function tests5. Even though it is rare, microangiopathies such as TTP, aHUS and AFLP should be carefully looked into when the woman presents with acute clinical features.
|
180 |
+
|
181 |
+
Patients with APLS and SLE may also present with thrombocytopenia.
|
182 |
+
|
183 |
+
ANA, thyroid function test, antiphospholipid antibodies and viral screening should be considered if clinically indicated.
|
184 |
+
|
185 |
+
GT is a condition with mild to moderate platelet drop and is a diagnosis of exclusion. The platelet count in GT is usually above 70×109/L. The patient is asymp- tomatic, and thrombocytopenia is commonly detected in the second half of pregnancy. The platelet count spontaneously reverts to normal within the first two months of postpartum but can recur in subsequent pregnancies.
|
186 |
+
|
187 |
+
The incidence of ITP is approximately in 1/1000-1/10 000 pregnancies. It is the commonest cause of a low platelet count presenting in the first and second trimesters6. Despite improved understanding of the pathophysiology, there is no specific diagnostic test, and, like GT, it is a diagnosis of exclusion. The presence of other autoimmune phenomena or a low platelet count during pre-pregnancy can help to diagnose.
|
188 |
+
|
189 |
+
Thrombocytopaenia associated with hypertensive disorders is the most frequent causes in the late second trimester onwards8.Therefore PE screening should be carried out to rule out hypertensive variants (HELLP, AFLP).
|
190 |
+
|
191 |
+
HELLP syndrome, which affects 0.6% of pregnant women, is a severe variant of pre-eclampsia. However, in 15-20% of cases of HELLP syndrome, neither hypertension nor proteinuria is present9.
|
192 |
+
|
193 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
194 |
+
|
195 |
+
AFLP occurs in 1 in 5000 to 10 000 pregnancies and is more common with multiple gestations than in singletons. Up to 75% of women present with nausea or vomiting, and 50% have abdominal pain or signs and symptoms similar to PE. Although it is often difficult to differentiate HELLP from AFLP, evidence of hepatic insufficiency, including hypoglycemia, DIC, or encephalopathy, is seen more often in AFLP5.
|
196 |
+
|
197 |
+
TTP is an acute life-threatening disorder associated
|
198 |
+
|
199 |
+
with thrombocytopenia, MAHA and microvascular thrombosis. It results from a deficiency of the enzymeADAMTS13, required to cleave secreted ultra- large von Willebrand factor molecules (ULVWF). An inherited deficiency or acquired reduction of ADAMTS13 due to IgG autoantibodies to ADAMTS13 leads to persistence of ULVWF molecules resulting in abnormal platelet aggregation and microvascular thrombosis. Pregnancy is an important precipitant of acute TTP, accounting for approximately 5-10% of all cases of TTP in women4. TTP classically consists of a pentad of thrombocytopenia, MAHA, neurological signs, renal impairment and fever. However, TTP commonly presents without the full spectrum of the pentad. Laboratory features indicating a diagnosis of TTP are MAHA with many schistocytes in the blood picture, increased Lactate dehydrogenase (LDH), which is often out of proportion to the degree of haemolysis due to associated tissue ischemia, normal PT/APTT and possibly elevated serum creatinine
|
200 |
+
|
201 |
+
level10.
|
202 |
+
|
203 |
+
aHUS is a rare MAHA associated with pregnancy. The majority of cases occur during the postpartum period. The patient has MAHA, thrombocytopenia and severe renal impairment. The outcome is severe, with two- thirds of cases developing end-stage renal failure within one month4.\n\n4.3 Management of GT
|
204 |
+
|
205 |
+
Antenatal platelet count should be monitored every 2 to 4 weeks.
|
206 |
+
|
207 |
+
No special management is required.
|
208 |
+
|
209 |
+
When the platelet count is less than 100×109/L, the woman should be referred to an anaesthetist prior to delivery.
|
210 |
+
|
211 |
+
GT is not associated with neonatal thrombocytopenia.
|
212 |
+
|
213 |
+
Vol. 43, No. 3, September 2021
|
214 |
+
|
215 |
+
SLCOG Guideline
|
216 |
+
|
217 |
+
GT does not require treatment except periodic moni- toring of platelet count. The thrombocytopenia resolves spontaneously. If the thrombocytopenia persists beyond 6 to 8 weeks, the patient should undergo further haematological investigations.\n\n4.4 Management of ITP in pregnancy
|
218 |
+
|
219 |
+
In ITP, a multidisciplinary approach involving the obstetrician, haematologist, anaesthetist, transfusion physician and neonatologist, is required for optimal care.
|
220 |
+
|
221 |
+
FBC should be monitored at 2-4 weeks intervals or more frequently if indicated.
|
222 |
+
|
223 |
+
If the platelet count is less than 30 ×109/L or bleeding manifestations are present, first-line therapy is oral corticosteroids, and if a rapid platelet increment is required as in impending delivery or significant bleeding, IVIg should be given.
|
224 |
+
|
225 |
+
Treatment to increase the platelet count for delivery is initiated by 36 weeks or earlier if early delivery is planned.
|
226 |
+
|
227 |
+
Delivery should be planned in a setting where 24 hours blood bank facilities and ICU care are available.
|
228 |
+
|
229 |
+
The obstetric team should liaise with the haematologist, the transfusion physician and the anaesthetist when planning delivery.
|
230 |
+
|
231 |
+
Platelets count of at least 50×109 /L should be obtained for safe delivery.
|
232 |
+
|
233 |
+
If platelet count of less than 50×109/L, platelet concentrate should be available on-site for transfusion if necessary.
|
234 |
+
|
235 |
+
Caesarean delivery is reserved for obstetric indications only.
|
236 |
+
|
237 |
+
At a platelet count ≥ 80×109/L, regional anaesthesia can be performed in the absence of other hemostatic abnormalities.
|
238 |
+
|
239 |
+
IgG antibodies in ITP are known to cross the placenta, causing thrombocytopenia in the fetus and neonate. The occurrence of intracranial haemorrhage (ICH) is a major neonatal concern. Measures should be taken to avoid traumatic delivery to the baby and the mother
|
240 |
+
|
241 |
+
263
|
242 |
+
|
243 |
+
SLCOG Guideline
|
244 |
+
|
245 |
+
during delivery. Scalp electrodes, fetal blood sampling, vacuum and difficult forceps delivery should be avoided. If instrumental delivery is indicated, forceps is the choice.
|
246 |
+
|
247 |
+
Prophylactic measures should be taken to prevent Postpartum Haemorrhage (PPH), which includes active management of the third stage of labour, oxytocin infusion and intravenous tranexamic acid.
|
248 |
+
|
249 |
+
Pregnant women who are on long term steroids should have regular blood sugar monitoring with PPBS and blood pressure monitoring.
|
250 |
+
|
251 |
+
Non-Steroidal Anti-Inflammatory drugs (NSAIDs) should be avoided for postpartum or postoperative analgesia in women with thrombocytopenia due to increased hemorrhagic risk.
|
252 |
+
|
253 |
+
In ITP, a multidisciplinary approach involving the obstetrician, haematologist, transfusion physician, anaesthetist and neonatologist, is required for optimal care.
|
254 |
+
|
255 |
+
Women with no bleeding manifestations and platelet counts above 30×109/L do not require any treatment until 36 weeks gestation9.
|
256 |
+
|
257 |
+
If the platelet count is <30×109/L or bleeding mani- festations are present, first-line therapy is oral corticosteroids 0.25-1mg/kg daily (dose to be adjusted to achieve a safe platelet count) or if a rapid platelet increment is required as in impending delivery or significant bleeding, IVIg 1g/kg9.
|
258 |
+
|
259 |
+
IVIg has a relatively rapid therapeutic response (within 1-3 days). Prednisolone shows a therapeutic response within 2-14 days11.
|
260 |
+
|
261 |
+
Current recommendations aim for a platelet count of ≥ 50×109/L prior to labour and delivery as the risk of cesarean delivery is present with everylabour9.
|
262 |
+
|
263 |
+
For spinal anaesthesia, the British Committee for Haematology and Anaesthetic Guideline standards recommends a threshold of >80×1012,13. An anaesthetic consultation in the third trimester to discuss options for delivery is required.
|
264 |
+
|
265 |
+
While platelet transfusion alone is generally not effective in ITP, if an adequate platelet count has not been achieved and delivery is emergent, or if there is blee-\n\n264
|
266 |
+
|
267 |
+
ding, platelet transfusion in conjunction with IVIg can be considered9.
|
268 |
+
|
269 |
+
After delivery, close monitoring of the neonate is required as 21% to 28% will develop thrombocytopenia presumably from passive transfer of maternal auto- antibodies (IgG) against platelet antigens13. Less than 1% of neonates develop intracranial hemorrhage14. Risk for thrombocytopenia is increased if siblings had thrombocytopenia at delivery. Maternal platelet count during pregnancy does not impact the risk of thrombocytopenia in the neonate15. The mode of delivery is determined by the obstetric indications, with avoidance of procedures associated with an increased haemorrhagic risk to the fetus, such as fetal scalp electrode/fetal blood sampling and operative vaginal delivery14. A cord blood sample should be taken to check neonatal platelet count. Intramuscular injection of vitamin K should not be given if the platelet count is not available, but intravenous or subcutaneous vitamin K can be administered.
|
270 |
+
|
271 |
+
4.5 Management of thrombocytopaenia due to Pre-eclampsia/HELLP/AFLP
|
272 |
+
|
273 |
+
Urgent delivery should be arranged as it is the mainstay of treatment.
|
274 |
+
|
275 |
+
Maternal corticosteroids should be administered considering fetal maturity to reduce fetal respiratory morbidity.
|
276 |
+
|
277 |
+
If DIC present, supportive care with FFP, platelet and cryoprecipitate should be administered with advice from the haematologist.
|
278 |
+
|
279 |
+
PET affects 4% of all first pregnancies16. Thrombo- cytopenia is the commonest abnormality, occurring in up to 50% of women with pre-eclampsia. HELLP syndrome is a serious complication specific to preg- nancy characterized by haemolysis, elevated liver enzymes, and low platelets. It occurs in about 0.5- 0.9% of pregnancies and 10-20% of cases with severe pre-eclampsia17. As delivery is the definitive mode of treatment for maternal concerns, steroid should be administered for fetal lung maturity. Supportive care with the correction of clotting derangement following delivery should be arranged. Careful observation is needed to detect DIC as a complication in 20% of women with HELLP syndrome18. AFLP treatment consists of supportive management and resuscitation of the mother and prompt delivery of the fetus, irres- pective of the gestational age.
|
280 |
+
|
281 |
+
Sri Lanka Journal of Obstetrics and Gynaecology\n\n4.6 Management of thrombotic thrombo- cytopaenic purpura and atypical haemolytic uraemic syndrome
|
282 |
+
|
283 |
+
Despite the diagnostic challenge, plasma exchange (plasmapheresis) needs to be commenced as soon as TTP/aHUS is suspected. Management requires a multidisciplinary approach with the transfusion physician, the obstetrician and the haematologist. Plasma transfusions should be given if there is any delay in plasmapheresis.
|
284 |
+
|
285 |
+
In TTP, plasmapheresis should continue daily until the platelet count is maintained in the normal range (>150×109/L)for a minimum of 2 days.
|
286 |
+
|
287 |
+
Platelet transfusions are contraindicated as they are known to precipitate or exacerbate thrombosis.
|
288 |
+
|
289 |
+
Plasmapheresis is the first-line therapy in TTP and aHUS. Plasmapheresis removes substances promoting platelet-aggregation and is successful with TTP but is less successful with HUS. Plasma infusion should be considered if there is any delay in plasmapheresis.
|
290 |
+
|
291 |
+
Clinical governance
|
292 |
+
|
293 |
+
According to the national recommendation, all pregnant women should have a FBC at booking and repeated at 26 to 28 weeks of gestation. Haemoglobin and platelet count should be recorded in maternity notes.\n\nReferences
|
294 |
+
|
295 |
+
1. Verdy E, Bessous V, Dreyfus M, Kaplan C, Tchernia G, Uzan S. Longitudinal analysis of platelet count and volume in normal pregnancy. Thrombosis and Haemostasis 1997; 77: 806-7.
|
296 |
+
|
297 |
+
2. Gernsheimer T, James AH, Stasi R. How I treat thrombocytopenia in pregnancy blood 2013; 121(1): 38-47.
|
298 |
+
|
299 |
+
3. Burrows RF, Kelton JG. Thrombocytopenia at delivery: a prospective survey of 6715 deliveries. American Journal of Obstetrics and Gynecology 1990; 162: 732-4.
|
300 |
+
|
301 |
+
4. Mari R. Thomas, Susan Robinson, Marie A. Scully: How we manage thrombotic microangiopathies in pregnancy: British Journal of Haematology 2016; (173): 821-30.
|
302 |
+
|
303 |
+
5. Douglas B. Cines, Lisa D. Levine: Thrombo- cytopenia in pregnancy: Blood 2017; 130(21): 2271-7.
|
304 |
+
|
305 |
+
6. Gill KK, KeltonJG Management of idiopathic
|
306 |
+
|
307 |
+
Vol. 43, No. 3, September 2021
|
308 |
+
|
309 |
+
SLCOG Guideline
|
310 |
+
|
311 |
+
thrombocytopenic purpura in pregnancy, Semin Hematol. 2000; 37(3): 275-89.
|
312 |
+
|
313 |
+
7. Terry Gernsheimer, Andra H. James,Roberto Stasi: How I treat thrombocytopenia in pregnancy: Blood 2013; 12(1): 38-47.
|
314 |
+
|
315 |
+
8. Provan D and et al. International consensus report on the investigation and management of primary immune thrombocytopenia. Blood 2010; 115(2): 168-86.
|
316 |
+
|
317 |
+
9. Rajasekhar A, Gernsheimer T, Stasi R, James AH. Clinical Practice Guide on Thrombocytopenia in Pregnancy. American Society of Hematology. Available at http://www.hematology.org/Clinicians/ Guidelines-Quality/Quick-Reference.aspx. 2013; Accessed on 14.04.2021.
|
318 |
+
|
319 |
+
10. Scully M, Hunt BJ, Benjamin S, Liesner R, Rose P, Peyvandi F, Cheung B, Machin SJ; British Committee for Standards in Haematology. Guidelines on the diagnosis and management of thrombotic thrombocytopenic purpura and other thrombotic microangiopathies. Br J Haematol 2012; 158(3): 323-35.
|
320 |
+
|
321 |
+
11. Ciobanu AM, Colibaba S, Cimpoca B, Peltecu G, Panaitescu AM. Thrombocytopenia in Pregnancy. Maedica (Bucur) 2016; 11(1): 55-60.
|
322 |
+
|
323 |
+
12. Gill KK, Kelton JG. Management of idiopathic thrombocytopenic purpura in pregnancy. Semin Hematol. 2000; 37(3): 275-89.
|
324 |
+
|
325 |
+
13. Eslick R, McLintock C. Managing ITP and thrombocytopenia in pregnancy. Platelets 2020; 31: 300-6.
|
326 |
+
|
327 |
+
14. Provan D, Arnold DM, Bussel JB, et al. Updated international consensus report on the investigation and management of primary immune thrombo- cytopenia. Blood Adv 2019; 3(22): 3780-817.
|
328 |
+
|
329 |
+
15. Payne SD, Resnik R, Moore TR, et al. Maternal characteristics and risk of severe neonatal thrombo- cytopenia and intracranial hemorrhage in preg- nancies complicated by autoimmune thrombo- cytopenia. Am J Obstet Gynecol 1997; 177: 149-55.
|
330 |
+
|
331 |
+
16. HernÃindez-DÃaz S, Toh S, Cnattingius S. Risk of pre-eclampsia in first and subsequent pregnancies: prospective cohort study BMJ 2009; 338: b2255 doi:10.1136/BMJ.b2255, assessed on 14.04.2021. Thrombosis and Haemostasis,1997; 77: 806- 807.
|
332 |
+
|
333 |
+
17. Kirkpatrick CA. The HELLP syndrome. ActaClin Belg. 2010; 65(2): 91-7.
|
334 |
+
|
335 |
+
18. Martin JN Jr, Rinehart BK, May WL, Magann EF, Terrone DA, Blake PG. The spectrum of severe pre-eclampsia: comparative analysis by HELLP (hemolysis, elevated liver enzyme levels, and low platelet count) syndrome classification. Am J Obstet Gynecol. 1999; 180(6 Pt 1): 1373-84.
|
336 |
+
|
337 |
+
265
|
338 |
+
|
339 |
+
SLCOG Guideline\n\nAppendix
|
340 |
+
|
341 |
+
Etiological workup
|
342 |
+
|
343 |
+
Diagnosis Gestational Thrombocytopenia Immune Thrombocytopenic Purpura (ITP) Thrombotic Thrombocytopenic Purpura (TTP) Atypical Haemolytic Uraemic Syndrome (aHUS) Pre-eclampsia, Eclampsia, Haemolysis, Elevated liver enzymes and low platelet count syndrome (HELLP) Hereditary thrombocytopenia Pseudo thrombocytopenia Viral infections: HIV, Epstein-Barr virus Medications: heparin-induced Leukaemia/Lymphoma Severe Vitamin B12 or Folate Deficiency Splenomegaly Proportion Pathophysiology About 75% Physiological dilution, accelerated destruction About 3% Immune destruction, suppressed production Peripheral consumption, microthrombi Peripheral consumption, microthrombi About 15-20% Peripheral consumption, microthrombi Bone marrow underproduction Laboratory artefact Secondary autoimmune thrombocytopenia, Marrow suppression Immunological reaction Failure of platelet production, bone marrow infiltration Failure of platelet production Splenic sequestration
|
344 |
+
|
345 |
+
266
|
346 |
+
|
347 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
348 |
+
|
349 |
+
SLCOG Guideline
|
350 |
+
|
351 |
+
Initial detection of a pregnant woman with thrombocytopenia. Confirm thrombo- cytopenia with repeat FBC and manual platelet count
|
352 |
+
|
353 |
+
!
|
354 |
+
|
355 |
+
Thrombocytopenia confirmed Good clinical assessment Blood picture and haematology referral
|
356 |
+
|
357 |
+
"A
|
358 |
+
|
359 |
+
MAHA absent in blood picture
|
360 |
+
|
361 |
+
LFT, ANA,TSH, Viralstudies, US scan abdomen, DAT, PT/APTT
|
362 |
+
|
363 |
+
If underlying pathology detected treat the cause
|
364 |
+
|
365 |
+
}
|
366 |
+
|
367 |
+
Monitor counts, Regular haematological review, Steroids, Anticoagulation
|
368 |
+
|
369 |
+
MAHA present in the blood picture LFT, PET screening, LDH, PT/APTT, Creatinine, US scan abdomen, RBS
|
370 |
+
|
371 |
+
|
|
372 |
+
|
373 |
+
Severe PET, HELLP, AFLP Stabilize the mother
|
374 |
+
|
375 |
+
TTP, aHUS Plasmapheresis, Deliver the baby
|
376 |
+
|
377 |
+
If the platelet count less than 70×109/L with no identifiable cause, ITP should be considered
|
378 |
+
|
379 |
+
• Monitor counts
|
380 |
+
|
381 |
+
• Avoid NSAIDs /Aspirin
|
382 |
+
|
383 |
+
• Treatment to elevate count if bleeding or platelet less than 30×109/L
|
384 |
+
|
385 |
+
• Take haematology advice regarding IM injections
|
386 |
+
|
387 |
+
• Elevate platelet count to 50×109/L for antenatal procedures
|
388 |
+
|
389 |
+
• At 35-36wk, treat to keep platelet count above 80×109/L to allow epidural anaesthesia and delivery
|
390 |
+
|
391 |
+
• Document the need to avoid traumatic delivery – avoid ventouse, forceps, scalp sampling, scalp electrodes
|
392 |
+
|
393 |
+
•
|
394 |
+
|
395 |
+
Inform neonatologist – paediatric alert to be sent
|
396 |
+
|
397 |
+
• Cord blood for neonatal platele count, if less than normal-monitor for thrombocytopenia, nadir 3-5 days
|
398 |
+
|
399 |
+
Vol. 43, No. 3, September 2021
|
400 |
+
|
401 |
+
267
|
402 |
+
|
403 |
+
SLCOG Guideline
|
404 |
+
|
405 |
+
1. New presentation of thrombocytopenia in 1st / 2nd trimester: Check for: drugs: pre-pregnancy FBC: medical disorder; auto-immune phenomena: renal/liver functions
|
406 |
+
|
407 |
+
2. Presentation of patient with known platelet disorder Platelet count >100×109/l
|
408 |
+
|
409 |
+
Platelet count <80 - 100×109/l
|
410 |
+
|
411 |
+
In
|
412 |
+
|
413 |
+
|
|
414 |
+
|
415 |
+
In all cases exclude presence red cell fragments
|
416 |
+
|
417 |
+
indicating thrombotic microangiopathy
|
418 |
+
|
419 |
+
Monthly checks by midwife / GP
|
420 |
+
|
421 |
+
Refer back if platelet count
|
422 |
+
|
423 |
+
!
|
424 |
+
|
425 |
+
In 1/2" trimester low
|
426 |
+
|
427 |
+
platelet counts probabably secondary to immune
|
428 |
+
|
429 |
+
; 24/3" trimesters Anytime: Refer back if known ITP in 3" |) ?BP, Proteinuria Fever, . . neurological trimester TLFTs signs — Check maternal platelet count: *PET; HELLP ‘nereatinine A If <34 weeks: try . risk of low neonatal platelet count F Raise platelet count to : to stabilize. © Likely TTP — ensure measures to avoid wary K : ~>Plasmapheresis >50x10°/1 for ante-natal 22 WEEKS: procedures.
|
430 |
+
|
431 |
+
80-100 10°/1 bleeding
|
432 |
+
|
433 |
+
process.
|
434 |
+
|
435 |
+
Monitor monthly, treat if : bleeding or platelet count <20-30*10°/1
|
436 |
+
|
437 |
+
traumatic delivery and check cord platelet count
|
438 |
+
|
439 |
+
Advise avoidance of
|
440 |
+
|
441 |
+
NSAIDS, aspirin, IM injections.
|
442 |
+
|
443 |
+
Assess balance of risks.
|
444 |
+
|
445 |
+
Deliver when possible
|
446 |
+
|
447 |
+
From 35-36 weeks, aim to raise platelet count >80×109 /l if possible, to allow for epidural. May require combination of treatments
|
448 |
+
|
449 |
+
Monitor more frequently, depending on level, treatment and rate of change of platelet count\n\nDocument need for atraumatic delivery: advise avoid ventouse, rotational forceps, scalp clips/sampling Ensure paediatric alert sent
|
450 |
+
|
451 |
+
Take cord sample to assess neonatal platelet count. If < normal, needs monitoring over next few days – nadir is at 2-5 days
|
452 |
+
|
453 |
+
Safe levels of platelets for interventions
|
454 |
+
|
455 |
+
Intervention
|
456 |
+
|
457 |
+
Platelet count
|
458 |
+
|
459 |
+
Antenatal, no invasive procedures planned >20 Vaginal delivery >50 Operative or instrumental delivery >50 Epidural anaesthesia >80
|
460 |
+
|
461 |
+
268
|
462 |
+
|
463 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
src/processed_markdown/PROM/PROM.md
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---\n\ncitation: "PROM"\n\n---\n\nManagement of preterm rupture of membranes
|
2 |
+
|
3 |
+
PRESENTATION i. Sudden leakage of amniotic o Check for pooling of amniotic fluid fluid, which may be o Check for leakage of amniotic fluid from intermittent or continuous. ii. Feeling of wetness. sensation of inability to stop urination - HISTORY cervical os with coughing or fundal pressure o Perform speculum examination for evidence of cervical dilatation under strict aseptic conditions. o Perform ultrasonography for amniotic fluid EXAMINATION index IF PROM CONFIRMED IF PROM NOT CONFIRMED Discharge patient home after observing for 24 hours • Fetal heart tracing is normal • No evidence of Preterm labour Look for evidence of o Intra-amniotic infection o Non-reassuring fetal heart tracing o Abruption o Cord prolapse o Active labour. VOG decision. Depending on No Yes maturity & neonatal facilities To deliver Manage conservatively Send to unit with better neonatal facilities Management in specialist units 24 TO 31 WEEKS OF GESTATION • Administer corticosteroids • Administer Management depending on D o c u m e n t a t i o n M a n d a t o r y
|
4 |
+
|
5 |
+
antibiotics
|
6 |
+
|
7 |
+
• Deliver at 34
|
8 |
+
|
9 |
+
32 TO 34 WEEKS OF
|
10 |
+
|
11 |
+
GESTATION
|
12 |
+
|
13 |
+
the condition
|
14 |
+
|
15 |
+
weeks if lung
|
16 |
+
|
17 |
+
maturity is
|
18 |
+
|
19 |
+
• Administer
|
20 |
+
|
21 |
+
indicated by
|
22 |
+
|
23 |
+
amniocentesis(Z)
|
24 |
+
|
25 |
+
amniocentesis(Z)
|
26 |
+
|
27 |
+
corticosteroids
|
28 |
+
|
29 |
+
• Administer antibiotics
|
30 |
+
|
31 |
+
• Consider
|
32 |
+
|
33 |
+
amniocentesis(Z)
|
34 |
+
|
35 |
+
34 TO
|
36 |
+
|
37 |
+
36 WEEKS OF
|
38 |
+
|
39 |
+
GESTATION
|
40 |
+
|
41 |
+
• Administer antibiotics for
|
42 |
+
|
43 |
+
GBS prophylaxis
|
44 |
+
|
45 |
+
• Steroid therapy - optional
|
46 |
+
|
47 |
+
Ew
|
48 |
+
|
49 |
+
Send to unit with better neonatal
|
50 |
+
|
51 |
+
facilities when necessary
|
52 |
+
|
53 |
+
Delivery
|
54 |
+
|
55 |
+
Sri Lanka College of Obstetrics and Gynaecology Health sector development Project Guidelines- Management of preterm rupture of membranes
|
src/processed_markdown/Postnatal-care-during-hospital-stay-Sept-6/Postnatal-care-during-hospital-stay-Sept-6.md
ADDED
@@ -0,0 +1,387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---\n\ncitation: "Postnatal care during hospital stay Sept 6"\n\n---\n\nSLCOG Guideline
|
2 |
+
|
3 |
+
SLCOG Guideline
|
4 |
+
|
5 |
+
Postnatal care during hospital stay
|
6 |
+
|
7 |
+
D L W Dasanayakea on behalf of Sri Lanka College of Obstetricians and Gynaecologists
|
8 |
+
|
9 |
+
Correspondence: Sri Lanka College of Obstetricians and Gynaecologists, No. 112, Model Farm Road, Colombo 08. E-mail: [email protected]
|
10 |
+
|
11 |
+
1. Scope and background
|
12 |
+
|
13 |
+
2.2 Pain management
|
14 |
+
|
15 |
+
The purpose of this guideline is to describe the routine essential postnatal care during hospital stay and provide currently available best evidence to health care professionals to provide optimal care for postnatal mothers and newborns. This guideline also recom- mends management options depending on the resources available in the local setting. The guideline explains the postnatal care except management of psychological wellbeing as it is separately addressed by another guideline.
|
16 |
+
|
17 |
+
Immediate postpartum period is critical phase of the life for both mother and infant, setting the stage for an ongoing process of optimizing health and well-being. First 24 hours of delivery where both mother and baby within the facility will provide excellent opportunity for health professionals to initiate essential postnatal care for them and continue thereafter.
|
18 |
+
|
19 |
+
A stepwise approach using multi-model combination of agents should be prescribed.
|
20 |
+
|
21 |
+
Acetaminophen (Paracetamol) should be prescribed for perineal discomfort and pain following uncomplicated vaginal delivery.
|
22 |
+
|
23 |
+
Non-Steroidal Ante-Inflammatory Drugs (NSAID’s) such as diclofenac and ibuprofen with acetaminophen are relatively safe during postpartum period and should be prescribed for postnatal women with more severe pain.
|
24 |
+
|
25 |
+
When, a multimodal approach to analgesia using NSAID’s and acetaminophen given simultaneously on a set schedule is insufficient, a milder opioid (codeine) should be considered especially for caesarean delivery for enhanced recovery.
|
26 |
+
|
27 |
+
2. Summary of key recommendations 2.1 Immediate postpartum monitoring
|
28 |
+
|
29 |
+
Modified Obstetric Early Warning System (MOEWS) should be used to monitor vital para- meters to recognize early abnormalities of postnatal women.
|
30 |
+
|
31 |
+
Monitoring with MOEWS chart should be continued for two hours for vaginal delivery and four hours for caesarean delivery.
|
32 |
+
|
33 |
+
When caesarean delivery is conducted following general anaesthesia or when intrathecal long acting opioids are not used for spinal anaesthesia, Transversus Abdominis Plane field block (TAP block) should be considered as it provides excellent postoperative pain control and improves postoperative analgesia.
|
34 |
+
|
35 |
+
Stronger opioid analgesics (morphine, diamorphine and pethidine) are best reserved for women with inadequate pain control with sufficient doses of multimodal approach.
|
36 |
+
|
37 |
+
Drowsiness from opioids use can be interfered with maternal activities and breast feeding.
|
38 |
+
|
39 |
+
Sri Lanka Journal of Obstetrics and Gynaecology 2021; 43: 269-276
|
40 |
+
|
41 |
+
DOI: http://doi.org/10.4038/sljog.v43i3.8021
|
42 |
+
|
43 |
+
a Consultant Obstetrician and Gynaecologist, Mahamodara Teaching Hospital, Galle
|
44 |
+
|
45 |
+
Vol. 43, No. 3, September 2021
|
46 |
+
|
47 |
+
269
|
48 |
+
|
49 |
+
SLCOG Guideline\n\n2.3 Perineal/surgical wound care
|
50 |
+
|
51 |
+
For the uncomplicated vaginal delivery, cold packs could be applied for 10 to 20 minutes as it helps to improve pain and edema at the episiotomy site.
|
52 |
+
|
53 |
+
Postnatal women should change perineal pad frequently (4 to 6 hours) and have shower at least daily to keep the perineum clean.
|
54 |
+
|
55 |
+
Vaginal douching is not recommended in the early pueperium.
|
56 |
+
|
57 |
+
The vulva should be cleaned from anterior to posterior and not vice versa, to prevent the possibility of fecal contamination of traumatized area.
|
58 |
+
|
59 |
+
If a woman has painful defecation or constipation, laxatives should be prescribed for easy bowel motion.
|
60 |
+
|
61 |
+
Routine antibiotics are not recommended for first and second degree perineal tears or episiotomy.
|
62 |
+
|
63 |
+
Health professionals should follow a standard protocol for management of Obstetric Anal Sphincter Injuries for the additional recommended care.
|
64 |
+
|
65 |
+
A visual assessment of the perineum and vaginal examination should be carried out in all postnatal women prior to discharge to assess healing, breakdown and presence of foreign bodies.
|
66 |
+
|
67 |
+
Standard dressings should be removed 24 hours after the caesarean delivery and thereafter consider applying a soft dressing.
|
68 |
+
|
69 |
+
Assement of wound should be done for signs of infection, separation or dehiscence.
|
70 |
+
|
71 |
+
The woman should be encouraged to wear loose, comfortable clothes and cotton underwear.
|
72 |
+
|
73 |
+
Gentle cleaning and drying the wound should be carried out daily.
|
74 |
+
|
75 |
+
Removal of sutures or clips should be arranged in 5 to 7 days of caesarean delivery.
|
76 |
+
|
77 |
+
2.4 Postpartum bladder care
|
78 |
+
|
79 |
+
Every postnatal woman should be educated from the labour ward to empty the bladder every 4 to 6 hours and,t he time and volume of first void following delivery must be recorded in the maternal notes.
|
80 |
+
|
81 |
+
270
|
82 |
+
|
83 |
+
To ensure that normal bladder function resumes, women should be left no more than six hours following delivery without voiding.
|
84 |
+
|
85 |
+
If the woman has not passed urine successfully by six hours following delivery, prompt action should be taken by the obstetric team.
|
86 |
+
|
87 |
+
Effort to assist urination should be advised, such as taking a warm bath or shower. If these measures are not successful, prompt assessment of bladder volume and catheterization should be done.
|
88 |
+
|
89 |
+
Where the Post Voidal Residue (PVR) is >150 or the women is unable to void, an indwelling catheter should be inserted for 24 hours.
|
90 |
+
|
91 |
+
Offer removal of the urinary bladder catheter once a woman is mobile after a regional anaesthetic for caesarean birth, but no sooner than 12 hours.\n\n2.5 Care for the newborn baby
|
92 |
+
|
93 |
+
Aim for a full clinical examination around one hour after birth, when the baby has had his/her first breastfeeding. The baby should be checked again before discharge.
|
94 |
+
|
95 |
+
Clean dry cord care is recommended for babies born in health facility.
|
96 |
+
|
97 |
+
Bathing should be delayed until 24 hours after birth. If it is not possible due to cultural reasons, bathing should be delayed at least six hours.
|
98 |
+
|
99 |
+
The new born baby should be clothed with one or two layers of cloth with hat/cap for ambient temperature.
|
100 |
+
|
101 |
+
Immunization should be promoted as per the Expanded Immunization Programme.
|
102 |
+
|
103 |
+
2.6 Postpartum contraception
|
104 |
+
|
105 |
+
Discussion on Postpartum Family Planning (PPFP) should be initiated prior to discharge which should be a continuum of antenatal contraception counselling.
|
106 |
+
|
107 |
+
The couple should be informed that they are at risk of pregnancy as early as four weeks after delivery if the woman is not exclusively breastfeeding.
|
108 |
+
|
109 |
+
For women with no other medical illnesses, there is no restriction for the use of the following methods
|
110 |
+
|
111 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
112 |
+
|
113 |
+
during the immediate postpartum period: Post-Partum Intra uterine Devices (PPIUD) and progestogen implants.
|
114 |
+
|
115 |
+
If couple requests PPIUD, it should be offered to women within 48 hours of delivery.
|
116 |
+
|
117 |
+
If the couple wishes to have postpartum sterilization, it should be arranged within 48 hours after delivery.
|
118 |
+
|
119 |
+
Lactational Amenorrhoea (LAM) alone should not be promoted as a method of contraception due to its high failure rate.
|
120 |
+
|
121 |
+
2.7 Lactation management
|
122 |
+
|
123 |
+
Every effort should be taken to commence breastfeeding within the first hour after delivery.
|
124 |
+
|
125 |
+
Support must be immediately available for new mothers to initiate breast feeding soon after birth.
|
126 |
+
|
127 |
+
Extended support from trained staff should offer training of new mothers and then observe and monitor breastfeeding during hospital stay.
|
128 |
+
|
129 |
+
Women and their newborn baby should stay in hospital for at least 24 hours and should not be discharged early until mother is confident about breast feeding.
|
130 |
+
|
131 |
+
2.8 Nutrition and general health advice on discharge
|
132 |
+
|
133 |
+
Nurse in charge of health education should talk to women, preferably arrange small group discussions.
|
134 |
+
|
135 |
+
Women should be advised to eat a greater amount and variety of healthy foods, dairy products, oils, nuts, seeds, cereals, vegetables, to help her to be well and strong.
|
136 |
+
|
137 |
+
A liquid diet can be offered 2 hours after an uncom- plicated cesarean delivery. Women should be reassured that she can eat any normal food.
|
138 |
+
|
139 |
+
Continue iron, folic acid and calcium supplementation during lactation.
|
140 |
+
|
141 |
+
Women should avoid sexual intercourse until perineal wound heals and she feels comfortable, preferably until 4-6 weeks postpartum.
|
142 |
+
|
143 |
+
Vol. 43, No. 3, September 2021
|
144 |
+
|
145 |
+
SLCOG Guideline\n\n3. Introduction
|
146 |
+
|
147 |
+
Postnatal period is a time of great change, physically, mentally and socially for mothers, infants and families. While many mothers transition through this time uneventfully, others find it overwhelming or develop significant health issues that may persist for weeks and months after giving birth. Postnatal care of the woman and her newborn baby, is the weakest and the most neglected component of reproductive health care. Global data shows that almost half of the post natal maternal deaths occur within the first 24 hrs of child- birth1 and one million of newborns died on the first day2,3. As the first day of the postpartum period carries the highest risk of adverse outcomes for the woman and her baby, it is essential that comprehensive postnatal care is initiated immediately after delivery and continued until the woman is discharged from hospital.
|
148 |
+
|
149 |
+
Essential postnatal care which should be commenced on the first postpartum day itself include: pain manage- ment, perineal care, bladder care, care of the new born, postpartum contraception, lactation management and assessment of psychological wellbeing.
|
150 |
+
|
151 |
+
The World Health Organization (WHO) recognized the importance of the postnatal management and has issued detailed, evidence-based recommendations for postnatal care4.
|
152 |
+
|
153 |
+
In Sri Lanka, almost all births take place in hospitals with skill birth attendance5. Therefore, we have excellent opportunity to commence comprehensive care for postnatal mothers until they are discharged from the facility.
|
154 |
+
|
155 |
+
4. Recommendations and discussion
|
156 |
+
|
157 |
+
4.1 Immediate postpartum monitoring
|
158 |
+
|
159 |
+
Modified Obstetric Early Warning System (MOEWS) should be used to monitor vital parameters to recognize early abnormalities of postnatal women.
|
160 |
+
|
161 |
+
Monitoring with MOEWS chart should be continued for two hours for vaginal delivery and four hours for caesarean delivery.
|
162 |
+
|
163 |
+
Early Warning Scoring Systems are a simple, quick- to-use tool based on routine physiological observations. The scoring of these observations can provide an indication of the overall status of the patient’s condition. Prompt action and urgent medical review when indi-
|
164 |
+
|
165 |
+
271
|
166 |
+
|
167 |
+
SLCOG Guideline
|
168 |
+
|
169 |
+
cated, allow for appropriate management of women at risk of deterioration. The MEOWS tool has been specifically adopted to reflect the physiological adap- tations of normal pregnancy and should therefore be used for pregnant, labouring and postnatal women. Use of MOEWS, which alerts care providers of poten- tial impending critical illnesses, is recommended to improve maternal outcomes and safety6.\n\n4.2 Postpartum pain management
|
170 |
+
|
171 |
+
A stepwise approach using multi-model combination of agents should be prescribed.
|
172 |
+
|
173 |
+
Acetaminophen (Paracetamol) should be prescribed for perineal discomfort and pain following uncomplicated vaginal delivery.
|
174 |
+
|
175 |
+
Non-Steroidal Ante-Inflammatory Drugs (NSAID’s) such as diclofenac and ibuprofen with acetaminophen are relatively safe during postpartum period and should be prescribed for postnatal women with more severe pain.
|
176 |
+
|
177 |
+
When, a multimodal approach to analgesia using NSAID’s and acetaminophen given simultaneously on a set schedule is insufficient, a milder opioid (codeine) should be considered especially for caesarean delivery for enhanced recovery.
|
178 |
+
|
179 |
+
When caesarean delivery is conducted following general anaesthesia or when intrathecal long acting opioids are not used for spinal anaesthesia, a Transversus Abdominis Plane field block (TAP block) should be considered as it provides excellent postoperative pain control and improves postoperative analgesia.
|
180 |
+
|
181 |
+
Stronger opioid analgesics (morphine, diamorphine and pethidine) are best reserved for women with inadequate pain control with sufficient doses of multimodal approach.
|
182 |
+
|
183 |
+
Drowsiness from opioids use can interfere with maternal activities and breast feeding.
|
184 |
+
|
185 |
+
Pain has been documented as a major concern for most TAP block women following childbirth. Management of postpartum pain, however, is a relatively neglected due to under estimation7. Inadequate pain relief could lead to interference with mobilization, breastfeeding, and newborn bonding by impeding mobility, can
|
186 |
+
|
187 |
+
272
|
188 |
+
|
189 |
+
increase the risk of postpartum complications8. Non- pharmacological and pharmacological therapies are options for pain management. It is also important to consider safety of drug therapy due to concerns of secretion through breast milk. Multimodal analgesia uses drugs that have different mechanism of action, which augments analgesic effect9 (Appendix no. 1). A Cochrane review of local analgesia infiltration and abdominal nerve blocks found that they improved postoperative analgesia for cesarean delivery10. Acetaminophen and NSAIDs are relatively safe during breast feeding11. However, opioids should be used cautiously as maternal and neonatal sedation12.\n\n4.3 Postpartum perineal /surgical wound care
|
190 |
+
|
191 |
+
For the uncomplicated vaginal delivery, cold packs could be applied for 10 to 20 minutes as it helps to improve pain and edema at the episiotomy site.
|
192 |
+
|
193 |
+
Postnatal women should change perineal pad frequently (4 to 6 hours) and have shower at least daily to keep the perineum clean.
|
194 |
+
|
195 |
+
Vaginal douching is not recommended in the early pueperium.
|
196 |
+
|
197 |
+
The vulva should be cleaned from anterior to posterior and not vice versa, to prevent the possibility of fecal contamination of traumatized area.
|
198 |
+
|
199 |
+
If a woman has painful defecation or constipation, laxatives should be prescribed for easy bowel motion.
|
200 |
+
|
201 |
+
Routine antibiotics are not recommended for first and second degree perineal tears or episiotomy.
|
202 |
+
|
203 |
+
Health professionals should follow a standard protocol for management of obstetric anal sphincter injuries for the additional recommended care.
|
204 |
+
|
205 |
+
A visual assessment of the perineum and vaginal examination should be carried out in all postnatal women prior to discharge to assess healing, breakdown and presence of foreign bodies.
|
206 |
+
|
207 |
+
Standard dressings should be removed 24 hours after the caesarean delivery and thereafter consider applying a soft dressing.
|
208 |
+
|
209 |
+
Assessment of wound should be done for signs of infection, separation or dehiscence.
|
210 |
+
|
211 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
212 |
+
|
213 |
+
The woman should be encouraged to wear loose, comfortable clothes and cotton underwear.
|
214 |
+
|
215 |
+
Gentle cleaning and drying the wound should be carried out daily.
|
216 |
+
|
217 |
+
Removal of sutures or clips should be arranged in 5 to 7 days of caesarean delivery.
|
218 |
+
|
219 |
+
Perineal damage can cause significant maternal morbidity both immediate and long term8. Vast majority of perineal trauma is due to intentionally made episio- tomy to facilitate vaginal delivery. Episiotomy rates vary considerably in various countries according to individual practices and policies of staff and institutions. Overall rates of episiotomy in different countries range from 8% to 99%13. In Sri Lanka, almost all primipara and most of the multipara experience episiotomy. Edema and discomfort may result painful defecation and interfere with mobilization. Although evidence is limited, a meta-analysis found that cold pack applied for 10 to 20 mins. improve perineal discomfort and edema14. Laxatives should be administered, in immediate postpartum period, if a women has painful defecation or constipation following perineal trauma, to aid easier bowel motion and early discharge from hospital15. Routine perinel examination should be carried out by a doctor before discharge to assess the perineum for signs of infection and wound breakdowns16. NICE guideline on caesarean delivery recommends to remove standard dressing in 8 to 24 hours but not advised for negative pressure dressing unless risk of bleeding17.\n\n4.4 Postpartum bladder care
|
220 |
+
|
221 |
+
Every postnatal women should be educated from the labour ward to empty the bladder every 4 to 6 hours and the time and volume of first void following delivery must be recorded in the maternal notes.
|
222 |
+
|
223 |
+
To ensure that normal bladder function resumes, women should be left no more than six hours following delivery without voiding.
|
224 |
+
|
225 |
+
If the woman has not passed urine successfully by six hours following delivery, prompt action should be taken by the obstetric team.
|
226 |
+
|
227 |
+
Effort to assist urination should be advised, such as taking a warm bath or shower. If these measures are not successful, prompt assessment of bladder volume and catheterization should be done.
|
228 |
+
|
229 |
+
Vol. 43, No. 3, September 2021
|
230 |
+
|
231 |
+
SLCOG Guideline
|
232 |
+
|
233 |
+
Where the Post Voidal Residue (PVR) is >150 or the women is unable to void, an indwelling catheter should be inserted for 24 hours.
|
234 |
+
|
235 |
+
Offer removal of the urinary bladder catheter once a woman is mobile after a regional anaesthetic for caesarean birth, but no sooner than 12 hours.
|
236 |
+
|
237 |
+
A small number of women (0.4% to 4%) experience long term bladder dysfunction following child birth18. This can cause embarrassment and distress19. The bladder could be an unfortunate victim of child birth. A single episode of bladder over distention can lead to irreversible damage to detrusor muscles20. PVR and total urine volume are considered as significant finding when a woman is managed for acute urinary retention. Short while after delivery, retention of urine with bladder distention can be a frequent phenomenon due to child birth related denervation an ischemia of the bladder muscles. Urinary retention is most likely to occur in the first 8 to 12 hours following delivery because of its onset may be slow and asymptomatic21. Early diagnosis, interventions and treatment are neces- sary to prevent permanent bladder damage. Simple measures such as education of women regarding effective voiding and frequency would prevent most of undiagnosed bladder distention. Even though it is recommended by Enhance Recovery After Surgery (ERAS) society to remove urinary catheter immediately after caesarean delivery, it is not practically possible in local setting.\n\n4.5 Care for the newborn baby
|
238 |
+
|
239 |
+
Aim for a full clinical examination around one hour after birth, when the baby has had his/her first breastfeeding. The baby should be checked again before discharge.
|
240 |
+
|
241 |
+
Clean dry cord care is recommended for babies born in health facility.
|
242 |
+
|
243 |
+
Bathing should be delayed until 24 hours after birth. If it is not possible due to cultural reasons, bathing should be delayed at least six hours.
|
244 |
+
|
245 |
+
The new born baby should be clothed one or two layers of cloth with hat/cap for ambient temperature.
|
246 |
+
|
247 |
+
Immunization should be promoted as per the Expanded Immunization Programme.
|
248 |
+
|
249 |
+
273
|
250 |
+
|
251 |
+
SLCOG Guideline
|
252 |
+
|
253 |
+
Newborn period refers to the first twenty-eight days of life. However first 24 hours of the life is the most challenging time of human life, since babies are born to an entirely new surrounding. There are several physiological adaptations occurring in this period in the baby, which is essential for their survival. Family Health Bureau has issued a comprehensive guideline on new born care for detailed reference22.
|
254 |
+
|
255 |
+
4.6 Postpartum contraception
|
256 |
+
|
257 |
+
Discussion on Postpartum Family Planning (PPFP) should be initiated prior to discharge which should be a continuum of antenatal contraception counselling. The couple should be informed that they are at risk of pregnancy as early as four weeks after delivery if the woman is not exclusively breastfeeding.
|
258 |
+
|
259 |
+
For women with no other medical illnesses, there is no restriction for the use of the following methods during the immediate postpartum period: Post-Partum Intra uterine Devices (PPIUD) and progestogen implants.
|
260 |
+
|
261 |
+
If couple requests PPIUD, it should be offered to women within 48 hours of delivery.
|
262 |
+
|
263 |
+
If the couple wishes to have postpartum sterilization, it should be arranged within 48 hours after delivery.
|
264 |
+
|
265 |
+
Lactational Amenorrhoea (LAM) alone should not be promoted as a method of contraception due to its high failure rate.
|
266 |
+
|
267 |
+
Fertility returns shortly after childbirth in non-breast feeding women23. Non-use of PPFP would result in unplanned and unwanted pregnancies. Closely spaced pregnancies leads to adverse maternal perinatal and infant outcomes. PPFP enables women to achieve healthy interval between births and potentially averting 25-40% of maternal deaths and reducing child mortality by an estimated 10%24,25. The post-partum period represents the critical window of opportunity for women to receive family planning services. Discussion on PPFP should be carried out antenatally and further discussions and the provision of PPFP should be initiated soon after delivery. For women with no other medical illnesses, there is no restrictions for the use of the following methods in the immediate postpartum period: Post-Partum Intra uterine Devices (PPIUD), progestogen implants and progestogen only pills26. The PPIUD enables women to leave the birth facility with\n\n274
|
268 |
+
|
269 |
+
a safe and extremely affective, long acting, reversible method already in place. The main advantage of this method is convenient to mother due to timing of insertion.
|
270 |
+
|
271 |
+
4.7 Lactation management
|
272 |
+
|
273 |
+
Every effort should be taken to commence breast- feeding within the first hour after delivery.
|
274 |
+
|
275 |
+
Support must be immediately available for new mothers to initiate breast feeding soon after birth.
|
276 |
+
|
277 |
+
Extended support from trained staff should offer training of new mothers and then observe and monitor breastfeeding during hospital stay.
|
278 |
+
|
279 |
+
Women and their newborn baby should stay in hospital for at least 24 hours and should not be discharged early until mother is confident about breast feeding.
|
280 |
+
|
281 |
+
Breast feeding is considered as the single most effective low cost intervention to reduce child morbidity and mortality worldwide27. Another effort for encouraging breastfeeding practice is “Baby Friendly” hospitals. Support must be available immediately for new mothers to initiate breastfeeding in maternity facilities. It is important to integrate the WHO/UNICEF Ten Steps of Successful Breastfeeding (established in 1989) that describe what maternity facilities should do to enable a successful start to breastfeeding. Improving access to skilled breastfeeding counseling and education, has been shown to result in a 90 percent increase in exclusive breastfeeding rates for infants up to five months of age28. Sri Lanka ranks first among 97 countries globally on breastfeeding rate according to a new survey conducted by the World Breastfeeding Trends Initiative (WBTi) achieving first “Green” nation status in supporting breastfeeding women29.
|
282 |
+
|
283 |
+
4.8 Nutrition and general health advice on discharge
|
284 |
+
|
285 |
+
Nurse in charge of health education should talk to women, preferably arrange small group discussions.
|
286 |
+
|
287 |
+
Women should be advised to eat a greater amount and variety of healthy foods, dairy products, oils, nuts, seeds, cereals, vegetables, to help her to be well and strong.
|
288 |
+
|
289 |
+
A liquid diet can be offered 2 hours after an uncom- plicated cesarean delivery.
|
290 |
+
|
291 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
292 |
+
|
293 |
+
Women should be reassured that she can eat any normal food.
|
294 |
+
|
295 |
+
Continue iron, folic acid and calcium supplementation during lactation.
|
296 |
+
|
297 |
+
Women should avoid sexual intercourse until perineal wound heals and she feels comfortable, preferably until 4-6 weeks postpartum.
|
298 |
+
|
299 |
+
As postnatal mothers have increased demand for nutrition due to rapid recovery of pregnancy related physiological changes and breastfeeding, they need high quality food and greater amount for eating. There are numerous myths and taboos in different cultures, exposing women to limited intake. Therefore, postnatal education and counseling is important, should com- plement antenatal education and counseling and should be implemented prior to discharge from the hospital. Ideally, postnatal education and counseling need to be individualized and flexible, although there could be barriers to do so30. The largest trial to study early feeding, conventional feeding within 18 hours or early feeding within 2 hours, demonstrated a reduction in thirst and hunger and improved maternal satisfaction, ambulation, and infections31. A systematic review and meta-analysis of 17 studies also supported these findings32.\n\n5. Clinical governance
|
300 |
+
|
301 |
+
5.1 Quality of care
|
302 |
+
|
303 |
+
With increasing numbers of births in health facilities, attention has shifted to the quality of care, as poor quality of care contributes to morbidity/mortality and maternal unsatisfaction. A hospital providing maternity services should have the mission of every pregnant woman and newborn receives high-quality care throughout pregnancy, childbirth and the postnatal period. To accomplish the mission, standard quality assessment procedure should be implemented and monitored in regular basis.
|
304 |
+
|
305 |
+
5.2 Training
|
306 |
+
|
307 |
+
The maternity staff should be regularly trained with updated knowledge and skills to provide comprehensive postnatal care. Communication and counseling workshops should be arranged for health professionals for better communication with postnatal women and their families.
|
308 |
+
|
309 |
+
Vol. 43, No. 3, September 2021
|
310 |
+
|
311 |
+
SLCOG Guideline
|
312 |
+
|
313 |
+
5.3 Incident reporting
|
314 |
+
|
315 |
+
The hospital should adopt effective way of incident reporting and feedback mechanism for adverse events. The prompt investigation of particular incident and implementation of recognized recommendations should be carried out by the institutions.\n\nReferences
|
316 |
+
|
317 |
+
1. Every Newborn, An Executive Summary for The Lancet’s Series. 2014.
|
318 |
+
|
319 |
+
2. The Inter-agency Group for Child Mortality Estimation (UN IGME). Levels & Trends in Child Mortality, Report 2014. United Nations Children’s Fund.
|
320 |
+
|
321 |
+
3. Lawn JE et al. Every Newborn: Progress, Priorities, and Potential Beyond Survival. Lancet 2014; 384: 189-205.
|
322 |
+
|
323 |
+
4. WHO. WHO Recommendations on Postnatal Care of the Mother and Newborn. October 2013. Geneva: WHO.
|
324 |
+
|
325 |
+
5. Department of Census and Statistics Sri Lanka. Sri Lanka Demographic and Health Survey 2016. Colombo, Sri Lanka http://www.statistics.gov.lk/ Resource/en/Health/DemographicAndHealth SurveyRep ort-2016-Contents. (Accessed 30. 09.2020)
|
326 |
+
|
327 |
+
6. Singh S, McGlennan A, England A, Simons R.A validation study of the CEMACH recommended modified early obstetric warning system (MEOWS). Anaesthesia 2012(67): 12-18.
|
328 |
+
|
329 |
+
7. Glazener CMA, Abdalla M, Stroud P, Naji S, Templeton A. Russell IT Postnatal morbidity. Extend, course, prevention and treatment. Br J Obstet Gynaecol 1995; 102: 286-7.
|
330 |
+
|
331 |
+
8. Sleep J. Perineal care: a series of 5 randomized control trials, In: Robinson S, Thomson A , Editors. Midwives Research and Child-birth. London : Chapman and Holl. 1991: 199-251.
|
332 |
+
|
333 |
+
9. Leung L. From ladder to platform: a new concept for pain management. J Prim Health Care 2012; 4: 254-8.
|
334 |
+
|
335 |
+
10. Bamigboye AA, Hofmeyr GJ. Local anaesthetic wound infiltration and abdominal nerves block during caesarean section for postoperative pain relief. Cochrane Database Syst Rev 2009; 3: CD006954.
|
336 |
+
|
337 |
+
275
|
338 |
+
|
339 |
+
SLCOG Guideline
|
340 |
+
|
341 |
+
11. Spigset O, Hagg S. Analgesics and breast-feeding: safety considerations. Paediatr Drugs 2000; 2: 223-38.
|
342 |
+
|
343 |
+
12. Fahey JO. Best practices in management of postpartum pain. J Perinat Neonatal Nurs 2017; 31: 126-36.
|
344 |
+
|
345 |
+
13. Renfew MT, Hannah W, Albert L, Floyed E. Practices that minimize trauma to the genital track in the child birth: A systematic review of the Literatur. Birth 1998 ; 25: 143-60.
|
346 |
+
|
347 |
+
14. East CE, Begg L, Henshall NE, Marchant PR, Wallace K. Local cooling for relieving pain from perineal trauma sustained during childbirth. Cochrane Database of Systematic Reviews 2012, Issue 5. Art. No.: CD006304.
|
348 |
+
|
349 |
+
15. Harvey MA, Pierce M, Alter JE, Chou Q, Diamond P, Epp A, et al. Obstetrical anal sphincter injuries (OASIS): Prevention, recognition, and repair. Clinical Practice Guideline No. 330. Journal of Obstetrics and Gynaecology Canada 2015; 37(12): 1131-48.
|
350 |
+
|
351 |
+
16. Bick D. Postpartum management of the perineum. British Journal of Midwifery 2009; 17(9): 571-7.
|
352 |
+
|
353 |
+
17. NICE clinical guideline on caesarean section, No. 132, 2011.
|
354 |
+
|
355 |
+
18. Ian N, Ramsay, Torbet TE. Incidence of abnormal voiding parameters in the immediate postpartum period. Neurology and urodynamics 1993 (12): 179-83.
|
356 |
+
|
357 |
+
19. Lennard, F. To wee or not to wee: that is the distention? Journal of the Association of Chartered Physiotherapists in Women’s Health 2005; 96: 41-6.
|
358 |
+
|
359 |
+
20. Ching-Chung, L, et al. ‘Postpartum urinary retention: assessment of contributing factors and long term clinical impact’ in Australian and New Zealand Journal of Obstetric Gynaecology, 2002; 42 (4): 367-70.
|
360 |
+
|
361 |
+
21. Glavind, K. and BjØrk, j . Incidence and treatment of urinary retention postpartum. International
|
362 |
+
|
363 |
+
276
|
364 |
+
|
365 |
+
Urogynaecology Journal, 2003; 14: 119-21. www.springerlink.com.
|
366 |
+
|
367 |
+
22. National Guidelines for Newborn Care, Family Health Bureau, 2020.
|
368 |
+
|
369 |
+
23. Jackson E, Glasier A. Return of ovulation and menses in postpartum non lactating women: a systematic review. Obstet Gynecol 2011; 117(3): 657-62.
|
370 |
+
|
371 |
+
24. Campbell MR, Graham WJ. Strategies for reducing maternal mortality. Getting on with what works, Lancet, 2006; 368(9543): 1284-99.
|
372 |
+
|
373 |
+
25. Cleland J, et al. Family planning. The unfinished agenda, Lancet 2006; 368(9549): 1810-27.
|
374 |
+
|
375 |
+
26. UK Medical Eligibility Criteria. 2016. https:// www.fsrh.org/standards-and-guidance/ documents/ukmec-2016 (Accessed 30.09.2020)\n\n27. Bhutta ZA, Das JK, Rizvi A, Gaffey MF, Walker N, Horton S, et al. Maternal and Child Nutrition Study Group. Evidence-based interventions for improvement of maternal and child nutrition: what can be done and at what cost? The lancet 2013; 382(9890): 452.
|
376 |
+
|
377 |
+
28. Sinha B, Chowdhury R, Sankar MJ, Martines J, Taneja S, Mazumder S, et al Interventions to improve breastfeeding outcomes: A systematic review and meta-analysis. ActaPaediatrica 2015; 104: 114-34.
|
378 |
+
|
379 |
+
29. World Breastfeeding Trends Initiative year 2019, https://www.worldbreastfeedingtrends.org/wbti- country-ranking.php (Accessed 30.09.2020)
|
380 |
+
|
381 |
+
30. World Health Organisation. WHO Recom- mendations on Postnatal Care of the Mother and Newborn. 2013. WHO. Geneva Switzerland.
|
382 |
+
|
383 |
+
31. Jalilian N, Ghadami MR. Randomized clinical trial comparing postoperative outcomes of early versus late oral feeding after cesarean section. J Obstet Gynaecol Res 2014; 40: 1649-52.
|
384 |
+
|
385 |
+
32. Hsu YY, Hung HY, Chang YI. Early oral intake and gastrointestinal function after cesarean delivery: a systematic review and metaanalysis. Obstet Gynecol 2013; 121: 1327.
|
386 |
+
|
387 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
src/processed_markdown/RhESUS/RhESUS.md
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---\n\ncitation: "RhESUS"\n\n---\n\nManagement Rhesus Negative Mother
|
2 |
+
|
3 |
+
Routine blood test Identification of Rh-negative mother Check unexpected antibody levels at booking visit, 28,32 and 36 weeks of POA A titre of >1:4 Non-sensitized mother o No potentially sensitizing events o Threatened miscarriage before 12 weeks Already sensitized Initial procedure is determined by past clinical history. Usually performed at least 4-8 weeks earlier than the previous point of Significant morbidity due to Early pregnancy previous complications event o Suspected termination Before 20 weeks Anti- D Ig-250 IU ROUTINE CARE Anti-D Ig-500 IU 28weeks o Ectopic pregnancy o Spontaneous miscarriage o Threatened miscarriage- After 12 weeks After 20 weeks Anti- D Ig-500 IU TEST FOR FMH Potentially sensitizing events o Antepartum Haemorrhage o External cephalic version o Closed abdominal Anti-D Ig- 500 IU Anti-D Ig-500 IU 32weeks >4ml Red cells injury o Intrauterine death o Invasive perinatal Additional anti-D Ig The dose to be diagnosis administered should assume that 500iu of anti-D Ig IV will suppress immunization by 8-10 ml of fetal RBC Post Partum management Gynaecology Mother Cord blood for, o 2ml (Plain bottle)-Grouping & Rh. o 2ml (EDTA bottle)-Fetal Hb. o 2ml (Plain bottle)-Serum bilirubin o 2ml (Plain bottle)-Direct Coomb’s test. o 2ml (EDTA bottle)-Reticulocyte count FMH test in (Kleihauer acid elution test), Traumatic delivery-LSCS Manual removal of placenta. Stillbirth/IUD. Abdominal trauma in 3rd trimester. Twin pregnancy (At delivery) Unexplained Hydrops Fetalis First sensitized Sensitized mother pregnancy. (Previously affected pregnancy) Initial procedure is determined by past clinical Check partners blood history. Usually performed at least 4-8 weeks earlier than the previous Rh positive Rh negative point of Significant morbidity No Further Investigations IAT titer ≤1:32 IAT titer Check >1:32/ partner’s blood Albumin titer >1:16 IAT titer ≥1:64 Repeat Amniocent antibody esis every titers every 2-3 weeks 2-4 weeks FMH-Feto-Maternal Transfusion IAT-Indirect Antibody Test Anti-D Ig recommended because of No risk silent FMH At risk Investigation D o c u m e n a t t i o n M a n d a t o r y
|
4 |
+
|
5 |
+
1ST
|
6 |
+
|
7 |
+
TRIMESTER
|
8 |
+
|
9 |
+
20 WEEKS
|
10 |
+
|
11 |
+
24 WEEKS
|
12 |
+
|
13 |
+
2ND
|
14 |
+
|
15 |
+
TRIMESTER
|
16 |
+
|
17 |
+
TRIMESTER
|
18 |
+
|
19 |
+
28WEEKS
|
20 |
+
|
21 |
+
3RD
|
22 |
+
|
23 |
+
TRIMESTER
|
24 |
+
|
25 |
+
LABOUR
|
26 |
+
|
27 |
+
POST
|
28 |
+
|
29 |
+
PARTUM
|
30 |
+
|
31 |
+
Sri Lanka College of Obstetrics and
|
32 |
+
|
33 |
+
Health sector development Project
|
34 |
+
|
35 |
+
Guidelines- Management Rhesus Negative
|
src/processed_markdown/SLJOG-June-2022-Page-115-124/SLJOG-June-2022-Page-115-124.md
ADDED
@@ -0,0 +1,351 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---\n\ncitation: "SLJOG June 2022 Page 115 124"\n\n---\n\nSri Lanka Journal of Obstetrics and Gynaecology
|
2 |
+
|
3 |
+
wares 9 EEA:
|
4 |
+
|
5 |
+
SLCOG
|
6 |
+
|
7 |
+
Thyroid Disease in Pregnancy and the Postpartum Period
|
8 |
+
|
9 |
+
Thyroid Disease in Pregnancy and the Postpartum Period
|
10 |
+
|
11 |
+
Guideline No: 02 June 2022
|
12 |
+
|
13 |
+
Guideline No: 02 June 2022
|
14 |
+
|
15 |
+
Please cite this paper as: de Silva PHP, Waththuhewa DY, Lanerolle S, Dodampahala HS, Silva R, Mathota C, on behalf of the Sri Lanka College of Obstetricians and Gynaecologists. Thyroid Disorders in Pregnancy and Postpartum Period
|
16 |
+
|
17 |
+
Sri Lanka College of Obstetricians and Gynaecologists
|
18 |
+
|
19 |
+
SLCOG Guideline
|
20 |
+
|
21 |
+
SLCOG Guideline
|
22 |
+
|
23 |
+
Thyroid disease in pregnancy and the postpartum period
|
24 |
+
|
25 |
+
P H P de Silvaa, D Y Waththuhewab, Sanath Lanerollec, H S Dodampahalad, Ruwan Silvae, C Mathotaf on behalf of the Sri Lanka College of Obstetricians and Gynaecologists
|
26 |
+
|
27 |
+
Correspondence: Sri Lanka College of Obstetricians and Gynaecologists, No. 112, Model Farm Road, Colombo 08. E-mail: [email protected]
|
28 |
+
|
29 |
+
Background
|
30 |
+
|
31 |
+
Thyroid disease in pregnancy, Hypothyroidism and Hyperthyroidism (thyrotoxicosis) can lead to adverse pregnancy outcomes. It can also affect foetal development and contribute to negative outcomes in infancy and childhood1.
|
32 |
+
|
33 |
+
by three-fold. Maternal Thyroid-Binding Globulin level increases due to the increased hepatic synthesis under oestrogen stimulation. TSH receptors in the thyroid gland are weakly stimulated by Human Chorionic Gonadotropin (hCG) hormone. Therefore, the total thyroxine (T4) and triiodothyronine (T3) levels increase, although free T4 levels are altered slightly and usually fall during the late course of pregnancy1.
|
34 |
+
|
35 |
+
Worldwide, the most common cause of hypo- thyroidism is an inadequate dietary intake of iodine. Universal Salt Iodination (USI) was first introduced in Sri Lanka in 1995, which led to a remarkable decrease in the prevalence of iodine deficiency and goitre2. Updated data regarding the prevalence of thyroid disease in the Sri Lankan population is relatively sparse. According to population-based studies done in Sri Lanka, prevalence of goitre was found to be around 6.8% while that of subclinical hypothyroidism was found to be approximately 4-5% with females being the most commonly affected group3,4,5. It is also interesting to note that the prevalence of the presence of thyroid auto-antibodies has been observed to be rising following the introduction of USI4.
|
36 |
+
|
37 |
+
During pregnancy, Thyroid Stimulating Hormone (TSH) levels initially rise with conception and then fall during the first trimester as the increased T4, T3 levels suppress the hypothalamic Thyroid Releasing Hormone (TRH) thus in turn suppressing the release of TSH from the pituitary gland6.
|
38 |
+
|
39 |
+
After the first trimester, TSH levels normalize to baseline levels and can increase gradually in the third trimester due to the presence of Placental Deiodinase. In Hyperemesis Gravidarum, increased hCG levels can result in a benign transient biochemical hyperthyroidism in around 60% of cases.\n\nPhysiological changes of thyroid function during pregnancy
|
40 |
+
|
41 |
+
During an average pregnancy, the volume of the thyroid gland increases by 10-30% and the iodine uptake rises
|
42 |
+
|
43 |
+
Foetal thyroid gland starts functioning at about 12 weeks after gestation. However, maternal T4 is transferred to the foetus throughout the pregnancy and is considered to be important factor for foetal neural development. This is of particular significance during the first 12 weeks. At birth, about 30% of umbilical
|
44 |
+
|
45 |
+
Sri Lanka Journal of Obstetrics and Gynaecology 2022; 44: 117-123
|
46 |
+
|
47 |
+
DOI: http://doi.org/10.4038/sljog.v44i2.8055
|
48 |
+
|
49 |
+
a Consultant Obstetrician and Gynaecologist, Colombo North Teaching Hospital, Ragama, Sri Lanka
|
50 |
+
|
51 |
+
b Senior Registrar, Colombo North Teaching Hospital, Ragama, Sri Lanka
|
52 |
+
|
53 |
+
c Consultant Obstetrician and Gynaecologist, Castle Street Hospital for Women, Colombo 8, Sri Lanka
|
54 |
+
|
55 |
+
d Professor in Obstetrics and Gynaecology Department of Obstetrics and Gynaecology, University of Colombo, Sri Lanka
|
56 |
+
|
57 |
+
e Consultant Obstetrician and Gynaecologist, Colombo North Teaching Hospital, Ragama, Sri Lanka
|
58 |
+
|
59 |
+
f Consultant Obstetrician and Gynaecologist, Colombo North Teaching Hospital, Ragama, Sri Lanka
|
60 |
+
|
61 |
+
Vol. 44, No. 2, June 2022
|
62 |
+
|
63 |
+
117
|
64 |
+
|
65 |
+
SLCOG Guideline
|
66 |
+
|
67 |
+
cord-measured T4 is derived from the maternal thyroid. Therefore, a history of anti-thyroid drugs or presence of Thyroid Receptor Antibodies in the mother should be communicated to the neonatal physician.
|
68 |
+
|
69 |
+
Thyroid function tests during pregnancy
|
70 |
+
|
71 |
+
SLCOG recommends the following cut-off limits in Thyroid Function Tests during pregnancy in accor-dance with the reference ranges accepted by the American Thyroid Association7.
|
72 |
+
|
73 |
+
Hormone 1st trimester 2nd trimester 3rd trimester TSH 0.1 - 2.5 mIU/L 0.2 - 3.0 mIU/L 0.3 - 3.0 mIU/L Total T 4 6.5 - 10.1 ug/dl 7.5 - 10.3 ug/dl 6.3 - 9.7 ug/dl Total T 3 97 - 149 ng/dl 117 - 169 ng/dl 123 - 162 ng/dl Free T 4 0.8 - 1.7 ng/dl 0.6 - 1.0 ng/dl 0.5 - 0.8 ng/dl Free T 3 4.1 - 4.4 pg/ml 4.0 - 4.4 pg/ml 4.0 - 4.4 pg/ml
|
74 |
+
|
75 |
+
Early Gestational Hyperthyroidism (EGH)
|
76 |
+
|
77 |
+
EGH is a recognized new entity in the spectrum of thyroid disease in pregnancy, usually presenting with Hyperemesis Gravidarum and mildly symptomatic hyperthyroidism. It is more common in people of Asian descent. Management includes supportive care and hydration. We recommend not starting antithyroid medications for this condition. However, many with symptoms would require beta blockers to control symptoms which can generally be discontinued in the second trimester1.
|
78 |
+
|
79 |
+
With regard to thyroid functions, four clinical entities can be deduced apart from the normal euthyroid status. These are
|
80 |
+
|
81 |
+
• Overt Hyperthyroidism
|
82 |
+
|
83 |
+
• Subclinical Hyperthyroidism
|
84 |
+
|
85 |
+
• Overt Hypothyroidism
|
86 |
+
|
87 |
+
• Subclinical Hypothyroidism
|
88 |
+
|
89 |
+
Table 1 demonstrates the associated changes in thyroid function tests for each condition.\n\nTable 1. Pregnancy associated changes in thyroid function tests in thyroid disorders indicated above
|
90 |
+
|
91 |
+
Maternal Status Thyroid Stimulating Free T4 Level Hormone (TSH) Status • Overt Hyperthyroidism Decrease Increase • Subclinical Hyperthyroidism Decrease Unchanged • Overt Hypothyroidism Increase Decrease • Subclinical Hypothyroidism Increase Unchanged
|
92 |
+
|
93 |
+
Table 1. Abbreviations: T4, thyroxine; TSH, thyroid-stimulating hormone. *The level of TSH decreases in early pregnancy because of weak TSH receptor stimulation due to substantial quantities of human chorionic gonadotropin during the first 12 weeks of gestation. After the first trimester, TSH levels return to baseline values.
|
94 |
+
|
95 |
+
118
|
96 |
+
|
97 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
98 |
+
|
99 |
+
Hyperthyroidism
|
100 |
+
|
101 |
+
Hyperthyroidism occurs in about 1 in 500 pregnancies and is most commonly due to Graves’ Disease. De novo cases can be due to solitary toxic adenomas, toxic multinodular goitre, subacute thyroiditis, acute thyroiditis (viral/de Quervain’s) or due to medications (Iodine/Lithium/Amiodarone). Increased thyroid activity in pregnancy can lead to the aggravation of Grave’s thyrotoxicosis in the first trimester and puer- perium. Generally, auto-immune thyroid diseases are relatively quiescent during pregnancy due to the relatively immune-suppressive state of pregnancy.
|
102 |
+
|
103 |
+
Well controlled disease can achieve good maternal and foetal outcomes. If untreated however, can lead to miscarriage, fetal loss, fetal growth restriction, preterm labour and increased perinatal mortality. Thyroid antibodies can cross the placenta and result in foetal and neonatal thyrotoxicosis.
|
104 |
+
|
105 |
+
Hyperthyroidism will lead to maternal sinus tachycardia, supraventricular tachycardia, atrial fibrillation, thyroid storm and heart failure.
|
106 |
+
|
107 |
+
Clinical features
|
108 |
+
|
109 |
+
Resembles early normal pregnancy symptoms; heat intolerance, palpitations, tachycardia, palmar erythema, vomiting, emotional lability and goitre. De novo cases usually present in the early second trimester.
|
110 |
+
|
111 |
+
Discriminating features;
|
112 |
+
|
113 |
+
• Weight loss
|
114 |
+
|
115 |
+
• Persistent tachycardia
|
116 |
+
|
117 |
+
• Sleeping pulse > 100 per minute
|
118 |
+
|
119 |
+
• Tremor
|
120 |
+
|
121 |
+
• Lid lag
|
122 |
+
|
123 |
+
• Exophthalmos
|
124 |
+
|
125 |
+
• Symptoms predating the pregnancy\n\nManagement
|
126 |
+
|
127 |
+
• Normal ranges for pregnancy trimesters should be used for assessment and the diagnosis is by raised levels of free T4 and T3 and suppressed TSH.
|
128 |
+
|
129 |
+
Antithyroid Drugs (ATD)
|
130 |
+
|
131 |
+
• Medications used are Carbimazole, Methimazole and Propylthiouracil (PTU).
|
132 |
+
|
133 |
+
Vol. 44, No. 2, June 2022
|
134 |
+
|
135 |
+
SLCOG Guideline
|
136 |
+
|
137 |
+
• Aim to achieve rapid and optimal control with the lowest dose of medications to maintain euthyroid state with free T4 level at upper limit of normal range.
|
138 |
+
|
139 |
+
• Antithyroid medication response is delayed and takes 3-4 weeks. Once response is achieved, dose should be gradually reduced to main- tenance dose for 12-18 months6.
|
140 |
+
|
141 |
+
Eg: Carbimazole starting dose 15-40 mg, then reduced to 5-15mg,
|
142 |
+
|
143 |
+
PTU starting dose 150-400 mg, then reduced to 50-150 mg.
|
144 |
+
|
145 |
+
• Both drugs can cross the placenta (PTU less than Carbimazole) and can result in foetal hypothyroidism and goitre.
|
146 |
+
|
147 |
+
• Both drugs can cause congenital abnormalities (2-4%) although more severe with Carbimazole.
|
148 |
+
|
149 |
+
• Carbimazole and Methimazole, when used in the first trimester can cause a rare side effect; Aplasia Cutis of the foetus (Foetus is born with the absence of certain layers of skin, most often on the scalp, but also on the trunk, and/or arms and legs).
|
150 |
+
|
151 |
+
• PTU can cause a rare complication i.e. liver failure of the mother (1 in 10,000).
|
152 |
+
|
153 |
+
• Doses below 15mg/day of Carbimazole and 150mg/ day of PTU are unlikely to cause foetal effects.
|
154 |
+
|
155 |
+
• We recommend starting PTU for newly diag- nosed cases in the first trimester and then con- verting to Carbimazole in the second trimester and onwards. It is preferable to continue low dose Carbimazole without changing drugs if already diagnosed and under control with Carbimazole since preconception period.
|
156 |
+
|
157 |
+
• “Block and replace” therapy is not recom- mended.
|
158 |
+
|
159 |
+
• Both drugs can cause a drug urticaria in 1-5% of patients and the medication should be changed to a different preparation.
|
160 |
+
|
161 |
+
• Rarely both drugs may cause agranulocytosis and result in neutropenia, thus patients should be monitored for symptoms with Full Blood Count at an early point of the treatment process.
|
162 |
+
|
163 |
+
• Grave’s Disease can relapse in postpartum, therefore all mothers should be re-tested in 2-4 months after delivery.
|
164 |
+
|
165 |
+
119
|
166 |
+
|
167 |
+
SLCOG Guideline
|
168 |
+
|
169 |
+
• Breastfeeding is safe if it is on low doses of drugs and needs foetal thyroid function monitoring in the case of mother taking higher doses.\n\nBeta Blockers
|
170 |
+
|
171 |
+
• Will provide symptom control in the early phase of treatment and during relapse. Eg: Propranolol 40mg three times daily.
|
172 |
+
|
173 |
+
It will also reduce peripheral conversion of T4.
|
174 |
+
|
175 |
+
• Can be discontinued after the achievement of the antithyroid medication response. As it is used for a short duration, it will not cause harmful foetal effects.
|
176 |
+
|
177 |
+
Surgery
|
178 |
+
|
179 |
+
• Can be done for those who present with large goitre causing dysphagia and stridor, confirmed or suspected thyroid malignancy or if allergic to antithyroid medication. If indicated it is done in the second trimester. Need close follow up and treatment for hypothyroidism as 25-50% will be hypothyroid following surgery.
|
180 |
+
|
181 |
+
• 1-2% of patients will develop hypocalcemia due to removal of the parathyroid gland.
|
182 |
+
|
183 |
+
Radio-active Iodine
|
184 |
+
|
185 |
+
• As it is taken up by foetal thyroid and causes foetal thyroid ablation, radio-iodine therapy is contra-indicated in pregnancy and post-partum.
|
186 |
+
|
187 |
+
• Radio-iodine scans for diagnostic purposes are also contra-indicated in pregnancy and breastfeeding. Breastfeeding should be withheld for 24 hrs if radio iodine tests done postpartum.
|
188 |
+
|
189 |
+
Thyroid Storm – Diagnosis and Management
|
190 |
+
|
191 |
+
A rare disorder with a mortality rate of 8-25% which presents with multi-organ dysfunction. Symptoms include; pyrexia, tachycardia, arrhythmia, heart failure, delirium, stupor or coma, liver failure, vomiting and diarrhoea.
|
192 |
+
|
193 |
+
Precipitants; sudden withdrawal of ATD, following radio-iodine treatment, stress due trauma (surgery) or acute febrile illness. Thus, ensuring euthyroid status of the mother at the elective caesarean section or at labour is of paramount importance.
|
194 |
+
|
195 |
+
120
|
196 |
+
|
197 |
+
Diagnosis should be made clinically in severe-level thyrotoxicosis patients with evidence of decom- pensation. Burch-Wartofsky point scale or Japanese Thyroid Association categories can be used to decide on the need for aggressive treatment.
|
198 |
+
|
199 |
+
Supportive care, starting PTU recommended for control of thyroxin production from both in gland and peripheral conversion (preferred over Carbimazole/ Methimazole), beta blockers, glucocorticoid therapy with strict ICU / HDU care is useful for control of effect or symptoms and to revive decompensated systems.
|
200 |
+
|
201 |
+
Poor respondents should be offered plasmapheresis and emergency surgery10.\n\nFoetal/ Neonatal monitoring
|
202 |
+
|
203 |
+
• Transplacental passage of thyroid stimulating antibodies results in foetal or neonatal thyrotoxicosis which will cause a 25% mortality if untreated.
|
204 |
+
|
205 |
+
• Mothers known to be positive for thyroid anti- bodies, antibody level testing should be done in early pregnancy. If titers are high or do not fall with treatment, foetal ultrasound should be offered to detect foetal growth restriction in second and third trimesters. Looking for Goitre and tachycardia should be done after delivery. Thyroid function tests in cord blood and neonate should be performed11.
|
206 |
+
|
207 |
+
• Foetal thyrotoxicosis should be treated with antithyroid medications to the mother, with thyroxine replacement if she is euthyroid.
|
208 |
+
|
209 |
+
• Neonate should be closely monitored by the Paediatric team. Following diagnosis of thyroid disease, it should be treated as soon as possible. However, the abnormalities will settle once maternal antibodies are completely cleared after around 4th month of life.
|
210 |
+
|
211 |
+
Subclinical Hyperthyroidism
|
212 |
+
|
213 |
+
Subclinical Hyperthyroidism is reported in about 0.8-1.7 percent of pregnant women12,13. Diagnosis is done using low TSH levels with normal free T4, T3 levels. This diagnosis not shown to be associated with an effect on pregnancy. Therefore, treatment is not recommended.
|
214 |
+
|
215 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
216 |
+
|
217 |
+
Hypothyroidism
|
218 |
+
|
219 |
+
Hypothyroidism affects around 1% of pregnancies. Most women will have a positive family history of auto-immune hypothyroidism and will be diagnosed and placed on treatment prenatally. Most common types are Atrophic Thyroiditis and Hashimoto’s Thyroiditis (Auto-Immune Thyroiditis and goitre). Hashimoto’s Thyroiditis is the most common cause of hypothy- roidism in developed countries. In contrast, worldwide, the most common cause of hypothyroidism is the inadequate dietary intake of iodine.
|
220 |
+
|
221 |
+
Hypothyroidism can also be iatrogenic; due to radio- iodine therapy, thyroidectomy, and due to medications (Antithyroid drugs, Iodine, Lithium, Amiodarone). It can also be associated with other auto-immune diseases.
|
222 |
+
|
223 |
+
Hashimoto Thyroiditis is an autoimmune disease that destroys thyroid cells by cell and antibody-mediated immune responses. The pathology of the disease involves the formation of antithyroid antibodies that target and destroy the thyroid tissue, causing pro- gressive fibrosis. Most patients develop antibodies to a variety of thyroid antigens, the most common of which is anti-thyroid peroxidase (anti-TPO, previously named Anti-microsomal antibody). Many also form antithyroglobulin (anti-Tg) and TSH receptor-blocking antibodies (TBII).
|
224 |
+
|
225 |
+
Pregnancy has no effect on hypothyroidism. Twenty- five percent of women will require higher requirements of thyroxine dosing during the course of the preg- nancy. If untreated, it can lead to miscarriage, fetal loss, foetal anaemia and low birthweight. Foetal thyroid functions begin around the 12th week of gestation. Thus, the foetus is dependent on maternal thyroxine during early gestation. Therefore, if untreated, hypothy- roidism and severe maternal iodine deficiency will affect fetal neuro-development leading to cretinism (condition of severe physical and mental retardation specifically due to deficiency of thyroid hormones during early pregnancy, hypothyroidism, spastic motor disorder and deaf mutism-congenital deafness that results in inability to speak). Untreated maternal hypothyroidism has a higher chance of low birth- weight. In rare cases, maternal thyroid antibodies could cross the placenta and cause foetal hypothyroidism but this is extremely rare.
|
226 |
+
|
227 |
+
Vol. 44, No. 2, June 2022
|
228 |
+
|
229 |
+
SLCOG Guideline
|
230 |
+
|
231 |
+
Mothers who are well controlled and euthyroid at conception can achieve good maternal and foetal outcomes.
|
232 |
+
|
233 |
+
Diagnosis of hypothyroidism is done when TSH level is over the reference range for the gestational age of pregnancy and the free T4/T3 levels are below the lower limit of normal.
|
234 |
+
|
235 |
+
Adverse perinatal outcomes could be reduced by appropriate therapy.\n\nClinical features
|
236 |
+
|
237 |
+
Symptoms may resemble normal pregnancy symptoms; lethargy, tiredness, weight gain, hair loss, dry skin, constipation, fluid retention and goitre.
|
238 |
+
|
239 |
+
Discriminating features;
|
240 |
+
|
241 |
+
• Cold intolerance
|
242 |
+
|
243 |
+
• Bradycardia
|
244 |
+
|
245 |
+
• Delayed ankle reflex
|
246 |
+
|
247 |
+
Management
|
248 |
+
|
249 |
+
• Normal ranges for pregnancy trimesters should be used for assessment, and diagnosed by reduced levels of free T4, T3 and increased TSH.
|
250 |
+
|
251 |
+
• Presence of auto-antibodies will help the diagnosis but is not recommended to be per- formed (anti-thyroid peroxidase antibody) routinely.
|
252 |
+
|
253 |
+
• Thyroxine does not freely cross the placenta except for very slight amounts. This will not cause foetal thyrotoxicosis.
|
254 |
+
|
255 |
+
• Women who are already on levothyroxine therapy can continue the same dose guided by thyroid function tests (TFT).
|
256 |
+
|
257 |
+
• Women who are under replacement therapy need adjustment of dose and TFT should be repeated after 4-6 weeks.
|
258 |
+
|
259 |
+
• Immediate replacement therapy should be started for newly diagnosed hypothyroidism with a starting dose of 100 μμμμμg/day. If in case of history of cardiac disease, a lower dose should be introduced.
|
260 |
+
|
261 |
+
• If dose adjustments are made during pregnancy, the dose should be reduced to pre-pregnancy dose after delivery to prevent hyperthyroidism.
|
262 |
+
|
263 |
+
121
|
264 |
+
|
265 |
+
SLCOG Guideline
|
266 |
+
|
267 |
+
Subclinical Hypothyroidism
|
268 |
+
|
269 |
+
Include the group of women who do not have symptoms and signs suggestive of thyroid dysfunction and who present with high TSH and normal thyroxine levels. It is common in the presence of anti-thyroid antibodies. Evidence reports improved pregnancy outcome in women supplemented with thyroxine in the presence of anti-thyroid antibodies. However, TSH level between 2.5-4.0 mU/L in asymptomatic patients does not require treatment5.
|
270 |
+
|
271 |
+
Controlled Anti Thyroid Screening trial (CATS) and Maternal-Foetal Medicine Units Networks randomized trials published in 2017 demonstrated no difference in neuro cognitive functions of babies born to mothers with sub clinical hypothyroidism up to the age of 5 in both arms of treatment or no treatment. Recently CATs study in its publication of follow up at 9 years also confirmed no difference in the neurodevelopment of the offspring. However, reading through published trials some have shown higher incidences of preterm birth, abruption, admission to (PBU) premature baby unit, Preeclampsia and gestational diabetes14,15,16,17. But some studies have not shown the same results18,19,20. There- fore our conclusion is at present there is no clinical advantage in treatment of subclinical hypothy- roidism unless there is the presence of anti-thyroid antibodies of the mother.
|
272 |
+
|
273 |
+
We recommend thyroxine replacement with 25-50 microgram/ day for prenatal women with positive antibodies and subclinical hypothyroidism and titration of TSH to normal levels.
|
274 |
+
|
275 |
+
Untreated severe hypothyroidism in the mother can lead to impaired brain development in the foetus. Given ambiguity in outcome of many studies in evaluating pros and cons of treating subclinical hypothyroidism, there is no world-wide consensus of opinion regarding screening all women for hypothyroidism during pregnancy.
|
276 |
+
|
277 |
+
General recommendation is to check a woman’s TSH as soon as pregnancy is confirmed in women at high risk for thyroid disease, such as those with prior treatment for hyper- or hypothyroidism, a family history of thyroid disease, a personal history of autoimmune disease, and those with a goiter.
|
278 |
+
|
279 |
+
Women with established hypothyroidism should have a TSH test as soon as pregnancy is confirmed. They also should immediately increase their levothyroxine\n\n122
|
280 |
+
|
281 |
+
dose, because thyroid hormone requirements increase during pregnancy. If new onset hypothyroidism has been detected, the woman should be treated with levothyroxine to normalize her TSH values.
|
282 |
+
|
283 |
+
Foetal / Neonatal Hypothyroidism
|
284 |
+
|
285 |
+
Occur due to transplacental passage of maternal anti- thyroid antibodies with incidence of 1 in 180,000 pregnancies.
|
286 |
+
|
287 |
+
We recommend screening of all neonates with TSH levels via Guthrie Heel Prick Neonatal Screening test.
|
288 |
+
|
289 |
+
Postpartum Thyroiditis
|
290 |
+
|
291 |
+
Incidence around 1-17% of pregnancies and is more common among women with anti-thyroid peroxidase (anti-TPO) antibodies. It is usually asymptomatic and present around 3-4 months postpartum. It can present as transient hyperthyroidism, transient hypothyroidism or as a biphasic disease (first hyperthyroidism followed by prolonged hypothyroidism). Small, painless goitre can be present in about 50% of women.
|
292 |
+
|
293 |
+
Treatment should be guided by symptom control while most recover spontaneously without treatment. 3-4% of women will have permanent hypothyroidism and about 10-25% of women will have recurrence in future pregnancies.
|
294 |
+
|
295 |
+
Most women with positive antibodies will develop postpartum depression despite thyroid status.
|
296 |
+
|
297 |
+
SLCOG is of the view, that uncomplicated thyroid disease could be managed by the Obstetrics and Gynaecology Consultant with clear knowledge of the disease process.\n\nReferences
|
298 |
+
|
299 |
+
1. Studd L. Progress in Obstetrics and Gynaecology. Volume 18.
|
300 |
+
|
301 |
+
2. ICCIDD, UNICEF, WHO. Assessment of iodine deficiency disorders and monitoring their elimination: a guide for programme managers. Geneva: World Health Organisation; 2007.
|
302 |
+
|
303 |
+
3. Chandrasinghe P, Fernando R, Nandasena S, Pathmeswaran A. Epidemiology of goitres in Sri Lanka with geographic information system mapping: population-based cross-sectional study. World J Endocr Surg 2015; 7(3): 55-9.
|
304 |
+
|
305 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
306 |
+
|
307 |
+
4. Fernando RF, Chandrasinghe PC, Pathmeswaran AA. The prevalence of autoimmune thyroiditis after universal salt iodisation in Sri Lanka. Ceylon Med J 2012; 57(3): 116-19.
|
308 |
+
|
309 |
+
5. Gunawardane IK, Somasundaram N. Update on subclinical thyroid disease. Sri Lanka Journal of Diabetes, Endocrinology and Metabolism 2013; 3: 84-7.
|
310 |
+
|
311 |
+
6. Thyroid disease in pregnancy. ACOG Practice Bulletin No.223. American College of Obstetricians and Gynaecologists. Obstet Gynecol 2020; 135: e261-74.
|
312 |
+
|
313 |
+
7. Alexander EK, Pearce EN, Brent GA, Brown RS, Chen H, Dosiou C, et al. 2017 guidelines of the American Thyroid Association for the diagnosis and management of thyroid disease during pregnancy and the postpartum. Thyroid 2017; 27: 315-89.
|
314 |
+
|
315 |
+
8. Dong AC, Stagnaro-Green A. Differences in diagnostic criteria mask the true prevalence of thyroid disease in pregnancy: a systematic review and meta-analysis. Thyroid 2019; 29: 278-89.
|
316 |
+
|
317 |
+
9. Harding KB, Peña?Rosas JP, Webster AC, Yap CM, Payne BA, Ota E, et al. Iodine supplementation for women during the preconception, pregnancy and postpartum period.
|
318 |
+
|
319 |
+
Cochrane Database of Systematic Reviews 2017, Issue 3. Art. No.: CD011761. DOI: 10.1002/ 14651858.CD011761.
|
320 |
+
|
321 |
+
10. Ross DS, Burch HB, Cooper DS, Greenlee MC, Laurberg P, Maia AL, Rivkees SA, Samuels M, Sosa JA, Stan MN, Walter MA. 2016 American Thyroid Association Guidelines for Diagnosis and Management of Hyperthyroidism and Other Causes of Thyrotoxicosis. Thyroid 2016; 25: 10 DOI: 10.1089/thy.2016.0229.
|
322 |
+
|
323 |
+
11. Pearce EN. Management of thyrotoxicosis: preconception, pregnancy, and the postpartum period. Endocr Pract 2019; 25: 62-8.
|
324 |
+
|
325 |
+
12. Casey BM, Dashe JS, Wells CE, McIntire DD, Leveno KJ, Cunningham FG. Subclinical hyperthyroidism and pregnancy outcomes. Obstet Gynecol 2006; 107: 337-41. (Level II-2)
|
326 |
+
|
327 |
+
13. Diéguez M, Herrero A, Avello N, Suárez P, Delgado E, Menéndez E. Prevalence of thyroid dysfunction in women in early pregnancy: does it increase with
|
328 |
+
|
329 |
+
Vol. 44, No. 2, June 2022
|
330 |
+
|
331 |
+
SLCOG Guideline
|
332 |
+
|
333 |
+
maternal age? Clin Endocrinol (Oxf) 2016; 84: 121-6. (Level II-3)
|
334 |
+
|
335 |
+
14. Tudela CM, Casey BM, McIntire DD, Cunningham FG. Relationship of subclinical thyroid disease to the incidence of gestational diabetes. Obstet Gynecol 2012; 119: 983-8. (Level II-3)
|
336 |
+
|
337 |
+
15. Wilson KL, Casey BM, McIntire DD, Halvorson LM, Cunningham FG. Subclinical thyroid disease and the incidence of hypertension in pregnancy. Obstet Gynecol 2012; 119: 315-20. (Level II-3)
|
338 |
+
|
339 |
+
16. Casey BM, Dashe JS, Wells CE, McIntire DD, Byrd W, Leveno KJ, et al. Subclinical hypothy- roidism and pregnancy outcomes. Obstet Gynecol 2005; 105: 239-45. (Level II-2)
|
340 |
+
|
341 |
+
17. Korevaar TI, Derakhshan A, Taylor PN, Meima M, Chen L, Bliddal S, et al. Association of thyroid function test abnormalities and thyroid auto- immunity with preterm birth: a systematic review and meta-analysis. Consortium on Thyroid and Pregnancy-Study Group on Preterm Birth [published erratum appears in JAMA 2019; 322: 1718]. JAMA 2019; 322: 632-41. (Systematic Review and MetaAnalysis
|
342 |
+
|
343 |
+
18. Sheehan PM, Nankervis A, Araujo Júnior E, Da SC. Maternal thyroid disease and preterm birth: systematic review and meta-analysis. J Clin Endocrinol Metab 2015; 100: 4325-31. (Systematic Review and Meta-Analysis)
|
344 |
+
|
345 |
+
19. Cleary-Goldman J, Malone FD, Lambert- Messerlian G, Sullivan L, Canick J, Porter TF, et al. Maternal thyroid hypofunction and pregnancy outcome. Obstet Gynecol 2008; 112: 85-92. (Level II-3)\n\n20. Casey BM, Dashe JS, Spong CY, McIntire DD, Leveno KJ, Cunningham GF. Perinatal significance of isolated maternal hypothyroxinemia identified in the first half of pregnancy. Obstet Gynecol 2007; 109: 1129-35. (Level II3)
|
346 |
+
|
347 |
+
21. Leung AKC, Leung AAC. Evaluation and management of the child with hypothyroidism. World J Pediatr. 2019; 15(2): 124-134. [PubMed]
|
348 |
+
|
349 |
+
22. Yuan J, Sun C, Jiang S, Lu Y, Zhang Y, Gao XH, Wu Y, Chen HD. The Prevalence of Thyroid Disorders in Patients With Vitiligo: A Systematic Review and Meta-Analysis. Front Endocrinol (Lausanne). 2018; 9: 803.
|
350 |
+
|
351 |
+
123
|
src/processed_markdown/SLJOG-March-2022-Page-65-73-Final-1/SLJOG-March-2022-Page-65-73-Final-1.md
ADDED
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---\n\ncitation: "SLJOG March 2022 Page 65 73 Final 1"\n\n---\n\nSri Lanka Journal of Obstetrics and Gynaecology
|
2 |
+
|
3 |
+
*s-mIe8 g wpa:
|
4 |
+
|
5 |
+
SLCOG
|
6 |
+
|
7 |
+
Hypertensive disorders of pregnancy
|
8 |
+
|
9 |
+
Guideline No: 02
|
10 |
+
|
11 |
+
March 2022
|
12 |
+
|
13 |
+
Please cite this paper as: De Silva PHP et al, on behalf of Sri Lanka College of Obstetricians and Gynaecologists. Hypertensive disorders of pregnancy
|
14 |
+
|
15 |
+
Sri Lanka College of Obstetricians and Gynaecologists
|
16 |
+
|
17 |
+
SLCOG Guideline
|
18 |
+
|
19 |
+
SLCOG Guideline
|
20 |
+
|
21 |
+
Hypertensive disorders of pregnancy
|
22 |
+
|
23 |
+
P H P De Silvaa, S Lanerolleb, S H Dodampahalac, R Silvad, C Mathotae on behalf of the Sri Lanka College of Obstetricians and Gynaecologists
|
24 |
+
|
25 |
+
Correspondence: Sri Lanka College of Obstetricians and Gynaecologists, No. 112, Model Farm Road, Colombo 08. E-mail: [email protected]
|
26 |
+
|
27 |
+
Background
|
28 |
+
|
29 |
+
Hypertensive disorders of pregnancy (HDP) as a group, is one of the leading causes of both maternal and foetal perinatal mortality/morbidity and resultant long term-disability. It accounts for approximately 14% of all maternal deaths globally1.
|
30 |
+
|
31 |
+
mortality, there is an inconsistent downward trend. Maternal hypertensive disease has reached the level of the top second cause of maternal mortality as recently as 2009 followed by a clearly observed down-trend until 2019, finally posting a fourth-highest cause of maternal mortality in Sri Lanka3.
|
32 |
+
|
33 |
+
Hypertensive disorders of pregnancy broadly define a group of conditions closely associated with high blood pressure, proteinuria and/or seizures during pregnancy. Eclampsia is usually a consequence of pre-eclampsia consisting of central nervous system seizures which often leave the patient unconscious. If untreated, it can subsequently lead to death.
|
34 |
+
|
35 |
+
The serious consequences of such pre-eclampsia and eclampsia are associated with vasospasm, pathologic vascular lesions in multiple organ systems, increased platelet activation and subsequent activation of the coagulation cascade in the microvasculature2.
|
36 |
+
|
37 |
+
Preeclampsia complicates an approximate 2-8% of pregnancies world-wide. Even in resource-high countries, there has been an observed increase in the maternal deaths that can be attributed to hypertensive disorders2.
|
38 |
+
|
39 |
+
Hypertensive disease is one of the causes that could be significantly modified to decrease its negative impact on maternal and neonatal health. This guideline is developed to aid in the dissemination of information with this objective in mind.\n\nPathophysiology
|
40 |
+
|
41 |
+
In Sri Lanka, hypertensive disease has remained among the top five causes of maternal mortality for the last two decades3. While it has trended down in its significance as one of the top causes of maternal
|
42 |
+
|
43 |
+
During an average pregnancy blood pressure generally falls by a detectable level in the first trimester and usually reaches a lowest level in the second trimester. It then rises back up to preconception pressure levels at term gestation.
|
44 |
+
|
45 |
+
Sri Lanka Journal of Obstetrics and Gynaecology 2022; 44: 65-73
|
46 |
+
|
47 |
+
DOI: http://doi.org/10.4038/sljog.v44i1.8046
|
48 |
+
|
49 |
+
a Consultant Obstetrician and Gynaecologist, Colombo North Teaching Hospital, Ragama, Sri Lanka
|
50 |
+
|
51 |
+
b Consultant Obstetrician and Gynaecologist, Castle Street Hospital for Women, Colombo 8, Sri Lanka
|
52 |
+
|
53 |
+
c Professor in Obstetrics and Gynaecology Department of Obstetrics and Gynaecology, University of Colombo, Sri Lanka
|
54 |
+
|
55 |
+
d Consultant Obstetrician and Gynaecologist, Colombo North Teaching Hospital, Ragama, Sri Lanka
|
56 |
+
|
57 |
+
e Consultant Obstetrician and Gynaecologist, Colombo North Teaching Hospital, Ragama, Sri Lanka
|
58 |
+
|
59 |
+
Vol. 44, No. 1, March 2022
|
60 |
+
|
61 |
+
65
|
62 |
+
|
63 |
+
SLCOG Guideline
|
64 |
+
|
65 |
+
Hypertensive disorders of pregnancy are classified by SLCOG as
|
66 |
+
|
67 |
+
1. Preeclampsia – Pregnancy specific disorder with Hypertension cured following the delivery of the conceptus.
|
68 |
+
|
69 |
+
2. Chronic hypertension – Hypertension pre-existing the pregnancy due to various causes.
|
70 |
+
|
71 |
+
3. Preeclampsia – Superimposed on chronic hypertension.
|
72 |
+
|
73 |
+
4. Hypertension discovered for the first-time during pregnancy without clinical criteria necessary for the diagnosis of preeclampsia – May or may not disappear after delivery.
|
74 |
+
|
75 |
+
5. Supra-physiological hypertension – Exaggerated physiological response in the latter part of the pregnancy in the presence of multiple pregnancies without other symptoms or signs of preeclampsia.
|
76 |
+
|
77 |
+
Hypertension is defined in pregnancy as systolic blood pressure greater than or equal to 140mmhg or a diastolic blood pressure of greater than or equal to 90mmHg or more, or both, on two occasions at least 4 hours apart after 20th weeks of gestation, in seated or left lateral position with at least ten minutes rest before the measurement was taken.
|
78 |
+
|
79 |
+
In a woman with a previously normal blood pressure, hypertension is considered to be severe when the systolic level reaches 160mmHg or the diastolic level reaches 110mmHg with a mean arterial pressure of more than 130mmHg even on one occasion.
|
80 |
+
|
81 |
+
Preeclampsia is defined as hypertension found for the first time during current pregnancy with significant proteinuria (300mg per 24 hours or urine Protein/ Creatinine ratio of 30 mg/mmol or more)7. If urine albumin to creatinine ratio is considered an alternative for the diagnosis of significant proteinuria, the cut-off value of 8mg /mmol is taken as the value for con- sideration7.
|
82 |
+
|
83 |
+
It is not essential to have significant proteinuria for the diagnosis of preeclampsia (although it is the most commonly used supportive evidence for preeclampsia in the presence of significant hypertension). However, the absence of significant proteinuria, other parameters as given below with preeclampsia-specific organ involvement could use for the diagnosis of Preec- lampsia. They are;\n\n66
|
84 |
+
|
85 |
+
• Platelet count (Less than 100 × 109 /l )
|
86 |
+
|
87 |
+
• Liver profile (Elevation of liver transaminases twice the normal value)
|
88 |
+
|
89 |
+
• Renal insufficiency (creatinine more than 1.1 mg/ dl or doubling of serum creatinine concentration observed in the absence of other renal disease)
|
90 |
+
|
91 |
+
• Exaggerated neurological reflexes
|
92 |
+
|
93 |
+
• Pulmonary oedema
|
94 |
+
|
95 |
+
• Foetal indicators: Such as growth retardation, reduction in liquor volume, CTG and doppler waveform-abnormalities are allowed to be used for the diagnosis of preeclampsia7.
|
96 |
+
|
97 |
+
It is the clinical experience that after making the diagnosis of preeclampsia without proteinuria, most if not all patients subsequently develop proteinuria during the time taken for management of such pregnancies. Longer the time given, more developed the proteinuria.
|
98 |
+
|
99 |
+
In a case of preeclampsia, the aim is to control blood pressure values at about 140/90mmHg as further reduction has not shown to improve maternal or foetal outcome in preeclampsia.
|
100 |
+
|
101 |
+
As in any medical condition, identifying risk categories for development of preeclampsia and taking actions to prevent the onset or worsening of the disease is of great importance.
|
102 |
+
|
103 |
+
The major risk factors for preeclampsia are;
|
104 |
+
|
105 |
+
1. Preeclampsia in first pregnancy
|
106 |
+
|
107 |
+
2. Pre-existing renal disease
|
108 |
+
|
109 |
+
3. Autoimmune conditions such as APLS and SLE
|
110 |
+
|
111 |
+
4. Diabetes mellitus
|
112 |
+
|
113 |
+
5. Pre-existing hypertension
|
114 |
+
|
115 |
+
Any of the above factors are considered to be major indicators for the risk. Therefore, instituting antiplatelet therapy in the form of 75-150mg of aspirin is recommended8.
|
116 |
+
|
117 |
+
Undermentioned factors are considered lesser risk factors for occurrence of preeclampsia.
|
118 |
+
|
119 |
+
In the presence of more than one such condition, it is advisable to start antiplatelet treatment in the form of 75-150 mg of aspirin from early second trimester until the birth of the baby.
|
120 |
+
|
121 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
122 |
+
|
123 |
+
1. First pregnancy age 35 years old
|
124 |
+
|
125 |
+
2. Pregnancy with an interval more than 10 years
|
126 |
+
|
127 |
+
3. BMI more than 35 kg/m2 or more at first visit
|
128 |
+
|
129 |
+
4. Family history of preeclampsia
|
130 |
+
|
131 |
+
5. Multiple pregnancies
|
132 |
+
|
133 |
+
It is said that prophylactic aspirin therapy for above risk categories are preventive of preterm preeclampsia when aspirin is started between 12 and 20 weeks of gestation optimally before 16 weeks of gestation but it has not shown to reduce term-preeclampsia6,7. Although there is some evidence for early calcium supple- mentation in pregnancy with a favorable effect on preeclampsia, there are no accepted guidance for such by other recognized colleges and bodies6,7.
|
134 |
+
|
135 |
+
It is recommended that achieving better control of pre- existing hypertension prior to planned pregnancy is beneficial. This has proven value in literature7. There are no recommendations for salt restriction to prevent preeclampsia or hypertension in pregnancy6.\n\nControl of blood pressure before
|
136 |
+
|
137 |
+
pregnancy
|
138 |
+
|
139 |
+
It is recommended that any woman contemplating pregnancy, if possible, to have a preconception-health check, including the measurement of blood pressure. This is more important when the maternal age is advanced (more than 35 years), history of renal disease, relevant medical disorders or with family history of early onset hypertensive disorders. If hypertension is observed, taking steps to control it is recommended as well as looking for any underlying pathology.
|
140 |
+
|
141 |
+
If essential hypertension or anything else is diagnosed, management should be aimed at controlling the blood pressure to equal to less than 140/90, using anti- hypertensives considered safe in pregnancy. Any woman with the possibility of being pregnant planned or otherwise, should avoid ACE Inhibitors or AR Blockers.
|
142 |
+
|
143 |
+
If a woman gets pregnant while on ACE inhibitors or ARBs, take steps to stop such medications immediately and offer suitable alternatives. Hydrochlorothiazide is not recommended for this category of women as it has shown increased risk of congenital abnormalities and complications of the neonate when the drug is used in pregnancy.
|
144 |
+
|
145 |
+
Vol. 44, No. 1, March 2022
|
146 |
+
|
147 |
+
SLCOG Guideline
|
148 |
+
|
149 |
+
As in any case of medically important high blood pressure management, weight management, exercise, modification of life-style leading to a stress-free life- style with sufficient rest, is advocated in hypertension in pregnancy.
|
150 |
+
|
151 |
+
When drug therapy is considered, the following drugs are proven for their efficacy and for their safety profile for the foetus. There are two categories of drugs. First used for long term control of blood pressure and the second group of drugs are used for rapidly lowering of blood pressure.
|
152 |
+
|
153 |
+
Elevations of both systolic and diastolic blood pressures are associated with negative maternal and foetal outcomes1.
|
154 |
+
|
155 |
+
Control of blood pressure during
|
156 |
+
|
157 |
+
Pregnancy
|
158 |
+
|
159 |
+
Once blood pressure elevation is diagnosed during pregnancy be it pre-existing hypertension or preec- lampsia, the drugs used are not different. However, subcategories of safe medications, if taken by the patient prior to the pregnancy, need not change if that is safe in pregnancy (eg. metoprolol, verapamil, sotalol, carvedilol etc.)
|
160 |
+
|
161 |
+
Two types of medications are used for treatment of Hypertension in pregnancy:
|
162 |
+
|
163 |
+
1. Long-term control of blood pressure
|
164 |
+
|
165 |
+
2. Rapid lowering of blood pressure.\n\nDrugs used for long term control of blood
|
166 |
+
|
167 |
+
pressure
|
168 |
+
|
169 |
+
Taking the availability, cost and side effects of the drugs available in Sri Lanka, the drug of choice for control of blood pressure in pregnancy is oral nifedipine slow release tablets followed by methyldopa and labetalol6.
|
170 |
+
|
171 |
+
Regarding pharmacotherapy for rapidly lowering of blood pressure in preeclampsia, use of hydralazine IV and labetalol IV or oral nifedipine is discussed in our previous guidance10.
|
172 |
+
|
173 |
+
Labetalol IV is very scarce in Sri Lanka. However, it is to be considered the drug of choice in the absence of contraindications, for use in the presence of tachy- cardia as a manifestation of preeclampsia. IV hydra- lazine could make the condition of tachycardia worse.
|
174 |
+
|
175 |
+
67
|
176 |
+
|
177 |
+
SLCOG Guideline
|
178 |
+
|
179 |
+
Nifedipine used in rapidly controlling blood pressure is quick-release nifedipine which is not commonly available in Sri Lanka.
|
180 |
+
|
181 |
+
Cochrane review on all three drugs recently showed no difference between the efficacy12,13.
|
182 |
+
|
183 |
+
Table 1. Outline of drugs commonly used in control of hypertension14
|
184 |
+
|
185 |
+
Drug – Mechanism Dose Contraindications Notes of action Methyldopa – 250-750 mg Depression Slow onset of action Centrally acting three times a day over 24 hours dry mouth sedation depression blurred vision Withdrawal: rebound hypertension Labetolol – Beta blocker 100-400 mg Asthma Bradycardia with mild alpha every 8 hours Chronic airways Bronchospasm vasodilator effect limitation (COPD) Headache Nausea Scalp tingling (labetolol oly) which usually resolves within 24 hours Nifedipine – Calcium 20-60 mg Aortic stenosis Severe headache in first channel antagonist slow release 24 hours twice a day Flushing Tachycardia Peripheral oedema Constipation Hydralazine – Vasodilator 25-50 mg Flushing every 8 hours Headache Nausea Lupus-like syndrome
|
186 |
+
|
187 |
+
68
|
188 |
+
|
189 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
190 |
+
|
191 |
+
Management of hypertension detected for the first time in pregnancy\n\nMild to moderate hypertension
|
192 |
+
|
193 |
+
It is advised to check blood pressure in seated or left lateral position with an appropriate blood pressure cuff, with an accurate mechanical or mercury sphyg- momanometer, four hours apart for the confirmation of the diagnosis.
|
194 |
+
|
195 |
+
Once the diagnosis is confirmed of hypertension, basic preeclampsia screening should be carried on.
|
196 |
+
|
197 |
+
This includes
|
198 |
+
|
199 |
+
• Urine Full Report
|
200 |
+
|
201 |
+
• Urine Culture and Antibiotic Sensitivity Test
|
202 |
+
|
203 |
+
• Urine Protein Quantification
|
204 |
+
|
205 |
+
• Full Blood Count
|
206 |
+
|
207 |
+
• Blood Picture
|
208 |
+
|
209 |
+
• Serum Creatinine
|
210 |
+
|
211 |
+
• Liver Profile
|
212 |
+
|
213 |
+
• PT/INR is indicated only when other investigations are showing liver involvement
|
214 |
+
|
215 |
+
Uric acid is not usually tested. Though some suggest predictive value of uric acid level interpreted in relation to the gestation to correlate better with adverse events14,15.
|
216 |
+
|
217 |
+
It is mandatory to check for foetal wellbeing with ultrasound scanning with emphasis on foetal biophysical profile, foetal doppler parameters and growth para- meters. Further monitoring of foetus with a cardio- tocographic tracing is essential. These would give an assessment of possible foetal effects of preeclampsia. In some cases foetal effects maybe the most significant finding other than the presence of hypertension.
|
218 |
+
|
219 |
+
Aim of management is to achieve maximum possible maturity of the foetus with no reasonable threat to the mother and the foetus. When the gestation is less than 34 weeks, the opinion is that it is unlikely to be favourable for achieving vaginal delivery though there are no contraindications for vaginal delivery because of the condition preeclampsia per se.
|
220 |
+
|
221 |
+
In the presence of hypertension, be it preeclampsia or not, delivery should be aimed at the completion of the 37th week of pregnancy. From the first time of detection
|
222 |
+
|
223 |
+
Vol. 44, No. 1, March 2022
|
224 |
+
|
225 |
+
SLCOG Guideline
|
226 |
+
|
227 |
+
of hypertension, until completion of 37 weeks of gestation, all patient’s clinical characteristics need to be considered in deciding the time of delivery. This includes available infrastructure facilities of neonatal care, availability of the theater and available manpower resources.
|
228 |
+
|
229 |
+
In the absence of proteinuria and derangement of other above mentioned laboratory parameters identified as indicators of preeclampsia before the 35th week of pregnancy, prediction of onset of preeclampsia can be done using PlGF (Placental Growth Factor) alone or in comparison with soluble fms-like tyrosine kinase (sFlt-1). These blood tests are widely available for use in developed countries. Results from PELICAN study (Table 2) show a cut off value of 100 picogram/ ml for PlGF as a high sensitivity test for women heading for preeclampsia which needs delivery within 14 days of the test.
|
230 |
+
|
231 |
+
The negative result would give confidence for outpatient management of women with hypertension with pregnancy. As these tests are not available in Sri Lanka, SLCOG Guidance Committee suggests outpatient management with no less than 14 days review appointments for women with hypertension in pregnancy in the absence of any other maternal, foetal, biochemical or ultrasound scan derangement of significance. The blood pressure control also need to be at a level for the satisfaction of the obstetrician concerned.
|
232 |
+
|
233 |
+
Though the 2019 NICE guideline gives an aim of keeping control of blood pressure 135/85 mmHg, there is controversy about the control need for mild to moderate hypertension in pregnancies even with preeclampsia. Treatment of blood pressure has not been shown to have prevented preeclampsia or perinatal outcomes. But the evidence shows reduction of development of severe blood pressure among treated women with mild blood pressure. Approximately 10 women need to be put on antihypertensive therapy to prevent one episode of severe hypertension11.
|
234 |
+
|
235 |
+
However, uncontrolled spikes of blood pressure in untreated pregnancies may prompt action for delivery. Therefore, achieving blood pressure control by pharmaco-therapeutic means would facilitate prolon- gation of the pregnancy to achieve greater maturity of the foetus.\n\n69
|
236 |
+
|
237 |
+
SLCOG Guideline
|
238 |
+
|
239 |
+
Table 2. PELICAN 2013 study results: Triage PlGF (Placental Growth Factor) test accuracy for predicting preeclampsia needing delivery within 14 days for women presenting between 20 weeks and 34 weeks plus 6 days gestation7
|
240 |
+
|
241 |
+
Test cut-off Sensitivity Specificity PPV NPV (95% CI) (95% CI) (95% CI) (95% CI) <100pg/ml 0.96 .56 .44 .98 (0.89 to 0.99) (0.46 - 0.63) (0.36 to 0.52) (0.93 to 1.00) >/= 100pg/ml 0.96 .56 .43 .98 (0.89 to 0.99) (0.49 to 0.63) (0.36 to 0.51) (0.93 to 1.00) <fifth percentile .96 0.56 0.43 .98 (0.89 to 0.99) (0.48 to 0.61) (0.36 to 0.51) (0.93 to 1.00) <12 pg/ml 0.63 0.90 0.70 0.87 (0.51 to 0.74) (0.85 to 0.94) (0.57 to 0.80) (0.82 to 0.91)
|
242 |
+
|
243 |
+
Cochrane review of treatment has shown the possibility of clinically relevant reduction in preeclampsia related foetal or neonatal death particularly early pregnancy loss with treatment of mild to moderate hypertension in pregnancy. Antihypertensive therapy does not prevent preeclampsia (RR 0.99; 95% CI-0.84-1.18) or the associated adverse perinatal outcomes, but it decreases by half the incidence of development of severe hypertension among women with mild hypertension (RR 0.52; 95% CI-0.41 - 0.64)11.
|
244 |
+
|
245 |
+
In the presence of biochemical markers for systemic involvement, the patient is recommended for in-ward patient care. When a patient is admitted to a ward for preeclampsia, an obstetrician needs to review the patient at least 72 hours apart. Repetition of frequency of biochemistry depends on the available clinical data on the patient. Progression of the disease as indicated by investigative deterioration is to be considered important for more action: eg: Observed drop in platelet count even though the total count is over 100, mm9/L or rising liver enzymes.
|
246 |
+
|
247 |
+
The focus of control, if antihypertensives are started, is aimed at achieving blood pressure targets bet- ween140-160 /90-100 mmHg, taking local practice and existence of hypertension predating pregnancy into consideration11. SLCOG recommends aiming to keep blood pressure at or below 150/100 mmHg.
|
248 |
+
|
249 |
+
However, once significant proteinuria is observed, increasing the amount of protein is not indicative of outcome of preeclampsia.
|
250 |
+
|
251 |
+
When the delivery decision is taken, the appropriate mode of delivery would be decided by;\n\nMonitoring
|
252 |
+
|
253 |
+
• The clinical picture
|
254 |
+
|
255 |
+
In the absence of any investigative derangement of biochemical or foetal parameters, deviations of only the blood pressure which is judged to be controlled by the obstetrician. Repetition of full assessment of the patient inclusive of biochemistry and foetus is recommended in intervals not less than 14 days apart until the time of delivery.
|
256 |
+
|
257 |
+
• Period of gestation
|
258 |
+
|
259 |
+
• Platelet count
|
260 |
+
|
261 |
+
• Liver involvement.
|
262 |
+
|
263 |
+
Patients with significant liver involvement or a drop in platelet count less than 70 × 109/L6, should be delivered preferably in the presence of the specialist team.
|
264 |
+
|
265 |
+
70
|
266 |
+
|
267 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
268 |
+
|
269 |
+
NICE guidance does not recommend planned early birth before 37th week to a woman with chronic hypertension whose blood pressure is less than 160/ 110 mmHg with or without antihypertensive treatment unless there are other medical indicators.
|
270 |
+
|
271 |
+
If planned birth before completion of 37th is necessary a course of corticosteroids and magnesium sulfate is to be used if indicated.\n\nSevere hypertension
|
272 |
+
|
273 |
+
Severe Hypertension is considered to be present when the blood pressure recorded is more than 160/110 mmHg or a Mean Arterial Pressure of more than 130 mmHg is detected in pregnancy. This could be due to any one of the above mentioned (1) - (4) hypertensive disorders of pregnancy. Eclampsia (or occurrence of seizures) is a common complication of severe hypertension though the relationship is not linear.
|
274 |
+
|
275 |
+
If eclampsia is present the SLCOG in keeping up with all available international guidance, recommends delivery as early as possible before 24 hours of occurrence of the first fit. For an ongoing convulsion, use of anticonvulsant agents such as IV magnesium sulfate is recommended.
|
276 |
+
|
277 |
+
Any woman who is being treated for severe hyper- tension whose birth is planned within the next 24 hours, consideration should be given for medication of intravenous magnesium sulfate. Following symptoms are recommended as points to consider magnesium sulfate treatment
|
278 |
+
|
279 |
+
• Severe headache
|
280 |
+
|
281 |
+
• Visual disturbance
|
282 |
+
|
283 |
+
• Nausea and vomiting
|
284 |
+
|
285 |
+
• Epigastric pain
|
286 |
+
|
287 |
+
• Oliguria
|
288 |
+
|
289 |
+
• Deterioration of laboratory parameters
|
290 |
+
|
291 |
+
(NICE 2010, amended 2019)
|
292 |
+
|
293 |
+
SLCOG recommends the use of collaborative eclampsia trial for administration of magnesium sulfate7.
|
294 |
+
|
295 |
+
Vol. 44, No. 1, March 2022
|
296 |
+
|
297 |
+
SLCOG Guideline
|
298 |
+
|
299 |
+
• A loading dose of 4g should be given intravenously over 5 to 15 minutes, followed by an infusion of 1g/hour maintained for 24 hours. If the woman has had an eclamptic fit, the infusion should be continued for 24 hours after the last fit.
|
300 |
+
|
301 |
+
• Recurrent fits should be treated with a further dose of 2-4 g given intravenously over 5 to 15 minutes [NICE 2010, amended 2019].
|
302 |
+
|
303 |
+
• Do not use diazepam, phenytoin or other anti- convulsants as an alternative to magnesium sulfate in women with eclampsia [2010, amended 2019].
|
304 |
+
|
305 |
+
Antihypertensive treatment is aimed at rapidly lowering blood pressure to a safer level. SLCOG recommends bringing down blood pressure to 150/100 or less with the use of medication recommended for rapidly lowering blood pressure. They are IV hydralazine, IV labetalol, oral nifedipine quick-release. Medication regimen is indicated in our previous guidance10.
|
306 |
+
|
307 |
+
It is recommended to use a crystalloid load of 500ml prior to or concomitantly when drugs are used for rapidly lowering of blood pressure. This is very important especially in managing patients with oliguria but is not confined to the management of oliguria.
|
308 |
+
|
309 |
+
In women managed for preeclampsia with severe hypertension, decision of delivery should be considered when the foetal maturity is 35 weeks or more. But before 34 weeks +6 days if blood pressure control is achieved and laboratory parameters are favorable with due consideration of infrastructure and manpower and continuing pregnancy until 35 weeks is recommended with close scrutiny of the patient every 24 hours.
|
310 |
+
|
311 |
+
Mode of delivery when decided should be done on the clinical criteria, available infrastructure and monitoring facilities in consultation with the mother’s wish.
|
312 |
+
|
313 |
+
It is important that appropriate critical care provision is the duty of the head of the institution when requested by the in-charge obstetrician.
|
314 |
+
|
315 |
+
SLCOG supports the clinical criteria for choice of critical care, as given in Table 4 of NICE guideline, June 25: 2019 (7), given below.
|
316 |
+
|
317 |
+
71
|
318 |
+
|
319 |
+
SLCOG Guideline\n\nClinical criteria for choice of critical care level
|
320 |
+
|
321 |
+
Level 3 care Severe pre-eclampsia and needing ventilation Level 2 care Step-down from level 3 or severe pre-eclampsia with any of the following complications: • Eclampsia • HELLP syndrome • Haemorrhage • Hyperkalemia • Severe oliguria • Coagulation support • Intravenous antihypertensive treatment • Initial stabilization of severe hypertension • Evidence of cardiac failure • Abnormal neurology Level 1 care Pre-eclampsia with hypertension Ongoing conservative antenatal management of severe preterm hypertension Step-down treatment after birth
|
322 |
+
|
323 |
+
Care of woman after delivery
|
324 |
+
|
325 |
+
Continue monitoring of clinical parameters with the same vigilance in the first 48 hours following delivery of a patient who has been delivered. Medications used in pregnancy can be continued.
|
326 |
+
|
327 |
+
The patients who had preeclampsia who were found to have no hypertension or proteinuria at 6 to 8 weeks postpartum could be reassured about their renal status as the absolute risk for End Stage Kidney disease is very low.
|
328 |
+
|
329 |
+
It is preferable the case is that of a preeclampsia urine albumin to be negative before discharge from the hospital. In patients with proteinuria persisting, discharge from the hospital for care in the community should be done by the consultant/specialist in charge of the care.
|
330 |
+
|
331 |
+
They can be assured that no further follow up on renal component or hypertension is necessary if they are in the normal range at 6 to 8 weeks. Hypertension persisting after 6-8 weeks from delivery should be referred for a medical specialists care.
|
332 |
+
|
333 |
+
Drugs used in hypertension are excreted through breast milk, though no harmful effects are observed, manufacturers do not commit themselves on lactation. As preeclampsia settles down after delivery, by six weeks postpartum most medication can be tapered off and stopped with the individual assessment of patients. Providing appropriate contraceptive advice is recommended.
|
334 |
+
|
335 |
+
In Sri Lanka consideration should be for offering a permanent method of contraception to women who have completed their family or had experienced recurrent severe hypertension in pregnancy if cesarean delivery was contemplated as the mode of delivery.
|
336 |
+
|
337 |
+
Preeclampsia is a state where SLCOG recommends use of postoperative thromboprophylaxis with enoxaparin when operative delivery was the mode of delivery.\n\nReferences
|
338 |
+
|
339 |
+
1. Lowe SA, Brown MA, Dekker GA, Gatt S, McLintock CK, McMahon LP, et al. Guidelines for the management of hypertensive disorders of pregnancy 2008, Austr N S J Obstet Gynaecol 2009; 49(3): 242-6 (Epub 2009/07/02).
|
340 |
+
|
341 |
+
2. AbouZahr C, Guidotti R. Hypertensive disorders of pregnancy. In: Murray, CJL and Lopez, AD, eds,. Health dimensions of sex and reproduction:
|
342 |
+
|
343 |
+
72
|
344 |
+
|
345 |
+
Sri Lanka Journal of Obstetrics and Gynaecology
|
346 |
+
|
347 |
+
the global burden of sexually transmitted diseases, maternal conditions, perinatal disorders, and congenital anomalies. WHO 1998.
|
348 |
+
|
349 |
+
3. Family Health Bureau, Ministry of Health Sri Lanka, 2020 National statistics, <https://fhb.health.gov.lk/ index.php/en/statistics> Date accessed 03/03/2022
|
350 |
+
|
351 |
+
4. Family Health Bureau, Ministry of Health Sri Lanka, 2019 Report, <http://www.fhb.health.gov.lk/ index.php/si/resources/annual-report> Date accessed 3/32022
|
352 |
+
|
353 |
+
5. Brown MA, Lindheimer MD, de Swiet M, Assche AV, Moutquin J-M. The classification and diagnosis of the hypertensive disorders of pregnancy: statement from the international society for the study of hypertension in pregnancy (ISSHP). Hypertens Pregnancy 2001; 20 (1): ix-xiv
|
354 |
+
|
355 |
+
6. Gestational Hypertension and Preeclampsia. Acog Practice Bulletin Number 202. American College of Obstetricians and Gynecologists. Obstet Gynecol 2019; 133: No.1
|
356 |
+
|
357 |
+
7. Nice.org.uk. June 25, 2019. Overview | Hyper- tension in pregnancy: diagnosis and management | Guidance | NICE. [online] Available at: <https:// www.nice.org.uk/guidance/ng133> [Accessed 22 March 2022]
|
358 |
+
|
359 |
+
8. Rolnik DL, Wright D, Poon LC, O’Gorman N, Syngelaki A, de Paco Matallana C, et al. Aspirin versus placebo in pregnancies at high risk for preterm preeclampsia. N Engl J Med 2017; 377: 613-22.
|
360 |
+
|
361 |
+
9. Hofmeyr GJ, Lawrie TA, Atallah AN, Duley L, Torloni MR. Calcium supplementation during pregnancy for preventing hypertensive disorders and related problems. Cochrane Database of Systemic Reviews 2014, Issue 6. Art. No.: CD001059. (Systematic Review and Meta- Analysis)
|
362 |
+
|
363 |
+
10. Senadheera D, Jayasundara DMSC, Jayawardane,
|
364 |
+
|
365 |
+
Vol. 44, No. 1, March 2022
|
366 |
+
|
367 |
+
SLCOG Guideline
|
368 |
+
|
369 |
+
IA, Ratnasiri UDP, 2021. Management of hypertensive disease in pregnancy. Sri Lanka Journal of Obstetrics and Gynaecology 2021; 43(4): 383-94. DOI: http://doi.org/10.4038/ sljog.v43i4.8033
|
370 |
+
|
371 |
+
11. Lowe S, Bowyer L, Lust K, McMahon L, Morton M, North R, Paech M, Said J. 2014. The SOMANZ Guideline for the Management of Hypertensive Disorders of Pregnancy. [online] Somanz.org. Available at: <https://www.somanz.org/documents/ HTPregnancyGuidelineJuly2014.pdf> [Accessed 18 March 2022].
|
372 |
+
|
373 |
+
12. Duley L, MEher S, Jones L. Drugs for treatment of very high blood pressure during pregnancy. Cochrane-Database of Systemic Reviews 2013, Issue 7. Art. No.: CD001449. (Systemic Review and Meta-Analysis)
|
374 |
+
|
375 |
+
13. Emergent therapy for acute-onset, severe hypertension during pregnancy and the postpartum period. Committee Opinion No. 692. American College of Obstetricians and Gynecologists, Monster Gynecol 2017: 129: e90-5. (Level III)
|
376 |
+
|
377 |
+
14. Koopmans CM, van Pampus MG, Groen H, Aarnoudse JG, van den Berg PP, Mol BW. Accuracy of serum uric acid as a predictive test for maternal complications in pre-eclampsia: bivariate meta-analysis and decision analysis, European Journal of Obstetrics, Gynecology & Reproductive Biology 2009; 146(1): 8-14.
|
378 |
+
|
379 |
+
15. Lind T, Godfrey KA, Otun H, Philips PR. Changes in serum uric acid concentrations during normal pregnancy. British Journal of Obstetrics & Gynaecology 1984; 91 (2): 128-32.
|
380 |
+
|
381 |
+
16. Abalos E, Duley L, Steyn DW, Henderson-Smart DJ. Antihypertensive drug therapy for mild to moderate hypertension during pregnancy. Cochrane Database of Systematic Reviews 2007 (1): CD002252.
|
382 |
+
|
383 |
+
73
|