kaushalkrishnax commited on
Commit
0cbdfcf
·
1 Parent(s): c4bb573
Files changed (2) hide show
  1. app.py +199 -140
  2. requirements.txt +6 -9
app.py CHANGED
@@ -5,175 +5,225 @@ import json
5
  import hashlib
6
  import re
7
  import logging
8
- from typing import Any, List, Dict, Optional
9
  from functools import lru_cache
 
10
 
11
  # --- Configuration ---
12
  REQUESTS_HEADERS = {
13
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
14
  }
15
  MIN_TEXT_LENGTH = 10
16
  CHUNK_TARGET_SIZE = 150
17
  EMBEDDING_MODEL = "all-MiniLM-L6-v2"
18
  EMBEDDING_BATCH_SIZE = 32
19
- STOPWORDS = {'the', 'and', 'for', 'with', 'this', 'that'}
 
 
20
 
21
  # --- Setup Logging ---
22
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
23
  logger = logging.getLogger(__name__)
24
 
 
 
 
 
 
 
 
25
  # --- Lazy Load Model ---
26
  @lru_cache(maxsize=1)
27
  def get_model():
28
- from sentence_transformers import SentenceTransformer
29
- return SentenceTransformer(EMBEDDING_MODEL)
 
 
 
 
30
 
31
  # --- Utility Functions ---
32
  @lru_cache(maxsize=1000)
33
  def get_hash(text: str, title: str, source: str) -> str:
34
- return hashlib.md5((text + title + source).encode()).hexdigest()
35
 
36
  @lru_cache(maxsize=1000)
37
  def extract_keywords(text: str, top_k: int = 5) -> tuple:
38
- words = re.findall(r'\b\w+\b', text.lower())
39
- word_freq = {}
40
- for word in words:
41
- if len(word) > 3 and word not in STOPWORDS:
42
- word_freq[word] = word_freq.get(word, 0) + 1
43
- return tuple(sorted(word_freq, key=word_freq.get, reverse=True)[:top_k])
 
 
 
 
44
 
45
  def generate_title(text: str, fallback: str = "Untitled") -> str:
46
- keywords = extract_keywords(text, top_k=3)
47
- if keywords:
48
- return " ".join(keywords[:3]).title()[:30]
49
- return fallback
 
50
 
51
  def sent_tokenize_fallback(text: str) -> List[str]:
52
- return re.split(r'(?<=[.!?])\s+', text.strip())
 
 
 
 
53
 
54
  def chunk_text(text: str, fallback_title: str = "Untitled", chunk_size: int = CHUNK_TARGET_SIZE) -> List[Dict[str, str]]:
55
- if len(text.strip()) < MIN_TEXT_LENGTH:
56
- return []
57
-
58
- sentences = sent_tokenize_fallback(text)
59
- chunks = []
60
- current_chunk = []
61
- current_length = 0
62
-
63
- for sentence in sentences:
64
- sentence_words = len(sentence.split())
65
- if current_length + sentence_words > chunk_size and current_chunk:
66
- chunk_body = " ".join(current_chunk)
67
- chunks.append({"title": generate_title(chunk_body, fallback_title), "text": chunk_body})
68
- current_chunk = []
69
- current_length = 0
70
- current_chunk.append(sentence)
71
- current_length += sentence_words
72
-
73
- if current_chunk:
74
- chunk_body = " ".join(current_chunk)
75
- chunks.append({"title": generate_title(chunk_body, fallback_title), "text": chunk_body})
76
 
77
- return chunks
 
 
78
 
79
- async def extract_from_url(url: str, session: aiohttp.ClientSession) -> Optional[Dict[str, str]]:
80
- try:
81
- async with session.get(url, timeout=10, headers=REQUESTS_HEADERS) as response:
82
- content = await response.read()
83
- encoding = response.charset or 'utf-8'
84
- html = content.decode(encoding, errors='ignore')
85
-
86
- import trafilatura
87
- metadata_doc = trafilatura.extract_metadata(html)
88
- fallback_title = metadata_doc.as_dict().get('title', 'Untitled') if metadata_doc else 'Untitled'
89
- text = trafilatura.extract(html)
90
-
91
- if not text:
92
- logger.warning("Trafilatura failed for %s, using BeautifulSoup fallback...", url)
93
- from bs4 import BeautifulSoup
94
- soup = BeautifulSoup(html, "html.parser")
95
- for tag in soup(["script", "style", "nav", "footer", "noscript"]):
96
- tag.decompose()
97
- text = soup.get_text(" ", strip=True)
98
-
99
- return {"title": fallback_title, "text": text} if text and len(text.strip()) > MIN_TEXT_LENGTH else None
100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  except Exception as e:
102
- logger.error("Failed to process URL %s: %s", url, e)
103
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
  # --- Vector Store ---
