File size: 13,010 Bytes
c4bb573
 
 
 
 
 
 
daa09ee
 
0cbdfcf
c4bb573
0cbdfcf
c4bb573
 
 
0cbdfcf
c4bb573
58913a2
c4bb573
 
 
0cbdfcf
 
 
c4bb573
 
 
 
 
0cbdfcf
 
 
 
 
 
 
c4bb573
 
 
0cbdfcf
 
 
 
 
 
c4bb573
 
 
 
0cbdfcf
c4bb573
 
 
0cbdfcf
 
 
 
 
 
 
 
 
 
c4bb573
 
0cbdfcf
 
 
 
 
c4bb573
 
0cbdfcf
 
 
 
 
c4bb573
 
0cbdfcf
 
 
c4bb573
0cbdfcf
 
 
c4bb573
0cbdfcf
 
 
c4bb573
0cbdfcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4bb573
0cbdfcf
 
 
 
 
 
 
 
 
 
375e62f
 
0cbdfcf
375e62f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cbdfcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4bb573
 
 
 
0cbdfcf
 
 
c4bb573
0cbdfcf
c4bb573
 
 
 
0cbdfcf
 
 
 
c4bb573
0cbdfcf
 
 
 
 
 
 
 
 
 
 
daa09ee
0cbdfcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4bb573
 
0cbdfcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4bb573
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cbdfcf
c4bb573
 
 
0cbdfcf
c4bb573
 
 
0cbdfcf
 
c4bb573
0cbdfcf
c4bb573
 
0cbdfcf
c4bb573
 
 
0cbdfcf
c4bb573
 
 
 
 
 
0cbdfcf
 
 
 
 
 
 
 
 
 
daa09ee
0cbdfcf
 
 
 
 
 
 
c4bb573
 
0cbdfcf
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
import gradio as gr
import aiohttp
import asyncio
import json
import hashlib
import re
import logging
import io
import pdfplumber
from typing import Any, List, Dict, Optional, Set
from functools import lru_cache
from dataclasses import dataclass

# --- Configuration ---
REQUESTS_HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
MIN_TEXT_LENGTH = 1
CHUNK_TARGET_SIZE = 150
EMBEDDING_MODEL = "all-MiniLM-L6-v2"
EMBEDDING_BATCH_SIZE = 32
STOPWORDS = frozenset({'the', 'and', 'for', 'with', 'this', 'that', 'is', 'in', 'to', 'of'})
MAX_URL_RETRIES = 2
REQUEST_TIMEOUT = 10

# --- Setup Logging ---
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# --- Data Structures ---
@dataclass
class Chunk:
    id: str
    text: str
    payload: Dict[str, Any]

# --- Lazy Load Model ---
@lru_cache(maxsize=1)
def get_model():
    try:
        from sentence_transformers import SentenceTransformer
        return SentenceTransformer(EMBEDDING_MODEL, device='cpu')
    except Exception as e:
        logger.error(f"Failed to load model {EMBEDDING_MODEL}: {e}")
        raise

# --- Utility Functions ---
@lru_cache(maxsize=1000)
def get_hash(text: str, title: str, source: str) -> str:
    return hashlib.md5((text + title + source).encode('utf-8')).hexdigest()

@lru_cache(maxsize=1000)
def extract_keywords(text: str, top_k: int = 5) -> tuple:
    try:
        words = re.findall(r'\b\w+\b', text.lower())
        word_freq = {}
        for word in words:
            if len(word) > 3 and word not in STOPWORDS:
                word_freq[word] = word_freq.get(word, 0) + 1
        return tuple(sorted(word_freq, key=word_freq.get, reverse=True)[:min(top_k, len(word_freq))])
    except Exception as e:
        logger.error(f"Error extracting keywords: {e}")
        return ()

def generate_title(text: str, fallback: str = "Untitled") -> str:
    try:
        keywords = extract_keywords(text, top_k=3)
        return " ".join(keywords).title()[:50] if keywords else fallback
    except Exception:
        return fallback

def sent_tokenize_fallback(text: str) -> List[str]:
    try:
        return re.split(r'(?<=[.!?])\s+', text.strip()) if text.strip() else []
    except Exception as e:
        logger.error(f"Error in sentence tokenization: {e}")
        return [text.strip()] if text.strip() else []

def chunk_text(text: str, fallback_title: str = "Untitled", chunk_size: int = CHUNK_TARGET_SIZE) -> List[Dict[str, str]]:
    try:
        if len(text.strip()) < MIN_TEXT_LENGTH:
            return []

        sentences = sent_tokenize_fallback(text)
        if not sentences:
            return []

        chunks = []
        current_chunk = []
        current_length = 0

        for sentence in sentences:
            sentence = sentence.strip()
            if not sentence:
                continue
            sentence_words = len(sentence.split())
            if current_length + sentence_words > chunk_size and current_chunk:
                chunk_body = " ".join(current_chunk).strip()
                if chunk_body:
                    chunks.append({"title": generate_title(chunk_body, fallback_title), "text": chunk_body})
                current_chunk = []
                current_length = 0
            current_chunk.append(sentence)
            current_length += sentence_words

        if current_chunk:
            chunk_body = " ".join(current_chunk).strip()
            if chunk_body:
                chunks.append({"title": generate_title(chunk_body, fallback_title), "text": chunk_body})

        return chunks
    except Exception as e:
        logger.error(f"Error chunking text: {e}")
        return []

async def extract_from_url(url: str, session: aiohttp.ClientSession, retries: int = MAX_URL_RETRIES) -> Optional[Dict[str, str]]:
    for attempt in range(retries):
        try:
            async with session.get(url, timeout=REQUEST_TIMEOUT, headers=REQUESTS_HEADERS) as response:
                if response.status != 200:
                    logger.warning(f"Non-200 status {response.status} for URL: {url}")
                    continue
                
                content_type = response.headers.get('Content-Type', '').lower()
                content = await response.read()

                # Handle PDF content
                if 'application/pdf' in content_type:
                    try:
                        text = ""
                        with pdfplumber.open(io.BytesIO(content)) as pdf:
                            for page in pdf.pages:
                                page_text = page.extract_text()
                                if page_text:
                                    text += page_text + "\n"
                        if text and len(text.strip()) >= MIN_TEXT_LENGTH:
                            return {"title": "PDF Document", "text": text.strip()}
                        logger.warning(f"No valid text extracted from PDF at {url}")
                        return None
                    except Exception as e:
                        logger.error(f"Failed to process PDF at {url}: {e}")
                        return None

                # Handle HTML content
                encoding = response.charset or 'utf-8'
                html = content.decode(encoding, errors='ignore')

                import trafilatura
                metadata_doc = trafilatura.extract_metadata(html)
                fallback_title = metadata_doc.as_dict().get('title', 'Untitled') if metadata_doc else 'Untitled'
                text = trafilatura.extract(html, include_comments=False, include_tables=False)

                if not text or len(text.strip()) < MIN_TEXT_LENGTH:
                    logger.warning(f"No valid content extracted from {url}, trying BeautifulSoup...")
                    from bs4 import BeautifulSoup
                    soup = BeautifulSoup(html, "html.parser")
                    for tag in soup(["script", "style", "nav", "footer", "noscript"]):
                        tag.decompose()
                    text = soup.get_text(" ", strip=True)

                return {"title": fallback_title, "text": text} if text and len(text.strip()) >= MIN_TEXT_LENGTH else None

        except aiohttp.ClientError as e:
            logger.warning(f"Attempt {attempt + 1} failed for {url}: {e}")
            if attempt + 1 == retries:
                logger.error(f"Failed to process URL {url} after {retries} attempts")
                return None
            await asyncio.sleep(1)

    return None

# --- Vector Store ---
class VectorStore:
    def __init__(self):
        self.dedup_hashes: Set[str] = set()
        self.results: List[Dict[str, Any]] = []
        self._chunks_to_embed: List[Chunk] = []

    def reset(self) -> None:
        self.dedup_hashes.clear()
        self.results.clear()
        self._chunks_to_embed.clear()

    async def add_chunks(self, text: str, source: str, title: str, extra_payload: Optional[Dict] = None) -> None:
        try:
            if len(text.strip()) < MIN_TEXT_LENGTH:
                return

            for chunk in chunk_text(text, fallback_title=title):
                chunk_id = get_hash(chunk['text'], chunk['title'], source)
                if chunk_id in self.dedup_hashes:
                    continue
                self.dedup_hashes.add(chunk_id)
                payload = {
                    "title": chunk['title'],
                    "text": chunk['text'],
                    "source": source,
                    **(extra_payload or {})
                }
                self._chunks_to_embed.append(Chunk(chunk_id, text=chunk['text'], payload=payload))
        except Exception as e:
            logger.error(f"Error adding chunks: {e}")

    def embed_and_finalize(self, batch_size: int = EMBEDDING_BATCH_SIZE) -> None:
        try:
            if not self._chunks_to_embed:
                return

            all_texts = [chunk.text for chunk in self._chunks_to_embed]
            logger.info(f"Embedding {len(all_texts)} chunks...")
            model = get_model()
            all_vectors = model.encode(all_texts, batch_size=batch_size, show_progress_bar=False, normalize_embeddings=True)
            logger.info("Embedding complete.")

            seen_hashes = set()
            for chunk, vector in zip(self._chunks_to_embed, all_vectors):
                if chunk.id not in seen_hashes:
                    seen_hashes.add(chunk.id)
                    self.results.append({
                        "id": chunk.id,
                        "vector": vector.tolist(),
                        "payload": chunk.payload
                    })
        except Exception as e:
            logger.error(f"Error during embedding: {e}")

