Spaces:
Build error
Build error
Update rag_pipeline.py
Browse files- rag_pipeline.py +26 -85
rag_pipeline.py
CHANGED
|
@@ -1,114 +1,55 @@
|
|
|
|
|
|
|
|
| 1 |
import pdfplumber
|
| 2 |
-
import faiss
|
| 3 |
-
import torch
|
| 4 |
-
from transformers import pipeline
|
| 5 |
-
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_input):
|
| 14 |
text = ""
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
text += page.extract_text() or ""
|
| 19 |
-
except Exception as e:
|
| 20 |
-
raise ValueError(f"Failed to open PDF: {e}")
|
| 21 |
return text
|
| 22 |
|
| 23 |
-
def
|
| 24 |
-
chunks = []
|
| 25 |
-
start = 0
|
| 26 |
-
while start < len(text):
|
| 27 |
-
end = start + chunk_size
|
| 28 |
-
chunks.append(text[start:end])
|
| 29 |
-
start += chunk_size - overlap
|
| 30 |
-
return chunks
|
| 31 |
-
|
| 32 |
-
def embed_chunks(chunks):
|
| 33 |
-
return embedder.encode(chunks)
|
| 34 |
-
|
| 35 |
-
def build_faiss_index(embeddings):
|
| 36 |
-
dim = embeddings[0].shape[0]
|
| 37 |
-
index = faiss.IndexFlatL2(dim)
|
| 38 |
-
index.add(embeddings)
|
| 39 |
-
return index
|
| 40 |
-
|
| 41 |
-
def retrieve_relevant_chunks(query, chunks, embeddings, index, top_k=3):
|
| 42 |
-
query_vec = embedder.encode([query])
|
| 43 |
-
distances, indices = index.search(query_vec, top_k)
|
| 44 |
-
return [chunks[i] for i in indices[0]]
|
| 45 |
-
|
| 46 |
-
def generate_prompt(context):
|
| 47 |
return f"""
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
|
|
|
|
| 53 |
|
| 54 |
-
|
| 55 |
{{
|
| 56 |
-
"
|
| 57 |
-
"
|
| 58 |
-
"
|
| 59 |
-
"
|
| 60 |
{{
|
| 61 |
-
"name":
|
| 62 |
-
"dosage":
|
| 63 |
}}
|
| 64 |
]
|
| 65 |
}}
|
| 66 |
-
</json>
|
| 67 |
-
|
| 68 |
-
Only return the JSON block, nothing else.
|
| 69 |
"""
|
| 70 |
|
| 71 |
-
def replace_empty_with_null(data):
|
| 72 |
-
if isinstance(data, dict):
|
| 73 |
-
return {k: replace_empty_with_null(v) for k, v in data.items()}
|
| 74 |
-
elif isinstance(data, list):
|
| 75 |
-
return [replace_empty_with_null(v) for v in data]
|
| 76 |
-
elif data in ("", [], {}):
|
| 77 |
-
return None
|
| 78 |
-
else:
|
| 79 |
-
return data
|
| 80 |
-
|
| 81 |
def extract_structured_data(pdf_file):
|
| 82 |
text = extract_text_from_pdf(pdf_file)
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
prompt = generate_prompt(text)
|
| 86 |
-
else:
|
| 87 |
-
chunks = chunk_text(text)
|
| 88 |
-
embeddings = embed_chunks(chunks)
|
| 89 |
-
index = build_faiss_index(embeddings)
|
| 90 |
-
|
| 91 |
-
query = "Extract doctor name, patient name, date, and medications from prescription"
|
| 92 |
-
top_chunks = retrieve_relevant_chunks(query, chunks, embeddings, index)
|
| 93 |
-
prompt = generate_prompt("\n\n".join(top_chunks))
|
| 94 |
-
|
| 95 |
-
print(f"\nGenerated Prompt:\n{prompt[:500]}...\n") # Debug
|
| 96 |
-
|
| 97 |
-
result = qa_model(prompt, max_new_tokens=500)[0]['generated_text']
|
| 98 |
-
print(f"Model Output:\n{result[:500]}...\n") # Debug
|
| 99 |
|
| 100 |
try:
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
if json_match:
|
| 104 |
-
cleaned_json = json_match.group(1).strip()
|
| 105 |
-
parsed = json.loads(cleaned_json)
|
| 106 |
-
return replace_empty_with_null(parsed)
|
| 107 |
-
else:
|
| 108 |
-
raise ValueError("No valid JSON found.")
|
| 109 |
except Exception as e:
|
| 110 |
return {
|
| 111 |
-
"error": "Failed to parse model
|
| 112 |
"raw_output": result,
|
| 113 |
"exception": str(e)
|
| 114 |
}
|
|
|
|
| 1 |
+
# rag_pipeline.py
|
| 2 |
+
|
| 3 |
import pdfplumber
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import json
|
| 5 |
import re
|
| 6 |
+
from transformers import pipeline
|
| 7 |
|
|
|
|
|
|
|
| 8 |
qa_model = pipeline("text2text-generation", model="google/flan-t5-base", device=-1)
|
| 9 |
|
| 10 |
def extract_text_from_pdf(pdf_input):
|
| 11 |
text = ""
|
| 12 |
+
with pdfplumber.open(pdf_input) as pdf:
|
| 13 |
+
for page in pdf.pages:
|
| 14 |
+
text += page.extract_text() or ""
|
|
|
|
|
|
|
|
|
|
| 15 |
return text
|
| 16 |
|
| 17 |
+
def generate_prompt(text):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
return f"""
|
| 19 |
+
Extract the following information from the text below:
|
| 20 |
+
1. Doctor's Name
|
| 21 |
+
2. Patient's Name
|
| 22 |
+
3. Date
|
| 23 |
+
4. Medications (name and dosage)
|
| 24 |
|
| 25 |
+
Text:
|
| 26 |
+
\"\"\"{text[:1500]}\"\"\"
|
| 27 |
|
| 28 |
+
Return a JSON like this:
|
| 29 |
{{
|
| 30 |
+
"doctor_name": "...",
|
| 31 |
+
"patient_name": "...",
|
| 32 |
+
"date": "...",
|
| 33 |
+
"medications": [
|
| 34 |
{{
|
| 35 |
+
"name": "...",
|
| 36 |
+
"dosage": "..."
|
| 37 |
}}
|
| 38 |
]
|
| 39 |
}}
|
|
|
|
|
|
|
|
|
|
| 40 |
"""
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
def extract_structured_data(pdf_file):
|
| 43 |
text = extract_text_from_pdf(pdf_file)
|
| 44 |
+
prompt = generate_prompt(text)
|
| 45 |
+
result = qa_model(prompt, max_new_tokens=512)[0]["generated_text"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
try:
|
| 48 |
+
json_block = re.search(r"\{.*\}", result, re.DOTALL).group(0)
|
| 49 |
+
return json.loads(json_block)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
except Exception as e:
|
| 51 |
return {
|
| 52 |
+
"error": "Failed to parse model output",
|
| 53 |
"raw_output": result,
|
| 54 |
"exception": str(e)
|
| 55 |
}
|