106
  class VectorStore:
107
  def __init__(self):
108
- self.dedup_hashes = set()
109
- self.results = []
110
- self._chunks_to_embed = []
111
 
112
- def reset(self):
113
  self.dedup_hashes.clear()
114
  self.results.clear()
115
  self._chunks_to_embed.clear()
116
 
117
- async def add_chunks(self, text: str, source: str, title: str, extra_payload: Optional[Dict] = None):
118
- if len(text.strip()) < MIN_TEXT_LENGTH:
119
- return
 
120
 
121
- for chunk in chunk_text(text, fallback_title=title):
122
- chunk_id = get_hash(chunk['text'], chunk['title'], source)
123
- if chunk_id in self.dedup_hashes:
124
- continue
125
- self.dedup_hashes.add(chunk_id)
126
- payload = {
127
- "title": chunk['title'],
128
- "text": chunk['text'],
129
- "source": source,
130
- **(extra_payload or {})
131
- }
132
- self._chunks_to_embed.append({
133
- "id": chunk_id,
134
- "text": chunk['text'],
135
- "payload": payload
136
- })
137
-
138
- def embed_and_finalize(self, batch_size: int = EMBEDDING_BATCH_SIZE):
139
- if not self._chunks_to_embed:
140
- return
141
-
142
- all_texts = [item['text'] for item in self._chunks_to_embed]
143
- logger.info(f"Starting batch embedding for {len(all_texts)} chunks...")
144
- all_vectors = get_model().encode(all_texts, batch_size=batch_size, show_progress_bar=False)
145
- logger.info("Batch embedding complete.")
146
-
147
- seen_hashes = set()
148
- for item, vector in zip(self._chunks_to_embed, all_vectors):
149
- if item['id'] not in seen_hashes:
150
- seen_hashes.add(item['id'])
151
- self.results.append({
152
- "id": item['id'],
153
- "vector": vector.tolist(),
154
- "payload": item['payload']
155
- })
 
 
156
 
157
  # --- Processing Logic ---
158
- async def traverse_and_process(data: Any, vector_store: VectorStore, source_key: str = "json_root", session: aiohttp.ClientSession = None, processed_urls: set = None):
159
- if processed_urls is None:
160
- processed_urls = set()
161
-
162
- if isinstance(data, dict):
163
- for key, value in data.items():
164
- await traverse_and_process(value, vector_store, source_key=key, session=session, processed_urls=processed_urls)
165
- elif isinstance(data, list):
166
- for item in data:
167
- await traverse_and_process(item, vector_store, source_key=source_key, session=session, processed_urls=processed_urls)
168
- elif isinstance(data, str) and data.strip():
169
- content = data.strip()
170
- if content.startswith("http") and content not in processed_urls:
171
- processed_urls.add(content)
172
- extracted = await extract_from_url(content, session)
173
- if extracted:
174
- await vector_store.add_chunks(extracted['text'], source=content, title=extracted['title'])
175
- else:
176
- await vector_store.add_chunks(content, source="json_text", title=generate_title(content, source_key))
 
 
 
177
 
178
  async def process_input_async(input_json: str) -> str:
179
  vector_store = VectorStore()
@@ -189,40 +239,49 @@ async def process_input_async(input_json: str) -> str:
189
  kind = entry.get("type")
190
  content = entry.get("content")
191
  if not kind or not content:
 
192
  continue
193
 
194
  if kind == "context":
195
- tasks.append(traverse_and_process(content, vector_store, session=session, processed_urls=processed_urls))
196
  elif kind == "text":
197
  keywords = extract_keywords(content)
198
  tasks.append(vector_store.add_chunks(content, source="user_message", title=generate_title(content, "User Message"), extra_payload={"keywords": list(keywords)}))
 
 
199
 
200
- await asyncio.gather(*tasks)
201
 
202
  vector_store.embed_and_finalize()
203
- return json.dumps(vector_store.results, indent=2)
204
  except json.JSONDecodeError as e:
205
  return json.dumps({"error": "Invalid JSON provided", "details": str(e)}, indent=2)
206
  except Exception as e:
207
- logger.error("Unexpected error during processing: %s", e, exc_info=True)
208
  return json.dumps({"error": "An unexpected error occurred", "details": str(e)}, indent=2)
