Spaces:
Running
Running
Commit ·
19bbd13
1
Parent(s): c9902dd
Add logging for chunking processes and ChromaDB initialization; enhance OCR page processing with logging
Browse files- infrastructure/chunker.py +77 -63
- infrastructure/database.py +12 -0
- infrastructure/document_processor.py +1 -0
infrastructure/chunker.py
CHANGED
|
@@ -110,12 +110,17 @@ def _chunk_paragraphs(paragraphs: List[Tuple[int, str]], max_chars: int, overlap
|
|
| 110 |
buf.append(para)
|
| 111 |
buf_pages.append(page_idx)
|
| 112 |
current_len += para_len + 2 # account for join newlines
|
|
|
|
|
|
|
| 113 |
|
| 114 |
# Final flush
|
| 115 |
if buf:
|
| 116 |
chunk_text = "\n\n".join(buf).strip()
|
| 117 |
if chunk_text:
|
| 118 |
chunks.append((chunk_text, min(buf_pages), max(buf_pages)))
|
|
|
|
|
|
|
|
|
|
| 119 |
return chunks
|
| 120 |
|
| 121 |
|
|
@@ -156,6 +161,7 @@ def _chunk_paragraphs_tokens(paragraphs: List[Tuple[int, str]], max_tokens: int,
|
|
| 156 |
paragraphs: list of (page_index, text)
|
| 157 |
Returns list of (chunk_text, page_start, page_end)
|
| 158 |
"""
|
|
|
|
| 159 |
# Pre-tokenize paragraphs (cache by object id / value) to avoid repeats
|
| 160 |
tokenized: List[Tuple[int, List[int], str]] = [] # (page_idx, token_ids, original_text)
|
| 161 |
for page_idx, para in paragraphs:
|
|
@@ -172,6 +178,8 @@ def _chunk_paragraphs_tokens(paragraphs: List[Tuple[int, str]], max_tokens: int,
|
|
| 172 |
buf_pages: List[int] = []
|
| 173 |
tail_tokens: List[int] = []
|
| 174 |
|
|
|
|
|
|
|
| 175 |
for page_idx, toks, original in tokenized:
|
| 176 |
needed = len(toks)
|
| 177 |
if buf_tokens and (len(buf_tokens) + needed) > max_tokens:
|
|
@@ -187,6 +195,8 @@ def _chunk_paragraphs_tokens(paragraphs: List[Tuple[int, str]], max_tokens: int,
|
|
| 187 |
buf_tokens.extend(toks)
|
| 188 |
buf_pages.append(page_idx)
|
| 189 |
|
|
|
|
|
|
|
| 190 |
if buf_tokens:
|
| 191 |
chunk_text = _decode_tokens(buf_tokens).strip()
|
| 192 |
if chunk_text:
|
|
@@ -195,73 +205,75 @@ def _chunk_paragraphs_tokens(paragraphs: List[Tuple[int, str]], max_tokens: int,
|
|
| 195 |
|
| 196 |
def get_chunk_info(text: str, chunk_text: str) -> Dict[str, Optional[str]]:
|
| 197 |
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
|
|
|
|
|
|
| 216 |
--- CHUNK TEXT START ---\n
|
| 217 |
{chunk_text}\n
|
| 218 |
--- CHUNK TEXT END ---
|
| 219 |
-
|
| 220 |
-
|
| 221 |
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
text={"verbosity": "low"},
|
| 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 |
def chunk_doc(text: str, doc_id: int, max_chars: int = 1200, overlap: int = 150, *, max_tokens: Optional[int] = None, token_overlap: Optional[int] = None) -> List[int]:
|
| 267 |
"""Chunk a cleaned text file, persist chunks, metadata, embeddings, and index.
|
|
@@ -271,6 +283,7 @@ def chunk_doc(text: str, doc_id: int, max_chars: int = 1200, overlap: int = 150,
|
|
| 271 |
# Validate modes
|
| 272 |
use_tokens = max_tokens is not None
|
| 273 |
if use_tokens:
|
|
|
|
| 274 |
if max_tokens is None or max_tokens <= 0:
|
| 275 |
raise ValueError("max_tokens must be positive when provided")
|
| 276 |
if token_overlap is None:
|
|
@@ -282,6 +295,7 @@ def chunk_doc(text: str, doc_id: int, max_chars: int = 1200, overlap: int = 150,
|
|
| 282 |
logger.error("token_overlap (%d) >= max_tokens (%d); reducing", token_overlap, max_tokens)
|
| 283 |
token_overlap = max(0, max_tokens // 5)
|
| 284 |
else:
|
|
|
|
| 285 |
if max_chars <= 0:
|
| 286 |
raise ValueError("max_chars must be positive")
|
| 287 |
if overlap < 0:
|
|
@@ -424,7 +438,7 @@ def chunk_doc(text: str, doc_id: int, max_chars: int = 1200, overlap: int = 150,
|
|
| 424 |
except FileNotFoundError:
|
| 425 |
with open(path, "w", encoding="utf-8") as f:
|
| 426 |
f.write(records)
|
| 427 |
-
logger.
|
| 428 |
except Exception as e:
|
| 429 |
logger.error(f"Failed to write chunk records to {path}: {e}")
|
| 430 |
|
|
|
|
| 110 |
buf.append(para)
|
| 111 |
buf_pages.append(page_idx)
|
| 112 |
current_len += para_len + 2 # account for join newlines
|
| 113 |
+
|
| 114 |
+
logger.info("Chunking %d paragraphs into max_chars=%d with overlap=%d", len(paragraphs), max_chars, overlap)
|
| 115 |
|
| 116 |
# Final flush
|
| 117 |
if buf:
|
| 118 |
chunk_text = "\n\n".join(buf).strip()
|
| 119 |
if chunk_text:
|
| 120 |
chunks.append((chunk_text, min(buf_pages), max(buf_pages)))
|
| 121 |
+
|
| 122 |
+
logger.info("Generated %d chunks from paragraphs", len(chunks))
|
| 123 |
+
|
| 124 |
return chunks
|
| 125 |
|
| 126 |
|
|
|
|
| 161 |
paragraphs: list of (page_index, text)
|
| 162 |
Returns list of (chunk_text, page_start, page_end)
|
| 163 |
"""
|
| 164 |
+
logger.info("Token chunking mode tokenizer=%s max_tokens=%d overlap_tokens=%d", TOKENIZER_NAME, max_tokens, overlap_tokens)
|
| 165 |
# Pre-tokenize paragraphs (cache by object id / value) to avoid repeats
|
| 166 |
tokenized: List[Tuple[int, List[int], str]] = [] # (page_idx, token_ids, original_text)
|
| 167 |
for page_idx, para in paragraphs:
|
|
|
|
| 178 |
buf_pages: List[int] = []
|
| 179 |
tail_tokens: List[int] = []
|
| 180 |
|
| 181 |
+
logger.info("Tokenized %d paragraphs into %d tokenized segments", len(paragraphs), len(tokenized))
|
| 182 |
+
|
| 183 |
for page_idx, toks, original in tokenized:
|
| 184 |
needed = len(toks)
|
| 185 |
if buf_tokens and (len(buf_tokens) + needed) > max_tokens:
|
|
|
|
| 195 |
buf_tokens.extend(toks)
|
| 196 |
buf_pages.append(page_idx)
|
| 197 |
|
| 198 |
+
logger.info("Token chunking %d segments into max_tokens=%d with overlap_tokens=%d", len(tokenized), max_tokens, overlap_tokens)
|
| 199 |
+
|
| 200 |
if buf_tokens:
|
| 201 |
chunk_text = _decode_tokens(buf_tokens).strip()
|
| 202 |
if chunk_text:
|
|
|
|
| 205 |
|
| 206 |
def get_chunk_info(text: str, chunk_text: str) -> Dict[str, Optional[str]]:
|
| 207 |
|
| 208 |
+
logger.info("Extracting chunk info from text of length %d", len(text))
|
| 209 |
+
|
| 210 |
+
try:
|
| 211 |
+
client = OpenAI(api_key=API_KEY)
|
| 212 |
+
prompt = (
|
| 213 |
+
f"""
|
| 214 |
+
You are an expert in legal research and analysis, specializing in technology transactions. Examine the attached technology transactions document and the chunk taken from the document then identify respective values for each of the following keys: section_number (full section, heading, subheading, subsection, paragraph, etc. number(s), letter(s),level(s), etc., applicable to the chunk -- e.g., 9.2(b); VII.A.i; etc.; note the section_number applicable to this chunk may not necessarily be included in this chunk), section_title (heading, section, subheading, subsection, etc. name(s), label(s), etc. applicable to this chunk), clause_type (the type(s) of clause(s) captured in this chunk -- e.g., indemnity, force majure, confidentiality, etc. note that section_number is not a type of clause; however, section_heading may be a type of clause in some instances), path (the heading, section, subheading, subsection, paragraph, etc. level(s)/name(s)/number(s) that lead to the value of section_number for this chunk -- e.g., if section_number is 9.2(b) for the chunk, the path would be 9 → 9.2 → 9.2(b)), numbers_present (Boolean value: true if this chunk includes a section_number in the chunk_text; false if not), and definition_terms (a list of all legal terms defined in this chunk, exclude company and party names; include only legal terms, which are often followed with "shall mean", "means", "is defined as", etc.). Do not include section_number(s) in section_title, and do not include section_title(s) in section_number or path. Consider the substantive meaning of words (e.g., "Page 1 of 12" is not likely to be the clause_type), placement in the document, surrounding text, applicable section, and any other factors that might inform your decision. Chunks may include multiple values for a given key (e.g., multiple section titles or clause types); in such cases, return all applicable values as a comma-separated list. If you cannot identify a value corresponding to one of the keys, respond with null for that key.
|
| 215 |
+
Return a response in following JSON format only:
|
| 216 |
+
{{
|
| 217 |
+
"section_number": section_number,
|
| 218 |
+
"section_title": section_title,
|
| 219 |
+
"clause_type": clause_type,
|
| 220 |
+
"path": path,
|
| 221 |
+
"numbers_present": numbers_present,
|
| 222 |
+
"definition_terms": [definition_terms]
|
| 223 |
+
}}.
|
| 224 |
+
Do not return anything else outside of the JSON object.
|
| 225 |
+
--- DOCUMENT TEXT START ---\n
|
| 226 |
+
{text}\n
|
| 227 |
+
--- DOCUMENT TEXT END ---\n\n
|
| 228 |
--- CHUNK TEXT START ---\n
|
| 229 |
{chunk_text}\n
|
| 230 |
--- CHUNK TEXT END ---
|
| 231 |
+
"""
|
| 232 |
+
)
|
| 233 |
|
| 234 |
+
response = client.responses.create(
|
| 235 |
+
model="gpt-5-nano",
|
| 236 |
+
input=prompt,
|
| 237 |
text={"verbosity": "low"},
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
response = response.output_text if response else ""
|
| 241 |
+
candidate = (response or [])
|
| 242 |
+
logger.info(f"AI chunk response: {candidate}")
|
| 243 |
+
expected_keys = [
|
| 244 |
+
"section_number",
|
| 245 |
+
"section_title",
|
| 246 |
+
"clause_type",
|
| 247 |
+
"path",
|
| 248 |
+
"numbers_present",
|
| 249 |
+
"definition_terms",
|
| 250 |
+
]
|
| 251 |
+
|
| 252 |
+
data = {}
|
| 253 |
+
if isinstance(candidate, dict):
|
| 254 |
+
data = candidate
|
| 255 |
+
elif isinstance(candidate, str):
|
| 256 |
+
try:
|
| 257 |
+
data = json.loads(candidate)
|
| 258 |
+
except Exception:
|
| 259 |
+
logger.error("AI manifest response not valid JSON; returning defaults")
|
| 260 |
+
data = {}
|
| 261 |
+
else:
|
| 262 |
+
logger.error("AI manifest response unexpected type %s", type(candidate))
|
| 263 |
+
|
| 264 |
+
# Build normalized manifest dict
|
| 265 |
+
manifest = {k: (data.get(k) if isinstance(data, dict) else None) for k in expected_keys}
|
| 266 |
+
|
| 267 |
+
# Coerce obvious placeholder / unknown strings to None
|
| 268 |
+
for k, v in manifest.items():
|
| 269 |
+
if isinstance(v, str) and v.strip().lower() in {"unknown", "null", "n/a", "none", ""}:
|
| 270 |
+
manifest[k] = None
|
| 271 |
+
|
| 272 |
+
return manifest
|
| 273 |
+
|
| 274 |
+
except Exception as e:
|
| 275 |
+
logger.error(f"Error extracting values from text: {e}")
|
| 276 |
+
return {}
|
| 277 |
|
| 278 |
def chunk_doc(text: str, doc_id: int, max_chars: int = 1200, overlap: int = 150, *, max_tokens: Optional[int] = None, token_overlap: Optional[int] = None) -> List[int]:
|
| 279 |
"""Chunk a cleaned text file, persist chunks, metadata, embeddings, and index.
|
|
|
|
| 283 |
# Validate modes
|
| 284 |
use_tokens = max_tokens is not None
|
| 285 |
if use_tokens:
|
| 286 |
+
logger.info("Using token-based chunking for doc_id=%s", doc_id)
|
| 287 |
if max_tokens is None or max_tokens <= 0:
|
| 288 |
raise ValueError("max_tokens must be positive when provided")
|
| 289 |
if token_overlap is None:
|
|
|
|
| 295 |
logger.error("token_overlap (%d) >= max_tokens (%d); reducing", token_overlap, max_tokens)
|
| 296 |
token_overlap = max(0, max_tokens // 5)
|
| 297 |
else:
|
| 298 |
+
logger.info("Using character-based chunking for doc_id=%s", doc_id)
|
| 299 |
if max_chars <= 0:
|
| 300 |
raise ValueError("max_chars must be positive")
|
| 301 |
if overlap < 0:
|
|
|
|
| 438 |
except FileNotFoundError:
|
| 439 |
with open(path, "w", encoding="utf-8") as f:
|
| 440 |
f.write(records)
|
| 441 |
+
logger.error(f"Created new chunks file with {len(chunk_metadata_records)} records as it did not exist")
|
| 442 |
except Exception as e:
|
| 443 |
logger.error(f"Failed to write chunk records to {path}: {e}")
|
| 444 |
|
infrastructure/database.py
CHANGED
|
@@ -79,8 +79,10 @@ def _init_chroma_client():
|
|
| 79 |
# Order of path attempts (most desired first)
|
| 80 |
candidates: list[str] = []
|
| 81 |
if force_tmp:
|
|
|
|
| 82 |
candidates = ["/tmp/chroma_db"]
|
| 83 |
else:
|
|
|
|
| 84 |
if env_path:
|
| 85 |
candidates.append(env_path)
|
| 86 |
# Common writable locations on HF Spaces
|
|
@@ -94,20 +96,24 @@ def _init_chroma_client():
|
|
| 94 |
|
| 95 |
def _dir_writeable(path: str) -> bool:
|
| 96 |
try:
|
|
|
|
| 97 |
test_file = os.path.join(path, f".write_test_{int(time.time()*1000)}")
|
| 98 |
with open(test_file, "w", encoding="utf-8") as tf:
|
| 99 |
tf.write("ok")
|
| 100 |
os.remove(test_file)
|
| 101 |
return True
|
| 102 |
except Exception as e: # pragma: no cover - env specific
|
|
|
|
| 103 |
tried.append((path, f"dir not writable: {e}"))
|
| 104 |
return False
|
| 105 |
|
| 106 |
for cand in candidates:
|
| 107 |
abs_path = os.path.abspath(cand)
|
| 108 |
try:
|
|
|
|
| 109 |
os.makedirs(abs_path, exist_ok=True)
|
| 110 |
except Exception as e:
|
|
|
|
| 111 |
tried.append((abs_path, f"makedirs failed: {e}"))
|
| 112 |
continue
|
| 113 |
|
|
@@ -117,6 +123,7 @@ def _init_chroma_client():
|
|
| 117 |
continue
|
| 118 |
|
| 119 |
try:
|
|
|
|
| 120 |
client = chromadb.PersistentClient(path=abs_path)
|
| 121 |
except Exception as e: # immediate failure
|
| 122 |
tried.append((abs_path, f"create failed: {e}"))
|
|
@@ -125,24 +132,29 @@ def _init_chroma_client():
|
|
| 125 |
|
| 126 |
# Basic list works?
|
| 127 |
try:
|
|
|
|
| 128 |
client.list_collections()
|
| 129 |
except Exception as e:
|
|
|
|
| 130 |
tried.append((abs_path, f"list failed: {e}"))
|
| 131 |
continue
|
| 132 |
|
| 133 |
# WRITE TEST (critical)
|
| 134 |
test_coll_name = f"rw_test_{int(time.time()*10)}"
|
| 135 |
try:
|
|
|
|
| 136 |
tc = client.get_or_create_collection(name=test_coll_name) # type: ignore
|
| 137 |
tc.add(ids=["0"], metadatas=[{"t": "x"}], documents=["test"])
|
| 138 |
client.delete_collection(name=test_coll_name)
|
| 139 |
_logger.info(f"Chroma connected with write access at {abs_path}")
|
| 140 |
return client
|
| 141 |
except Exception as e:
|
|
|
|
| 142 |
msg = str(e).lower()
|
| 143 |
tried.append((abs_path, f"write test failed: {e}"))
|
| 144 |
# Clean up partial collection if it exists
|
| 145 |
try:
|
|
|
|
| 146 |
client.delete_collection(name=test_coll_name)
|
| 147 |
except Exception:
|
| 148 |
pass
|
|
|
|
| 79 |
# Order of path attempts (most desired first)
|
| 80 |
candidates: list[str] = []
|
| 81 |
if force_tmp:
|
| 82 |
+
_logger.info("CHROMA_FORCE_TMP set; forcing /tmp usage for ChromaDB")
|
| 83 |
candidates = ["/tmp/chroma_db"]
|
| 84 |
else:
|
| 85 |
+
_logger.info("Initializing ChromaDB PersistentClient with path candidates")
|
| 86 |
if env_path:
|
| 87 |
candidates.append(env_path)
|
| 88 |
# Common writable locations on HF Spaces
|
|
|
|
| 96 |
|
| 97 |
def _dir_writeable(path: str) -> bool:
|
| 98 |
try:
|
| 99 |
+
_logger.debug(f"Testing writability of directory: {path}")
|
| 100 |
test_file = os.path.join(path, f".write_test_{int(time.time()*1000)}")
|
| 101 |
with open(test_file, "w", encoding="utf-8") as tf:
|
| 102 |
tf.write("ok")
|
| 103 |
os.remove(test_file)
|
| 104 |
return True
|
| 105 |
except Exception as e: # pragma: no cover - env specific
|
| 106 |
+
_logger.error(f"Error testing writability of directory {path}: {e}")
|
| 107 |
tried.append((path, f"dir not writable: {e}"))
|
| 108 |
return False
|
| 109 |
|
| 110 |
for cand in candidates:
|
| 111 |
abs_path = os.path.abspath(cand)
|
| 112 |
try:
|
| 113 |
+
_logger.debug(f"Creating directories for ChromaDB at {abs_path}")
|
| 114 |
os.makedirs(abs_path, exist_ok=True)
|
| 115 |
except Exception as e:
|
| 116 |
+
_logger.error(f"Failed to create ChromaDB directory {abs_path}: {e}")
|
| 117 |
tried.append((abs_path, f"makedirs failed: {e}"))
|
| 118 |
continue
|
| 119 |
|
|
|
|
| 123 |
continue
|
| 124 |
|
| 125 |
try:
|
| 126 |
+
_logger.debug(f"Initializing ChromaDB PersistentClient at {abs_path}")
|
| 127 |
client = chromadb.PersistentClient(path=abs_path)
|
| 128 |
except Exception as e: # immediate failure
|
| 129 |
tried.append((abs_path, f"create failed: {e}"))
|
|
|
|
| 132 |
|
| 133 |
# Basic list works?
|
| 134 |
try:
|
| 135 |
+
_logger.debug(f"Listing collections for ChromaDB at {abs_path}")
|
| 136 |
client.list_collections()
|
| 137 |
except Exception as e:
|
| 138 |
+
_logger.error(f"Chroma path {abs_path} list_collections failed: {e}")
|
| 139 |
tried.append((abs_path, f"list failed: {e}"))
|
| 140 |
continue
|
| 141 |
|
| 142 |
# WRITE TEST (critical)
|
| 143 |
test_coll_name = f"rw_test_{int(time.time()*10)}"
|
| 144 |
try:
|
| 145 |
+
_logger.debug(f"Performing write test for ChromaDB at {abs_path}")
|
| 146 |
tc = client.get_or_create_collection(name=test_coll_name) # type: ignore
|
| 147 |
tc.add(ids=["0"], metadatas=[{"t": "x"}], documents=["test"])
|
| 148 |
client.delete_collection(name=test_coll_name)
|
| 149 |
_logger.info(f"Chroma connected with write access at {abs_path}")
|
| 150 |
return client
|
| 151 |
except Exception as e:
|
| 152 |
+
_logger.error(f"Chroma path {abs_path} write test failed: {e}")
|
| 153 |
msg = str(e).lower()
|
| 154 |
tried.append((abs_path, f"write test failed: {e}"))
|
| 155 |
# Clean up partial collection if it exists
|
| 156 |
try:
|
| 157 |
+
_logger.debug(f"Cleaning up partial collection {test_coll_name} at {abs_path}")
|
| 158 |
client.delete_collection(name=test_coll_name)
|
| 159 |
except Exception:
|
| 160 |
pass
|
infrastructure/document_processor.py
CHANGED
|
@@ -20,6 +20,7 @@ MANIFEST_DIR = os.getenv("MANIFEST_DIR", "/data/manifest")
|
|
| 20 |
CHUNKS_DIR = os.getenv("CHUNKS_DIR", "/data/chunks")
|
| 21 |
|
| 22 |
def ocr_page(page: fitz.Page, zoom: float = 2.0) -> str:
|
|
|
|
| 23 |
mat = fitz.Matrix(zoom, zoom)
|
| 24 |
|
| 25 |
pix = page.get_pixmap(matrix=mat, alpha=False) # type: ignore
|
|
|
|
| 20 |
CHUNKS_DIR = os.getenv("CHUNKS_DIR", "/data/chunks")
|
| 21 |
|
| 22 |
def ocr_page(page: fitz.Page, zoom: float = 2.0) -> str:
|
| 23 |
+
logger.info(f"Performing OCR on page {page.number}")
|
| 24 |
mat = fitz.Matrix(zoom, zoom)
|
| 25 |
|
| 26 |
pix = page.get_pixmap(matrix=mat, alpha=False) # type: ignore
|