Spaces:
Build error
Build error
Update rag_pipeline.py
Browse files- rag_pipeline.py +27 -39
rag_pipeline.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
import pdfplumber
|
| 2 |
import faiss
|
| 3 |
import torch
|
| 4 |
from transformers import pipeline
|
|
@@ -6,22 +6,18 @@ from sentence_transformers import SentenceTransformer
|
|
| 6 |
import json
|
| 7 |
import re
|
| 8 |
|
| 9 |
-
# Load models (
|
| 10 |
embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 11 |
qa_model = pipeline("text2text-generation", model="google/flan-t5-base", device=-1)
|
| 12 |
|
| 13 |
def extract_text_from_pdf(pdf_file):
|
| 14 |
-
"""Extracts text from all pages in the PDF."""
|
| 15 |
text = ""
|
| 16 |
with pdfplumber.open(pdf_file) as pdf:
|
| 17 |
for page in pdf.pages:
|
| 18 |
-
|
| 19 |
-
if page_text: # only add if there's text
|
| 20 |
-
text += page_text + "\n"
|
| 21 |
return text
|
| 22 |
|
| 23 |
def chunk_text(text, chunk_size=2000, overlap=200):
|
| 24 |
-
"""Splits text into overlapping chunks."""
|
| 25 |
chunks = []
|
| 26 |
start = 0
|
| 27 |
while start < len(text):
|
|
@@ -31,32 +27,26 @@ def chunk_text(text, chunk_size=2000, overlap=200):
|
|
| 31 |
return chunks
|
| 32 |
|
| 33 |
def embed_chunks(chunks):
|
| 34 |
-
"""Generates embeddings for each text chunk."""
|
| 35 |
return embedder.encode(chunks)
|
| 36 |
|
| 37 |
def build_faiss_index(embeddings):
|
| 38 |
-
"""Builds a FAISS index for the embeddings to allow efficient retrieval."""
|
| 39 |
dim = embeddings[0].shape[0]
|
| 40 |
index = faiss.IndexFlatL2(dim)
|
| 41 |
index.add(embeddings)
|
| 42 |
return index
|
| 43 |
|
| 44 |
def retrieve_relevant_chunks(query, chunks, embeddings, index, top_k=3):
|
| 45 |
-
"""Searches for the top_k chunks most relevant to the query."""
|
| 46 |
query_vec = embedder.encode([query])
|
| 47 |
distances, indices = index.search(query_vec, top_k)
|
| 48 |
return [chunks[i] for i in indices[0]]
|
| 49 |
|
| 50 |
def generate_prompt(context):
|
| 51 |
-
"""Generates a prompt instructing the model to extract structured data.
|
| 52 |
-
|
| 53 |
-
If any information is missing in the prescription, it will be represented as an empty string or an empty list.
|
| 54 |
-
"""
|
| 55 |
return f"""
|
| 56 |
You are an AI that extracts structured data from prescriptions.
|
| 57 |
Prescription text:
|
| 58 |
\"\"\"{context[:1000]}\"\"\"
|
| 59 |
-
Return
|
|
|
|
| 60 |
{{
|
| 61 |
"Doctor Name": "",
|
| 62 |
"Patient Name": "",
|
|
@@ -68,45 +58,46 @@ Return only a valid JSON object in the following format. If any information is m
|
|
| 68 |
}}
|
| 69 |
]
|
| 70 |
}}
|
| 71 |
-
Strictly output only valid JSON. Do not include
|
| 72 |
"""
|
| 73 |
|
| 74 |
def extract_structured_data(pdf_file):
|
| 75 |
-
"""Extracts structured data (Doctor Name, Patient Name, Date, Medications) from a prescription PDF."""
|
| 76 |
text = extract_text_from_pdf(pdf_file)
|
| 77 |
|
| 78 |
-
# For smaller texts, we handle directly
|
| 79 |
if len(text) < 2000:
|
| 80 |
prompt = generate_prompt(text)
|
| 81 |
else:
|
| 82 |
chunks = chunk_text(text)
|
| 83 |
embeddings = embed_chunks(chunks)
|
| 84 |
index = build_faiss_index(embeddings)
|
| 85 |
-
|
| 86 |
query = "Extract doctor name, patient name, date, and medications from prescription"
|
| 87 |
top_chunks = retrieve_relevant_chunks(query, chunks, embeddings, index)
|
| 88 |
prompt = generate_prompt("\n\n".join(top_chunks))
|
| 89 |
-
|
| 90 |
-
print("
|
| 91 |
-
|
| 92 |
-
|
| 93 |
result = qa_model(prompt, max_new_tokens=300)[0]['generated_text']
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
print("\nDEBUG: Raw model output:")
|
| 97 |
-
print(result)
|
| 98 |
-
|
| 99 |
try:
|
| 100 |
-
#
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
if json_match:
|
| 103 |
cleaned_json = json_match.group(0)
|
| 104 |
-
|
| 105 |
-
return structured_data
|
| 106 |
else:
|
| 107 |
-
raise ValueError("No valid JSON found
|
| 108 |
except Exception as e:
|
| 109 |
-
# Return debugging information if JSON extraction fails
|
| 110 |
return {
|
| 111 |
"error": "Failed to parse model response",
|
| 112 |
"raw_output": result,
|
|
@@ -114,8 +105,5 @@ def extract_structured_data(pdf_file):
|
|
| 114 |
}
|
| 115 |
|
| 116 |
# Example usage:
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
data = extract_structured_data(pdf_path)
|
| 120 |
-
print("\nExtracted Data:")
|
| 121 |
-
print(json.dumps(data, indent=2))
|
|
|
|
| 1 |
+
import pdfplumber
|
| 2 |
import faiss
|
| 3 |
import torch
|
| 4 |
from transformers import pipeline
|
|
|
|
| 6 |
import json
|
| 7 |
import re
|
| 8 |
|
| 9 |
+
# Load models (switch to distilflan-t5-small for speed improvement)
|
| 10 |
embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 11 |
qa_model = pipeline("text2text-generation", model="google/flan-t5-base", device=-1)
|
| 12 |
|
| 13 |
def extract_text_from_pdf(pdf_file):
|
|
|
|
| 14 |
text = ""
|
| 15 |
with pdfplumber.open(pdf_file) as pdf:
|
| 16 |
for page in pdf.pages:
|
| 17 |
+
text += page.extract_text() or ""
|
|
|
|
|
|
|
| 18 |
return text
|
| 19 |
|
| 20 |
def chunk_text(text, chunk_size=2000, overlap=200):
|
|
|
|
| 21 |
chunks = []
|
| 22 |
start = 0
|
| 23 |
while start < len(text):
|
|
|
|
| 27 |
return chunks
|
| 28 |
|
| 29 |
def embed_chunks(chunks):
|
|
|
|
| 30 |
return embedder.encode(chunks)
|
| 31 |
|
| 32 |
def build_faiss_index(embeddings):
|
|
|
|
| 33 |
dim = embeddings[0].shape[0]
|
| 34 |
index = faiss.IndexFlatL2(dim)
|
| 35 |
index.add(embeddings)
|
| 36 |
return index
|
| 37 |
|
| 38 |
def retrieve_relevant_chunks(query, chunks, embeddings, index, top_k=3):
|
|
|
|
| 39 |
query_vec = embedder.encode([query])
|
| 40 |
distances, indices = index.search(query_vec, top_k)
|
| 41 |
return [chunks[i] for i in indices[0]]
|
| 42 |
|
| 43 |
def generate_prompt(context):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
return f"""
|
| 45 |
You are an AI that extracts structured data from prescriptions.
|
| 46 |
Prescription text:
|
| 47 |
\"\"\"{context[:1000]}\"\"\"
|
| 48 |
+
Return a valid JSON object with all the fields below, even if some values are empty. If a value is missing in the prescription, use an empty string ("") or empty list ([]) as appropriate.
|
| 49 |
+
|
| 50 |
{{
|
| 51 |
"Doctor Name": "",
|
| 52 |
"Patient Name": "",
|
|
|
|
| 58 |
}}
|
| 59 |
]
|
| 60 |
}}
|
| 61 |
+
Strictly output only valid JSON. Do not include any commentary, markdown, or extra characters.
|
| 62 |
"""
|
| 63 |
|
| 64 |
def extract_structured_data(pdf_file):
|
|
|
|
| 65 |
text = extract_text_from_pdf(pdf_file)
|
| 66 |
|
|
|
|
| 67 |
if len(text) < 2000:
|
| 68 |
prompt = generate_prompt(text)
|
| 69 |
else:
|
| 70 |
chunks = chunk_text(text)
|
| 71 |
embeddings = embed_chunks(chunks)
|
| 72 |
index = build_faiss_index(embeddings)
|
| 73 |
+
|
| 74 |
query = "Extract doctor name, patient name, date, and medications from prescription"
|
| 75 |
top_chunks = retrieve_relevant_chunks(query, chunks, embeddings, index)
|
| 76 |
prompt = generate_prompt("\n\n".join(top_chunks))
|
| 77 |
+
|
| 78 |
+
print(f"\nGenerated Prompt:\n{prompt[:500]}...\n") # Debugging
|
| 79 |
+
|
|
|
|
| 80 |
result = qa_model(prompt, max_new_tokens=300)[0]['generated_text']
|
| 81 |
+
print(f"Model Output:\n{result[:500]}...\n") # Debugging
|
| 82 |
+
|
|
|
|
|
|
|
|
|
|
| 83 |
try:
|
| 84 |
+
# Fail-safe: model returned just []
|
| 85 |
+
if result.strip() == "[]":
|
| 86 |
+
return {
|
| 87 |
+
"Doctor Name": "",
|
| 88 |
+
"Patient Name": "",
|
| 89 |
+
"Date": "",
|
| 90 |
+
"Medications": []
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
# Extract valid JSON object
|
| 94 |
+
json_match = re.search(r'{.*}', result, re.DOTALL)
|
| 95 |
if json_match:
|
| 96 |
cleaned_json = json_match.group(0)
|
| 97 |
+
return json.loads(cleaned_json)
|
|
|
|
| 98 |
else:
|
| 99 |
+
raise ValueError("No valid JSON found.")
|
| 100 |
except Exception as e:
|
|
|
|
| 101 |
return {
|
| 102 |
"error": "Failed to parse model response",
|
| 103 |
"raw_output": result,
|
|
|
|
| 105 |
}
|
| 106 |
|
| 107 |
# Example usage:
|
| 108 |
+
extracted_data = extract_structured_data("/mnt/data/251052753219049.pdf")
|
| 109 |
+
print("\nFinal Extracted Data:\n", extracted_data)
|
|
|
|
|
|
|
|
|