209
 
210
  def process_input(input_json: str) -> str:
211
  return asyncio.run(process_input_async(input_json))
212
 
213
  # --- Gradio UI ---
214
- iface = gr.Interface(
215
- fn=process_input,
216
- inputs=gr.Textbox(
217
- label="Paste JSON Array [{type, content}]",
218
- lines=15,
219
- 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?"}]'
220
- ),
221
- outputs=gr.Code(label="Qdrant-Ready Embeddings", language="json"),
222
- title="Fast Messaging Embedder",
223
- description="Optimized for messaging: processes text and URLs, generates descriptive titles, and produces embeddings for Qdrant.",
224
- allow_flagging="never"
225
- )
 
 
 
 
 
 
226
 
227
  if __name__ == "__main__":
228
- iface.launch()
 
5
  import hashlib
6
  import re
7
  import logging
8
+ from typing import Any, List, Dict, Optional, Set
9
  from functools import lru_cache
10
+ from dataclasses import dataclass
11
 
12
  # --- Configuration ---
13
  REQUESTS_HEADERS = {
14
+ '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'
15
  }
16
  MIN_TEXT_LENGTH = 10
17
  CHUNK_TARGET_SIZE = 150
18
  EMBEDDING_MODEL = "all-MiniLM-L6-v2"
19
  EMBEDDING_BATCH_SIZE = 32
20
+ STOPWORDS = frozenset({'the', 'and', 'for', 'with', 'this', 'that', 'is', 'in', 'to', 'of'})
21
+ MAX_URL_RETRIES = 2
22
+ REQUEST_TIMEOUT = 10
23
 
24
  # --- Setup Logging ---
25
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
26
  logger = logging.getLogger(__name__)
27
 
28
+ # --- Data Structures ---
29
+ @dataclass
30
+ class Chunk:
31
+ id: str
32
+ text: str
33
+ payload: Dict[str, Any]
34
+
35
  # --- Lazy Load Model ---
36
  @lru_cache(maxsize=1)
37
  def get_model():
38
+ try:
39
+ from sentence_transformers import SentenceTransformer
40
+ return SentenceTransformer(EMBEDDING_MODEL, device='cpu')
41
+ except Exception as e:
42
+ logger.error(f"Failed to load model {EMBEDDING_MODEL}: {e}")
43
+ raise
44
 
45
  # --- Utility Functions ---
46
  @lru_cache(maxsize=1000)
47
  def get_hash(text: str, title: str, source: str) -> str:
48
+ return hashlib.md5((text + title + source).encode('utf-8')).hexdigest()
49
 
50
  @lru_cache(maxsize=1000)
51
  def extract_keywords(text: str, top_k: int = 5) -> tuple:
52
+ try:
53
+ words = re.findall(r'\b\w+\b', text.lower())
54
+ word_freq = {}
55
+ for word in words:
56
+ if len(word) > 3 and word not in STOPWORDS:
57
+ word_freq[word] = word_freq.get(word, 0) + 1
58
+ return tuple(sorted(word_freq, key=word_freq.get, reverse=True)[:min(top_k, len(word_freq))])
59
+ except Exception as e:
60
+ logger.error(f"Error extracting keywords: {e}")
61
+ return ()
62
 
63
  def generate_title(text: str, fallback: str = "Untitled") -> str:
64
+ try:
65
+ keywords = extract_keywords(text, top_k=3)
66
+ return " ".join(keywords).title()[:50] if keywords else fallback
67
+ except Exception:
68
+ return fallback
69
 
70
  def sent_tokenize_fallback(text: str) -> List[str]:
71
+ try:
72
+ return re.split(r'(?<=[.!?])\s+', text.strip()) if text.strip() else []
73
+ except Exception as e:
74
+ logger.error(f"Error in sentence tokenization: {e}")
75
+ return [text.strip()] if text.strip() else []
76
 
77
  def chunk_text(text: str, fallback_title: str = "Untitled", chunk_size: int = CHUNK_TARGET_SIZE) -> List[Dict[str, str]]:
78
+ try:
79
+ if len(text.strip()) < MIN_TEXT_LENGTH:
80
+ return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
+ sentences = sent_tokenize_fallback(text)
83
+ if not sentences:
84
+ return []
85
 
