vertex-engine / services /crawler.py
VADITYA307's picture
Update services/crawler.py
6d5a72d verified
Raw History Blame Contribute Delete
4.97 kB
import os
import requests
import json
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from services.ingestion import VertexIndexer
from main import nvidia_manager # Reuse your resilient NVIDIA failover pool
load_dotenv()
class VertexAICrawler:
def __init__(self):
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
self.indexer = VertexIndexer()
def fetch_raw_webpage(self, url: str) -> str:
"""Downloads HTML and extracts readable text blocks."""
try:
response = requests.get(url, headers=self.headers, timeout=15)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
# Remove scripts, style sheets, and nav components to save tokens
for element in soup(["script", "style", "nav", "footer", "header"]):
element.extract()
return soup.get_text(separator=" ", strip=True)
except Exception as e:
print(f"Crawler Network Error fetching {url}: {str(e)}")
return ""
def process_content_with_ai(self, raw_text: str, url: str) -> dict:
"""
Uses NVIDIA NIM infrastructure to assess accuracy, verify content quality,
and cleanly structure the scraped data.
"""
# Truncate raw string to fit safety context windows
sample_text = raw_text[:6000]
system_prompt = (
"You are Vertex Crawler AI, an expert data extraction engine. Your job is to analyze raw web text, "
"verify its content quality, filter out spam, and extract information into a clean JSON structure.\n\n"
"You must return response strictly as a valid JSON object matching this structure exactly:\n"
"{\n"
" \"is_valid_content\": true/false,\n"
" \"title\": \"Clear Document Title\",\n"
" \"clean_body_text\": \"Pristine text without page clutter or UI buttons\",\n"
" \"accuracy_confidence_score\": 0.95\n"
"}"
)
user_prompt = f"URL: {url}\nRaw Web Text Content:\n{sample_text}"
try:
ai_response = nvidia_manager.get_completion(
model="google/gemma-4-31b-it",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
temperature=0.1 # Low temperature for highly structured consistency
)
# Clean up potential markdown formatting wrapping the JSON string
cleaned_json = ai_response.strip()
if cleaned_json.startswith("```json"):
cleaned_json = cleaned_json.split("```json")[1].split("```")[0].strip()
elif cleaned_json.startswith("```"):
cleaned_json = cleaned_json.split("```")[1].split("```")[0].strip()
return json.loads(cleaned_json)
except Exception as e:
print(f"AI Content processing failed: {str(e)}")
return {"is_valid_content": False, "title": "Extraction Failed", "clean_body_text": "", "accuracy_confidence_score": 0.0}
def scrape_and_index(self, url: str):
"""Orchestrates fetching, AI processing, and indexing into Qdrant Cloud."""
print(f"\n[1/3] Fetching webpage raw data from: {url}")
raw_text = self.fetch_raw_webpage(url)
if not raw_text or len(raw_text.strip()) < 100:
print("πŸ›‘ Extraction cancelled: Webpage text content too short or inaccessible.")
return False
print("[2/3] Passing text to NVIDIA LLM for verification and structuring...")
structured_data = self.process_content_with_ai(raw_text, url)
# Guard clause check against low-quality data or site scraping blocks
if not structured_data.get("is_valid_content") or structured_data.get("accuracy_confidence_score", 0) < 0.6:
print(f"πŸ›‘ AI Filtered Out: Content from {url} detected as low accuracy, spam, or a captcha page.")
return False
print(f"[3/3] AI Verified (Confidence: {structured_data['accuracy_confidence_score']}). Indexing into Qdrant Cloud...")
self.indexer.index_source(
title=structured_data["title"],
raw_text=structured_data["clean_body_text"],
source_url=url
)
print(f"πŸŽ‰ Successfully ingested '{structured_data['title']}' via AI crawler loop.")
return True
if __name__ == "__main__":
crawler = VertexAICrawler()
# Test your crawler on a live, real-world educational page
target_url = "https://en.wikipedia.org/wiki/Heat"
crawler.scrape_and_index(target_url)