|
| 1 | +import os |
| 2 | +import uuid |
| 3 | +import logging |
| 4 | +import cohere |
| 5 | +from qdrant_client import QdrantClient |
| 6 | +from qdrant_client.http.models import Distance, VectorParams, PointStruct |
| 7 | +import requests |
| 8 | +from bs4 import BeautifulSoup |
| 9 | +from dotenv import load_dotenv |
| 10 | +from urllib.parse import urljoin, urlparse |
| 11 | + |
| 12 | +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') |
| 13 | + |
| 14 | + |
| 15 | +def get_all_urls(url, visited, base_domain): |
| 16 | + """ |
| 17 | + Recursively crawls a website to get all unique URLs within the same domain. |
| 18 | + """ |
| 19 | + if url in visited: |
| 20 | + return |
| 21 | + |
| 22 | + if urlparse(url).netloc != base_domain: |
| 23 | + return |
| 24 | + |
| 25 | + visited.add(url) |
| 26 | + try: |
| 27 | + response = requests.get(url, timeout=5) |
| 28 | + response.raise_for_status() |
| 29 | + soup = BeautifulSoup(response.content, 'html.parser') |
| 30 | + |
| 31 | + for link in soup.find_all('a', href=True): |
| 32 | + absolute_link = urljoin(url, link['href']).split('#')[0] |
| 33 | + if absolute_link not in visited and urlparse(absolute_link).netloc == base_domain: |
| 34 | + get_all_urls(absolute_link, visited, base_domain) |
| 35 | + except requests.RequestException as e: |
| 36 | + logging.warning(f"Could not crawl {url}: {e}") |
| 37 | + except Exception as e: |
| 38 | + logging.error(f"An unexpected error occurred while crawling {url}: {e}") |
| 39 | + |
| 40 | + |
| 41 | +def extract_text_from_url(url): |
| 42 | + """ |
| 43 | + Extracts the main text content from a URL. |
| 44 | + """ |
| 45 | + try: |
| 46 | + response = requests.get(url, timeout=5) |
| 47 | + response.raise_for_status() |
| 48 | + soup = BeautifulSoup(response.content, 'html.parser') |
| 49 | + main_content = soup.find('main') |
| 50 | + if main_content: |
| 51 | + return main_content.get_text(separator=' ', strip=True) |
| 52 | + return "" |
| 53 | + except requests.RequestException as e: |
| 54 | + logging.warning(f"Could not fetch {url}: {e}") |
| 55 | + return "" |
| 56 | + except Exception as e: |
| 57 | + logging.error(f"An unexpected error occurred while extracting text from {url}: {e}") |
| 58 | + return "" |
| 59 | + |
| 60 | + |
| 61 | +def chunk_text(text, chunk_size=384, overlap=48): |
| 62 | + """ |
| 63 | + Splits a text into chunks of a specified size with a given overlap. |
| 64 | + """ |
| 65 | + words = text.split() |
| 66 | + if not words: |
| 67 | + return [] |
| 68 | + |
| 69 | + chunks = [] |
| 70 | + for i in range(0, len(words), chunk_size - overlap): |
| 71 | + chunk = words[i:i + chunk_size] |
| 72 | + chunks.append(' '.join(chunk)) |
| 73 | + return chunks |
| 74 | + |
| 75 | + |
| 76 | +def embed_chunks(chunks, co_client): |
| 77 | + """ |
| 78 | + Generates vector embeddings for a list of text chunks. |
| 79 | + """ |
| 80 | + if not chunks: |
| 81 | + return [] |
| 82 | + |
| 83 | + try: |
| 84 | + response = co_client.embed(texts=chunks, model="embed-english-v2.0", truncate="END") |
| 85 | + return response.embeddings |
| 86 | + except Exception as e: |
| 87 | + logging.error(f"An unexpected error occurred while embedding chunks: {e}") |
| 88 | + return [] |
| 89 | + |
| 90 | + |
| 91 | +def save_chunks_to_qdrant(qdrant, collection_name, chunks, embeddings, chunk_to_url_map): |
| 92 | + """ |
| 93 | + Saves chunks and their embeddings to Qdrant. |
| 94 | + """ |
| 95 | + if not embeddings: |
| 96 | + return |
| 97 | + |
| 98 | + points = [] |
| 99 | + for i, embedding in enumerate(embeddings): |
| 100 | + points.append(PointStruct( |
| 101 | + id=str(uuid.uuid4()), |
| 102 | + vector=embedding, |
| 103 | + payload={"text": chunks[i], "source_url": chunk_to_url_map[i]} |
| 104 | + )) |
| 105 | + |
| 106 | + qdrant.upsert(collection_name=collection_name, wait=True, points=points) |
| 107 | + |
| 108 | + |
| 109 | +def main(): |
| 110 | + """ |
| 111 | + Main function to run the embedding pipeline. |
| 112 | + """ |
| 113 | + load_dotenv() |
| 114 | + |
| 115 | + # Cohere client |
| 116 | + cohere_api_key = os.getenv("COHERE_API_KEY") |
| 117 | + co = cohere.Client(cohere_api_key) |
| 118 | + |
| 119 | + # Qdrant client |
| 120 | + qdrant_url = os.getenv("QDRANT_URL") |
| 121 | + qdrant_api_key = os.getenv("QDRANT_API_KEY") |
| 122 | + qdrant = QdrantClient(url=qdrant_url, api_key=qdrant_api_key) |
| 123 | + |
| 124 | + # Collection setup |
| 125 | + collection_name = "rag_embedding" |
| 126 | + |
| 127 | + # Forcefully delete and recreate with correct dimensions |
| 128 | + logging.info(f"Recreating collection '{collection_name}' with 4096 dims...") |
| 129 | + qdrant.recreate_collection( |
| 130 | + collection_name=collection_name, |
| 131 | + vectors_config=VectorParams(size=4096, distance=Distance.COSINE), |
| 132 | + ) |
| 133 | + logging.info(f"Collection '{collection_name}' is now FRESH and READY.") |
| 134 | + |
| 135 | + logging.info("Pipeline starting...") |
| 136 | + root_url = "https://codewithsuleman.github.io/hackathon-physical-AI-humanoid-textbook/" |
| 137 | + base_domain = urlparse(root_url).netloc |
| 138 | + visited_urls = set() |
| 139 | + logging.info(f"Crawling starting from {root_url}...") |
| 140 | + get_all_urls(root_url, visited_urls, base_domain) |
| 141 | + logging.info(f"Found {len(visited_urls)} URLs to process.") |
| 142 | + |
| 143 | + all_chunks = [] |
| 144 | + chunk_to_url_map = [] |
| 145 | + for url in visited_urls: |
| 146 | + logging.info(f"Extracting and chunking text from {url}...") |
| 147 | + text = extract_text_from_url(url) |
| 148 | + if text: |
| 149 | + chunks = chunk_text(text) |
| 150 | + all_chunks.extend(chunks) |
| 151 | + chunk_to_url_map.extend([url] * len(chunks)) |
| 152 | + |
| 153 | + logging.info(f"Total chunks to process: {len(all_chunks)}") |
| 154 | + |
| 155 | + batch_size = 96 |
| 156 | + for i in range(0, len(all_chunks), batch_size): |
| 157 | + batch_chunks = all_chunks[i:i + batch_size] |
| 158 | + batch_urls = chunk_to_url_map[i:i + batch_size] |
| 159 | + logging.info(f"Processing batch {i // batch_size + 1}...") |
| 160 | + |
| 161 | + batch_embeddings = embed_chunks(batch_chunks, co) |
| 162 | + if batch_embeddings: |
| 163 | + save_chunks_to_qdrant(qdrant, collection_name, batch_chunks, batch_embeddings, batch_urls) |
| 164 | + |
| 165 | + logging.info("Pipeline finished successfully!") |
| 166 | + |
| 167 | + |
| 168 | +if __name__ == "__main__": |
| 169 | + main() |
0 commit comments