# --- Processing Logic ---
async def traverse_and_process(data: Any, vector_store: VectorStore, source_key: str = "json_root", session: aiohttp.ClientSession = None, processed_urls: Set[str] = None) -> None:
    try:
        if processed_urls is None:
            processed_urls = set()

        if isinstance(data, dict):
            for key, value in data.items():
                await traverse_and_process(value, vector_store, source_key=key, session=session, processed_urls=processed_urls)
        elif isinstance(data, list):
            for item in data:
                await traverse_and_process(item, vector_store, source_key=source_key, session=session, processed_urls=processed_urls)
        elif isinstance(data, str) and data.strip():
            content = data.strip()
            if re.match(r'^https?://', content) and content not in processed_urls:
                processed_urls.add(content)
                extracted = await extract_from_url(content, session)
                if extracted:
                    await vector_store.add_chunks(extracted['text'], source=content, title=extracted['title'])
            else:
                await vector_store.add_chunks(content, source="json_text", title=generate_title(content, source_key))
    except Exception as e:
        logger.error(f"Error in traverse_and_process: {e}")

async def process_input_async(input_json: str) -> str:
    vector_store = VectorStore()
    try:
        input_obj = json.loads(input_json)
        if not isinstance(input_obj, list):
            return json.dumps({"error": "Input must be a list of {type, content} items"}, indent=2)

        async with aiohttp.ClientSession() as session:
            tasks = []
            processed_urls = set()
            for entry in input_obj:
                kind = entry.get("type")
                content = entry.get("content")
                if not kind or not content:
                    logger.warning(f"Skipping invalid entry: {entry}")
                    continue

                if kind == "context":
                    tasks.append(traverse_and_process(content, vector_store, source_key=kind, session=session, processed_urls=processed_urls))
                elif kind == "text":
                    keywords = extract_keywords(content)
                    tasks.append(vector_store.add_chunks(content, source="user_message", title=generate_title(content, "User Message"), extra_payload={"keywords": list(keywords)}))
                else:
                    logger.warning(f"Unsupported entry type: {kind}")

            await asyncio.gather(*tasks, return_exceptions=True)

        vector_store.embed_and_finalize()
        return json.dumps(vector_store.results, indent=2, ensure_ascii=False)
    except json.JSONDecodeError as e:
        return json.dumps({"error": "Invalid JSON provided", "details": str(e)}, indent=2)
    except Exception as e:
        logger.error(f"Unexpected error during processing: {e}", exc_info=True)
        return json.dumps({"error": "An unexpected error occurred", "details": str(e)}, indent=2)

def process_input(input_json: str) -> str:
    return asyncio.run(process_input_async(input_json))

# --- Gradio UI ---
def launch_gradio():
    try:
        iface = gr.Interface(
            fn=process_input,
            inputs=gr.Textbox(
                label="Paste JSON Array [{type, content}]",
                lines=15,
                placeholder='[{"type": "context", "content": {"url": "https://www.gradio.app/guides/quickstart", "summary": "Sample summary..."}}, {"type": "text", "content": "What is the main topic of this page?"}]'
            ),
            outputs=gr.Code(label="Qdrant-Ready Embeddings", language="json"),
            title="Fast Messaging Embedder",
            description="Processes text and URLs, generates descriptive titles, and produces embeddings for Qdrant. Optimized for messaging and context handling.",
            allow_flagging="never"
        )
        iface.launch()
    except Exception as e:
        logger.error(f"Failed to launch Gradio interface: {e}")
        raise

if __name__ == "__main__":
    launch_gradio()