File size: 7,971 Bytes
862be58
 
 
395c9ad
862be58
395c9ad
698b399
862be58
395c9ad
6d70778
862be58
395c9ad
862be58
 
 
698b399
862be58
 
 
 
 
 
 
 
 
698b399
 
 
 
862be58
 
 
 
 
 
6d70778
 
 
 
 
 
698b399
862be58
 
 
 
 
 
 
 
 
6d70778
 
 
862be58
 
 
6d70778
 
862be58
5b48ad6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
862be58
 
 
 
6885e0c
 
395c9ad
 
 
 
 
 
862be58
 
4a2e58c
862be58
698b399
73d3d37
 
862be58
698b399
 
862be58
 
 
698b399
862be58
 
 
 
73d3d37
862be58
 
73d3d37
 
698b399
73d3d37
 
 
 
 
 
 
 
 
 
 
 
 
 
28ba0c9
 
73d3d37
 
 
862be58
 
 
 
 
 
 
 
 
6d70778
 
 
698b399
 
 
 
862be58
698b399
6d70778
 
 
 
 
 
 
 
 
 
 
 
 
698b399
6d70778
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
698b399
 
6d70778
 
 
 
 
698b399
6d70778
 
698b399
6d70778
 
 
 
 
 
 
 
 
 
862be58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import time
from typing import Any, List, Optional

import numpy as np
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.schema import Document
from loguru import logger

from models.state import State
from utils.embedding_utils import batched_embed


class ProcessingAgent:
    """State-aware processing agent that chunks texts.

    Usage:
        agent = ProcessingAgent(chunk_size=500, chunk_overlap=50)
        updated_state = agent.process(state)
    """

    def __init__(self, chunk_size: int = 500, chunk_overlap: int = 50):
        self.chunk_size = int(chunk_size)
        self.chunk_overlap = int(chunk_overlap)

        # Single-stage parsing: split by token size/sentences
        # This is sufficient for plain text extracted via fitz
        self.splitter = SentenceSplitter(
            chunk_size=self.chunk_size, chunk_overlap=self.chunk_overlap
        )
        logger.debug(
            f"ProcessingAgent initialized: chunk_size={chunk_size}, overlap={chunk_overlap}"
        )

    def process(
        self,
        state: State,
        embedding_model: Optional[object] = None,
        batch_size: int = 32,
    ) -> State:
        """Process `state.passages` and populate `state.chunks`."""
        start_time = time.perf_counter()

        if not state.passages:
            msg = "No passages available for processing"
            logger.warning(msg)
            state.append_error(msg)
            return state

        logger.info(f"Processing {len(state.passages)} passages")
        chunking_time = 0.0
        embedding_time = 0.0

        all_chunks: List[Any] = []
        had_nonempty_passage = False

        loop_start = time.perf_counter()

        for idx, passage in enumerate(state.passages):
            # Refactored to use Passage object attributes
            paper_id = passage.paper_id or f"paper_{idx}"
            text = passage.text or ""

            # Metadata extraction
            meta = passage.metadata
            title = meta.get("title", "")
            citation_count = meta.get("citationCount", 0)
            year = meta.get("year")
            venue = meta.get("venue")
            influential = meta.get("influentialCitationCount", 0)

            # Handle PDF URL extraction from metadata
            oa_pdf = meta.get("openAccessPdf")
            pdf_url = None
            if oa_pdf and isinstance(oa_pdf, dict):
                pdf_url = oa_pdf.get("url")

            if not pdf_url:
                pdf_url = meta.get("url")

            if not text.strip():
                logger.warning({"event": "empty_passage_skipped", "paper_id": paper_id})
                continue

            # Text truncation to save memory on large PDFs
            original_len = len(text)
            if original_len > 40000:
                text = text[:40000]
                logger.warning(
                    f"✂️ Truncated paper {paper_id} from {original_len} to 40000 chars to save memory"
                )
            had_nonempty_passage = True

            logger.debug({"event": "processing_paper_start", "paper_id": paper_id})

            # Create document
            doc = Document(text=text)

            try:
                # DIRECT SPLIT: Use SentenceSplitter directly on the document
                nodes = self.splitter.get_nodes_from_documents([doc])
            except Exception as e:
                logger.warning(
                    {
                        "event": "parsing_failed",
                        "paper_id": paper_id,
                        "error": str(e),
                    }
                )
                nodes = []

            paper_chunk_count = 0

            for chunk_idx, node in enumerate(nodes):
                # Attach metadata
                node.metadata.update(
                    {
                        "paper_id": paper_id,
                        "chunk_index": chunk_idx,
                        "paper_title": title,
                        "citation_count": citation_count,
                    }
                )
                if year is not None:
                    node.metadata["year"] = year
                if venue is not None:
                    node.metadata["venue"] = venue
                if influential is not None:
                    node.metadata["influential_citation_count"] = influential
                if pdf_url:
                    node.metadata["pdf_url"] = pdf_url

                all_chunks.append(node)
                paper_chunk_count += 1

            logger.debug(
                {
                    "event": "processing_paper_done",
                    "paper_id": paper_id,
                    "chunks": paper_chunk_count,
                }
            )

        loop_end = time.perf_counter()
        chunking_time = loop_end - loop_start

        if not all_chunks and had_nonempty_passage:
            msg = "Zero chunks generated from passages"
            logger.error(msg)
            state.append_error(msg)

        # Embedding Logic (unchanged)
        if embedding_model is not None and all_chunks:
            texts: List[str] = []
            for node in all_chunks:
                if hasattr(node, "get_text"):
                    try:
                        texts.append(node.get_text())
                    except Exception:
                        texts.append("")
                elif hasattr(node, "text"):
                    texts.append(getattr(node, "text") or "")
                else:
                    texts.append("")

            # Retry logic
            max_attempts = 3
            base_backoff = 0.5
            embeddings = None
            for attempt in range(1, max_attempts + 1):
                try:
                    emb_start = time.perf_counter()
                    embeddings = batched_embed(
                        texts,
                        embedding_model=embedding_model,
                        batch_size=int(batch_size),
                    )
                    emb_end = time.perf_counter()
                    embedding_time = emb_end - emb_start
                    break
                except Exception as exc:
                    logger.exception(
                        {
                            "event": "embedding_attempt_failed",
                            "attempt": attempt,
                            "error": str(exc),
                        }
                    )
                    if attempt < max_attempts:
                        wait = base_backoff * (2 ** (attempt - 1))
                        time.sleep(wait)
                        continue
                    else:
                        state.append_error("Batched embedding failed")

            if embeddings is not None:
                for idx, (node, emb) in enumerate(zip(all_chunks, embeddings)):
                    try:
                        arr = np.asarray(emb, dtype=float)
                        if arr.shape != (384,):
                            continue
                        node.metadata["embedding"] = arr.tolist()
                    except Exception as e:
                        logger.exception("Failed to attach embedding", idx=idx)

            logger.info(
                {
                    "event": "embedding_complete",
                    "chunks_embedded": len(all_chunks) if embeddings is not None else 0,
                    "embedding_time_s": embedding_time,
                    "chunking_time_s": chunking_time,
                }
            )

        state.update_fields(chunks=all_chunks)

        elapsed = time.perf_counter() - start_time
        logger.info(
            {
                "event": "processing_complete",
                "passages": len(state.passages),
                "chunks": len(all_chunks),
                "elapsed_s": elapsed,
            }
        )
        return state


__all__ = ["ProcessingAgent"]