86
+ chunks = []
87
+ current_chunk = []
88
+ current_length = 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
+ for sentence in sentences:
91
+ sentence = sentence.strip()
92
+ if not sentence:
93
+ continue
94
+ sentence_words = len(sentence.split())
95
+ if current_length + sentence_words > chunk_size and current_chunk:
96
+ chunk_body = " ".join(current_chunk).strip()
97
+ if chunk_body:
98
+ chunks.append({"title": generate_title(chunk_body, fallback_title), "text": chunk_body})
99
+ current_chunk = []
100
+ current_length = 0
101
+ current_chunk.append(sentence)
102
+ current_length += sentence_words
103
+
104
+ if current_chunk:
105
+ chunk_body = " ".join(current_chunk).strip()
106
+ if chunk_body:
107
+ chunks.append({"title": generate_title(chunk_body, fallback_title), "text": chunk_body})
108
+
109
+ return chunks
110
  except Exception as e:
111
+ logger.error(f"Error chunking text: {e}")
112
+ return []
113
+
114
+ async def extract_from_url(url: str, session: aiohttp.ClientSession, retries: int = MAX_URL_RETRIES) -> Optional[Dict[str, str]]:
115
+ for attempt in range(retries):
116
+ try:
117
+ async with session.get(url, timeout=REQUEST_TIMEOUT, headers=REQUESTS_HEADERS) as response:
118
+ if response.status != 200:
119
+ logger.warning(f"Non-200 status {response.status} for URL: {url}")
120
+ continue
121
+ content = await response.read()
122
+ encoding = response.charset or 'utf-8'
123
+ html = content.decode(encoding, errors='ignore')
124
+
125
+ import trafilatura
126
+ metadata_doc = trafilatura.extract_metadata(html)
127
+ fallback_title = metadata_doc.as_dict().get('title', 'Untitled') if metadata_doc else 'Untitled'
128
+ text = trafilatura.extract(html, include_comments=False, include_tables=False)
129
+
130
+ if not text or len(text.strip()) < MIN_TEXT_LENGTH:
131
+ logger.warning(f"No valid content extracted from {url}, trying BeautifulSoup...")
132
+ from bs4 import BeautifulSoup
133
+ soup = BeautifulSoup(html, "html.parser")
134
+ for tag in soup(["script", "style", "nav", "footer", "noscript"]):
135
+ tag.decompose()
136
+ text = soup.get_text(" ", strip=True)
137
+
138
+ return {"title": fallback_title, "text": text} if text and len(text.strip()) >= MIN_TEXT_LENGTH else None
139
+
140
+ except aiohttp.ClientError as e:
141
+ logger.warning(f"Attempt {attempt + 1} failed for {url}: {e}")
142
+ if attempt + 1 == retries:
143
+ logger.error(f"Failed to process URL {url} after {retries} attempts")
144
+ return None
145
+ await asyncio.sleep(1)
146
+
147
+ return None
148
 
149
  # --- Vector Store ---
150
  class VectorStore:
151
  def __init__(self):
152
+ self.dedup_hashes: Set[str] = set()
153
+ self.results: List[Dict[str, Any]] = []
154
+ self._chunks_to_embed: List[Chunk] = []
155
 
156
+ def reset(self) -> None:
157
  self.dedup_hashes.clear()
158
  self.results.clear()
159
  self._chunks_to_embed.clear()
160
 
161
+ async def add_chunks(self, text: str, source: str, title: str, extra_payload: Optional[Dict] = None) -> None:
162
+ try:
163
+ if len(text.strip()) < MIN_TEXT_LENGTH:
164
+ return
165
 
166
+ for chunk in chunk_text(text, fallback_title=title):
167
+ chunk_id = get_hash(chunk['text'], chunk['title'], source)
168
+ if chunk_id in self.dedup_hashes:
169
+ continue
170
+ self.dedup_hashes.add(chunk_id)
171
+ payload = {
172
+ "title": chunk['title'],
173
+ "text": chunk['text'],
174
+ "source": source,
175
+ **(extra_payload or {})
176
+ }
177
+ self._chunks_to_embed.append(Chunk(id=chunk_id, text=chunk['text'], payload=payload))
178
+ except Exception as e:
179
+ logger.error(f"Error adding chunks: {e}")
180
+
181
+ def embed_and_finalize(self, batch_size: int = EMBEDDING_BATCH_SIZE) -> None:
182
+ try:
183
+ if not self._chunks_to_embed:
184
+ return
185
+
186
+ all_texts = [chunk.text for chunk in self._chunks_to_embed]
187
+ logger.info(f"Embedding {len(all_texts)} chunks...")
188
+ model = get_model()
189
+ all_vectors = model.encode(all_texts, batch_size=batch_size, show_progress_bar=False, normalize_embeddings=True)
190
+ logger.info("Embedding complete.")
191
+
192
+ seen_hashes = set()
193
+ for chunk, vector in zip(self._chunks_to_embed, all_vectors):
194
+ if chunk.id not in seen_hashes:
195
+ seen_hashes.add(chunk.id)
196
+ self.results.append({
197
+ "id": chunk.id,
198
+ "vector": vector.tolist(),
199
+ "payload": chunk.payload
200
+ })
201
+ except Exception as e:
202
+ logger.error(f"Error during embedding: {e}")
203
 
204
  # --- Processing Logic ---
205
+ 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:
206
+ try:
207
+ if processed_urls is None:
208
+ processed_urls = set()
209
+
210
+ if isinstance(data, dict):
211
+ for key, value in data.items():
212
+ await traverse_and_process(value, vector_store, source_key=key, session=session, processed_urls=processed_urls)
213
+ elif isinstance(data, list):
214
+ for item in data:
215
+ await traverse_and_process(item, vector_store, source_key=source_key, session=session, processed_urls=processed_urls)
216
+ elif isinstance(data, str) and data.strip():
217
+ content = data.strip()
218
+ if re.match(r'^https?://', content) and content not in processed_urls:
219
+ processed_urls.add(content)
220
+ extracted = await extract_from_url(content, session)
221
+ if extracted:
222
+ await vector_store.add_chunks(extracted['text'], source=content, title=extracted['title'])
223
+ else:
224
+ await vector_store.add_chunks(content, source="json_text", title=generate_title(content, source_key))
225
+ except Exception as e:
226
+ logger.error(f"Error in traverse_and_process: {e}")
227
 
228
  async def process_input_async(input_json: str) -> str:
229
  vector_store = VectorStore()
 
239
  kind = entry.get("type")
240
  content = entry.get("content")
241
  if not kind or not content:
242
+ logger.warning(f"Skipping invalid entry: {entry}")
243
  continue
244
 
245
  if kind == "context":
246
+ tasks.append(traverse_and_process(content, vector_store, source_key=kind, session=session, processed_urls=processed_urls))
247
  elif kind == "text":
248
  keywords = extract_keywords(content)
249
  tasks.append(vector_store.add_chunks(content, source="user_message", title=generate_title(content, "User Message"), extra_payload={"keywords": list(keywords)}))
250
+ else:
251
+ logger.warning(f"Unsupported entry type: {kind}")
252
 
253
+ await asyncio.gather(*tasks, return_exceptions=True)
254
 
255
  vector_store.embed_and_finalize()
256
+ return json.dumps(vector_store.results, indent=2, ensure_ascii=False)
257
  except json.JSONDecodeError as e:
258
  return json.dumps({"error": "Invalid JSON provided", "details": str(e)}, indent=2)
259
  except Exception as e:
260
+ logger.error(f"Unexpected error during processing: {e}", exc_info=True)
261
  return json.dumps({"error": "An unexpected error occurred", "details": str(e)}, indent=2)
262
 
263
  def process_input(input_json: str) -> str:
264
  return asyncio.run(process_input_async(input_json))
265
 
266
  # --- Gradio UI ---
267
+ def launch_gradio():
268
+ try:
269
+ iface = gr.Interface(
270
+ fn=process_input,
271
+ inputs=gr.Textbox(
272
+ label="Paste JSON Array [{type, content}]",
273
+ lines=15,
274
+ 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?"}]'
275
+ ),
276
+ outputs=gr.Code(label="Qdrant-Ready Embeddings", language="json"),
277
+ title="Chatbot Context Embedder",
278
+ description="Processes text and URLs, generates descriptive titles, and produces embeddings for Qdrant. Optimized for messaging and context handling.",
279
+ allow_flagging="never"
280
+ )
281
+ iface.launch()
282
+ except Exception as e:
283
+ logger.error(f"Failed to launch Gradio interface: {e}")
284
+ raise
285
 
286
  if __name__ == "__main__":
287
+ launch_gradio()
requirements.txt CHANGED
@@ -1,9 +1,6 @@
1
- gradio
2
- sentence-transformers
3
- requests
4
- beautifulsoup4
5
- scikit-learn
6
- lxml
7
- trafilatura
8
- python-docx
9
- nltk
 
1
+ gradio==4.44.0
2
+ aiohttp==3.10.5
3
+ sentence-transformers==3.1.1
4
+ trafilatura==1.12.0
5
+ beautifulsoup4==4.12.3
6
+ numpy==2.1.1