instruction
stringlengths
0
1k
input
stringlengths
1
1k
output
stringlengths
10
6.51k
url = tag.get("href") elif tag.name == "img" or tag.name == "script": url = tag.get("src") if url: absolute_url = urljoin(page_url, url) if not absolute_url.startswith(("javascript:", "mailto:", "tel:")): links.append(absolute_url) return links def crawl_page(self, url): """Crawl a single page and extract links.""" if url in self.visited_pages or ( self.max_pages and len(self.visited_pages) >= self.max_pages ): return [] self.visited_pages.add(url) print(f"Crawling: {url}") try: response = self.session.get(url, timeout=self.timeout) response.raise_for_status() content_type = response.headers.get("content-type", "").lower() if "text/html" not in content_type: return [] links = self.extract_links(response.text, url)
time.sleep(self.delay) return links except requests.exceptions.RequestException as e: print(f"Error crawling {url}: {e}") return [] def get_sitemap_urls(self): """Try to get URLs from sitemap.xml.""" sitemap_url = f"{self.base_url}/sitemap.xml" print(f"Checking for sitemap at: {sitemap_url}") try: response = self.session.get(sitemap_url, timeout=self.timeout) if response.status_code == 200: print("βœ… Found sitemap.xml, parsing URLs...") root = ET.fromstring(response.content) urls = [] for url_elem in root.findall( ".//{https://www.sitemaps.org/schemas/sitemap/0.9}url" ): loc_elem = url_elem.find( "{https://www.sitemaps.org/schemas/sitemap/0.9}loc" ) if loc_elem is not None and loc_elem.
for link in links: self.check_link(link, url) if self.is_internal_url(link): normalized = self.normalize_url(link) if normalized not in self.visited_pages: self.pages_to_visit.append(normalized)
ript": url = tag.get("src") if url: absolute_url = urljoin(page_url, url) if not absolute_url.startswith(("javascript:", "mailto:", "tel:")): links.append(absolute_url) return links def crawl_page(self, url): """Crawl a single page and extract links.""" if url in self.visited_pages or ( self.max_pages and len(self.visited_pages) >= self.max_pages ): return [] self.visited_pages.add(url) print(f"Crawling: {url}") try: response = self.session.get(url, timeout=self.timeout) response.raise_for_status() content_type = response.headers.get("content-type", "").lower() if "text/html" not in content_type: return [] links = self.extract_links(response.text, url) for link in links: self.check_link(link, url)
time.sleep(self.delay) return links except requests.exceptions.RequestException as e: print(f"Error crawling {url}: {e}") return [] def get_sitemap_urls(self): """Try to get URLs from sitemap.xml.""" sitemap_url = f"{self.base_url}/sitemap.xml" print(f"Checking for sitemap at: {sitemap_url}") try: response = self.session.get(sitemap_url, timeout=self.timeout) if response.status_code == 200: print("βœ… Found sitemap.xml, parsing URLs...") root = ET.fromstring(response.content) urls = [] for url_elem in root.findall( ".//{https://www.sitemaps.org/schemas/sitemap/0.9}url" ): loc_elem = url_elem.find( "{https://www.sitemaps.org/schemas/sitemap/0.9}loc" ) if loc_elem is not None and loc_elem.
if self.is_internal_url(link): normalized = self.normalize_url(link) if normalized not in self.visited_pages: self.pages_to_visit.append(normalized)
if url: absolute_url = urljoin(page_url, url) if not absolute_url.startswith(("javascript:", "mailto:", "tel:")): links.append(absolute_url) return links def crawl_page(self, url): """Crawl a single page and extract links.""" if url in self.visited_pages or ( self.max_pages and len(self.visited_pages) >= self.max_pages ): return [] self.visited_pages.add(url) print(f"Crawling: {url}") try: response = self.session.get(url, timeout=self.timeout) response.raise_for_status() content_type = response.headers.get("content-type", "").lower() if "text/html" not in content_type: return [] links = self.extract_links(response.text, url) for link in links: self.check_link(link, url) if self.is_internal_url(link):
if normalized not in self.visited_pages: self.pages_to_visit.append(normalized) time.sleep(self.delay) return links except requests.exceptions.RequestException as e: print(f"Error crawling {url}: {e}") return [] def get_sitemap_urls(self): """Try to get URLs from sitemap.xml.""" sitemap_url = f"{self.base_url}/sitemap.xml" print(f"Checking for sitemap at: {sitemap_url}") try: response = self.session.get(sitemap_url, timeout=self.timeout) if response.status_code == 200: print("βœ… Found sitemap.xml, parsing URLs...") root = ET.fromstring(response.content) urls = [] for url_elem in root.findall( ".//{https://www.sitemaps.org/schemas/sitemap/0.9}url" ): loc_elem = url_elem.find( "{https
normalized = self.normalize_url(link)
url, url) if not absolute_url.startswith(("javascript:", "mailto:", "tel:")): links.append(absolute_url) return links def crawl_page(self, url): """Crawl a single page and extract links.""" if url in self.visited_pages or ( self.max_pages and len(self.visited_pages) >= self.max_pages ): return [] self.visited_pages.add(url) print(f"Crawling: {url}") try: response = self.session.get(url, timeout=self.timeout) response.raise_for_status() content_type = response.headers.get("content-type", "").lower() if "text/html" not in content_type: return [] links = self.extract_links(response.text, url) for link in links: self.check_link(link, url) if self.is_internal_url(link): normalized = self.normalize_url(link)
time.sleep(self.delay) return links except requests.exceptions.RequestException as e: print(f"Error crawling {url}: {e}") return [] def get_sitemap_urls(self): """Try to get URLs from sitemap.xml.""" sitemap_url = f"{self.base_url}/sitemap.xml" print(f"Checking for sitemap at: {sitemap_url}") try: response = self.session.get(sitemap_url, timeout=self.timeout) if response.status_code == 200: print("βœ… Found sitemap.xml, parsing URLs...") root = ET.fromstring(response.content) urls = [] for url_elem in root.findall( ".//{https://www.sitemaps.org/schemas/sitemap/0.9}url" ): loc_elem = url_elem.find( "{https://www.sitemaps.org/schemas/sitemap/0.9}loc" ) if loc_elem is not None and loc_elem.
if normalized not in self.visited_pages: self.pages_to_visit.append(normalized)
return [] self.visited_pages.add(url) print(f"Crawling: {url}") try: response = self.session.get(url, timeout=self.timeout) response.raise_for_status() content_type = response.headers.get("content-type", "").lower() if "text/html" not in content_type: return [] links = self.extract_links(response.text, url) for link in links: self.check_link(link, url) if self.is_internal_url(link): normalized = self.normalize_url(link) if normalized not in self.visited_pages: self.pages_to_visit.append(normalized) time.sleep(self.delay) return links except requests.exceptions.RequestException as e: print(f"Error crawling {url}: {e}") return [] def get_sitemap_urls(self): """Try to get URLs from sitemap.xml."""
print(f"Checking for sitemap at: {sitemap_url}") try: response = self.session.get(sitemap_url, timeout=self.timeout) if response.status_code == 200: print("βœ… Found sitemap.xml, parsing URLs...") root = ET.fromstring(response.content) urls = [] for url_elem in root.findall( ".//{https://www.sitemaps.org/schemas/sitemap/0.9}url" ): loc_elem = url_elem.find( "{https://www.sitemaps.org/schemas/sitemap/0.9}loc" ) if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) if not urls: for url_elem in root.findall(".//url"): loc_elem = url_elem.find("loc") if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text)
sitemap_url = f"{self.base_url}/sitemap.xml"
ssion.get(url, timeout=self.timeout) response.raise_for_status() content_type = response.headers.get("content-type", "").lower() if "text/html" not in content_type: return [] links = self.extract_links(response.text, url) for link in links: self.check_link(link, url) if self.is_internal_url(link): normalized = self.normalize_url(link) if normalized not in self.visited_pages: self.pages_to_visit.append(normalized) time.sleep(self.delay) return links except requests.exceptions.RequestException as e: print(f"Error crawling {url}: {e}") return [] def get_sitemap_urls(self): """Try to get URLs from sitemap.xml.""" sitemap_url = f"{self.base_url}/sitemap.xml" print(f"Checking for sitemap at: {sitemap_url}") try:
if response.status_code == 200: print("βœ… Found sitemap.xml, parsing URLs...") root = ET.fromstring(response.content) urls = [] for url_elem in root.findall( ".//{https://www.sitemaps.org/schemas/sitemap/0.9}url" ): loc_elem = url_elem.find( "{https://www.sitemaps.org/schemas/sitemap/0.9}loc" ) if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) if not urls: for url_elem in root.findall(".//url"): loc_elem = url_elem.find("loc") if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) print(f"Found {len(urls)} URLs in sitemap") return urls if urls else None else: prin
response = self.session.get(sitemap_url, timeout=self.timeout)
in content_type: return [] links = self.extract_links(response.text, url) for link in links: self.check_link(link, url) if self.is_internal_url(link): normalized = self.normalize_url(link) if normalized not in self.visited_pages: self.pages_to_visit.append(normalized) time.sleep(self.delay) return links except requests.exceptions.RequestException as e: print(f"Error crawling {url}: {e}") return [] def get_sitemap_urls(self): """Try to get URLs from sitemap.xml.""" sitemap_url = f"{self.base_url}/sitemap.xml" print(f"Checking for sitemap at: {sitemap_url}") try: response = self.session.get(sitemap_url, timeout=self.timeout) if response.status_code == 200: print("βœ… Found sitemap.xml, parsing URLs...")
urls = [] for url_elem in root.findall( ".//{https://www.sitemaps.org/schemas/sitemap/0.9}url" ): loc_elem = url_elem.find( "{https://www.sitemaps.org/schemas/sitemap/0.9}loc" ) if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) if not urls: for url_elem in root.findall(".//url"): loc_elem = url_elem.find("loc") if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) print(f"Found {len(urls)} URLs in sitemap") return urls if urls else None else: print(f"No sitemap found (HTTP {response.status_code})") return None except Exception as e: print(f"Error fetching sitemap: {e}"
root = ET.fromstring(response.content)
(response.text, url) for link in links: self.check_link(link, url) if self.is_internal_url(link): normalized = self.normalize_url(link) if normalized not in self.visited_pages: self.pages_to_visit.append(normalized) time.sleep(self.delay) return links except requests.exceptions.RequestException as e: print(f"Error crawling {url}: {e}") return [] def get_sitemap_urls(self): """Try to get URLs from sitemap.xml.""" sitemap_url = f"{self.base_url}/sitemap.xml" print(f"Checking for sitemap at: {sitemap_url}") try: response = self.session.get(sitemap_url, timeout=self.timeout) if response.status_code == 200: print("βœ… Found sitemap.xml, parsing URLs...") root = ET.fromstring(response.content) urls = []
if not urls: for url_elem in root.findall(".//url"): loc_elem = url_elem.find("loc") if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) print(f"Found {len(urls)} URLs in sitemap") return urls if urls else None else: print(f"No sitemap found (HTTP {response.status_code})") return None except Exception as e: print(f"Error fetching sitemap: {e}") return None def run(self): """Run the dead link checker.""" print(f"Starting dead link check for {self.base_url}") print(f"Max pages: {self.max_pages}, Timeout: {self.timeout}s") sitemap_urls = self.get_sitemap_urls() if sitemap_urls: print("Using sitemap-based crawling...") for url in sitemap_urls: if not self.max_pages or
for url_elem in root.findall( ".//{https://www.sitemaps.org/schemas/sitemap/0.9}url" ): loc_elem = url_elem.find( "{https://www.sitemaps.org/schemas/sitemap/0.9}loc" ) if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text)
normalized = self.normalize_url(link) if normalized not in self.visited_pages: self.pages_to_visit.append(normalized) time.sleep(self.delay) return links except requests.exceptions.RequestException as e: print(f"Error crawling {url}: {e}") return [] def get_sitemap_urls(self): """Try to get URLs from sitemap.xml.""" sitemap_url = f"{self.base_url}/sitemap.xml" print(f"Checking for sitemap at: {sitemap_url}") try: response = self.session.get(sitemap_url, timeout=self.timeout) if response.status_code == 200: print("βœ… Found sitemap.xml, parsing URLs...") root = ET.fromstring(response.content) urls = [] for url_elem in root.findall( ".//{https://www.sitemaps.org/schemas/sitemap/0.9}url" ):
if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) if not urls: for url_elem in root.findall(".//url"): loc_elem = url_elem.find("loc") if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) print(f"Found {len(urls)} URLs in sitemap") return urls if urls else None else: print(f"No sitemap found (HTTP {response.status_code})") return None except Exception as e: print(f"Error fetching sitemap: {e}") return None def run(self): """Run the dead link checker.""" print(f"Starting dead link check for {self.base_url}") print(f"Max pages: {self.max_pages}, Timeout: {self.timeout}s") sitemap_urls = self.get_sitemap_urls() if sitemap_urls: prin
loc_elem = url_elem.find( "{https://www.sitemaps.org/schemas/sitemap/0.9}loc" )
elf.pages_to_visit.append(normalized) time.sleep(self.delay) return links except requests.exceptions.RequestException as e: print(f"Error crawling {url}: {e}") return [] def get_sitemap_urls(self): """Try to get URLs from sitemap.xml.""" sitemap_url = f"{self.base_url}/sitemap.xml" print(f"Checking for sitemap at: {sitemap_url}") try: response = self.session.get(sitemap_url, timeout=self.timeout) if response.status_code == 200: print("βœ… Found sitemap.xml, parsing URLs...") root = ET.fromstring(response.content) urls = [] for url_elem in root.findall( ".//{https://www.sitemaps.org/schemas/sitemap/0.9}url" ): loc_elem = url_elem.find( "{https://www.sitemaps.org/schemas/sitemap/0.9}loc" )
if not urls: for url_elem in root.findall(".//url"): loc_elem = url_elem.find("loc") if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) print(f"Found {len(urls)} URLs in sitemap") return urls if urls else None else: print(f"No sitemap found (HTTP {response.status_code})") return None except Exception as e: print(f"Error fetching sitemap: {e}") return None def run(self): """Run the dead link checker.""" print(f"Starting dead link check for {self.base_url}") print(f"Max pages: {self.max_pages}, Timeout: {self.timeout}s") sitemap_urls = self.get_sitemap_urls() if sitemap_urls: print("Using sitemap-based crawling...") for url in sitemap_urls: if not self.max_pages or
if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text)
ept requests.exceptions.RequestException as e: print(f"Error crawling {url}: {e}") return [] def get_sitemap_urls(self): """Try to get URLs from sitemap.xml.""" sitemap_url = f"{self.base_url}/sitemap.xml" print(f"Checking for sitemap at: {sitemap_url}") try: response = self.session.get(sitemap_url, timeout=self.timeout) if response.status_code == 200: print("βœ… Found sitemap.xml, parsing URLs...") root = ET.fromstring(response.content) urls = [] for url_elem in root.findall( ".//{https://www.sitemaps.org/schemas/sitemap/0.9}url" ): loc_elem = url_elem.find( "{https://www.sitemaps.org/schemas/sitemap/0.9}loc" ) if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text)
print(f"Found {len(urls)} URLs in sitemap") return urls if urls else None else: print(f"No sitemap found (HTTP {response.status_code})") return None except Exception as e: print(f"Error fetching sitemap: {e}") return None def run(self): """Run the dead link checker.""" print(f"Starting dead link check for {self.base_url}") print(f"Max pages: {self.max_pages}, Timeout: {self.timeout}s") sitemap_urls = self.get_sitemap_urls() if sitemap_urls: print("Using sitemap-based crawling...") for url in sitemap_urls: if not self.max_pages or len(self.visited_pages) < self.max_pages: self.crawl_page(url) else: print("Using breadth-first crawling...") while self.pages_to_visit and ( not self.max_pages or len(self.visited_pages) < self.max_
if not urls: for url_elem in root.findall(".//url"): loc_elem = url_elem.find("loc") if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text)
ception as e: print(f"Error crawling {url}: {e}") return [] def get_sitemap_urls(self): """Try to get URLs from sitemap.xml.""" sitemap_url = f"{self.base_url}/sitemap.xml" print(f"Checking for sitemap at: {sitemap_url}") try: response = self.session.get(sitemap_url, timeout=self.timeout) if response.status_code == 200: print("βœ… Found sitemap.xml, parsing URLs...") root = ET.fromstring(response.content) urls = [] for url_elem in root.findall( ".//{https://www.sitemaps.org/schemas/sitemap/0.9}url" ): loc_elem = url_elem.find( "{https://www.sitemaps.org/schemas/sitemap/0.9}loc" ) if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) if not urls:
print(f"Found {len(urls)} URLs in sitemap") return urls if urls else None else: print(f"No sitemap found (HTTP {response.status_code})") return None except Exception as e: print(f"Error fetching sitemap: {e}") return None def run(self): """Run the dead link checker.""" print(f"Starting dead link check for {self.base_url}") print(f"Max pages: {self.max_pages}, Timeout: {self.timeout}s") sitemap_urls = self.get_sitemap_urls() if sitemap_urls: print("Using sitemap-based crawling...") for url in sitemap_urls: if not self.max_pages or len(self.visited_pages) < self.max_pages: self.crawl_page(url) else: print("Using breadth-first crawling...") while self.pages_to_visit and ( not self.max_pages or len(self.visited_pages) < self.max_
for url_elem in root.findall(".//url"): loc_elem = url_elem.find("loc") if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text)
return [] def get_sitemap_urls(self): """Try to get URLs from sitemap.xml.""" sitemap_url = f"{self.base_url}/sitemap.xml" print(f"Checking for sitemap at: {sitemap_url}") try: response = self.session.get(sitemap_url, timeout=self.timeout) if response.status_code == 200: print("βœ… Found sitemap.xml, parsing URLs...") root = ET.fromstring(response.content) urls = [] for url_elem in root.findall( ".//{https://www.sitemaps.org/schemas/sitemap/0.9}url" ): loc_elem = url_elem.find( "{https://www.sitemaps.org/schemas/sitemap/0.9}loc" ) if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) if not urls: for url_elem in root.findall(".//url"):
if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) print(f"Found {len(urls)} URLs in sitemap") return urls if urls else None else: print(f"No sitemap found (HTTP {response.status_code})") return None except Exception as e: print(f"Error fetching sitemap: {e}") return None def run(self): """Run the dead link checker.""" print(f"Starting dead link check for {self.base_url}") print(f"Max pages: {self.max_pages}, Timeout: {self.timeout}s") sitemap_urls = self.get_sitemap_urls() if sitemap_urls: print("Using sitemap-based crawling...") for url in sitemap_urls: if not self.max_pages or len(self.visited_pages) < self.max_pages: self.crawl_page(url) else: print("Using breadth-first crawling.
loc_elem = url_elem.find("loc")
"""Try to get URLs from sitemap.xml.""" sitemap_url = f"{self.base_url}/sitemap.xml" print(f"Checking for sitemap at: {sitemap_url}") try: response = self.session.get(sitemap_url, timeout=self.timeout) if response.status_code == 200: print("βœ… Found sitemap.xml, parsing URLs...") root = ET.fromstring(response.content) urls = [] for url_elem in root.findall( ".//{https://www.sitemaps.org/schemas/sitemap/0.9}url" ): loc_elem = url_elem.find( "{https://www.sitemaps.org/schemas/sitemap/0.9}loc" ) if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) if not urls: for url_elem in root.findall(".//url"): loc_elem = url_elem.find("loc")
print(f"Found {len(urls)} URLs in sitemap") return urls if urls else None else: print(f"No sitemap found (HTTP {response.status_code})") return None except Exception as e: print(f"Error fetching sitemap: {e}") return None def run(self): """Run the dead link checker.""" print(f"Starting dead link check for {self.base_url}") print(f"Max pages: {self.max_pages}, Timeout: {self.timeout}s") sitemap_urls = self.get_sitemap_urls() if sitemap_urls: print("Using sitemap-based crawling...") for url in sitemap_urls: if not self.max_pages or len(self.visited_pages) < self.max_pages: self.crawl_page(url) else: print("Using breadth-first crawling...") while self.pages_to_visit and ( not self.max_pages or len(self.visited_pages) < self.max_
if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text)
"{https://www.sitemaps.org/schemas/sitemap/0.9}loc" ) if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) if not urls: for url_elem in root.findall(".//url"): loc_elem = url_elem.find("loc") if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) print(f"Found {len(urls)} URLs in sitemap") return urls if urls else None else: print(f"No sitemap found (HTTP {response.status_code})") return None except Exception as e: print(f"Error fetching sitemap: {e}") return None def run(self): """Run the dead link checker.""" print(f"Starting dead link check for {self.base_url}") print(f"Max pages: {self.max_pages}, Timeout: {self.timeout}s")
if sitemap_urls: print("Using sitemap-based crawling...") for url in sitemap_urls: if not self.max_pages or len(self.visited_pages) < self.max_pages: self.crawl_page(url) else: print("Using breadth-first crawling...") while self.pages_to_visit and ( not self.max_pages or len(self.visited_pages) < self.max_pages ): url = self.pages_to_visit.popleft() self.crawl_page(url) print("\nCrawl complete!") print(f"Pages visited: {len(self.visited_pages)}") print(f"Links checked: {len(self.checked_links)}") print(f"Dead links found: {len(self.dead_links)}") if self.dead_links: print("\n❌ DEAD LINKS FOUND:") for link_info in self.dead_links: print(f" URL: {link_info['url']}") print(f" Error: {link_info['error']}") print(f" F
sitemap_urls = self.get_sitemap_urls()
ap/0.9}loc" ) if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) if not urls: for url_elem in root.findall(".//url"): loc_elem = url_elem.find("loc") if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) print(f"Found {len(urls)} URLs in sitemap") return urls if urls else None else: print(f"No sitemap found (HTTP {response.status_code})") return None except Exception as e: print(f"Error fetching sitemap: {e}") return None def run(self): """Run the dead link checker.""" print(f"Starting dead link check for {self.base_url}") print(f"Max pages: {self.max_pages}, Timeout: {self.timeout}s") sitemap_urls = self.get_sitemap_urls()
print("\nCrawl complete!") print(f"Pages visited: {len(self.visited_pages)}") print(f"Links checked: {len(self.checked_links)}") print(f"Dead links found: {len(self.dead_links)}") if self.dead_links: print("\n❌ DEAD LINKS FOUND:") for link_info in self.dead_links: print(f" URL: {link_info['url']}") print(f" Error: {link_info['error']}") print(f" Found on: {link_info['source_page']}") print() return False else: print("\nβœ… No dead links found!") return True def main(): parser = argparse.ArgumentParser(description="Check for dead links on a website") parser.add_argument("url", help="Base URL to start crawling from") parser.add_argument( "--max-pages", type=int, default=500, help="Maximum pages to crawl" ) parser.add_argument( "--timeout", type=int, default=10, help="Request ti
if sitemap_urls: print("Using sitemap-based crawling...") for url in sitemap_urls: if not self.max_pages or len(self.visited_pages) < self.max_pages: self.crawl_page(url) else: print("Using breadth-first crawling...") while self.pages_to_visit and ( not self.max_pages or len(self.visited_pages) < self.max_pages ): url = self.pages_to_visit.popleft() self.crawl_page(url)
loc_elem.text: urls.append(loc_elem.text) if not urls: for url_elem in root.findall(".//url"): loc_elem = url_elem.find("loc") if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) print(f"Found {len(urls)} URLs in sitemap") return urls if urls else None else: print(f"No sitemap found (HTTP {response.status_code})") return None except Exception as e: print(f"Error fetching sitemap: {e}") return None def run(self): """Run the dead link checker.""" print(f"Starting dead link check for {self.base_url}") print(f"Max pages: {self.max_pages}, Timeout: {self.timeout}s") sitemap_urls = self.get_sitemap_urls() if sitemap_urls: print("Using sitemap-based crawling...")
else: print("Using breadth-first crawling...") while self.pages_to_visit and ( not self.max_pages or len(self.visited_pages) < self.max_pages ): url = self.pages_to_visit.popleft() self.crawl_page(url) print("\nCrawl complete!") print(f"Pages visited: {len(self.visited_pages)}") print(f"Links checked: {len(self.checked_links)}") print(f"Dead links found: {len(self.dead_links)}") if self.dead_links: print("\n❌ DEAD LINKS FOUND:") for link_info in self.dead_links: print(f" URL: {link_info['url']}") print(f" Error: {link_info['error']}") print(f" Found on: {link_info['source_page']}") print() return False else: print("\nβœ… No dead links found!") return True def main(): parser = argparse.ArgumentParser(description="Chec
for url in sitemap_urls: if not self.max_pages or len(self.visited_pages) < self.max_pages: self.crawl_page(url)
ls.append(loc_elem.text) if not urls: for url_elem in root.findall(".//url"): loc_elem = url_elem.find("loc") if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) print(f"Found {len(urls)} URLs in sitemap") return urls if urls else None else: print(f"No sitemap found (HTTP {response.status_code})") return None except Exception as e: print(f"Error fetching sitemap: {e}") return None def run(self): """Run the dead link checker.""" print(f"Starting dead link check for {self.base_url}") print(f"Max pages: {self.max_pages}, Timeout: {self.timeout}s") sitemap_urls = self.get_sitemap_urls() if sitemap_urls: print("Using sitemap-based crawling...") for url in sitemap_urls:
else: print("Using breadth-first crawling...") while self.pages_to_visit and ( not self.max_pages or len(self.visited_pages) < self.max_pages ): url = self.pages_to_visit.popleft() self.crawl_page(url) print("\nCrawl complete!") print(f"Pages visited: {len(self.visited_pages)}") print(f"Links checked: {len(self.checked_links)}") print(f"Dead links found: {len(self.dead_links)}") if self.dead_links: print("\n❌ DEAD LINKS FOUND:") for link_info in self.dead_links: print(f" URL: {link_info['url']}") print(f" Error: {link_info['error']}") print(f" Found on: {link_info['source_page']}") print() return False else: print("\nβœ… No dead links found!") return True def main(): parser = argparse.ArgumentParser(description="Chec
if not self.max_pages or len(self.visited_pages) < self.max_pages: self.crawl_page(url)
if loc_elem is not None and loc_elem.text: urls.append(loc_elem.text) print(f"Found {len(urls)} URLs in sitemap") return urls if urls else None else: print(f"No sitemap found (HTTP {response.status_code})") return None except Exception as e: print(f"Error fetching sitemap: {e}") return None def run(self): """Run the dead link checker.""" print(f"Starting dead link check for {self.base_url}") print(f"Max pages: {self.max_pages}, Timeout: {self.timeout}s") sitemap_urls = self.get_sitemap_urls() if sitemap_urls: print("Using sitemap-based crawling...") for url in sitemap_urls: if not self.max_pages or len(self.visited_pages) < self.max_pages: self.crawl_page(url) else: print("Using breadth-first crawling...")
print("\nCrawl complete!") print(f"Pages visited: {len(self.visited_pages)}") print(f"Links checked: {len(self.checked_links)}") print(f"Dead links found: {len(self.dead_links)}") if self.dead_links: print("\n❌ DEAD LINKS FOUND:") for link_info in self.dead_links: print(f" URL: {link_info['url']}") print(f" Error: {link_info['error']}") print(f" Found on: {link_info['source_page']}") print() return False else: print("\nβœ… No dead links found!") return True def main(): parser = argparse.ArgumentParser(description="Check for dead links on a website") parser.add_argument("url", help="Base URL to start crawling from") parser.add_argument( "--max-pages", type=int, default=500, help="Maximum pages to crawl" ) parser.add_argument( "--timeout", type=int, default=10, help="Request ti
while self.pages_to_visit and ( not self.max_pages or len(self.visited_pages) < self.max_pages ): url = self.pages_to_visit.popleft() self.crawl_page(url)
urls)} URLs in sitemap") return urls if urls else None else: print(f"No sitemap found (HTTP {response.status_code})") return None except Exception as e: print(f"Error fetching sitemap: {e}") return None def run(self): """Run the dead link checker.""" print(f"Starting dead link check for {self.base_url}") print(f"Max pages: {self.max_pages}, Timeout: {self.timeout}s") sitemap_urls = self.get_sitemap_urls() if sitemap_urls: print("Using sitemap-based crawling...") for url in sitemap_urls: if not self.max_pages or len(self.visited_pages) < self.max_pages: self.crawl_page(url) else: print("Using breadth-first crawling...") while self.pages_to_visit and ( not self.max_pages or len(self.visited_pages) < self.max_pages ):
self.crawl_page(url) print("\nCrawl complete!") print(f"Pages visited: {len(self.visited_pages)}") print(f"Links checked: {len(self.checked_links)}") print(f"Dead links found: {len(self.dead_links)}") if self.dead_links: print("\n❌ DEAD LINKS FOUND:") for link_info in self.dead_links: print(f" URL: {link_info['url']}") print(f" Error: {link_info['error']}") print(f" Found on: {link_info['source_page']}") print() return False else: print("\nβœ… No dead links found!") return True def main(): parser = argparse.ArgumentParser(description="Check for dead links on a website") parser.add_argument("url", help="Base URL to start crawling from") parser.add_argument( "--max-pages", type=int, default=500, help="Maximum pages to crawl" ) parser.add_argument( "--timeout", t
url = self.pages_to_visit.popleft()
def run(self): """Run the dead link checker.""" print(f"Starting dead link check for {self.base_url}") print(f"Max pages: {self.max_pages}, Timeout: {self.timeout}s") sitemap_urls = self.get_sitemap_urls() if sitemap_urls: print("Using sitemap-based crawling...") for url in sitemap_urls: if not self.max_pages or len(self.visited_pages) < self.max_pages: self.crawl_page(url) else: print("Using breadth-first crawling...") while self.pages_to_visit and ( not self.max_pages or len(self.visited_pages) < self.max_pages ): url = self.pages_to_visit.popleft() self.crawl_page(url) print("\nCrawl complete!") print(f"Pages visited: {len(self.visited_pages)}") print(f"Links checked: {len(self.checked_links)}") print(f"Dead links found: {len(self.dead_links)}")
def main(): parser = argparse.ArgumentParser(description="Check for dead links on a website") parser.add_argument("url", help="Base URL to start crawling from") parser.add_argument( "--max-pages", type=int, default=500, help="Maximum pages to crawl" ) parser.add_argument( "--timeout", type=int, default=10, help="Request timeout in seconds" ) parser.add_argument( "--delay", type=float, default=0.5, help="Delay between requests" ) args = parser.parse_args() checker = DeadLinkChecker( base_url=args.url, max_pages=args.max_pages, timeout=args.timeout, delay=args.delay, ) success = checker.run() sys.exit(0 if success else 1) if __name__ == "__main__": main()
if self.dead_links: print("\n❌ DEAD LINKS FOUND:") for link_info in self.dead_links: print(f" URL: {link_info['url']}") print(f" Error: {link_info['error']}") print(f" Found on: {link_info['source_page']}") print() return False else: print("\nβœ… No dead links found!") return True
(f"Starting dead link check for {self.base_url}") print(f"Max pages: {self.max_pages}, Timeout: {self.timeout}s") sitemap_urls = self.get_sitemap_urls() if sitemap_urls: print("Using sitemap-based crawling...") for url in sitemap_urls: if not self.max_pages or len(self.visited_pages) < self.max_pages: self.crawl_page(url) else: print("Using breadth-first crawling...") while self.pages_to_visit and ( not self.max_pages or len(self.visited_pages) < self.max_pages ): url = self.pages_to_visit.popleft() self.crawl_page(url) print("\nCrawl complete!") print(f"Pages visited: {len(self.visited_pages)}") print(f"Links checked: {len(self.checked_links)}") print(f"Dead links found: {len(self.dead_links)}") if self.dead_links: print("\n❌ DEAD LINKS FOUND:")
return False else: print("\nβœ… No dead links found!") return True def main(): parser = argparse.ArgumentParser(description="Check for dead links on a website") parser.add_argument("url", help="Base URL to start crawling from") parser.add_argument( "--max-pages", type=int, default=500, help="Maximum pages to crawl" ) parser.add_argument( "--timeout", type=int, default=10, help="Request timeout in seconds" ) parser.add_argument( "--delay", type=float, default=0.5, help="Delay between requests" ) args = parser.parse_args() checker = DeadLinkChecker( base_url=args.url, max_pages=args.max_pages, timeout=args.timeout, delay=args.delay, ) success = checker.run() sys.exit(0 if success else 1) if __name__ == "__main__": main()
for link_info in self.dead_links: print(f" URL: {link_info['url']}") print(f" Error: {link_info['error']}") print(f" Found on: {link_info['source_page']}") print()
_pages) < self.max_pages: self.crawl_page(url) else: print("Using breadth-first crawling...") while self.pages_to_visit and ( not self.max_pages or len(self.visited_pages) < self.max_pages ): url = self.pages_to_visit.popleft() self.crawl_page(url) print("\nCrawl complete!") print(f"Pages visited: {len(self.visited_pages)}") print(f"Links checked: {len(self.checked_links)}") print(f"Dead links found: {len(self.dead_links)}") if self.dead_links: print("\n❌ DEAD LINKS FOUND:") for link_info in self.dead_links: print(f" URL: {link_info['url']}") print(f" Error: {link_info['error']}") print(f" Found on: {link_info['source_page']}") print() return False else: print("\nβœ… No dead links found!") return True
if __name__ == "__main__": main()
def main(): parser = argparse.ArgumentParser(description="Check for dead links on a website") parser.add_argument("url", help="Base URL to start crawling from") parser.add_argument( "--max-pages", type=int, default=500, help="Maximum pages to crawl" ) parser.add_argument( "--timeout", type=int, default=10, help="Request timeout in seconds" ) parser.add_argument( "--delay", type=float, default=0.5, help="Delay between requests" ) args = parser.parse_args() checker = DeadLinkChecker( base_url=args.url, max_pages=args.max_pages, timeout=args.timeout, delay=args.delay, ) success = checker.run() sys.exit(0 if success else 1)
ax_pages: self.crawl_page(url) else: print("Using breadth-first crawling...") while self.pages_to_visit and ( not self.max_pages or len(self.visited_pages) < self.max_pages ): url = self.pages_to_visit.popleft() self.crawl_page(url) print("\nCrawl complete!") print(f"Pages visited: {len(self.visited_pages)}") print(f"Links checked: {len(self.checked_links)}") print(f"Dead links found: {len(self.dead_links)}") if self.dead_links: print("\n❌ DEAD LINKS FOUND:") for link_info in self.dead_links: print(f" URL: {link_info['url']}") print(f" Error: {link_info['error']}") print(f" Found on: {link_info['source_page']}") print() return False else: print("\nβœ… No dead links found!") return True def main():
parser.add_argument("url", help="Base URL to start crawling from") parser.add_argument( "--max-pages", type=int, default=500, help="Maximum pages to crawl" ) parser.add_argument( "--timeout", type=int, default=10, help="Request timeout in seconds" ) parser.add_argument( "--delay", type=float, default=0.5, help="Delay between requests" ) args = parser.parse_args() checker = DeadLinkChecker( base_url=args.url, max_pages=args.max_pages, timeout=args.timeout, delay=args.delay, ) success = checker.run() sys.exit(0 if success else 1) if __name__ == "__main__": main()
parser = argparse.ArgumentParser(description="Check for dead links on a website")
lf.checked_links)}") print(f"Dead links found: {len(self.dead_links)}") if self.dead_links: print("\n❌ DEAD LINKS FOUND:") for link_info in self.dead_links: print(f" URL: {link_info['url']}") print(f" Error: {link_info['error']}") print(f" Found on: {link_info['source_page']}") print() return False else: print("\nβœ… No dead links found!") return True def main(): parser = argparse.ArgumentParser(description="Check for dead links on a website") parser.add_argument("url", help="Base URL to start crawling from") parser.add_argument( "--max-pages", type=int, default=500, help="Maximum pages to crawl" ) parser.add_argument( "--timeout", type=int, default=10, help="Request timeout in seconds" ) parser.add_argument( "--delay", type=float, default=0.5, help="Delay between requests" )
checker = DeadLinkChecker( base_url=args.url, max_pages=args.max_pages, timeout=args.timeout, delay=args.delay, ) success = checker.run() sys.exit(0 if success else 1) if __name__ == "__main__": main()
args = parser.parse_args()
nt(f"Dead links found: {len(self.dead_links)}") if self.dead_links: print("\n❌ DEAD LINKS FOUND:") for link_info in self.dead_links: print(f" URL: {link_info['url']}") print(f" Error: {link_info['error']}") print(f" Found on: {link_info['source_page']}") print() return False else: print("\nβœ… No dead links found!") return True def main(): parser = argparse.ArgumentParser(description="Check for dead links on a website") parser.add_argument("url", help="Base URL to start crawling from") parser.add_argument( "--max-pages", type=int, default=500, help="Maximum pages to crawl" ) parser.add_argument( "--timeout", type=int, default=10, help="Request timeout in seconds" ) parser.add_argument( "--delay", type=float, default=0.5, help="Delay between requests" ) args = parser.parse_args()
success = checker.run() sys.exit(0 if success else 1) if __name__ == "__main__": main()
checker = DeadLinkChecker( base_url=args.url, max_pages=args.max_pages, timeout=args.timeout, delay=args.delay, )
ead_links: print(f" URL: {link_info['url']}") print(f" Error: {link_info['error']}") print(f" Found on: {link_info['source_page']}") print() return False else: print("\nβœ… No dead links found!") return True def main(): parser = argparse.ArgumentParser(description="Check for dead links on a website") parser.add_argument("url", help="Base URL to start crawling from") parser.add_argument( "--max-pages", type=int, default=500, help="Maximum pages to crawl" ) parser.add_argument( "--timeout", type=int, default=10, help="Request timeout in seconds" ) parser.add_argument( "--delay", type=float, default=0.5, help="Delay between requests" ) args = parser.parse_args() checker = DeadLinkChecker( base_url=args.url, max_pages=args.max_pages, timeout=args.timeout, delay=args.delay, )
sys.exit(0 if success else 1) if __name__ == "__main__": main()
success = checker.run()
") print(f" Error: {link_info['error']}") print(f" Found on: {link_info['source_page']}") print() return False else: print("\nβœ… No dead links found!") return True def main(): parser = argparse.ArgumentParser(description="Check for dead links on a website") parser.add_argument("url", help="Base URL to start crawling from") parser.add_argument( "--max-pages", type=int, default=500, help="Maximum pages to crawl" ) parser.add_argument( "--timeout", type=int, default=10, help="Request timeout in seconds" ) parser.add_argument( "--delay", type=float, default=0.5, help="Delay between requests" ) args = parser.parse_args() checker = DeadLinkChecker( base_url=args.url, max_pages=args.max_pages, timeout=args.timeout, delay=args.delay, ) success = checker.run() sys.exit(0 if success else 1)
if __name__ == "__main__": main()
import os
from PIL import Image def convert_images_to_webp(folder_path, quality=80): if not os.path.isdir(folder_path): print(f"Error: {folder_path} is not a valid folder.") return count = 0 # Add all formats you want to handle valid_extensions = (".png", ".jpg", ".jpeg", ".webp") for filename in os.listdir(folder_path): if filename.lower().endswith(valid_extensions): img_path = os.path.join(folder_path, filename) base, _ext = os.path.splitext(filename) webp_path = os.path.join(folder_path, base + ".webp") try: with Image.open(img_path) as img: img.save(webp_path, "WEBP", quality=quality, optimize=True) count += 1 print(f"Processed: {filename} β†’ {os.path.basename(webp_path)}") except Exception as e: print(f"⚠️ Skipped {filename}: {e}") print(f"\nDone! Processed {count} image(s) in '{folder_path}'.")
import sys
import os import sys
def convert_images_to_webp(folder_path, quality=80): if not os.path.isdir(folder_path): print(f"Error: {folder_path} is not a valid folder.") return count = 0 # Add all formats you want to handle valid_extensions = (".png", ".jpg", ".jpeg", ".webp") for filename in os.listdir(folder_path): if filename.lower().endswith(valid_extensions): img_path = os.path.join(folder_path, filename) base, _ext = os.path.splitext(filename) webp_path = os.path.join(folder_path, base + ".webp") try: with Image.open(img_path) as img: img.save(webp_path, "WEBP", quality=quality, optimize=True) count += 1 print(f"Processed: {filename} β†’ {os.path.basename(webp_path)}") except Exception as e: print(f"⚠️ Skipped {filename}: {e}") print(f"\nDone! Processed {count} image(s) in '{folder_path}'.") if __name__ == "__ma
from PIL import Image
import os import sys from PIL import Image def convert_images_to_webp(folder_path, quality=80):
count = 0 # Add all formats you want to handle valid_extensions = (".png", ".jpg", ".jpeg", ".webp") for filename in os.listdir(folder_path): if filename.lower().endswith(valid_extensions): img_path = os.path.join(folder_path, filename) base, _ext = os.path.splitext(filename) webp_path = os.path.join(folder_path, base + ".webp") try: with Image.open(img_path) as img: img.save(webp_path, "WEBP", quality=quality, optimize=True) count += 1 print(f"Processed: {filename} β†’ {os.path.basename(webp_path)}") except Exception as e: print(f"⚠️ Skipped {filename}: {e}") print(f"\nDone! Processed {count} image(s) in '{folder_path}'.") if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python convert_to_webp.py <folder_path>") else: folder = sys.argv[1] convert_images_to_webp(fold
if not os.path.isdir(folder_path): print(f"Error: {folder_path} is not a valid folder.") return
import os import sys from PIL import Image def convert_images_to_webp(folder_path, quality=80): if not os.path.isdir(folder_path): print(f"Error: {folder_path} is not a valid folder.") return count = 0 # Add all formats you want to handle
for filename in os.listdir(folder_path): if filename.lower().endswith(valid_extensions): img_path = os.path.join(folder_path, filename) base, _ext = os.path.splitext(filename) webp_path = os.path.join(folder_path, base + ".webp") try: with Image.open(img_path) as img: img.save(webp_path, "WEBP", quality=quality, optimize=True) count += 1 print(f"Processed: {filename} β†’ {os.path.basename(webp_path)}") except Exception as e: print(f"⚠️ Skipped {filename}: {e}") print(f"\nDone! Processed {count} image(s) in '{folder_path}'.") if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python convert_to_webp.py <folder_path>") else: folder = sys.argv[1] convert_images_to_webp(folder)
valid_extensions = (".png", ".jpg", ".jpeg", ".webp")
import os import sys from PIL import Image def convert_images_to_webp(folder_path, quality=80): if not os.path.isdir(folder_path): print(f"Error: {folder_path} is not a valid folder.") return count = 0 # Add all formats you want to handle valid_extensions = (".png", ".jpg", ".jpeg", ".webp") for filename in os.listdir(folder_path): if filename.lower().endswith(valid_extensions):
base, _ext = os.path.splitext(filename) webp_path = os.path.join(folder_path, base + ".webp") try: with Image.open(img_path) as img: img.save(webp_path, "WEBP", quality=quality, optimize=True) count += 1 print(f"Processed: {filename} β†’ {os.path.basename(webp_path)}") except Exception as e: print(f"⚠️ Skipped {filename}: {e}") print(f"\nDone! Processed {count} image(s) in '{folder_path}'.") if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python convert_to_webp.py <folder_path>") else: folder = sys.argv[1] convert_images_to_webp(folder)
img_path = os.path.join(folder_path, filename)
import os import sys from PIL import Image def convert_images_to_webp(folder_path, quality=80): if not os.path.isdir(folder_path): print(f"Error: {folder_path} is not a valid folder.") return count = 0 # Add all formats you want to handle valid_extensions = (".png", ".jpg", ".jpeg", ".webp") for filename in os.listdir(folder_path): if filename.lower().endswith(valid_extensions): img_path = os.path.join(folder_path, filename)
webp_path = os.path.join(folder_path, base + ".webp") try: with Image.open(img_path) as img: img.save(webp_path, "WEBP", quality=quality, optimize=True) count += 1 print(f"Processed: {filename} β†’ {os.path.basename(webp_path)}") except Exception as e: print(f"⚠️ Skipped {filename}: {e}") print(f"\nDone! Processed {count} image(s) in '{folder_path}'.") if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python convert_to_webp.py <folder_path>") else: folder = sys.argv[1] convert_images_to_webp(folder)
base, _ext = os.path.splitext(filename)
import os import sys from PIL import Image def convert_images_to_webp(folder_path, quality=80): if not os.path.isdir(folder_path): print(f"Error: {folder_path} is not a valid folder.") return count = 0 # Add all formats you want to handle valid_extensions = (".png", ".jpg", ".jpeg", ".webp") for filename in os.listdir(folder_path): if filename.lower().endswith(valid_extensions): img_path = os.path.join(folder_path, filename) base, _ext = os.path.splitext(filename)
try: with Image.open(img_path) as img: img.save(webp_path, "WEBP", quality=quality, optimize=True) count += 1 print(f"Processed: {filename} β†’ {os.path.basename(webp_path)}") except Exception as e: print(f"⚠️ Skipped {filename}: {e}") print(f"\nDone! Processed {count} image(s) in '{folder_path}'.") if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python convert_to_webp.py <folder_path>") else: folder = sys.argv[1] convert_images_to_webp(folder)
webp_path = os.path.join(folder_path, base + ".webp")
r: {folder_path} is not a valid folder.") return count = 0 # Add all formats you want to handle valid_extensions = (".png", ".jpg", ".jpeg", ".webp") for filename in os.listdir(folder_path): if filename.lower().endswith(valid_extensions): img_path = os.path.join(folder_path, filename) base, _ext = os.path.splitext(filename) webp_path = os.path.join(folder_path, base + ".webp") try: with Image.open(img_path) as img: img.save(webp_path, "WEBP", quality=quality, optimize=True) count += 1 print(f"Processed: {filename} β†’ {os.path.basename(webp_path)}") except Exception as e: print(f"⚠️ Skipped {filename}: {e}") print(f"\nDone! Processed {count} image(s) in '{folder_path}'.") if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python convert_to_webp.py <folder_path>") else:
convert_images_to_webp(folder)
folder = sys.argv[1]
"""Dynamically generate synonyms for docs to better type match.""" import os
import typesense from typesense_indexer import TYPESENSE_CONFIG client = typesense.Client(TYPESENSE_CONFIG) def get_folder_hierarchy(root: str) -> dict: """Recursively build folder hierarchy from root, ignoring unwanted folders.""" hierarchy = {} for entry in os.scandir(root): if entry.is_dir() and entry.name not in ("__pycache__", ".git", ".venv"): hierarchy[entry.name] = get_folder_hierarchy(entry.path) return hierarchy def generate_synonyms(name: str) -> list[str]: """Generate multiple synonym forms for a folder/component name: - flattened lowercase: reactflow - lowercase spaced: react flow - title case spaced: React Flow - underscore: react_flow - hyphen: react-flow - camelcase: ReactFlow. """ clean_name = name.replace("_", " ").replace("-", " ").strip() words = clean_name.split() synonyms = set() # 1) Flattened lowercase synonyms.add("".join(w.lower() for w in words)) # 2) Lowercas
import pathlib
"""Dynamically generate synonyms for docs to better type match.""" import os import pathlib
from typesense_indexer import TYPESENSE_CONFIG client = typesense.Client(TYPESENSE_CONFIG) def get_folder_hierarchy(root: str) -> dict: """Recursively build folder hierarchy from root, ignoring unwanted folders.""" hierarchy = {} for entry in os.scandir(root): if entry.is_dir() and entry.name not in ("__pycache__", ".git", ".venv"): hierarchy[entry.name] = get_folder_hierarchy(entry.path) return hierarchy def generate_synonyms(name: str) -> list[str]: """Generate multiple synonym forms for a folder/component name: - flattened lowercase: reactflow - lowercase spaced: react flow - title case spaced: React Flow - underscore: react_flow - hyphen: react-flow - camelcase: ReactFlow. """ clean_name = name.replace("_", " ").replace("-", " ").strip() words = clean_name.split() synonyms = set() # 1) Flattened lowercase synonyms.add("".join(w.lower() for w in words)) # 2) Lowercase spaced synon
import typesense
"""Dynamically generate synonyms for docs to better type match.""" import os import pathlib import typesense
client = typesense.Client(TYPESENSE_CONFIG) def get_folder_hierarchy(root: str) -> dict: """Recursively build folder hierarchy from root, ignoring unwanted folders.""" hierarchy = {} for entry in os.scandir(root): if entry.is_dir() and entry.name not in ("__pycache__", ".git", ".venv"): hierarchy[entry.name] = get_folder_hierarchy(entry.path) return hierarchy def generate_synonyms(name: str) -> list[str]: """Generate multiple synonym forms for a folder/component name: - flattened lowercase: reactflow - lowercase spaced: react flow - title case spaced: React Flow - underscore: react_flow - hyphen: react-flow - camelcase: ReactFlow. """ clean_name = name.replace("_", " ").replace("-", " ").strip() words = clean_name.split() synonyms = set() # 1) Flattened lowercase synonyms.add("".join(w.lower() for w in words)) # 2) Lowercase spaced synonyms.add(" ".join(w.lower() for w in words))
from typesense_indexer import TYPESENSE_CONFIG
"""Dynamically generate synonyms for docs to better type match.""" import os import pathlib import typesense from typesense_indexer import TYPESENSE_CONFIG
def get_folder_hierarchy(root: str) -> dict: """Recursively build folder hierarchy from root, ignoring unwanted folders.""" hierarchy = {} for entry in os.scandir(root): if entry.is_dir() and entry.name not in ("__pycache__", ".git", ".venv"): hierarchy[entry.name] = get_folder_hierarchy(entry.path) return hierarchy def generate_synonyms(name: str) -> list[str]: """Generate multiple synonym forms for a folder/component name: - flattened lowercase: reactflow - lowercase spaced: react flow - title case spaced: React Flow - underscore: react_flow - hyphen: react-flow - camelcase: ReactFlow. """ clean_name = name.replace("_", " ").replace("-", " ").strip() words = clean_name.split() synonyms = set() # 1) Flattened lowercase synonyms.add("".join(w.lower() for w in words)) # 2) Lowercase spaced synonyms.add(" ".join(w.lower() for w in words)) # 3) Title case spaced synonyms.add(" ".
client = typesense.Client(TYPESENSE_CONFIG)
"""Dynamically generate synonyms for docs to better type match.""" import os import pathlib import typesense from typesense_indexer import TYPESENSE_CONFIG client = typesense.Client(TYPESENSE_CONFIG) def get_folder_hierarchy(root: str) -> dict: """Recursively build folder hierarchy from root, ignoring unwanted folders."""
for entry in os.scandir(root): if entry.is_dir() and entry.name not in ("__pycache__", ".git", ".venv"): hierarchy[entry.name] = get_folder_hierarchy(entry.path) return hierarchy def generate_synonyms(name: str) -> list[str]: """Generate multiple synonym forms for a folder/component name: - flattened lowercase: reactflow - lowercase spaced: react flow - title case spaced: React Flow - underscore: react_flow - hyphen: react-flow - camelcase: ReactFlow. """ clean_name = name.replace("_", " ").replace("-", " ").strip() words = clean_name.split() synonyms = set() # 1) Flattened lowercase synonyms.add("".join(w.lower() for w in words)) # 2) Lowercase spaced synonyms.add(" ".join(w.lower() for w in words)) # 3) Title case spaced synonyms.add(" ".join(w.capitalize() for w in words)) # 4) Original underscore synonyms.add("_".join(w.lower() for w in words)) # 5) Original hyphen s
hierarchy = {}
"""Dynamically generate synonyms for docs to better type match.""" import os import pathlib import typesense from typesense_indexer import TYPESENSE_CONFIG client = typesense.Client(TYPESENSE_CONFIG) def get_folder_hierarchy(root: str) -> dict: """Recursively build folder hierarchy from root, ignoring unwanted folders.""" hierarchy = {}
return hierarchy def generate_synonyms(name: str) -> list[str]: """Generate multiple synonym forms for a folder/component name: - flattened lowercase: reactflow - lowercase spaced: react flow - title case spaced: React Flow - underscore: react_flow - hyphen: react-flow - camelcase: ReactFlow. """ clean_name = name.replace("_", " ").replace("-", " ").strip() words = clean_name.split() synonyms = set() # 1) Flattened lowercase synonyms.add("".join(w.lower() for w in words)) # 2) Lowercase spaced synonyms.add(" ".join(w.lower() for w in words)) # 3) Title case spaced synonyms.add(" ".join(w.capitalize() for w in words)) # 4) Original underscore synonyms.add("_".join(w.lower() for w in words)) # 5) Original hyphen synonyms.add("-".join(w.lower() for w in words)) # 6) CamelCase synonyms.add("".join(w.capitalize() for w in words)) return list(synonyms) def flatten_hierarchy(hierarchy:
for entry in os.scandir(root): if entry.is_dir() and entry.name not in ("__pycache__", ".git", ".venv"): hierarchy[entry.name] = get_folder_hierarchy(entry.path)
"""Dynamically generate synonyms for docs to better type match.""" import os import pathlib import typesense from typesense_indexer import TYPESENSE_CONFIG client = typesense.Client(TYPESENSE_CONFIG) def get_folder_hierarchy(root: str) -> dict: """Recursively build folder hierarchy from root, ignoring unwanted folders.""" hierarchy = {} for entry in os.scandir(root):
return hierarchy def generate_synonyms(name: str) -> list[str]: """Generate multiple synonym forms for a folder/component name: - flattened lowercase: reactflow - lowercase spaced: react flow - title case spaced: React Flow - underscore: react_flow - hyphen: react-flow - camelcase: ReactFlow. """ clean_name = name.replace("_", " ").replace("-", " ").strip() words = clean_name.split() synonyms = set() # 1) Flattened lowercase synonyms.add("".join(w.lower() for w in words)) # 2) Lowercase spaced synonyms.add(" ".join(w.lower() for w in words)) # 3) Title case spaced synonyms.add(" ".join(w.capitalize() for w in words)) # 4) Original underscore synonyms.add("_".join(w.lower() for w in words)) # 5) Original hyphen synonyms.add("-".join(w.lower() for w in words)) # 6) CamelCase synonyms.add("".join(w.capitalize() for w in words)) return list(synonyms) def flatten_hierarchy(hierarchy:
if entry.is_dir() and entry.name not in ("__pycache__", ".git", ".venv"): hierarchy[entry.name] = get_folder_hierarchy(entry.path)
"""Dynamically generate synonyms for docs to better type match.""" import os import pathlib import typesense from typesense_indexer import TYPESENSE_CONFIG client = typesense.Client(TYPESENSE_CONFIG) def get_folder_hierarchy(root: str) -> dict: """Recursively build folder hierarchy from root, ignoring unwanted folders.""" hierarchy = {} for entry in os.scandir(root): if entry.is_dir() and entry.name not in ("__pycache__", ".git", ".venv"):
return hierarchy def generate_synonyms(name: str) -> list[str]: """Generate multiple synonym forms for a folder/component name: - flattened lowercase: reactflow - lowercase spaced: react flow - title case spaced: React Flow - underscore: react_flow - hyphen: react-flow - camelcase: ReactFlow. """ clean_name = name.replace("_", " ").replace("-", " ").strip() words = clean_name.split() synonyms = set() # 1) Flattened lowercase synonyms.add("".join(w.lower() for w in words)) # 2) Lowercase spaced synonyms.add(" ".join(w.lower() for w in words)) # 3) Title case spaced synonyms.add(" ".join(w.capitalize() for w in words)) # 4) Original underscore synonyms.add("_".join(w.lower() for w in words)) # 5) Original hyphen synonyms.add("-".join(w.lower() for w in words)) # 6) CamelCase synonyms.add("".join(w.capitalize() for w in words)) return list(synonyms) def flatten_hierarchy(hierarchy:
hierarchy[entry.name] = get_folder_hierarchy(entry.path)
"""Dynamically generate synonyms for docs to better type match.""" import os import pathlib import typesense from typesense_indexer import TYPESENSE_CONFIG client = typesense.Client(TYPESENSE_CONFIG) def get_folder_hierarchy(root: str) -> dict: """Recursively build folder hierarchy from root, ignoring unwanted folders.""" hierarchy = {} for entry in os.scandir(root): if entry.is_dir() and entry.name not in ("__pycache__", ".git", ".venv"): hierarchy[entry.name] = get_folder_hierarchy(entry.path) return hierarchy def generate_synonyms(name: str) -> list[str]: """Generate multiple synonym forms for a folder/component name: - flattened lowercase: reactflow - lowercase spaced: react flow - title case spaced: React Flow - underscore: react_flow - hyphen: react-flow - camelcase: ReactFlow. """
words = clean_name.split() synonyms = set() # 1) Flattened lowercase synonyms.add("".join(w.lower() for w in words)) # 2) Lowercase spaced synonyms.add(" ".join(w.lower() for w in words)) # 3) Title case spaced synonyms.add(" ".join(w.capitalize() for w in words)) # 4) Original underscore synonyms.add("_".join(w.lower() for w in words)) # 5) Original hyphen synonyms.add("-".join(w.lower() for w in words)) # 6) CamelCase synonyms.add("".join(w.capitalize() for w in words)) return list(synonyms) def flatten_hierarchy(hierarchy: dict) -> dict: """Flatten nested folder hierarchy into a single dict with synonyms keyed by flattened lowercase name. """ flat = {} def recurse(subtree): for key, value in subtree.items(): # Flatten key for canonical form key_flat = "".join(key.lower().split("_")).replace("-", "") flat[key_flat] = {"synonyms": generate_synonyms(key)}
clean_name = name.replace("_", " ").replace("-", " ").strip()
"""Dynamically generate synonyms for docs to better type match.""" import os import pathlib import typesense from typesense_indexer import TYPESENSE_CONFIG client = typesense.Client(TYPESENSE_CONFIG) def get_folder_hierarchy(root: str) -> dict: """Recursively build folder hierarchy from root, ignoring unwanted folders.""" hierarchy = {} for entry in os.scandir(root): if entry.is_dir() and entry.name not in ("__pycache__", ".git", ".venv"): hierarchy[entry.name] = get_folder_hierarchy(entry.path) return hierarchy def generate_synonyms(name: str) -> list[str]: """Generate multiple synonym forms for a folder/component name: - flattened lowercase: reactflow - lowercase spaced: react flow - title case spaced: React Flow - underscore: react_flow - hyphen: react-flow - camelcase: ReactFlow. """ clean_name = name.replace("_", " ").replace("-", " ").strip()
synonyms = set() # 1) Flattened lowercase synonyms.add("".join(w.lower() for w in words)) # 2) Lowercase spaced synonyms.add(" ".join(w.lower() for w in words)) # 3) Title case spaced synonyms.add(" ".join(w.capitalize() for w in words)) # 4) Original underscore synonyms.add("_".join(w.lower() for w in words)) # 5) Original hyphen synonyms.add("-".join(w.lower() for w in words)) # 6) CamelCase synonyms.add("".join(w.capitalize() for w in words)) return list(synonyms) def flatten_hierarchy(hierarchy: dict) -> dict: """Flatten nested folder hierarchy into a single dict with synonyms keyed by flattened lowercase name. """ flat = {} def recurse(subtree): for key, value in subtree.items(): # Flatten key for canonical form key_flat = "".join(key.lower().split("_")).replace("-", "") flat[key_flat] = {"synonyms": generate_synonyms(key)} if value:
words = clean_name.split()
"""Dynamically generate synonyms for docs to better type match.""" import os import pathlib import typesense from typesense_indexer import TYPESENSE_CONFIG client = typesense.Client(TYPESENSE_CONFIG) def get_folder_hierarchy(root: str) -> dict: """Recursively build folder hierarchy from root, ignoring unwanted folders.""" hierarchy = {} for entry in os.scandir(root): if entry.is_dir() and entry.name not in ("__pycache__", ".git", ".venv"): hierarchy[entry.name] = get_folder_hierarchy(entry.path) return hierarchy def generate_synonyms(name: str) -> list[str]: """Generate multiple synonym forms for a folder/component name: - flattened lowercase: reactflow - lowercase spaced: react flow - title case spaced: React Flow - underscore: react_flow - hyphen: react-flow - camelcase: ReactFlow. """ clean_name = name.replace("_", " ").replace("-", " ").strip() words = clean_name.split()
# 1) Flattened lowercase synonyms.add("".join(w.lower() for w in words)) # 2) Lowercase spaced synonyms.add(" ".join(w.lower() for w in words)) # 3) Title case spaced synonyms.add(" ".join(w.capitalize() for w in words)) # 4) Original underscore synonyms.add("_".join(w.lower() for w in words)) # 5) Original hyphen synonyms.add("-".join(w.lower() for w in words)) # 6) CamelCase synonyms.add("".join(w.capitalize() for w in words)) return list(synonyms) def flatten_hierarchy(hierarchy: dict) -> dict: """Flatten nested folder hierarchy into a single dict with synonyms keyed by flattened lowercase name. """ flat = {} def recurse(subtree): for key, value in subtree.items(): # Flatten key for canonical form key_flat = "".join(key.lower().split("_")).replace("-", "") flat[key_flat] = {"synonyms": generate_synonyms(key)} if value: recurse(value)
synonyms = set()
- hyphen: react-flow - camelcase: ReactFlow. """ clean_name = name.replace("_", " ").replace("-", " ").strip() words = clean_name.split() synonyms = set() # 1) Flattened lowercase synonyms.add("".join(w.lower() for w in words)) # 2) Lowercase spaced synonyms.add(" ".join(w.lower() for w in words)) # 3) Title case spaced synonyms.add(" ".join(w.capitalize() for w in words)) # 4) Original underscore synonyms.add("_".join(w.lower() for w in words)) # 5) Original hyphen synonyms.add("-".join(w.lower() for w in words)) # 6) CamelCase synonyms.add("".join(w.capitalize() for w in words)) return list(synonyms) def flatten_hierarchy(hierarchy: dict) -> dict: """Flatten nested folder hierarchy into a single dict with synonyms keyed by flattened lowercase name. """ flat = {} def recurse(subtree): for key, value in subtree.items(): # Flatten key for canonical form
flat[key_flat] = {"synonyms": generate_synonyms(key)} if value: recurse(value) recurse(hierarchy) return flat def main() -> bool: try: docs_root = pathlib.Path("docs") hierarchy = get_folder_hierarchy(docs_root) synonyms = flatten_hierarchy(hierarchy) print("Upserting new synonyms to Typesense ...") for canonical, info in synonyms.items(): client.collections["docs"].synonyms.upsert( canonical, {"synonyms": info["synonyms"]} ) print("Synonyms synced successfully!") return True except Exception as e: print("Error syncing synonyms:", e) return False if __name__ == "__main__": success = main() exit(0 if success else 1)
key_flat = "".join(key.lower().split("_")).replace("-", "")
name = name.replace("_", " ").replace("-", " ").strip() words = clean_name.split() synonyms = set() # 1) Flattened lowercase synonyms.add("".join(w.lower() for w in words)) # 2) Lowercase spaced synonyms.add(" ".join(w.lower() for w in words)) # 3) Title case spaced synonyms.add(" ".join(w.capitalize() for w in words)) # 4) Original underscore synonyms.add("_".join(w.lower() for w in words)) # 5) Original hyphen synonyms.add("-".join(w.lower() for w in words)) # 6) CamelCase synonyms.add("".join(w.capitalize() for w in words)) return list(synonyms) def flatten_hierarchy(hierarchy: dict) -> dict: """Flatten nested folder hierarchy into a single dict with synonyms keyed by flattened lowercase name. """ flat = {} def recurse(subtree): for key, value in subtree.items(): # Flatten key for canonical form key_flat = "".join(key.lower().split("_")).replace("-", "")
if value: recurse(value) recurse(hierarchy) return flat def main() -> bool: try: docs_root = pathlib.Path("docs") hierarchy = get_folder_hierarchy(docs_root) synonyms = flatten_hierarchy(hierarchy) print("Upserting new synonyms to Typesense ...") for canonical, info in synonyms.items(): client.collections["docs"].synonyms.upsert( canonical, {"synonyms": info["synonyms"]} ) print("Synonyms synced successfully!") return True except Exception as e: print("Error syncing synonyms:", e) return False if __name__ == "__main__": success = main() exit(0 if success else 1)
flat[key_flat] = {"synonyms": generate_synonyms(key)}
= clean_name.split() synonyms = set() # 1) Flattened lowercase synonyms.add("".join(w.lower() for w in words)) # 2) Lowercase spaced synonyms.add(" ".join(w.lower() for w in words)) # 3) Title case spaced synonyms.add(" ".join(w.capitalize() for w in words)) # 4) Original underscore synonyms.add("_".join(w.lower() for w in words)) # 5) Original hyphen synonyms.add("-".join(w.lower() for w in words)) # 6) CamelCase synonyms.add("".join(w.capitalize() for w in words)) return list(synonyms) def flatten_hierarchy(hierarchy: dict) -> dict: """Flatten nested folder hierarchy into a single dict with synonyms keyed by flattened lowercase name. """ flat = {} def recurse(subtree): for key, value in subtree.items(): # Flatten key for canonical form key_flat = "".join(key.lower().split("_")).replace("-", "") flat[key_flat] = {"synonyms": generate_synonyms(key)}
recurse(hierarchy) return flat def main() -> bool: try: docs_root = pathlib.Path("docs") hierarchy = get_folder_hierarchy(docs_root) synonyms = flatten_hierarchy(hierarchy) print("Upserting new synonyms to Typesense ...") for canonical, info in synonyms.items(): client.collections["docs"].synonyms.upsert( canonical, {"synonyms": info["synonyms"]} ) print("Synonyms synced successfully!") return True except Exception as e: print("Error syncing synonyms:", e) return False if __name__ == "__main__": success = main() exit(0 if success else 1)
if value: recurse(value)
ds)) # 2) Lowercase spaced synonyms.add(" ".join(w.lower() for w in words)) # 3) Title case spaced synonyms.add(" ".join(w.capitalize() for w in words)) # 4) Original underscore synonyms.add("_".join(w.lower() for w in words)) # 5) Original hyphen synonyms.add("-".join(w.lower() for w in words)) # 6) CamelCase synonyms.add("".join(w.capitalize() for w in words)) return list(synonyms) def flatten_hierarchy(hierarchy: dict) -> dict: """Flatten nested folder hierarchy into a single dict with synonyms keyed by flattened lowercase name. """ flat = {} def recurse(subtree): for key, value in subtree.items(): # Flatten key for canonical form key_flat = "".join(key.lower().split("_")).replace("-", "") flat[key_flat] = {"synonyms": generate_synonyms(key)} if value: recurse(value) recurse(hierarchy) return flat def main() -> bool: try:
hierarchy = get_folder_hierarchy(docs_root) synonyms = flatten_hierarchy(hierarchy) print("Upserting new synonyms to Typesense ...") for canonical, info in synonyms.items(): client.collections["docs"].synonyms.upsert( canonical, {"synonyms": info["synonyms"]} ) print("Synonyms synced successfully!") return True except Exception as e: print("Error syncing synonyms:", e) return False if __name__ == "__main__": success = main() exit(0 if success else 1)
docs_root = pathlib.Path("docs")
ms.add(" ".join(w.lower() for w in words)) # 3) Title case spaced synonyms.add(" ".join(w.capitalize() for w in words)) # 4) Original underscore synonyms.add("_".join(w.lower() for w in words)) # 5) Original hyphen synonyms.add("-".join(w.lower() for w in words)) # 6) CamelCase synonyms.add("".join(w.capitalize() for w in words)) return list(synonyms) def flatten_hierarchy(hierarchy: dict) -> dict: """Flatten nested folder hierarchy into a single dict with synonyms keyed by flattened lowercase name. """ flat = {} def recurse(subtree): for key, value in subtree.items(): # Flatten key for canonical form key_flat = "".join(key.lower().split("_")).replace("-", "") flat[key_flat] = {"synonyms": generate_synonyms(key)} if value: recurse(value) recurse(hierarchy) return flat def main() -> bool: try: docs_root = pathlib.Path("docs")
synonyms = flatten_hierarchy(hierarchy) print("Upserting new synonyms to Typesense ...") for canonical, info in synonyms.items(): client.collections["docs"].synonyms.upsert( canonical, {"synonyms": info["synonyms"]} ) print("Synonyms synced successfully!") return True except Exception as e: print("Error syncing synonyms:", e) return False if __name__ == "__main__": success = main() exit(0 if success else 1)
hierarchy = get_folder_hierarchy(docs_root)
Title case spaced synonyms.add(" ".join(w.capitalize() for w in words)) # 4) Original underscore synonyms.add("_".join(w.lower() for w in words)) # 5) Original hyphen synonyms.add("-".join(w.lower() for w in words)) # 6) CamelCase synonyms.add("".join(w.capitalize() for w in words)) return list(synonyms) def flatten_hierarchy(hierarchy: dict) -> dict: """Flatten nested folder hierarchy into a single dict with synonyms keyed by flattened lowercase name. """ flat = {} def recurse(subtree): for key, value in subtree.items(): # Flatten key for canonical form key_flat = "".join(key.lower().split("_")).replace("-", "") flat[key_flat] = {"synonyms": generate_synonyms(key)} if value: recurse(value) recurse(hierarchy) return flat def main() -> bool: try: docs_root = pathlib.Path("docs") hierarchy = get_folder_hierarchy(docs_root)
print("Upserting new synonyms to Typesense ...") for canonical, info in synonyms.items(): client.collections["docs"].synonyms.upsert( canonical, {"synonyms": info["synonyms"]} ) print("Synonyms synced successfully!") return True except Exception as e: print("Error syncing synonyms:", e) return False if __name__ == "__main__": success = main() exit(0 if success else 1)
synonyms = flatten_hierarchy(hierarchy)
synonyms.add("_".join(w.lower() for w in words)) # 5) Original hyphen synonyms.add("-".join(w.lower() for w in words)) # 6) CamelCase synonyms.add("".join(w.capitalize() for w in words)) return list(synonyms) def flatten_hierarchy(hierarchy: dict) -> dict: """Flatten nested folder hierarchy into a single dict with synonyms keyed by flattened lowercase name. """ flat = {} def recurse(subtree): for key, value in subtree.items(): # Flatten key for canonical form key_flat = "".join(key.lower().split("_")).replace("-", "") flat[key_flat] = {"synonyms": generate_synonyms(key)} if value: recurse(value) recurse(hierarchy) return flat def main() -> bool: try: docs_root = pathlib.Path("docs") hierarchy = get_folder_hierarchy(docs_root) synonyms = flatten_hierarchy(hierarchy) print("Upserting new synonyms to Typesense ...")
print("Synonyms synced successfully!") return True except Exception as e: print("Error syncing synonyms:", e) return False if __name__ == "__main__": success = main() exit(0 if success else 1)
for canonical, info in synonyms.items(): client.collections["docs"].synonyms.upsert( canonical, {"synonyms": info["synonyms"]} )
gle dict with synonyms keyed by flattened lowercase name. """ flat = {} def recurse(subtree): for key, value in subtree.items(): # Flatten key for canonical form key_flat = "".join(key.lower().split("_")).replace("-", "") flat[key_flat] = {"synonyms": generate_synonyms(key)} if value: recurse(value) recurse(hierarchy) return flat def main() -> bool: try: docs_root = pathlib.Path("docs") hierarchy = get_folder_hierarchy(docs_root) synonyms = flatten_hierarchy(hierarchy) print("Upserting new synonyms to Typesense ...") for canonical, info in synonyms.items(): client.collections["docs"].synonyms.upsert( canonical, {"synonyms": info["synonyms"]} ) print("Synonyms synced successfully!") return True except Exception as e: print("Error syncing synonyms:", e) return False
if __name__ == "__main__": success = main() exit(0 if success else 1)
d by flattened lowercase name. """ flat = {} def recurse(subtree): for key, value in subtree.items(): # Flatten key for canonical form key_flat = "".join(key.lower().split("_")).replace("-", "") flat[key_flat] = {"synonyms": generate_synonyms(key)} if value: recurse(value) recurse(hierarchy) return flat def main() -> bool: try: docs_root = pathlib.Path("docs") hierarchy = get_folder_hierarchy(docs_root) synonyms = flatten_hierarchy(hierarchy) print("Upserting new synonyms to Typesense ...") for canonical, info in synonyms.items(): client.collections["docs"].synonyms.upsert( canonical, {"synonyms": info["synonyms"]} ) print("Synonyms synced successfully!") return True except Exception as e: print("Error syncing synonyms:", e) return False if __name__ == "__main__":
exit(0 if success else 1)
success = main()
"""Generate indexed docs + collection for typesense search."""
import logging import os import pathlib import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, r
import datetime
"""Generate indexed docs + collection for typesense search.""" import datetime
import os import pathlib import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var):
import logging
"""Generate indexed docs + collection for typesense search.""" import datetime import logging import os
import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_va
import pathlib
"""Generate indexed docs + collection for typesense search.""" import datetime import logging import os import pathlib import re
from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isins
import sys
"""Generate indexed docs + collection for typesense search.""" import datetime import logging import os import pathlib import re import sys
from typing import Any, Dict, List, Optional import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c)
from concurrent.futures import ThreadPoolExecutor, as_completed
"""Generate indexed docs + collection for typesense search.""" import datetime import logging import os import pathlib import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed
import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_componen
from typing import Any, Dict, List, Optional
"""Generate indexed docs + collection for typesense search.""" import datetime import logging import os import pathlib import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional
import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for
import reflex as rx
"""Generate indexed docs + collection for typesense search.""" import datetime import logging import os import pathlib import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx
import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.childr
import typesense
"""Generate indexed docs + collection for typesense search.""" import datetime import logging import os import pathlib import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx import typesense
project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.children] retu
import yaml
"""Generate indexed docs + collection for typesense search.""" import datetime import logging import os import pathlib import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx import typesense import yaml
if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts)) def _extract_headings_from_c
project_root = pathlib.Path(__file__).resolve().parent.parent
"""Generate indexed docs + collection for typesense search.""" import datetime import logging import os import pathlib import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent
from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts)) def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree."""
if str(project_root) not in sys.path: sys.path.insert(0, str(project_root))
"""Generate indexed docs + collection for typesense search.""" import datetime import logging import os import pathlib import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root))
from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts)) def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree.""" headings = [] if not isinstance(c, r
from pcweb.pages.docs.apiref import modules
"""Generate indexed docs + collection for typesense search.""" import datetime import logging import os import pathlib import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules
from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts)) def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree.""" headings = [] if not isinstance(c, rx.Component): return headings if c.t
from pcweb.pages.docs.env_vars import EnvVarDocs
"""Generate indexed docs + collection for typesense search.""" import datetime import logging import os import pathlib import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs
logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts)) def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree.""" headings = [] if not isinstance(c, rx.Component): return headings if c.tag and c.tag.startswith("h") and c.tag[1:].
from pcweb.pages.docs.source import Source
"""Generate indexed docs + collection for typesense search.""" import datetime import logging import os import pathlib import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" )
ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts)) def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree.""" headings = [] if not isinstance(c, rx.Component): return headings if c.tag and c.tag.startswith("h") and c.tag[1:].isdigit(): headings.append(_render_component_to_text(c)) for child in c.children: headings.extend(_extract_headings
logger = logging.getLogger(__name__)
"""Generate indexed docs + collection for typesense search.""" import datetime import logging import os import pathlib import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__)
def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts)) def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree.""" headings = [] if not isinstance(c, rx.Component): return headings if c.tag and c.tag.startswith("h") and c.tag[1:].isdigit(): headings.append(_render_component_to_text(c)) for child in c.children: headings.extend(_extract_headings_from_component(child)) return headings CLUSTERS = { "All Content": [], "AI Builder": ["ai_builder"], "Hosting": ["hosting"], "Components": ["custom-components", "recipes"]
ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", }
"""Generate indexed docs + collection for typesense search.""" import datetime import logging import os import pathlib import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", }
def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree.""" headings = [] if not isinstance(c, rx.Component): return headings if c.tag and c.tag.startswith("h") and c.tag[1:].isdigit(): headings.append(_render_component_to_text(c)) for child in c.children: headings.extend(_extract_headings_from_component(child)) return headings CLUSTERS = { "All Content": [], "AI Builder": ["ai_builder"], "Hosting": ["hosting"], "Components": ["custom-components", "recipes"], "Enterprise": ["enterprise"], "API Reference": ["api-reference", "api-routes"], "Docs": [ "advanced_onboarding", "assets", "authentication", "client_storage", "components", "database", "events", "getting_started", "library", "pages", "state", "state_structure", "styling", "ui", "utility
def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts))
ed docs + collection for typesense search.""" import datetime import logging import os import pathlib import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string."""
texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts)) def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree.""" headings = [] if not isinstance(c, rx.Component): return headings if c.tag and c.tag.startswith("h") and c.tag[1:].isdigit(): headings.append(_render_component_to_text(c)) for child in c.children: headings.extend(_extract_headings_from_component(child)) return headings CLUSTERS = { "All Content": [], "AI Builder": ["ai_builder"], "Hosting": ["hosting"], "Components": ["custom-components", "recipes"], "Enterprise": ["enterprise"], "API Reference": ["api-reference", "api-routes"], "Docs": [ "advanced_onboarding", "assets", "authentication", "client_storage", "components", "database", "events", "getting_started", "library
if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return ""
" import datetime import logging import os import pathlib import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component):
if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts)) def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree.""" headings = [] if not isinstance(c, rx.Component): return headings if c.tag and c.tag.startswith("h") and c.tag[1:].isdigit(): headings.append(_render_component_to_text(c)) for child in c.children: headings.extend(_extract_headings_from_component(child)) return headings CLUSTERS = { "All Content": [], "AI Builder": ["ai_builder"], "Hosting": ["hosting"], "Components": ["custom-components", "recipes"], "Enterprise": ["enterprise"], "API Reference": ["api-reference", "api-routes"], "Docs": [ "advanced_onboarding", "assets", "authentication", "client_storage",
if isinstance(c, rx.Var): return str(c._var_value)
port sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Dict, List, Optional import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value)
return "" texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts)) def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree.""" headings = [] if not isinstance(c, rx.Component): return headings if c.tag and c.tag.startswith("h") and c.tag[1:].isdigit(): headings.append(_render_component_to_text(c)) for child in c.children: headings.extend(_extract_headings_from_component(child)) return headings CLUSTERS = { "All Content": [], "AI Builder": ["ai_builder"], "Hosting": ["hosting"], "Components": ["custom-components", "recipes"], "Enterprise": ["enterprise"], "API Reference": ["api-reference", "api-routes"], "Docs": [ "advanced_onboarding", "assets", "authentication", "client_storage", "components", "database", "events", "getting_started"
if isinstance(c, (str, int, float, bool)): return str(c)
Any, Dict, List, Optional import reflex as rx import typesense import yaml project_root = pathlib.Path(__file__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return ""
return " ".join(filter(None, texts)) def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree.""" headings = [] if not isinstance(c, rx.Component): return headings if c.tag and c.tag.startswith("h") and c.tag[1:].isdigit(): headings.append(_render_component_to_text(c)) for child in c.children: headings.extend(_extract_headings_from_component(child)) return headings CLUSTERS = { "All Content": [], "AI Builder": ["ai_builder"], "Hosting": ["hosting"], "Components": ["custom-components", "recipes"], "Enterprise": ["enterprise"], "API Reference": ["api-reference", "api-routes"], "Docs": [ "advanced_onboarding", "assets", "authentication", "client_storage", "components", "database", "events", "getting_started", "library", "pages", "state", "state_structure",
texts = [_render_component_to_text(child) for child in c.children]
e__).resolve().parent.parent if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts))
CLUSTERS = { "All Content": [], "AI Builder": ["ai_builder"], "Hosting": ["hosting"], "Components": ["custom-components", "recipes"], "Enterprise": ["enterprise"], "API Reference": ["api-reference", "api-routes"], "Docs": [ "advanced_onboarding", "assets", "authentication", "client_storage", "components", "database", "events", "getting_started", "library", "pages", "state", "state_structure", "styling", "ui", "utility_methods", "vars", "wrapping-react", ], "Blog Posts": [], } TYPESENSE_CONFIG = { "nodes": [ {"host": os.getenv("TYPESENSE_HOST"), "port": "443", "protocol": "https"} ], "api_key": os.getenv("TYPESENSE_ADMIN_API_KEY"), "connection_timeout_seconds": 60, } COLLECTION_SCHEMA = { "name": "docs", "fields": [ {"name": "id", "type": "string", "infix": True},
def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree.""" headings = [] if not isinstance(c, rx.Component): return headings if c.tag and c.tag.startswith("h") and c.tag[1:].isdigit(): headings.append(_render_component_to_text(c)) for child in c.children: headings.extend(_extract_headings_from_component(child)) return headings
m pcweb.pages.docs.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts)) def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree."""
if not isinstance(c, rx.Component): return headings if c.tag and c.tag.startswith("h") and c.tag[1:].isdigit(): headings.append(_render_component_to_text(c)) for child in c.children: headings.extend(_extract_headings_from_component(child)) return headings CLUSTERS = { "All Content": [], "AI Builder": ["ai_builder"], "Hosting": ["hosting"], "Components": ["custom-components", "recipes"], "Enterprise": ["enterprise"], "API Reference": ["api-reference", "api-routes"], "Docs": [ "advanced_onboarding", "assets", "authentication", "client_storage", "components", "database", "events", "getting_started", "library", "pages", "state", "state_structure", "styling", "ui", "utility_methods", "vars", "wrapping-react", ], "Blog Posts": [], } TYPESENSE_CONFIG = { "nodes": [
headings = []
.apiref import modules from pcweb.pages.docs.env_vars import EnvVarDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts)) def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree.""" headings = []
if c.tag and c.tag.startswith("h") and c.tag[1:].isdigit(): headings.append(_render_component_to_text(c)) for child in c.children: headings.extend(_extract_headings_from_component(child)) return headings CLUSTERS = { "All Content": [], "AI Builder": ["ai_builder"], "Hosting": ["hosting"], "Components": ["custom-components", "recipes"], "Enterprise": ["enterprise"], "API Reference": ["api-reference", "api-routes"], "Docs": [ "advanced_onboarding", "assets", "authentication", "client_storage", "components", "database", "events", "getting_started", "library", "pages", "state", "state_structure", "styling", "ui", "utility_methods", "vars", "wrapping-react", ], "Blog Posts": [], } TYPESENSE_CONFIG = { "nodes": [ {"host": os.getenv("TYPESENSE_HOST"), "port": "443", "protocol":
if not isinstance(c, rx.Component): return headings
arDocs from pcweb.pages.docs.source import Source logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts)) def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree.""" headings = [] if not isinstance(c, rx.Component): return headings
for child in c.children: headings.extend(_extract_headings_from_component(child)) return headings CLUSTERS = { "All Content": [], "AI Builder": ["ai_builder"], "Hosting": ["hosting"], "Components": ["custom-components", "recipes"], "Enterprise": ["enterprise"], "API Reference": ["api-reference", "api-routes"], "Docs": [ "advanced_onboarding", "assets", "authentication", "client_storage", "components", "database", "events", "getting_started", "library", "pages", "state", "state_structure", "styling", "ui", "utility_methods", "vars", "wrapping-react", ], "Blog Posts": [], } TYPESENSE_CONFIG = { "nodes": [ {"host": os.getenv("TYPESENSE_HOST"), "port": "443", "protocol": "https"} ], "api_key": os.getenv("TYPESENSE_ADMIN_API_KEY"), "connection_timeout_seconds": 60, } COLLECT
if c.tag and c.tag.startswith("h") and c.tag[1:].isdigit(): headings.append(_render_component_to_text(c))
(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) ACRONYMS = { "AI", "API", "HTTP", "HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts)) def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree.""" headings = [] if not isinstance(c, rx.Component): return headings if c.tag and c.tag.startswith("h") and c.tag[1:].isdigit(): headings.append(_render_component_to_text(c))
return headings CLUSTERS = { "All Content": [], "AI Builder": ["ai_builder"], "Hosting": ["hosting"], "Components": ["custom-components", "recipes"], "Enterprise": ["enterprise"], "API Reference": ["api-reference", "api-routes"], "Docs": [ "advanced_onboarding", "assets", "authentication", "client_storage", "components", "database", "events", "getting_started", "library", "pages", "state", "state_structure", "styling", "ui", "utility_methods", "vars", "wrapping-react", ], "Blog Posts": [], } TYPESENSE_CONFIG = { "nodes": [ {"host": os.getenv("TYPESENSE_HOST"), "port": "443", "protocol": "https"} ], "api_key": os.getenv("TYPESENSE_ADMIN_API_KEY"), "connection_timeout_seconds": 60, } COLLECTION_SCHEMA = { "name": "docs", "fields": [ {"name": "id", "type": "string", "in
for child in c.children: headings.extend(_extract_headings_from_component(child))
"HTTPS", "SQL", "JSON", "XML", "CPU", "GPU", "OAuth", "CLI", "URL", "DNS", "IP", "UI", "MCP", } def _render_component_to_text(c: Any) -> str: """Render a Reflex component to a text string.""" if not isinstance(c, rx.Component): if isinstance(c, rx.Var): return str(c._var_value) if isinstance(c, (str, int, float, bool)): return str(c) return "" texts = [_render_component_to_text(child) for child in c.children] return " ".join(filter(None, texts)) def _extract_headings_from_component(c: Any) -> List[str]: """Extract headings from a component tree.""" headings = [] if not isinstance(c, rx.Component): return headings if c.tag and c.tag.startswith("h") and c.tag[1:].isdigit(): headings.append(_render_component_to_text(c)) for child in c.children: headings.extend(_extract_headings_from_component(child)) return headings
TYPESENSE_CONFIG = { "nodes": [ {"host": os.getenv("TYPESENSE_HOST"), "port": "443", "protocol": "https"} ], "api_key": os.getenv("TYPESENSE_ADMIN_API_KEY"), "connection_timeout_seconds": 60, } COLLECTION_SCHEMA = { "name": "docs", "fields": [ {"name": "id", "type": "string", "infix": True}, {"name": "title", "type": "string", "infix": True}, {"name": "content", "type": "string", "infix": True}, {"name": "headings", "type": "string[]"}, {"name": "components", "type": "string[]", "optional": True}, {"name": "path", "type": "string"}, {"name": "url", "type": "string"}, {"name": "section", "type": "string"}, {"name": "subsection", "type": "string", "optional": True}, {"name": "cluster", "type": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your ex
CLUSTERS = { "All Content": [], "AI Builder": ["ai_builder"], "Hosting": ["hosting"], "Components": ["custom-components", "recipes"], "Enterprise": ["enterprise"], "API Reference": ["api-reference", "api-routes"], "Docs": [ "advanced_onboarding", "assets", "authentication", "client_storage", "components", "database", "events", "getting_started", "library", "pages", "state", "state_structure", "styling", "ui", "utility_methods", "vars", "wrapping-react", ], "Blog Posts": [], }
from a component tree.""" headings = [] if not isinstance(c, rx.Component): return headings if c.tag and c.tag.startswith("h") and c.tag[1:].isdigit(): headings.append(_render_component_to_text(c)) for child in c.children: headings.extend(_extract_headings_from_component(child)) return headings CLUSTERS = { "All Content": [], "AI Builder": ["ai_builder"], "Hosting": ["hosting"], "Components": ["custom-components", "recipes"], "Enterprise": ["enterprise"], "API Reference": ["api-reference", "api-routes"], "Docs": [ "advanced_onboarding", "assets", "authentication", "client_storage", "components", "database", "events", "getting_started", "library", "pages", "state", "state_structure", "styling", "ui", "utility_methods", "vars", "wrapping-react", ], "Blog Posts": [], }
COLLECTION_SCHEMA = { "name": "docs", "fields": [ {"name": "id", "type": "string", "infix": True}, {"name": "title", "type": "string", "infix": True}, {"name": "content", "type": "string", "infix": True}, {"name": "headings", "type": "string[]"}, {"name": "components", "type": "string[]", "optional": True}, {"name": "path", "type": "string"}, {"name": "url", "type": "string"}, {"name": "section", "type": "string"}, {"name": "subsection", "type": "string", "optional": True}, {"name": "cluster", "type": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your existing logic.""" def __init__(self): self.client = typesense.Client(TYPESENSE_CONFIG) def smart_title_case(self, name: str) -> str: words = name.split(" ") title_cased_words = []
TYPESENSE_CONFIG = { "nodes": [ {"host": os.getenv("TYPESENSE_HOST"), "port": "443", "protocol": "https"} ], "api_key": os.getenv("TYPESENSE_ADMIN_API_KEY"), "connection_timeout_seconds": 60, }
ext(c)) for child in c.children: headings.extend(_extract_headings_from_component(child)) return headings CLUSTERS = { "All Content": [], "AI Builder": ["ai_builder"], "Hosting": ["hosting"], "Components": ["custom-components", "recipes"], "Enterprise": ["enterprise"], "API Reference": ["api-reference", "api-routes"], "Docs": [ "advanced_onboarding", "assets", "authentication", "client_storage", "components", "database", "events", "getting_started", "library", "pages", "state", "state_structure", "styling", "ui", "utility_methods", "vars", "wrapping-react", ], "Blog Posts": [], } TYPESENSE_CONFIG = { "nodes": [ {"host": os.getenv("TYPESENSE_HOST"), "port": "443", "protocol": "https"} ], "api_key": os.getenv("TYPESENSE_ADMIN_API_KEY"), "connection_timeout_seconds": 60, }
class SimpleTypesenseIndexer: """Simplified indexer using your existing logic.""" def __init__(self): self.client = typesense.Client(TYPESENSE_CONFIG) def smart_title_case(self, name: str) -> str: words = name.split(" ") title_cased_words = [] for word in words: if word.upper() in ACRONYMS: title_cased_words.append(word.upper()) else: title_cased_words.append(word.capitalize()) return " ".join(title_cased_words) def clean_name(self, name: str) -> str: if name.lower().endswith(".md"): name = name[:-3] name = name.replace("_", " ").replace("-", " ").strip() return self.smart_title_case(name) def clean_markdown(self, text: str) -> str: text = re.sub(r"^---[\s\S]*?---\s*", "", text, flags=re.MULTILINE) text = re.sub(r"```[\s\S]*?```", "", text) text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) tex
COLLECTION_SCHEMA = { "name": "docs", "fields": [ {"name": "id", "type": "string", "infix": True}, {"name": "title", "type": "string", "infix": True}, {"name": "content", "type": "string", "infix": True}, {"name": "headings", "type": "string[]"}, {"name": "components", "type": "string[]", "optional": True}, {"name": "path", "type": "string"}, {"name": "url", "type": "string"}, {"name": "section", "type": "string"}, {"name": "subsection", "type": "string", "optional": True}, {"name": "cluster", "type": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], }
"nodes": [ {"host": os.getenv("TYPESENSE_HOST"), "port": "443", "protocol": "https"} ], "api_key": os.getenv("TYPESENSE_ADMIN_API_KEY"), "connection_timeout_seconds": 60, } COLLECTION_SCHEMA = { "name": "docs", "fields": [ {"name": "id", "type": "string", "infix": True}, {"name": "title", "type": "string", "infix": True}, {"name": "content", "type": "string", "infix": True}, {"name": "headings", "type": "string[]"}, {"name": "components", "type": "string[]", "optional": True}, {"name": "path", "type": "string"}, {"name": "url", "type": "string"}, {"name": "section", "type": "string"}, {"name": "subsection", "type": "string", "optional": True}, {"name": "cluster", "type": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your existing logic."""
def smart_title_case(self, name: str) -> str: words = name.split(" ") title_cased_words = [] for word in words: if word.upper() in ACRONYMS: title_cased_words.append(word.upper()) else: title_cased_words.append(word.capitalize()) return " ".join(title_cased_words) def clean_name(self, name: str) -> str: if name.lower().endswith(".md"): name = name[:-3] name = name.replace("_", " ").replace("-", " ").strip() return self.smart_title_case(name) def clean_markdown(self, text: str) -> str: text = re.sub(r"^---[\s\S]*?---\s*", "", text, flags=re.MULTILINE) text = re.sub(r"```[\s\S]*?```", "", text) text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) text = re.sub(r"<div[\s\S]*?</div>", "", text, flags=re.IGNORECASE) text = re.sub(r"`[^`]+`", "", text) text = re.sub(r"^#+\s*", "", text, flags=re.MULTILINE
def __init__(self): self.client = typesense.Client(TYPESENSE_CONFIG)
st": os.getenv("TYPESENSE_HOST"), "port": "443", "protocol": "https"} ], "api_key": os.getenv("TYPESENSE_ADMIN_API_KEY"), "connection_timeout_seconds": 60, } COLLECTION_SCHEMA = { "name": "docs", "fields": [ {"name": "id", "type": "string", "infix": True}, {"name": "title", "type": "string", "infix": True}, {"name": "content", "type": "string", "infix": True}, {"name": "headings", "type": "string[]"}, {"name": "components", "type": "string[]", "optional": True}, {"name": "path", "type": "string"}, {"name": "url", "type": "string"}, {"name": "section", "type": "string"}, {"name": "subsection", "type": "string", "optional": True}, {"name": "cluster", "type": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your existing logic.""" def __init__(self):
def smart_title_case(self, name: str) -> str: words = name.split(" ") title_cased_words = [] for word in words: if word.upper() in ACRONYMS: title_cased_words.append(word.upper()) else: title_cased_words.append(word.capitalize()) return " ".join(title_cased_words) def clean_name(self, name: str) -> str: if name.lower().endswith(".md"): name = name[:-3] name = name.replace("_", " ").replace("-", " ").strip() return self.smart_title_case(name) def clean_markdown(self, text: str) -> str: text = re.sub(r"^---[\s\S]*?---\s*", "", text, flags=re.MULTILINE) text = re.sub(r"```[\s\S]*?```", "", text) text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) text = re.sub(r"<div[\s\S]*?</div>", "", text, flags=re.IGNORECASE) text = re.sub(r"`[^`]+`", "", text) text = re.sub(r"^#+\s*", "", text, flags=re.MULTILINE
self.client = typesense.Client(TYPESENSE_CONFIG)
ocol": "https"} ], "api_key": os.getenv("TYPESENSE_ADMIN_API_KEY"), "connection_timeout_seconds": 60, } COLLECTION_SCHEMA = { "name": "docs", "fields": [ {"name": "id", "type": "string", "infix": True}, {"name": "title", "type": "string", "infix": True}, {"name": "content", "type": "string", "infix": True}, {"name": "headings", "type": "string[]"}, {"name": "components", "type": "string[]", "optional": True}, {"name": "path", "type": "string"}, {"name": "url", "type": "string"}, {"name": "section", "type": "string"}, {"name": "subsection", "type": "string", "optional": True}, {"name": "cluster", "type": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your existing logic.""" def __init__(self): self.client = typesense.Client(TYPESENSE_CONFIG)
def clean_name(self, name: str) -> str: if name.lower().endswith(".md"): name = name[:-3] name = name.replace("_", " ").replace("-", " ").strip() return self.smart_title_case(name) def clean_markdown(self, text: str) -> str: text = re.sub(r"^---[\s\S]*?---\s*", "", text, flags=re.MULTILINE) text = re.sub(r"```[\s\S]*?```", "", text) text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) text = re.sub(r"<div[\s\S]*?</div>", "", text, flags=re.IGNORECASE) text = re.sub(r"`[^`]+`", "", text) text = re.sub(r"^#+\s*", "", text, flags=re.MULTILINE) text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text) text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL) text = re.sub(r"\n\s*\n+", "\n\n", text) return text.strip() def extract_headings(self, content: str) -> List[str]: """Extract headings from markdown content.""" headings = [] lines = co
def smart_title_case(self, name: str) -> str: words = name.split(" ") title_cased_words = [] for word in words: if word.upper() in ACRONYMS: title_cased_words.append(word.upper()) else: title_cased_words.append(word.capitalize()) return " ".join(title_cased_words)
ENSE_ADMIN_API_KEY"), "connection_timeout_seconds": 60, } COLLECTION_SCHEMA = { "name": "docs", "fields": [ {"name": "id", "type": "string", "infix": True}, {"name": "title", "type": "string", "infix": True}, {"name": "content", "type": "string", "infix": True}, {"name": "headings", "type": "string[]"}, {"name": "components", "type": "string[]", "optional": True}, {"name": "path", "type": "string"}, {"name": "url", "type": "string"}, {"name": "section", "type": "string"}, {"name": "subsection", "type": "string", "optional": True}, {"name": "cluster", "type": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your existing logic.""" def __init__(self): self.client = typesense.Client(TYPESENSE_CONFIG) def smart_title_case(self, name: str) -> str:
title_cased_words = [] for word in words: if word.upper() in ACRONYMS: title_cased_words.append(word.upper()) else: title_cased_words.append(word.capitalize()) return " ".join(title_cased_words) def clean_name(self, name: str) -> str: if name.lower().endswith(".md"): name = name[:-3] name = name.replace("_", " ").replace("-", " ").strip() return self.smart_title_case(name) def clean_markdown(self, text: str) -> str: text = re.sub(r"^---[\s\S]*?---\s*", "", text, flags=re.MULTILINE) text = re.sub(r"```[\s\S]*?```", "", text) text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) text = re.sub(r"<div[\s\S]*?</div>", "", text, flags=re.IGNORECASE) text = re.sub(r"`[^`]+`", "", text) text = re.sub(r"^#+\s*", "", text, flags=re.MULTILINE) text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text) text = re.su
words = name.split(" ")
ction_timeout_seconds": 60, } COLLECTION_SCHEMA = { "name": "docs", "fields": [ {"name": "id", "type": "string", "infix": True}, {"name": "title", "type": "string", "infix": True}, {"name": "content", "type": "string", "infix": True}, {"name": "headings", "type": "string[]"}, {"name": "components", "type": "string[]", "optional": True}, {"name": "path", "type": "string"}, {"name": "url", "type": "string"}, {"name": "section", "type": "string"}, {"name": "subsection", "type": "string", "optional": True}, {"name": "cluster", "type": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your existing logic.""" def __init__(self): self.client = typesense.Client(TYPESENSE_CONFIG) def smart_title_case(self, name: str) -> str: words = name.split(" ")
for word in words: if word.upper() in ACRONYMS: title_cased_words.append(word.upper()) else: title_cased_words.append(word.capitalize()) return " ".join(title_cased_words) def clean_name(self, name: str) -> str: if name.lower().endswith(".md"): name = name[:-3] name = name.replace("_", " ").replace("-", " ").strip() return self.smart_title_case(name) def clean_markdown(self, text: str) -> str: text = re.sub(r"^---[\s\S]*?---\s*", "", text, flags=re.MULTILINE) text = re.sub(r"```[\s\S]*?```", "", text) text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) text = re.sub(r"<div[\s\S]*?</div>", "", text, flags=re.IGNORECASE) text = re.sub(r"`[^`]+`", "", text) text = re.sub(r"^#+\s*", "", text, flags=re.MULTILINE) text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text) text = re.sub(r"<!--.*?-->", "", text, flag
title_cased_words = []
COLLECTION_SCHEMA = { "name": "docs", "fields": [ {"name": "id", "type": "string", "infix": True}, {"name": "title", "type": "string", "infix": True}, {"name": "content", "type": "string", "infix": True}, {"name": "headings", "type": "string[]"}, {"name": "components", "type": "string[]", "optional": True}, {"name": "path", "type": "string"}, {"name": "url", "type": "string"}, {"name": "section", "type": "string"}, {"name": "subsection", "type": "string", "optional": True}, {"name": "cluster", "type": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your existing logic.""" def __init__(self): self.client = typesense.Client(TYPESENSE_CONFIG) def smart_title_case(self, name: str) -> str: words = name.split(" ") title_cased_words = []
return " ".join(title_cased_words) def clean_name(self, name: str) -> str: if name.lower().endswith(".md"): name = name[:-3] name = name.replace("_", " ").replace("-", " ").strip() return self.smart_title_case(name) def clean_markdown(self, text: str) -> str: text = re.sub(r"^---[\s\S]*?---\s*", "", text, flags=re.MULTILINE) text = re.sub(r"```[\s\S]*?```", "", text) text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) text = re.sub(r"<div[\s\S]*?</div>", "", text, flags=re.IGNORECASE) text = re.sub(r"`[^`]+`", "", text) text = re.sub(r"^#+\s*", "", text, flags=re.MULTILINE) text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text) text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL) text = re.sub(r"\n\s*\n+", "\n\n", text) return text.strip() def extract_headings(self, content: str) -> List[str]: """Extract headings from markdown content."
for word in words: if word.upper() in ACRONYMS: title_cased_words.append(word.upper()) else: title_cased_words.append(word.capitalize())
e": "docs", "fields": [ {"name": "id", "type": "string", "infix": True}, {"name": "title", "type": "string", "infix": True}, {"name": "content", "type": "string", "infix": True}, {"name": "headings", "type": "string[]"}, {"name": "components", "type": "string[]", "optional": True}, {"name": "path", "type": "string"}, {"name": "url", "type": "string"}, {"name": "section", "type": "string"}, {"name": "subsection", "type": "string", "optional": True}, {"name": "cluster", "type": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your existing logic.""" def __init__(self): self.client = typesense.Client(TYPESENSE_CONFIG) def smart_title_case(self, name: str) -> str: words = name.split(" ") title_cased_words = [] for word in words:
return " ".join(title_cased_words) def clean_name(self, name: str) -> str: if name.lower().endswith(".md"): name = name[:-3] name = name.replace("_", " ").replace("-", " ").strip() return self.smart_title_case(name) def clean_markdown(self, text: str) -> str: text = re.sub(r"^---[\s\S]*?---\s*", "", text, flags=re.MULTILINE) text = re.sub(r"```[\s\S]*?```", "", text) text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) text = re.sub(r"<div[\s\S]*?</div>", "", text, flags=re.IGNORECASE) text = re.sub(r"`[^`]+`", "", text) text = re.sub(r"^#+\s*", "", text, flags=re.MULTILINE) text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text) text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL) text = re.sub(r"\n\s*\n+", "\n\n", text) return text.strip() def extract_headings(self, content: str) -> List[str]: """Extract headings from markdown content."
if word.upper() in ACRONYMS: title_cased_words.append(word.upper()) else: title_cased_words.append(word.capitalize())
{"name": "headings", "type": "string[]"}, {"name": "components", "type": "string[]", "optional": True}, {"name": "path", "type": "string"}, {"name": "url", "type": "string"}, {"name": "section", "type": "string"}, {"name": "subsection", "type": "string", "optional": True}, {"name": "cluster", "type": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your existing logic.""" def __init__(self): self.client = typesense.Client(TYPESENSE_CONFIG) def smart_title_case(self, name: str) -> str: words = name.split(" ") title_cased_words = [] for word in words: if word.upper() in ACRONYMS: title_cased_words.append(word.upper()) else: title_cased_words.append(word.capitalize()) return " ".join(title_cased_words)
def clean_markdown(self, text: str) -> str: text = re.sub(r"^---[\s\S]*?---\s*", "", text, flags=re.MULTILINE) text = re.sub(r"```[\s\S]*?```", "", text) text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) text = re.sub(r"<div[\s\S]*?</div>", "", text, flags=re.IGNORECASE) text = re.sub(r"`[^`]+`", "", text) text = re.sub(r"^#+\s*", "", text, flags=re.MULTILINE) text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text) text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL) text = re.sub(r"\n\s*\n+", "\n\n", text) return text.strip() def extract_headings(self, content: str) -> List[str]: """Extract headings from markdown content.""" headings = [] lines = content.split("\n") for line in lines: line = line.strip() if line.startswith("#"): heading_text = re.sub(r"^#+\s*", "", line) heading_text = re.sub(r"\{[^}]*\
def clean_name(self, name: str) -> str: if name.lower().endswith(".md"): name = name[:-3] name = name.replace("_", " ").replace("-", " ").strip() return self.smart_title_case(name)
{"name": "components", "type": "string[]", "optional": True}, {"name": "path", "type": "string"}, {"name": "url", "type": "string"}, {"name": "section", "type": "string"}, {"name": "subsection", "type": "string", "optional": True}, {"name": "cluster", "type": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your existing logic.""" def __init__(self): self.client = typesense.Client(TYPESENSE_CONFIG) def smart_title_case(self, name: str) -> str: words = name.split(" ") title_cased_words = [] for word in words: if word.upper() in ACRONYMS: title_cased_words.append(word.upper()) else: title_cased_words.append(word.capitalize()) return " ".join(title_cased_words) def clean_name(self, name: str) -> str:
name = name.replace("_", " ").replace("-", " ").strip() return self.smart_title_case(name) def clean_markdown(self, text: str) -> str: text = re.sub(r"^---[\s\S]*?---\s*", "", text, flags=re.MULTILINE) text = re.sub(r"```[\s\S]*?```", "", text) text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) text = re.sub(r"<div[\s\S]*?</div>", "", text, flags=re.IGNORECASE) text = re.sub(r"`[^`]+`", "", text) text = re.sub(r"^#+\s*", "", text, flags=re.MULTILINE) text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text) text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL) text = re.sub(r"\n\s*\n+", "\n\n", text) return text.strip() def extract_headings(self, content: str) -> List[str]: """Extract headings from markdown content.""" headings = [] lines = content.split("\n") for line in lines: line = line.strip() if line.startswith("#"):
if name.lower().endswith(".md"): name = name[:-3]
[]", "optional": True}, {"name": "path", "type": "string"}, {"name": "url", "type": "string"}, {"name": "section", "type": "string"}, {"name": "subsection", "type": "string", "optional": True}, {"name": "cluster", "type": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your existing logic.""" def __init__(self): self.client = typesense.Client(TYPESENSE_CONFIG) def smart_title_case(self, name: str) -> str: words = name.split(" ") title_cased_words = [] for word in words: if word.upper() in ACRONYMS: title_cased_words.append(word.upper()) else: title_cased_words.append(word.capitalize()) return " ".join(title_cased_words) def clean_name(self, name: str) -> str: if name.lower().endswith(".md"):
name = name.replace("_", " ").replace("-", " ").strip() return self.smart_title_case(name) def clean_markdown(self, text: str) -> str: text = re.sub(r"^---[\s\S]*?---\s*", "", text, flags=re.MULTILINE) text = re.sub(r"```[\s\S]*?```", "", text) text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) text = re.sub(r"<div[\s\S]*?</div>", "", text, flags=re.IGNORECASE) text = re.sub(r"`[^`]+`", "", text) text = re.sub(r"^#+\s*", "", text, flags=re.MULTILINE) text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text) text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL) text = re.sub(r"\n\s*\n+", "\n\n", text) return text.strip() def extract_headings(self, content: str) -> List[str]: """Extract headings from markdown content.""" headings = [] lines = content.split("\n") for line in lines: line = line.strip() if line.startswith("#"):
name = name[:-3]
{"name": "path", "type": "string"}, {"name": "url", "type": "string"}, {"name": "section", "type": "string"}, {"name": "subsection", "type": "string", "optional": True}, {"name": "cluster", "type": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your existing logic.""" def __init__(self): self.client = typesense.Client(TYPESENSE_CONFIG) def smart_title_case(self, name: str) -> str: words = name.split(" ") title_cased_words = [] for word in words: if word.upper() in ACRONYMS: title_cased_words.append(word.upper()) else: title_cased_words.append(word.capitalize()) return " ".join(title_cased_words) def clean_name(self, name: str) -> str: if name.lower().endswith(".md"): name = name[:-3]
return self.smart_title_case(name) def clean_markdown(self, text: str) -> str: text = re.sub(r"^---[\s\S]*?---\s*", "", text, flags=re.MULTILINE) text = re.sub(r"```[\s\S]*?```", "", text) text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) text = re.sub(r"<div[\s\S]*?</div>", "", text, flags=re.IGNORECASE) text = re.sub(r"`[^`]+`", "", text) text = re.sub(r"^#+\s*", "", text, flags=re.MULTILINE) text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text) text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL) text = re.sub(r"\n\s*\n+", "\n\n", text) return text.strip() def extract_headings(self, content: str) -> List[str]: """Extract headings from markdown content.""" headings = [] lines = content.split("\n") for line in lines: line = line.strip() if line.startswith("#"): heading_text = re.sub(r"^#+\s*", "", line)
name = name.replace("_", " ").replace("-", " ").strip()
section", "type": "string"}, {"name": "subsection", "type": "string", "optional": True}, {"name": "cluster", "type": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your existing logic.""" def __init__(self): self.client = typesense.Client(TYPESENSE_CONFIG) def smart_title_case(self, name: str) -> str: words = name.split(" ") title_cased_words = [] for word in words: if word.upper() in ACRONYMS: title_cased_words.append(word.upper()) else: title_cased_words.append(word.capitalize()) return " ".join(title_cased_words) def clean_name(self, name: str) -> str: if name.lower().endswith(".md"): name = name[:-3] name = name.replace("_", " ").replace("-", " ").strip() return self.smart_title_case(name)
def extract_headings(self, content: str) -> List[str]: """Extract headings from markdown content.""" headings = [] lines = content.split("\n") for line in lines: line = line.strip() if line.startswith("#"): heading_text = re.sub(r"^#+\s*", "", line) heading_text = re.sub(r"\{[^}]*\}", "", heading_text) if heading_text: headings.append(heading_text.strip()) return headings def summarize_markdown(self, md_path: str, max_lines: int = 100) -> str: """Your existing summarize function - simplified.""" with open(md_path, "r", encoding="utf-8") as f: content = f.read() cleaned = self.clean_markdown(content) lines = cleaned.splitlines() truncated_lines = lines[:max_lines] truncated_text = "\n".join(truncated_lines).strip() if len(truncated_lines) < max_lines: return trunc
def clean_markdown(self, text: str) -> str: text = re.sub(r"^---[\s\S]*?---\s*", "", text, flags=re.MULTILINE) text = re.sub(r"```[\s\S]*?```", "", text) text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) text = re.sub(r"<div[\s\S]*?</div>", "", text, flags=re.IGNORECASE) text = re.sub(r"`[^`]+`", "", text) text = re.sub(r"^#+\s*", "", text, flags=re.MULTILINE) text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text) text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL) text = re.sub(r"\n\s*\n+", "\n\n", text) return text.strip()
ction", "type": "string", "optional": True}, {"name": "cluster", "type": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your existing logic.""" def __init__(self): self.client = typesense.Client(TYPESENSE_CONFIG) def smart_title_case(self, name: str) -> str: words = name.split(" ") title_cased_words = [] for word in words: if word.upper() in ACRONYMS: title_cased_words.append(word.upper()) else: title_cased_words.append(word.capitalize()) return " ".join(title_cased_words) def clean_name(self, name: str) -> str: if name.lower().endswith(".md"): name = name[:-3] name = name.replace("_", " ").replace("-", " ").strip() return self.smart_title_case(name) def clean_markdown(self, text: str) -> str:
text = re.sub(r"```[\s\S]*?```", "", text) text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) text = re.sub(r"<div[\s\S]*?</div>", "", text, flags=re.IGNORECASE) text = re.sub(r"`[^`]+`", "", text) text = re.sub(r"^#+\s*", "", text, flags=re.MULTILINE) text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text) text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL) text = re.sub(r"\n\s*\n+", "\n\n", text) return text.strip() def extract_headings(self, content: str) -> List[str]: """Extract headings from markdown content.""" headings = [] lines = content.split("\n") for line in lines: line = line.strip() if line.startswith("#"): heading_text = re.sub(r"^#+\s*", "", line) heading_text = re.sub(r"\{[^}]*\}", "", heading_text) if heading_text: headings.append(heading_text.strip()) re
text = re.sub(r"^---[\s\S]*?---\s*", "", text, flags=re.MULTILINE)
ype": "string"}, {"name": "is_blog", "type": "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your existing logic.""" def __init__(self): self.client = typesense.Client(TYPESENSE_CONFIG) def smart_title_case(self, name: str) -> str: words = name.split(" ") title_cased_words = [] for word in words: if word.upper() in ACRONYMS: title_cased_words.append(word.upper()) else: title_cased_words.append(word.capitalize()) return " ".join(title_cased_words) def clean_name(self, name: str) -> str: if name.lower().endswith(".md"): name = name[:-3] name = name.replace("_", " ").replace("-", " ").strip() return self.smart_title_case(name) def clean_markdown(self, text: str) -> str: text = re.sub(r"^---[\s\S]*?---\s*", "", text, flags=re.MULTILINE)
text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) text = re.sub(r"<div[\s\S]*?</div>", "", text, flags=re.IGNORECASE) text = re.sub(r"`[^`]+`", "", text) text = re.sub(r"^#+\s*", "", text, flags=re.MULTILINE) text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text) text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL) text = re.sub(r"\n\s*\n+", "\n\n", text) return text.strip() def extract_headings(self, content: str) -> List[str]: """Extract headings from markdown content.""" headings = [] lines = content.split("\n") for line in lines: line = line.strip() if line.startswith("#"): heading_text = re.sub(r"^#+\s*", "", line) heading_text = re.sub(r"\{[^}]*\}", "", heading_text) if heading_text: headings.append(heading_text.strip()) return headings def summarize_markdown(self, md_
text = re.sub(r"```[\s\S]*?```", "", text)
: "bool"}, {"name": "parts", "type": "string[]"}, ], } class SimpleTypesenseIndexer: """Simplified indexer using your existing logic.""" def __init__(self): self.client = typesense.Client(TYPESENSE_CONFIG) def smart_title_case(self, name: str) -> str: words = name.split(" ") title_cased_words = [] for word in words: if word.upper() in ACRONYMS: title_cased_words.append(word.upper()) else: title_cased_words.append(word.capitalize()) return " ".join(title_cased_words) def clean_name(self, name: str) -> str: if name.lower().endswith(".md"): name = name[:-3] name = name.replace("_", " ").replace("-", " ").strip() return self.smart_title_case(name) def clean_markdown(self, text: str) -> str: text = re.sub(r"^---[\s\S]*?---\s*", "", text, flags=re.MULTILINE) text = re.sub(r"```[\s\S]*?```", "", text)
text = re.sub(r"<div[\s\S]*?</div>", "", text, flags=re.IGNORECASE) text = re.sub(r"`[^`]+`", "", text) text = re.sub(r"^#+\s*", "", text, flags=re.MULTILINE) text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text) text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL) text = re.sub(r"\n\s*\n+", "\n\n", text) return text.strip() def extract_headings(self, content: str) -> List[str]: """Extract headings from markdown content.""" headings = [] lines = content.split("\n") for line in lines: line = line.strip() if line.startswith("#"): heading_text = re.sub(r"^#+\s*", "", line) heading_text = re.sub(r"\{[^}]*\}", "", heading_text) if heading_text: headings.append(heading_text.strip()) return headings def summarize_markdown(self, md_path: str, max_lines: int = 100) -> str: """Your existi
text = re.sub(r"```.*?```", "", text, flags=re.DOTALL)