Analyze some sample web pages from www.statcan.gc.ca, such as the Daily pages, the IMDB pages, the NDM products page, the Census pages, use wget to download those pages into a folder in the local file system (the environment is cloud ubuntu linux vm with 64g of ram and 500g of space in the /mnt/ path) and use python codes to parse the saved files as sample pages for the html page, the pdf page, and the tables page, and use python codes to process them and index them into elasticsearch embeddings for AI RAG search that accept natural language queries such as "what is the population of Ottawa in 2025 and what is the estimate of population for Ottawa area in 2026". The fields information to put to the embeddings include the title, the description, the subject, the release date, the keywords (most of the information comes from the meta data section of the html page, such as dcterms, if not, try to get it from the body or contents part of the page ), the body content part which is properly chunked using different strategies such as the tags p, h1, h2, h3, list, div, table, tr, span etc, and if there is no such tags there use paragraphs with carriage returns to chunk them or use sentence boundary punctuations. The best chunks should be between 180 to 500 characters long except for those that cannot be chunked properly, use the 400 character chunk strategy. The python codes should be able to search the embeddings index, and give the response results in natural language, and also give reference to the source url, title, description, release_date. The response and results should be based only on the statcan contents, not the general answers from the llm. The llm used for inference and response should be open source llm easily downloadable without a key or access token, or passwords. In setting up the elasticsearch, try to make it not using the authentication, i.e. without a password to use it. Give me the scripts for the set up of the virtual environment for python, the requirements.txt file, the wget script file, the python codes where the open source llm is used, and also how to download and setup elasticsearch and the llm.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
#!/bin/bash
# Create directory for models
mkdir -p /mnt/models
# Download Llama 2 7B Chat model (quantized version for efficiency)
cd /mnt/models
git lfs install
git clone https://huggingface.co/microsoft/DialoGPT-medium
echo "LLM model downloaded to /mnt/models/"
5. Main Processing Script (statcan_processor.py)
python
import os
import re
import json
import requests
from pathlib import Path
from datetime import datetime
from typing import List, Dict, Any
from urllib.parse import urljoin, urlparse
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
from elasticsearch import Elasticsearch
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
import torch
class StatCanProcessor:
def __init__(self, data_dir="/mnt/statcan_data", es_host="localhost:9200"):
self.data_dir = Path(data_dir)
self.es = Elasticsearch([f"http://{es_host}"])
self.embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
self.index_name = "statcan_content"
# Setup LLM
self.setup_llm()
# Create ES index
self.create_index()
def setup_llm(self):
"""Setup the open source LLM"""
model_path = "/mnt/models/microsoft/DialoGPT-medium"
self.tokenizer = AutoTokenizer.from_pretrained(model_path)
self.model = AutoModelForCausalLM.from_pretrained(
model_path,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
device_map="auto" if torch.cuda.is_available() else None
)
# Add pad token if it doesn't exist
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
def create_index(self):
"""Create Elasticsearch index with proper mapping"""
mapping = {
"mappings": {
"properties": {
"title": {"type": "text", "analyzer": "english"},
"description": {"type": "text", "analyzer": "english"},
"subject": {"type": "text", "analyzer": "english"},
"keywords": {"type": "text", "analyzer": "english"},
"release_date": {"type": "date"},
"url": {"type": "keyword"},
"content_chunk": {"type": "text", "analyzer": "english"},
"chunk_index": {"type": "integer"},
"content_type": {"type": "keyword"},
"embedding": {
"type": "dense_vector",
"dims": 384 # all-MiniLM-L6-v2 dimension
}
}
}
}
if self.es.indices.exists(index=self.index_name):
self.es.indices.delete(index=self.index_name)
self.es.indices.create(index=self.index_name, body=mapping)
print(f"Created index: {self.index_name}")
def extract_metadata(self, soup: BeautifulSoup, url: str) -> Dict[str, Any]:
"""Extract metadata from HTML"""
metadata = {
"title": "",
"description": "",
"subject": "",
"keywords": "",
"release_date": None,
"url": url
}
# Extract title
title_tag = soup.find('title')
if title_tag:
metadata["title"] = title_tag.get_text().strip()
# Extract meta tags
meta_tags = soup.find_all('meta')
for tag in meta_tags:
name = tag.get('name', '').lower()
property_attr = tag.get('property', '').lower()
content = tag.get('content', '')
if name in ['description', 'dc.description', 'dcterms.description']:
metadata["description"] = content
elif name in ['keywords', 'dc.subject', 'dcterms.subject']:
metadata["keywords"] = content
elif name in ['subject', 'dc.title', 'dcterms.title']:
metadata["subject"] = content
elif name in ['dc.date', 'dcterms.date', 'dcterms.created', 'dcterms.modified']:
metadata["release_date"] = self.parse_date(content)
elif property_attr in ['article:published_time', 'article:modified_time']:
metadata["release_date"] = self.parse_date(content)
# Try to extract date from content if not found in meta
if not metadata["release_date"]:
date_patterns = [
r'Released:\s*(\d{4}-\d{2}-\d{2})',
r'Date:\s*(\d{4}-\d{2}-\d{2})',
r'(\d{4}-\d{2}-\d{2})',
r'(\w+ \d{1,2}, \d{4})'
]
text_content = soup.get_text()
for pattern in date_patterns:
match = re.search(pattern, text_content)
if match:
metadata["release_date"] = self.parse_date(match.group(1))
break
return metadata
def parse_date(self, date_str: str) -> str:
"""Parse various date formats"""
if not date_str:
return None
try:
# Try ISO format first
if re.match(r'\d{4}-\d{2}-\d{2}', date_str):
return date_str
# Try other formats
from dateutil import parser
parsed_date = parser.parse(date_str)
return parsed_date.strftime('%Y-%m-%d')
except:
return None
def chunk_content(self, text: str, target_size: int = 400) -> List[str]:
"""Chunk content into optimal sizes"""
if len(text) <= target_size:
return [text]
chunks = []
# Split by paragraphs first
paragraphs = text.split('\n\n')
current_chunk = ""
for paragraph in paragraphs:
paragraph = paragraph.strip()
if not paragraph:
continue
# If paragraph is too long, split by sentences
if len(paragraph) > target_size:
sentences = re.split(r'[.!?]+', paragraph)
for sentence in sentences:
sentence = sentence.strip()
if not sentence:
continue
if len(current_chunk) + len(sentence) + 1 <= target_size:
current_chunk += sentence + ". "
else:
if current_chunk:
chunks.append(current_chunk.strip())
current_chunk = sentence + ". "
else:
if len(current_chunk) + len(paragraph) + 2 <= target_size:
current_chunk += paragraph + "\n\n"
else:
if current_chunk:
chunks.append(current_chunk.strip())
current_chunk = paragraph + "\n\n"
if current_chunk:
chunks.append(current_chunk.strip())
# Filter out very short chunks
chunks = [chunk for chunk in chunks if len(chunk) >= 50]
return chunks
def extract_content(self, soup: BeautifulSoup) -> str:
"""Extract main content from HTML"""
# Remove script and style elements
for script in soup(["script", "style", "nav", "header", "footer"]):
script.decompose()
# Try to find main content areas
main_content = ""
# Look for main content containers
content_selectors = [
'main', 'article', '.content', '#content', '.main-content',
'.page-content', '.entry-content', '.post-content'
]
for selector in content_selectors:
content_div = soup.select_one(selector)
if content_div:
main_content = content_div.get_text(separator='\n\n')
break
# If no main content found, use body
if not main_content:
body = soup.find('body')
if body:
main_content = body.get_text(separator='\n\n')
# Clean up the text
main_content = re.sub(r'\n\s*\n', '\n\n', main_content)
main_content = re.sub(r'[ \t]+', ' ', main_content)
return main_content.strip()
def process_html_file(self, file_path: Path):
"""Process a single HTML file"""
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
soup = BeautifulSoup(content, 'html.parser')
# Generate URL from file path
relative_path = file_path.relative_to(self.data_dir)
url = f"https://www.statcan.gc.ca/{relative_path}"
# Extract metadata
metadata = self.extract_metadata(soup, url)
# Extract content
main_content = self.extract_content(soup)
if not main_content or len(main_content) < 100:
return
# Chunk content
chunks = self.chunk_content(main_content)
# Index each chunk
for i, chunk in enumerate(chunks):
doc = {
**metadata,
"content_chunk": chunk,
"chunk_index": i,
"content_type": "html",
"embedding": self.embedding_model.encode(chunk).tolist()
}
self.es.index(index=self.index_name, body=doc)
print(f"Processed: {file_path} ({len(chunks)} chunks)")
except Exception as e:
print(f"Error processing {file_path}: {e}")
def process_all_files(self):
"""Process all HTML files in the data directory"""
html_files = list(self.data_dir.rglob("*.html"))
print(f"Found {len(html_files)} HTML files to process")
for file_path in html_files:
self.process_html_file(file_path)
print("Processing complete!")
def search(self, query: str, top_k: int = 5) -> List[Dict]:
"""Search the index using semantic similarity"""
query_embedding = self.embedding_model.encode(query).tolist()
search_body = {
"query": {
"script_score": {
"query": {"match_all": {}},
"script": {
"source": "cosineSimilarity(params.query_vector, 'embedding') + 1.0",
"params": {"query_vector": query_embedding}
}
}
},
"size": top_k,
"_source": ["title", "description", "url", "content_chunk", "release_date", "subject"]
}
response = self.es.search(index=self.index_name, body=search_body)
results = []
for hit in response['hits']['hits']: