Spaces:
Sleeping
Sleeping
File size: 8,986 Bytes
5c32ed1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | import json
import re
import hashlib
from tqdm import tqdm
INPUT_FILE = "data/processed/extracted_sections.json"
OUTPUT_FILE = "data/processed/rag_chunks.json"
TARGET_CHUNK_TOKENS = 400
MAX_CHUNK_TOKENS = 600
OVERLAP_SENTENCES = 2
LOW_VALUE_SECTIONS = {"References", "U.S. Food and Drug Administration"}
BOILERPLATE_SECTIONS = {"Instructions for Use", "Policy History/Revision Information"}
def estimate_tokens(text):
return int(len(text.split()) * 1.3)
def split_sentences(text):
parts = re.split(r'(?<=[.;])\s+(?=[A-Z])', text)
sentences = []
for part in parts:
if estimate_tokens(part) > MAX_CHUNK_TOKENS:
sub_parts = re.split(r'(?<=[:;])\s+', part)
sentences.extend(sub_parts)
else:
sentences.append(part)
return [s.strip() for s in sentences if s.strip()]
def chunk_id(policy, section, idx):
raw = f"{policy}__{section}__{idx}"
return hashlib.md5(raw.encode()).hexdigest()[:12]
def chunk_by_criteria(text, policy_name):
blocks = re.split(
r'\n\n(?=(?:The following|For (?:initial|continuation|subsequent|revision|replacement)|'
r'(?:An?|The)\s+\w.*?is (?:proven|unproven|medically necessary|not medically)|'
r'(?:Multiplex|Implantable|Removable|Emergency|Non-Surgical|Surgical)))',
text
)
if len(blocks) <= 1:
blocks = re.split(r'\n\n', text)
result = []
current = []
current_tokens = 0
for block in blocks:
block = block.strip()
if not block:
continue
block_tokens = estimate_tokens(block)
if block_tokens > MAX_CHUNK_TOKENS:
if current:
result.append("\n\n".join(current))
current = []
current_tokens = 0
sents = split_sentences(block)
sent_group = []
sent_tokens = 0
for sent in sents:
st = estimate_tokens(sent)
if sent_tokens + st > TARGET_CHUNK_TOKENS and sent_group:
result.append(" ".join(sent_group))
overlap = sent_group[-OVERLAP_SENTENCES:] if len(sent_group) > OVERLAP_SENTENCES else []
sent_group = overlap
sent_tokens = sum(estimate_tokens(s) for s in sent_group)
sent_group.append(sent)
sent_tokens += st
if sent_group:
result.append(" ".join(sent_group))
elif current_tokens + block_tokens > TARGET_CHUNK_TOKENS and current:
result.append("\n\n".join(current))
current = [block]
current_tokens = block_tokens
else:
current.append(block)
current_tokens += block_tokens
if current:
result.append("\n\n".join(current))
return result
def chunk_code_table(text):
lines = text.split("\n")
chunks = []
current_lines = []
current_tokens = 0
header_line = None
for line in lines:
stripped = line.strip()
if not stripped:
continue
if re.match(r"^(?:CPT|HCPCS|Diagnosis|ICD-10)\s+(?:Code|Description)", stripped, re.IGNORECASE):
header_line = stripped
continue
if re.match(r"^The following list\(s\)", stripped):
continue
if re.match(r"^CPT®?\s+is a registered", stripped):
continue
if re.match(r"^Listing of a code", stripped):
continue
line_tokens = estimate_tokens(stripped)
if current_tokens + line_tokens > TARGET_CHUNK_TOKENS and current_lines:
chunk_text = "\n".join(current_lines)
if header_line:
chunk_text = header_line + "\n" + chunk_text
chunks.append(chunk_text)
current_lines = []
current_tokens = 0
current_lines.append(stripped)
current_tokens += line_tokens
if current_lines:
chunk_text = "\n".join(current_lines)
if header_line:
chunk_text = header_line + "\n" + chunk_text
chunks.append(chunk_text)
return chunks
def chunk_clinical_evidence(text):
study_splits = re.split(
r'\n\n(?=(?:[A-Z][a-z]+(?:\s+(?:et al\.|and|&))?.*?\(\d{4}\))|'
r'(?:A\s+(?:phase|prospective|retrospective|randomized|multicenter|systematic|meta-analysis|Cochrane))|'
r'(?:Professional Societies|American|European|National|International))',
text
)
if len(study_splits) <= 1:
study_splits = text.split("\n\n")
chunks = []
current = []
current_tokens = 0
for block in study_splits:
block = block.strip()
if not block:
continue
block_tokens = estimate_tokens(block)
if block_tokens > MAX_CHUNK_TOKENS:
if current:
chunks.append("\n\n".join(current))
current = []
current_tokens = 0
sents = split_sentences(block)
sent_group = []
sent_tokens = 0
for sent in sents:
st = estimate_tokens(sent)
if sent_tokens + st > TARGET_CHUNK_TOKENS and sent_group:
chunks.append(" ".join(sent_group))
overlap = sent_group[-OVERLAP_SENTENCES:] if len(sent_group) > OVERLAP_SENTENCES else []
sent_group = overlap
sent_tokens = sum(estimate_tokens(s) for s in sent_group)
sent_group.append(sent)
sent_tokens += st
if sent_group:
chunks.append(" ".join(sent_group))
elif current_tokens + block_tokens > MAX_CHUNK_TOKENS and current:
chunks.append("\n\n".join(current))
current = [block]
current_tokens = block_tokens
else:
current.append(block)
current_tokens += block_tokens
if current:
chunks.append("\n\n".join(current))
return chunks
def chunk_section(section_name, content, policy_name):
if section_name in BOILERPLATE_SECTIONS:
return []
if section_name == "Applicable Codes" or section_name == "Coverage Summary":
return chunk_code_table(content)
if section_name == "Clinical Evidence":
return chunk_clinical_evidence(content)
if section_name in ("Coverage Rationale", "Application", "Definitions",
"Documentation Requirements", "Medical Records Documentation Used for Reviews"):
return chunk_by_criteria(content, policy_name)
tokens = estimate_tokens(content)
if tokens <= TARGET_CHUNK_TOKENS:
return [content]
return chunk_by_criteria(content, policy_name)
def main():
with open(INPUT_FILE, "r", encoding="utf-8") as f:
policies = json.load(f)
all_chunks = []
for policy in tqdm(policies, desc="Creating chunks"):
policy_name = policy["policy_name"]
policy_number = policy.get("policy_number", "")
effective_date = policy.get("effective_date", "")
plan_type = policy.get("plan_type", "")
doc_type = policy.get("doc_type", "")
for section_data in policy["sections"]:
section_name = section_data["section"]
content = section_data["content"]
page_start = section_data.get("page_start", 0)
page_end = section_data.get("page_end", 0)
if section_name in BOILERPLATE_SECTIONS:
continue
text_chunks = chunk_section(section_name, content, policy_name)
for idx, chunk_text in enumerate(text_chunks):
chunk_text = chunk_text.strip()
if not chunk_text or len(chunk_text) < 20:
continue
all_chunks.append({
"id": chunk_id(policy_name, section_name, idx),
"policy_name": policy_name,
"policy_number": policy_number,
"effective_date": effective_date,
"plan_type": plan_type,
"doc_type": doc_type,
"section": section_name,
"page_start": page_start,
"page_end": page_end,
"chunk_index": idx,
"total_chunks_in_section": len(text_chunks),
"text": chunk_text,
})
with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
json.dump(all_chunks, f, indent=2, ensure_ascii=False)
print(f"Total chunks: {len(all_chunks)}")
print(f"Policies processed: {len(policies)}")
print(f"Saved to: {OUTPUT_FILE}")
section_counts = {}
for c in all_chunks:
section_counts[c["section"]] = section_counts.get(c["section"], 0) + 1
print("\nChunks per section:")
for sec, count in sorted(section_counts.items(), key=lambda x: -x[1]):
print(f" {sec}: {count}")
if __name__ == "__main__":
main() |