Adam Cseresznye commited on
Commit ·
862be58
1
Parent(s): d4cede8
Add ProcessingAgent and section detection utilities
Browse files- agents/processing_agent.py +160 -0
- models/state.py +3 -0
- requirements.txt +2 -2
- tests/unit/test_processing_agent.py +111 -0
- tests/unit/test_section_detector.py +97 -0
- utils/section_detector.py +209 -0
agents/processing_agent.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import List, Dict, Any
|
| 4 |
+
import time
|
| 5 |
+
from loguru import logger
|
| 6 |
+
|
| 7 |
+
from llama_index.core.node_parser import SimpleNodeParser
|
| 8 |
+
from llama_index.core.schema import Document
|
| 9 |
+
|
| 10 |
+
from models.state import State
|
| 11 |
+
from utils.section_detector import detect_sections
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ProcessingAgent:
|
| 15 |
+
"""State-aware processing agent that detects sections and chunks texts.
|
| 16 |
+
|
| 17 |
+
Usage:
|
| 18 |
+
agent = ProcessingAgent(chunk_size=500, chunk_overlap=50)
|
| 19 |
+
updated_state = agent.process(state)
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(self, chunk_size: int = 500, chunk_overlap: int = 50):
|
| 23 |
+
self.chunk_size = int(chunk_size)
|
| 24 |
+
self.chunk_overlap = int(chunk_overlap)
|
| 25 |
+
self.parser = SimpleNodeParser.from_defaults(
|
| 26 |
+
chunk_size=self.chunk_size, chunk_overlap=self.chunk_overlap
|
| 27 |
+
)
|
| 28 |
+
logger.debug(
|
| 29 |
+
f"ProcessingAgent initialized: chunk_size={chunk_size}, overlap={chunk_overlap}"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
def process(self, state: State) -> State:
|
| 33 |
+
"""Process `state.passages` and populate `state.chunks`.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
state: State containing passages produced by acquisition agent.
|
| 37 |
+
|
| 38 |
+
Returns:
|
| 39 |
+
The modified State instance with `chunks` attribute set.
|
| 40 |
+
"""
|
| 41 |
+
start_time = time.perf_counter()
|
| 42 |
+
|
| 43 |
+
if not state.passages:
|
| 44 |
+
msg = "No passages available for processing"
|
| 45 |
+
logger.warning(msg)
|
| 46 |
+
state.append_error(msg)
|
| 47 |
+
return state
|
| 48 |
+
|
| 49 |
+
logger.info(f"Processing {len(state.passages)} passages")
|
| 50 |
+
all_chunks: List[Any] = []
|
| 51 |
+
had_nonempty_passage = False
|
| 52 |
+
|
| 53 |
+
for idx, passage in enumerate(state.passages):
|
| 54 |
+
paper_id = (
|
| 55 |
+
passage.get("paperId") or passage.get("paper_id") or f"paper_{idx}"
|
| 56 |
+
)
|
| 57 |
+
title = passage.get("title", "")
|
| 58 |
+
citation_count = passage.get(
|
| 59 |
+
"citationCount", passage.get("citation_count", 0)
|
| 60 |
+
)
|
| 61 |
+
year = passage.get("year") or passage.get("publication_year")
|
| 62 |
+
venue = passage.get("venue") or passage.get("journal")
|
| 63 |
+
influential = passage.get(
|
| 64 |
+
"influentialCitationCount", passage.get("influential_citation_count", 0)
|
| 65 |
+
)
|
| 66 |
+
text = passage.get("text", "") or ""
|
| 67 |
+
|
| 68 |
+
if not text.strip():
|
| 69 |
+
logger.warning({"event": "empty_passage_skipped", "paper_id": paper_id})
|
| 70 |
+
continue
|
| 71 |
+
had_nonempty_passage = True
|
| 72 |
+
|
| 73 |
+
logger.info({"event": "processing_paper_start", "paper_id": paper_id})
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
sections = detect_sections(text, paper_id=paper_id)
|
| 77 |
+
except Exception as e:
|
| 78 |
+
logger.warning(
|
| 79 |
+
{
|
| 80 |
+
"event": "section_detection_failed",
|
| 81 |
+
"paper_id": paper_id,
|
| 82 |
+
"error": str(e),
|
| 83 |
+
}
|
| 84 |
+
)
|
| 85 |
+
sections = [{"name": "full_text", "text": text}]
|
| 86 |
+
|
| 87 |
+
paper_chunk_count = 0
|
| 88 |
+
for sec in sections:
|
| 89 |
+
sec_name = sec.get("name", "full_text")
|
| 90 |
+
sec_text = sec.get("text", "") or ""
|
| 91 |
+
if not sec_text.strip():
|
| 92 |
+
continue
|
| 93 |
+
|
| 94 |
+
doc = Document(text=sec_text)
|
| 95 |
+
try:
|
| 96 |
+
nodes = self.parser.get_nodes_from_documents([doc])
|
| 97 |
+
except Exception as e:
|
| 98 |
+
logger.warning(
|
| 99 |
+
{
|
| 100 |
+
"event": "chunking_failed",
|
| 101 |
+
"paper_id": paper_id,
|
| 102 |
+
"section": sec_name,
|
| 103 |
+
"error": str(e),
|
| 104 |
+
}
|
| 105 |
+
)
|
| 106 |
+
nodes = []
|
| 107 |
+
|
| 108 |
+
for chunk_idx, node in enumerate(nodes):
|
| 109 |
+
# Attach metadata directly; fail-fast if this raises
|
| 110 |
+
node.metadata.update(
|
| 111 |
+
{
|
| 112 |
+
"paper_id": paper_id,
|
| 113 |
+
"section_name": sec_name,
|
| 114 |
+
"chunk_index": chunk_idx,
|
| 115 |
+
"paper_title": title,
|
| 116 |
+
"citation_count": citation_count,
|
| 117 |
+
}
|
| 118 |
+
)
|
| 119 |
+
# Add optional fields if present
|
| 120 |
+
if year is not None:
|
| 121 |
+
node.metadata["year"] = year
|
| 122 |
+
if venue is not None:
|
| 123 |
+
node.metadata["venue"] = venue
|
| 124 |
+
if influential is not None:
|
| 125 |
+
node.metadata["influential_citation_count"] = influential
|
| 126 |
+
|
| 127 |
+
all_chunks.append(node)
|
| 128 |
+
paper_chunk_count += 1
|
| 129 |
+
|
| 130 |
+
logger.debug(
|
| 131 |
+
{
|
| 132 |
+
"event": "processing_paper_done",
|
| 133 |
+
"paper_id": paper_id,
|
| 134 |
+
"chunks": paper_chunk_count,
|
| 135 |
+
"sections": len(sections),
|
| 136 |
+
}
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
if not all_chunks:
|
| 140 |
+
# If there were non-empty passages but no chunks, record a critical error.
|
| 141 |
+
if had_nonempty_passage:
|
| 142 |
+
msg = "Zero chunks generated from passages"
|
| 143 |
+
logger.error(msg)
|
| 144 |
+
state.append_error(msg)
|
| 145 |
+
|
| 146 |
+
state.update_fields(chunks=all_chunks)
|
| 147 |
+
|
| 148 |
+
elapsed = time.perf_counter() - start_time
|
| 149 |
+
logger.info(
|
| 150 |
+
{
|
| 151 |
+
"event": "processing_complete",
|
| 152 |
+
"passages": len(state.passages),
|
| 153 |
+
"chunks": len(all_chunks),
|
| 154 |
+
"elapsed_s": elapsed,
|
| 155 |
+
}
|
| 156 |
+
)
|
| 157 |
+
return state
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
__all__ = ["ProcessingAgent"]
|
models/state.py
CHANGED
|
@@ -39,6 +39,9 @@ class State(BaseModel):
|
|
| 39 |
# Passages (Week 2)
|
| 40 |
passages: Optional[List[Dict[str, Any]]] = None
|
| 41 |
|
|
|
|
|
|
|
|
|
|
| 42 |
# Answer and citations (Week 3)
|
| 43 |
answer: Optional[str] = None
|
| 44 |
citations: Optional[List[Dict[str, Any]]] = None
|
|
|
|
| 39 |
# Passages (Week 2)
|
| 40 |
passages: Optional[List[Dict[str, Any]]] = None
|
| 41 |
|
| 42 |
+
# Chunks produced by processing agents (LlamaIndex Documents / node objects)
|
| 43 |
+
chunks: Optional[List[Any]] = None
|
| 44 |
+
|
| 45 |
# Answer and citations (Week 3)
|
| 46 |
answer: Optional[str] = None
|
| 47 |
citations: Optional[List[Dict[str, Any]]] = None
|
requirements.txt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:16661b3fde37f7912569994c2ab5098931d8b6ca3569b2095433b4a45dac1990
|
| 3 |
+
size 300
|
tests/unit/test_processing_agent.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from agents.processing_agent import ProcessingAgent
|
| 4 |
+
from models.state import State
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@pytest.fixture
|
| 8 |
+
def make_state():
|
| 9 |
+
def _make(query: str, passages):
|
| 10 |
+
return State(query=query, passages=passages)
|
| 11 |
+
|
| 12 |
+
return _make
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.mark.unit
|
| 16 |
+
def test_processing_enriches_state_single_passage(make_state):
|
| 17 |
+
state = make_state(
|
| 18 |
+
"test",
|
| 19 |
+
[
|
| 20 |
+
{
|
| 21 |
+
"paperId": "abc123",
|
| 22 |
+
"title": "Test Paper",
|
| 23 |
+
"text": "# Introduction\n"
|
| 24 |
+
+ "A " * 5000
|
| 25 |
+
+ "\n# Methods\n"
|
| 26 |
+
+ "B " * 5000,
|
| 27 |
+
"text_source": "pdf",
|
| 28 |
+
"year": 2020,
|
| 29 |
+
"venue": "Journal of Testing",
|
| 30 |
+
"influentialCitationCount": 2,
|
| 31 |
+
}
|
| 32 |
+
],
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
agent = ProcessingAgent(chunk_size=500, chunk_overlap=50)
|
| 36 |
+
updated_state = agent.process(state)
|
| 37 |
+
|
| 38 |
+
assert hasattr(updated_state, "chunks")
|
| 39 |
+
assert updated_state.chunks is not None
|
| 40 |
+
assert len(updated_state.chunks) >= 10
|
| 41 |
+
first_meta = updated_state.chunks[0].metadata
|
| 42 |
+
assert first_meta["paper_id"] == "abc123"
|
| 43 |
+
assert first_meta["paper_title"] == "Test Paper"
|
| 44 |
+
assert first_meta["year"] == 2020
|
| 45 |
+
assert first_meta["venue"] == "Journal of Testing"
|
| 46 |
+
assert first_meta["influential_citation_count"] == 2
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@pytest.mark.unit
|
| 50 |
+
def test_processing_multiple_passages_generates_chunks(make_state):
|
| 51 |
+
passages = []
|
| 52 |
+
for i in range(3):
|
| 53 |
+
passages.append(
|
| 54 |
+
{
|
| 55 |
+
"paperId": f"p{i}",
|
| 56 |
+
"title": f"Paper {i}",
|
| 57 |
+
"text": "# Introduction\n"
|
| 58 |
+
+ ("X " * 4000)
|
| 59 |
+
+ "\n# Results\n"
|
| 60 |
+
+ ("Y " * 4000),
|
| 61 |
+
"text_source": "pdf",
|
| 62 |
+
"year": 2019 + i,
|
| 63 |
+
"venue": "Conf",
|
| 64 |
+
"influentialCitationCount": i,
|
| 65 |
+
}
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
state = make_state("multi", passages)
|
| 69 |
+
agent = ProcessingAgent(chunk_size=500, chunk_overlap=50)
|
| 70 |
+
updated = agent.process(state)
|
| 71 |
+
|
| 72 |
+
assert hasattr(updated, "chunks")
|
| 73 |
+
assert len(updated.chunks) >= 30
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@pytest.mark.unit
|
| 77 |
+
def test_empty_passage_is_skipped(make_state):
|
| 78 |
+
state = make_state("empty", [{"paperId": "e1", "text": "", "text_source": "pdf"}])
|
| 79 |
+
agent = ProcessingAgent(chunk_size=200, chunk_overlap=20)
|
| 80 |
+
updated = agent.process(state)
|
| 81 |
+
|
| 82 |
+
assert hasattr(updated, "chunks")
|
| 83 |
+
assert isinstance(updated.chunks, list)
|
| 84 |
+
assert len(updated.chunks) == 0
|
| 85 |
+
# No critical error appended (empty passage skipped)
|
| 86 |
+
assert all("Zero chunks" not in e for e in updated.errors)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@pytest.mark.unit
|
| 90 |
+
def test_fallback_section_detection(make_state):
|
| 91 |
+
# No explicit headers -> triggers fallback chunking
|
| 92 |
+
long_text = "This is a paper without headers. " + ("word " * 3000)
|
| 93 |
+
state = make_state(
|
| 94 |
+
"fallback", [{"paperId": "f1", "text": long_text, "text_source": "pdf"}]
|
| 95 |
+
)
|
| 96 |
+
agent = ProcessingAgent(chunk_size=400, chunk_overlap=50)
|
| 97 |
+
updated = agent.process(state)
|
| 98 |
+
|
| 99 |
+
assert hasattr(updated, "chunks")
|
| 100 |
+
assert len(updated.chunks) > 0
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@pytest.mark.unit
|
| 104 |
+
def test_no_passages_triggers_error():
|
| 105 |
+
state = State(query="none", passages=None)
|
| 106 |
+
agent = ProcessingAgent()
|
| 107 |
+
res = agent.process(state)
|
| 108 |
+
assert len(res.errors) > 0
|
| 109 |
+
assert any(
|
| 110 |
+
"No passages available" in e or "Zero chunks generated" in e for e in res.errors
|
| 111 |
+
)
|
tests/unit/test_section_detector.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
|
| 3 |
+
from utils.section_detector import detect_sections
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
@pytest.mark.unit
|
| 7 |
+
def test_detect_standard_sections():
|
| 8 |
+
"""Test detection of standard 5-section paper."""
|
| 9 |
+
text = (
|
| 10 |
+
"# Introduction\nThis paper investigates...\n\n"
|
| 11 |
+
"# Methods\nWe conducted experiments...\n\n"
|
| 12 |
+
"# Results\nOur findings show...\n\n"
|
| 13 |
+
"# Discussion\nThese results indicate...\n\n"
|
| 14 |
+
"# Conclusion\nIn summary, we found...\n"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
sections = detect_sections(text, paper_id="test123", min_section_length=0)
|
| 18 |
+
|
| 19 |
+
assert len(sections) == 5
|
| 20 |
+
assert sections[0]["name"] == "Introduction"
|
| 21 |
+
assert sections[1]["name"] == "Methods"
|
| 22 |
+
assert "experiments" in sections[1]["text"]
|
| 23 |
+
assert sections[0]["start_idx"] == 0
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@pytest.mark.unit
|
| 27 |
+
def test_detect_three_sections_missing_some_headers():
|
| 28 |
+
text = (
|
| 29 |
+
"# Introduction\nShort intro...\n\n"
|
| 30 |
+
"# Methods\nMethod details...\n\n"
|
| 31 |
+
"# Results\nResults here...\n"
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
sections = detect_sections(text, paper_id="test_missing", min_section_length=0)
|
| 35 |
+
assert len(sections) == 3
|
| 36 |
+
names = [s["name"] for s in sections]
|
| 37 |
+
assert names == ["Introduction", "Methods", "Results"]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@pytest.mark.unit
|
| 41 |
+
def test_fallback_for_unstructured_text():
|
| 42 |
+
# Unstructured text with no headers should trigger fallback chunking
|
| 43 |
+
words = [f"word{i}" for i in range(3000)]
|
| 44 |
+
text = " ".join(words)
|
| 45 |
+
|
| 46 |
+
sections = detect_sections(
|
| 47 |
+
text, paper_id="fallback_test", fallback_token_size=1000, min_section_length=0
|
| 48 |
+
)
|
| 49 |
+
assert len(sections) >= 2
|
| 50 |
+
assert sections[0]["name"].startswith("chunk_")
|
| 51 |
+
# ensure chunks cover the whole text
|
| 52 |
+
total_len = sum((s["end_idx"] - s["start_idx"] for s in sections))
|
| 53 |
+
assert total_len > 0
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@pytest.mark.unit
|
| 57 |
+
def test_all_caps_headers():
|
| 58 |
+
text = (
|
| 59 |
+
"INTRODUCTION\nIntro text...\n\n"
|
| 60 |
+
"METHODS\nMethod text...\n\n"
|
| 61 |
+
"RESULTS\nResults...\n"
|
| 62 |
+
)
|
| 63 |
+
sections = detect_sections(text, paper_id="caps_test", min_section_length=0)
|
| 64 |
+
names = [s["name"] for s in sections]
|
| 65 |
+
assert "Introduction" in names
|
| 66 |
+
assert "Methods" in names
|
| 67 |
+
assert "Results" in names
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@pytest.mark.unit
|
| 71 |
+
def test_markdown_style_headers():
|
| 72 |
+
text = (
|
| 73 |
+
"## Introduction\nIntro here...\n\n"
|
| 74 |
+
"## Methods\nStuff...\n\n"
|
| 75 |
+
"## Results\nFindings...\n"
|
| 76 |
+
)
|
| 77 |
+
sections = detect_sections(text, paper_id="md_test", min_section_length=0)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@pytest.mark.unit
|
| 81 |
+
def test_numbered_headers():
|
| 82 |
+
text = (
|
| 83 |
+
"1. Introduction\nIntro text...\n\n"
|
| 84 |
+
"2) Methods\nMethod text...\n\n"
|
| 85 |
+
"III. Results\nResults...\n\n"
|
| 86 |
+
"(4) Discussion\nDiscuss...\n\n"
|
| 87 |
+
"5 Conclusion\nIn summary...\n"
|
| 88 |
+
)
|
| 89 |
+
sections = detect_sections(text, paper_id="numbered_test", min_section_length=0)
|
| 90 |
+
names = [s["name"] for s in sections]
|
| 91 |
+
assert "Introduction" in names
|
| 92 |
+
assert "Methods" in names
|
| 93 |
+
assert "Results" in names
|
| 94 |
+
assert "Discussion" in names
|
| 95 |
+
assert "Conclusion" in names
|
| 96 |
+
assert len(sections) == 5
|
| 97 |
+
assert sections[0]["name"] == "Introduction"
|
utils/section_detector.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Dict, Any, Optional
|
| 2 |
+
import re
|
| 3 |
+
import time
|
| 4 |
+
from loguru import logger
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def _map_title_to_canonical(title: str) -> str:
|
| 8 |
+
t = title.lower()
|
| 9 |
+
if t.startswith("intro") or t.startswith("background") or t.startswith("overview"):
|
| 10 |
+
return "Introduction"
|
| 11 |
+
if (
|
| 12 |
+
t.startswith("method")
|
| 13 |
+
or t.startswith("materials")
|
| 14 |
+
or t.startswith("methodology")
|
| 15 |
+
or t.startswith("experimental")
|
| 16 |
+
):
|
| 17 |
+
return "Methods"
|
| 18 |
+
if t.startswith("result") or t.startswith("finding"):
|
| 19 |
+
return "Results"
|
| 20 |
+
if t.startswith("discussion") or t.startswith("analysis"):
|
| 21 |
+
return "Discussion"
|
| 22 |
+
if t.startswith("conclusion") or t.startswith("summary") or t.startswith("future"):
|
| 23 |
+
return "Conclusion"
|
| 24 |
+
return title.strip().title()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _token_positions(text: str) -> List[str]:
|
| 28 |
+
# Return list of tokens (whitespace-separated)
|
| 29 |
+
return re.findall(r"\S+", text)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# Precompile header regex for performance
|
| 33 |
+
_TITLES = r"(Introduction|Background|Overview|Methods?|Materials?|Methodology|Experimental|Results?|Findings?|Discussion|Analysis|Conclusion|Summary|Future Work)"
|
| 34 |
+
# pattern covers: markdown headers (# Head), numbered headers (1. Head, I. Head, (1) Head), and lines that equal the title
|
| 35 |
+
_HEADER_PATTERN = rf"^(?:\s*#{{1,6}}\s*(?P<title>{_TITLES})\b.*$)|^(?:\s*(?:\d{{1,2}}|[IVXLCDM]+|\(\d{{1,2}}\))[\.\)]?\s*(?P<title_num>{_TITLES})\b.*$)|^(?P<title_only>{_TITLES})\s*$"
|
| 36 |
+
_HEADER_RE = re.compile(_HEADER_PATTERN, re.MULTILINE | re.IGNORECASE)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def detect_sections(
|
| 40 |
+
text: str,
|
| 41 |
+
paper_id: Optional[str] = None,
|
| 42 |
+
fallback_token_size: int = 1000,
|
| 43 |
+
min_section_length: int = 100,
|
| 44 |
+
) -> List[Dict[str, Any]]:
|
| 45 |
+
"""Detect standard sections in scientific paper text using regex.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
text: Full PDF text
|
| 49 |
+
paper_id: Optional paper ID for logging
|
| 50 |
+
fallback_token_size: Token count for naive splits if under 2 sections detected
|
| 51 |
+
min_section_length: minimum chars for a detected section to be kept
|
| 52 |
+
|
| 53 |
+
Returns:
|
| 54 |
+
List of section dicts with name, text, start_idx, end_idx
|
| 55 |
+
"""
|
| 56 |
+
start_time = time.perf_counter()
|
| 57 |
+
try:
|
| 58 |
+
logger.debug(
|
| 59 |
+
{
|
| 60 |
+
"event": "section_detection_start",
|
| 61 |
+
"paper_id": paper_id,
|
| 62 |
+
"length": len(text),
|
| 63 |
+
}
|
| 64 |
+
)
|
| 65 |
+
if not text:
|
| 66 |
+
logger.debug(
|
| 67 |
+
{
|
| 68 |
+
"event": "section_detection",
|
| 69 |
+
"paper_id": paper_id,
|
| 70 |
+
"sections": 0,
|
| 71 |
+
"fallback": True,
|
| 72 |
+
}
|
| 73 |
+
)
|
| 74 |
+
return [{"name": "full_text", "text": "", "start_idx": 0, "end_idx": 0}]
|
| 75 |
+
|
| 76 |
+
# Use module-level compiled regex to find headers
|
| 77 |
+
matches: List[tuple] = []
|
| 78 |
+
for m in _HEADER_RE.finditer(text):
|
| 79 |
+
title = m.group("title") or m.group("title_num") or m.group("title_only")
|
| 80 |
+
if title:
|
| 81 |
+
matches.append((title, m.start()))
|
| 82 |
+
|
| 83 |
+
sections: List[Dict[str, Any]] = []
|
| 84 |
+
|
| 85 |
+
if len(matches) < 2:
|
| 86 |
+
# Fallback to approximate char-based chunks for speed
|
| 87 |
+
logger.warning(
|
| 88 |
+
{
|
| 89 |
+
"event": "section_detection_fallback_triggered",
|
| 90 |
+
"paper_id": paper_id,
|
| 91 |
+
"matches_found": len(matches),
|
| 92 |
+
"reason": "matches<2",
|
| 93 |
+
}
|
| 94 |
+
)
|
| 95 |
+
chars_per_chunk = fallback_token_size * 4
|
| 96 |
+
|
| 97 |
+
chunks: List[Dict[str, Any]] = []
|
| 98 |
+
start_idx = 0
|
| 99 |
+
text_len = len(text)
|
| 100 |
+
while start_idx < text_len:
|
| 101 |
+
end_idx = min(text_len, start_idx + chars_per_chunk)
|
| 102 |
+
# try to extend to nearest sentence boundary (within next 1000 chars)
|
| 103 |
+
m = re.search(r"[\.\?!][\"']?\s+", text[end_idx : end_idx + 1000])
|
| 104 |
+
if m:
|
| 105 |
+
end_idx = end_idx + m.end()
|
| 106 |
+
chunk_text = text[start_idx:end_idx].strip()
|
| 107 |
+
if chunk_text:
|
| 108 |
+
if len(chunk_text) >= min_section_length:
|
| 109 |
+
chunks.append(
|
| 110 |
+
{
|
| 111 |
+
"name": f"chunk_{len(chunks)}",
|
| 112 |
+
"text": chunk_text,
|
| 113 |
+
"start_idx": start_idx,
|
| 114 |
+
"end_idx": end_idx,
|
| 115 |
+
}
|
| 116 |
+
)
|
| 117 |
+
else:
|
| 118 |
+
if chunks:
|
| 119 |
+
prev = chunks[-1]
|
| 120 |
+
prev_text = text[prev["start_idx"] : end_idx].strip()
|
| 121 |
+
prev.update({"text": prev_text, "end_idx": end_idx})
|
| 122 |
+
else:
|
| 123 |
+
chunks.append(
|
| 124 |
+
{
|
| 125 |
+
"name": "chunk_0",
|
| 126 |
+
"text": chunk_text,
|
| 127 |
+
"start_idx": start_idx,
|
| 128 |
+
"end_idx": end_idx,
|
| 129 |
+
}
|
| 130 |
+
)
|
| 131 |
+
start_idx = end_idx
|
| 132 |
+
|
| 133 |
+
elapsed = time.perf_counter() - start_time
|
| 134 |
+
logger.debug(
|
| 135 |
+
{
|
| 136 |
+
"event": "section_detection",
|
| 137 |
+
"paper_id": paper_id,
|
| 138 |
+
"sections": len(chunks),
|
| 139 |
+
"fallback": True,
|
| 140 |
+
"elapsed_s": elapsed,
|
| 141 |
+
"matches_found": len(matches),
|
| 142 |
+
}
|
| 143 |
+
)
|
| 144 |
+
return (
|
| 145 |
+
chunks
|
| 146 |
+
if chunks
|
| 147 |
+
else [
|
| 148 |
+
{
|
| 149 |
+
"name": "full_text",
|
| 150 |
+
"text": text,
|
| 151 |
+
"start_idx": 0,
|
| 152 |
+
"end_idx": len(text),
|
| 153 |
+
}
|
| 154 |
+
]
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
# Build sections from matches (matches is list of (title, start))
|
| 158 |
+
anchors: List[Dict[str, Any]] = []
|
| 159 |
+
for title, start in matches:
|
| 160 |
+
canonical = _map_title_to_canonical(title)
|
| 161 |
+
anchors.append({"name": canonical, "start": start})
|
| 162 |
+
|
| 163 |
+
# Sort anchors by start (should already be ordered)
|
| 164 |
+
anchors = sorted(anchors, key=lambda a: a["start"])
|
| 165 |
+
|
| 166 |
+
for idx, a in enumerate(anchors):
|
| 167 |
+
start_idx = a["start"]
|
| 168 |
+
end_idx = anchors[idx + 1]["start"] if idx + 1 < len(anchors) else len(text)
|
| 169 |
+
sect_text = text[start_idx:end_idx].strip()
|
| 170 |
+
sections.append(
|
| 171 |
+
{
|
| 172 |
+
"name": a["name"],
|
| 173 |
+
"text": sect_text,
|
| 174 |
+
"start_idx": start_idx,
|
| 175 |
+
"end_idx": end_idx,
|
| 176 |
+
}
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# Filter short sections if requested
|
| 180 |
+
filtered = [s for s in sections if len(s.get("text", "")) >= min_section_length]
|
| 181 |
+
if len(filtered) < 2:
|
| 182 |
+
# If filtering removed too many, keep original sections (prefer detection over nothing)
|
| 183 |
+
filtered = sections
|
| 184 |
+
|
| 185 |
+
elapsed = time.perf_counter() - start_time
|
| 186 |
+
logger.debug(
|
| 187 |
+
{
|
| 188 |
+
"event": "section_detection",
|
| 189 |
+
"paper_id": paper_id,
|
| 190 |
+
"sections": len(filtered),
|
| 191 |
+
"fallback": False,
|
| 192 |
+
"names": [s["name"] for s in filtered],
|
| 193 |
+
"elapsed_s": elapsed,
|
| 194 |
+
}
|
| 195 |
+
)
|
| 196 |
+
return filtered
|
| 197 |
+
|
| 198 |
+
except Exception as e: # Never raise
|
| 199 |
+
logger.debug(
|
| 200 |
+
{"event": "section_detection_error", "paper_id": paper_id, "error": str(e)}
|
| 201 |
+
)
|
| 202 |
+
return [
|
| 203 |
+
{
|
| 204 |
+
"name": "full_text",
|
| 205 |
+
"text": text or "",
|
| 206 |
+
"start_idx": 0,
|
| 207 |
+
"end_idx": len(text or ""),
|
| 208 |
+
}
|
| 209 |
+
]
|