Spaces:
Running
Running
File size: 17,202 Bytes
899d177 5b0ad58 899d177 5b0ad58 899d177 5b0ad58 7e6f24f f6c9c19 5b0ad58 f6c9c19 25d9750 5b0ad58 899d177 5b0ad58 899d177 5b0ad58 899d177 25d9750 5b0ad58 25d9750 899d177 5b0ad58 899d177 7e6f24f 899d177 5b0ad58 899d177 5b0ad58 899d177 5b0ad58 899d177 5b0ad58 |
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 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
import re
from typing import List, Dict, Optional
from pathlib import Path
from collections import defaultdict
from dataclasses import dataclass
import fitz # PyMuPDF
from docx import Document
from sentence_transformers import SentenceTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
@dataclass
class DocumentChunk:
chunk_id: int
text: str
embedding: List[float]
metadata: Dict
class DocumentChunker:
def __init__(self):
self.embed_model = SentenceTransformer("all-MiniLM-L6-v2")
self.category_patterns = {
"Project Summary": [r"\bsummary\b", r"\bproject overview\b"],
"Contact Information": [r"\bcontact\b", r"\bemail\b", r"\bphone\b", r"\baddress\b"],
"Problem/ Need": [r"\bproblem\b", r"\bneed\b", r"\bchallenge\b"],
"Mission Statement": [r"\bmission\b", r"\bvision\b"],
"Fit or Alignment to Grant": [r"\balignment\b", r"\bfit\b", r"\bgrant (focus|priority)\b"],
"Goals/ Vision / Objectives": [r"\bgoals?\b", r"\bobjectives?\b", r"\bvision\b"],
"Our Solution *PROGRAMS* and Approach": [r"\bsolution\b", r"\bprogram\b", r"\bapproach\b"],
"Impact, Results, or Outcomes": [r"\bimpact\b", r"\bresults?\b", r"\boutcomes?\b"],
"Beneficiaries": [r"\bbeneficiaries\b", r"\bwho we serve\b", r"\btarget audience\b"],
"Differentiation with Competitors": [r"\bcompetitor\b", r"\bdifferent\b", r"\bvalue proposition\b"],
"Plan and Timeline": [r"\btimeline\b", r"\bschedule\b", r"\bmilestone\b"],
"Budget and Funding": [r"\bbudget\b", r"\bfunding\b", r"\bcost\b"],
"Sustainability and Strategy": [r"\bsustainability\b", r"\bexit strategy\b"],
"Organization's History": [r"\bhistory\b", r"\borganization background\b"],
"Team Member Descriptions": [r"\bteam\b", r"\bstaff\b", r"\blived experience\b"],
}
self.patterns = {
'grant_application': {
'header_patterns': [r'\*\*([^*]+)\*\*', r'^([A-Z][^a-z]*[A-Z])$', r'^([A-Z][A-Za-z\s]+)$'],
'question_patterns': [r'^.+\?$', r'^\*?Please .+', r'^How .+', r'^What .+', r'^Describe .+']
}
}
def match_category(self, text: str, return_first: bool = True) -> Optional[str] or List[str]:
lower_text = text.lower()
match_scores = defaultdict(int)
for category, patterns in self.category_patterns.items():
for pattern in patterns:
matches = re.findall(pattern, lower_text)
match_scores[category] += len(matches)
if not match_scores:
return None if return_first else []
sorted_categories = sorted(match_scores.items(), key=lambda x: -x[1])
return sorted_categories[0][0] if return_first else [cat for cat, _ in sorted_categories if match_scores[cat] > 0]
def extract_text(self, file_path: str) -> str:
if file_path.endswith(".docx"):
doc = Document(file_path)
return '\n'.join([f"**{p.text}**" if any(r.bold for r in p.runs) else p.text for p in doc.paragraphs])
elif file_path.endswith(".pdf"):
text = ""
with fitz.open(file_path) as doc:
for page in doc:
text += page.get_text("text") # More accurate reading order
return text
else:
return Path(file_path).read_text()
def detect_document_type(self, text: str) -> str:
keywords = ['grant', 'funding', 'mission']
return 'grant_application' if sum(k in text.lower() for k in keywords) >= 2 else 'generic'
def extract_headers(self, text: str, doc_type: str) -> List[Dict]:
lines = text.split('\n')
headers = []
patterns = self.patterns.get(doc_type, self.patterns['grant_application'])
for i, line in enumerate(lines):
line = line.strip("* ")
if any(re.match(p, line, re.IGNORECASE) for p in patterns['question_patterns']):
headers.append({'text': line, 'line_number': i, 'pattern_type': 'question'})
elif any(re.match(p, line) for p in patterns['header_patterns']):
headers.append({'text': line, 'line_number': i, 'pattern_type': 'header'})
return headers
def fallback_chunking(self, text: str, max_words=150, stride=100) -> List[Dict]:
words = text.split()
chunks = []
for i in range(0, len(words), stride):
chunk_text = ' '.join(words[i:i + max_words])
if len(chunk_text.split()) < 20:
continue
chunks.append({
'chunk_id': len(chunks) + 1,
'header': '',
'questions': [],
'content': chunk_text,
'pattern_type': 'fallback',
'split_index': i // stride
})
return chunks
def chunk_by_headers(self, text: str, headers: List[Dict], max_words=150) -> List[Dict]:
lines = text.split('\n')
chunks = []
for i, header in enumerate(headers):
start, end = header['line_number'], headers[i + 1]['line_number'] if i + 1 < len(headers) else len(lines)
content_lines = lines[start + 1:end]
questions = [l.strip() for l in content_lines if l.strip().endswith('?') and len(l.split()) <= 20]
content = ' '.join([l.strip() for l in content_lines if l.strip() and l.strip() not in questions])
for j in range(0, len(content.split()), max_words):
chunk_text = ' '.join(content.split()[j:j + max_words])
if len(chunk_text.split()) < 20:
continue
chunks.append({
'chunk_id': len(chunks) + 1,
'header': header['text'] if header['pattern_type'] == 'header' else '',
'questions': questions if header['pattern_type'] == 'question' else [],
'content': chunk_text,
'pattern_type': header['pattern_type'],
'split_index': j // max_words
})
return chunks
def extract_topics_tfidf(self, text: str, max_features: int = 3) -> List[str]:
clean = re.sub(r'[^a-z0-9\s]', ' ', text.lower())
vectorizer = TfidfVectorizer(max_features=max_features * 2, stop_words='english')
tfidf = vectorizer.fit_transform([clean])
terms = vectorizer.get_feature_names_out()
scores = tfidf.toarray()[0]
top_terms = [term for term, score in sorted(zip(terms, scores), key=lambda x: -x[1]) if score > 0]
return top_terms[:max_features]
def calculate_confidence_score(self, chunk: Dict) -> float:
score = 0.0
if chunk.get('header'): score += 0.3
if chunk.get('content') and len(chunk['content'].split()) > 20: score += 0.3
if chunk.get('questions'): score += 0.2
return min(score, 1.0)
def process_document(self, file_path: str, title: Optional[str] = None) -> List[Dict]:
file_path = Path(file_path)
text = self.extract_text(str(file_path))
doc_type = self.detect_document_type(text)
headers = self.extract_headers(text, doc_type)
chunks = self.chunk_by_headers(text, headers)
if not chunks:
chunks = self.fallback_chunking(text)
final_chunks = []
for chunk in chunks:
full_text = f"{chunk['header']} {' '.join(chunk['questions'])} {chunk['content']}".strip()
category = self.match_category(full_text, return_first=True)
categories = self.match_category(full_text, return_first=False)
embedding = self.embed_model.encode(full_text).tolist()
topics = self.extract_topics_tfidf(full_text)
confidence = self.calculate_confidence_score(chunk)
final_chunks.append({
"chunk_id": chunk['chunk_id'],
"text": full_text,
"embedding": embedding,
"metadata": {
**chunk,
"title": title or file_path.name,
"category": category,
"categories": categories,
"topics": topics,
"chunking_strategy": chunk['pattern_type'],
"confidence_score": confidence
}
})
return final_chunks
# import re
# from typing import List, Dict, Optional
# from pathlib import Path
# from collections import defaultdict
# from dataclasses import dataclass
# from docx import Document
# from sentence_transformers import SentenceTransformer
# from sklearn.feature_extraction.text import TfidfVectorizer
# import fitz # PyMuPDF
# @dataclass
# class DocumentChunk:
# chunk_id: int
# text: str
# embedding: List[float]
# metadata: Dict
# class DocumentChunker:
# def __init__(self):
# self.embed_model = SentenceTransformer("all-MiniLM-L6-v2")
# self.category_patterns = {
# "Project Summary": [r"\bsummary\b", r"\bproject overview\b"],
# "Contact Information": [r"\bcontact\b", r"\bemail\b", r"\bphone\b", r"\baddress\b"],
# "Problem/ Need": [r"\bproblem\b", r"\bneed\b", r"\bchallenge\b"],
# "Mission Statement": [r"\bmission\b", r"\bvision\b"],
# "Fit or Alignment to Grant": [r"\balignment\b", r"\bfit\b", r"\bgrant (focus|priority)\b"],
# "Goals/ Vision / Objectives": [r"\bgoals?\b", r"\bobjectives?\b", r"\bvision\b"],
# "Our Solution *PROGRAMS* and Approach": [r"\bsolution\b", r"\bprogram\b", r"\bapproach\b"],
# "Impact, Results, or Outcomes": [r"\bimpact\b", r"\bresults?\b", r"\boutcomes?\b"],
# "Beneficiaries": [r"\bbeneficiaries\b", r"\bwho we serve\b", r"\btarget audience\b"],
# "Differentiation with Competitors": [r"\bcompetitor\b", r"\bdifferent\b", r"\bvalue proposition\b"],
# "Plan and Timeline": [r"\btimeline\b", r"\bschedule\b", r"\bmilestone\b"],
# "Budget and Funding": [r"\bbudget\b", r"\bfunding\b", r"\bcost\b"],
# "Sustainability and Strategy": [r"\bsustainability\b", r"\bexit strategy\b"],
# "Organization's History": [r"\bhistory\b", r"\borganization background\b"],
# "Team Member Descriptions": [r"\bteam\b", r"\bstaff\b", r"\blived experience\b"],
# }
# self.patterns = {
# 'grant_application': {
# 'header_patterns': [
# r'\*\*([^*]+)\*\*',
# r'^([A-Z][^a-z]*[A-Z])$',
# r'^([A-Z][A-Za-z\s]+)$',
# ],
# 'question_patterns': [
# r'^.+\?$',
# r'^\*?Please .+',
# r'^How .+',
# r'^What .+',
# r'^Describe .+',
# ]
# }
# }
# def extract_text(self, file_path: str) -> str:
# if file_path.endswith(".docx"):
# doc = Document(file_path)
# return '\n'.join([f"**{p.text}**" if any(r.bold for r in p.runs) else p.text for p in doc.paragraphs])
# elif file_path.endswith(".pdf"):
# text = ""
# with fitz.open(file_path) as doc:
# for page in doc:
# text += page.get_text()
# return text
# elif file_path.endswith(".txt"):
# return Path(file_path).read_text()
# else:
# raise ValueError("Unsupported file format")
# def detect_document_type(self, text: str) -> str:
# keywords = ['grant', 'funding', 'mission']
# return 'grant_application' if sum(k in text.lower() for k in keywords) >= 2 else 'generic'
# def extract_headers(self, text: str, doc_type: str) -> List[Dict]:
# lines = text.split('\n')
# headers = []
# patterns = self.patterns.get(doc_type, self.patterns['grant_application'])
# for i, line in enumerate(lines):
# line = line.strip("* ")
# if any(re.match(p, line, re.IGNORECASE) for p in patterns['question_patterns']):
# headers.append({'text': line, 'line_number': i, 'pattern_type': 'question'})
# elif any(re.match(p, line) for p in patterns['header_patterns']):
# headers.append({'text': line, 'line_number': i, 'pattern_type': 'header'})
# return headers
# def chunk_by_headers(self, text: str, headers: List[Dict], max_words=150) -> List[Dict]:
# lines = text.split('\n')
# chunks = []
# if not headers:
# words = text.split()
# for i in range(0, len(words), max_words):
# piece = ' '.join(words[i:i + max_words])
# chunks.append({
# 'chunk_id': len(chunks) + 1,
# 'header': '',
# 'questions': [],
# 'content': piece,
# 'pattern_type': 'auto'
# })
# return chunks
# for i, header in enumerate(headers):
# start, end = header['line_number'], headers[i + 1]['line_number'] if i + 1 < len(headers) else len(lines)
# content_lines = lines[start + 1:end]
# questions = [l.strip() for l in content_lines if l.strip().endswith('?') and len(l.split()) <= 20]
# content = ' '.join([l.strip() for l in content_lines if l.strip() and l.strip() not in questions])
# for j in range(0, len(content.split()), max_words):
# chunk_text = ' '.join(content.split()[j:j + max_words])
# chunks.append({
# 'chunk_id': len(chunks) + 1,
# 'header': header['text'] if header['pattern_type'] == 'header' else '',
# 'questions': questions if header['pattern_type'] == 'question' else [],
# 'content': chunk_text,
# 'pattern_type': header['pattern_type'],
# 'split_index': j // max_words
# })
# return chunks
# def match_category(self, text: str, return_first: bool = True) -> Optional[str] or List[str]:
# lower_text = text.lower()
# match_scores = defaultdict(int)
# for category, patterns in self.category_patterns.items():
# for pattern in patterns:
# matches = re.findall(pattern, lower_text)
# match_scores[category] += len(matches)
# if not match_scores:
# return None if return_first else []
# sorted_categories = sorted(match_scores.items(), key=lambda x: -x[1])
# return sorted_categories[0][0] if return_first else [cat for cat, _ in sorted_categories if match_scores[cat] > 0]
# def extract_topics_tfidf(self, text: str, max_features: int = 3) -> List[str]:
# clean = re.sub(r'[^\w\s]', ' ', text.lower())
# vectorizer = TfidfVectorizer(max_features=max_features * 2, stop_words='english')
# tfidf = vectorizer.fit_transform([clean])
# terms = vectorizer.get_feature_names_out()
# scores = tfidf.toarray()[0]
# top_terms = [term for term, score in sorted(zip(terms, scores), key=lambda x: -x[1]) if score > 0]
# return top_terms[:max_features]
# def calculate_confidence_score(self, chunk: Dict) -> float:
# score = 0.0
# if chunk.get('header'): score += 0.3
# if chunk.get('content') and len(chunk['content'].split()) > 20: score += 0.3
# if chunk.get('questions'): score += 0.2
# return min(score, 1.0)
# def process_document(self, file_path: str, title: Optional[str] = None) -> List[Dict]:
# file_path = Path(file_path)
# text = self.extract_text(str(file_path))
# doc_type = self.detect_document_type(text)
# headers = self.extract_headers(text, doc_type)
# raw_chunks = self.chunk_by_headers(text, headers)
# final_chunks = []
# for chunk in raw_chunks:
# full_text = f"{chunk['header']} {' '.join(chunk['questions'])} {chunk['content']}".strip()
# category = self.match_category(full_text, return_first=True)
# categories = self.match_category(full_text, return_first=False)
# embedding = self.embed_model.encode(full_text).tolist()
# topics = self.extract_topics_tfidf(full_text)
# confidence = self.calculate_confidence_score(chunk)
# final_chunks.append({
# "chunk_id": chunk['chunk_id'],
# "text": full_text,
# "embedding": embedding,
# "metadata": {
# **chunk,
# "title": title or file_path.name,
# "category": category,
# "categories": categories,
# "topics": topics,
# "confidence_score": confidence
# }
# })
# return final_chunks
|