Spaces:
Running
Running
File size: 14,923 Bytes
6855cb4 0b7fd0d ba88389 0b7fd0d ba88389 0b7fd0d ba88389 0b7fd0d ba88389 0b7fd0d ba88389 0b7fd0d 6855cb4 0b7fd0d 6855cb4 ba88389 0b7fd0d ba88389 0b7fd0d ba88389 0b7fd0d ba88389 0b7fd0d ba88389 699fe5f 6855cb4 699fe5f 0b7fd0d 699fe5f 0b7fd0d 699fe5f 0b7fd0d 699fe5f 6855cb4 699fe5f 6855cb4 699fe5f d995ec7 ba88389 d995ec7 699fe5f 6855cb4 699fe5f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 |
# Utilities to build a RAG system to query information from the
# gwIAS search pipeline using Langchain
# Thanks to Pablo Villanueva Domingo for sharing his CAMELS template
# https://huggingface.co/spaces/PabloVD/CAMELSDocBot
from langchain import hub
from langchain_chroma import Chroma
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import WebBaseLoader, PyPDFLoader
from langchain.schema import Document
import requests
import json
import base64
from bs4 import BeautifulSoup
import re
def github_to_raw(url):
"""Convert GitHub URL to raw content URL"""
return url.replace("github.com", "raw.githubusercontent.com").replace("/blob/", "/")
def load_github_notebook(url):
"""Load Jupyter notebook from GitHub URL using GitHub API"""
try:
# Convert GitHub blob URL to API URL
if "github.com" in url and "/blob/" in url:
# Extract owner, repo, branch and path from URL
parts = url.replace("https://github.com/", "").split("/")
owner = parts[0]
repo = parts[1]
branch = parts[3] # usually 'main' or 'master'
path = "/".join(parts[4:])
api_url = f"https://api.github.com/repos/{owner}/{repo}/contents/{path}?ref={branch}"
else:
raise ValueError("URL must be a GitHub blob URL")
# Fetch notebook content
response = requests.get(api_url)
response.raise_for_status()
content_data = response.json()
if content_data.get('encoding') == 'base64':
notebook_content = base64.b64decode(content_data['content']).decode('utf-8')
else:
notebook_content = content_data['content']
# Parse notebook JSON
notebook = json.loads(notebook_content)
docs = []
cell_count = 0
# Process each cell
for cell in notebook.get('cells', []):
cell_count += 1
cell_type = cell.get('cell_type', 'unknown')
source = cell.get('source', [])
# Join source lines
if isinstance(source, list):
content = ''.join(source)
else:
content = str(source)
if content.strip(): # Only add non-empty cells
metadata = {
'source': url,
'cell_type': cell_type,
'cell_number': cell_count,
'name': f"{url} - Cell {cell_count} ({cell_type})"
}
# Add cell type prefix for better context
formatted_content = f"[{cell_type.upper()} CELL {cell_count}]\n{content}"
docs.append(Document(page_content=formatted_content, metadata=metadata))
return docs
except Exception as e:
print(f"Error loading notebook from {url}: {str(e)}")
return []
def clean_text(text):
"""Clean text content from a webpage"""
# Remove excessive newlines
text = re.sub(r'\n{3,}', '\n\n', text)
# Remove excessive whitespace
text = re.sub(r'\s{2,}', ' ', text)
return text.strip()
def clean_github_content(html_content):
"""Extract meaningful content from GitHub pages"""
# Ensure we're working with a BeautifulSoup object
if isinstance(html_content, str):
soup = BeautifulSoup(html_content, 'html.parser')
else:
soup = html_content
# Remove navigation, footer, and other boilerplate
for element in soup.find_all(['nav', 'footer', 'header']):
element.decompose()
# For README and code files
readme_content = soup.find('article', class_='markdown-body')
if readme_content:
return clean_text(readme_content.get_text())
# For code files
code_content = soup.find('table', class_='highlight')
if code_content:
return clean_text(code_content.get_text())
# For directory listings
file_list = soup.find('div', role='grid')
if file_list:
return clean_text(file_list.get_text())
# Fallback to main content
main_content = soup.find('main')
if main_content:
return clean_text(main_content.get_text())
# If no specific content found, get text from body
body = soup.find('body')
if body:
return clean_text(body.get_text())
# Final fallback
return clean_text(soup.get_text())
class GitHubLoader(WebBaseLoader):
"""Custom loader for GitHub pages with better content cleaning"""
def clean_text(self, text):
"""Clean text content"""
# Remove excessive newlines and spaces
text = re.sub(r'\n{2,}', '\n', text)
text = re.sub(r'\s{2,}', ' ', text)
# Remove common GitHub boilerplate
text = re.sub(r'Skip to content|Sign in|Search or jump to|Footer navigation|Terms|Privacy|Security|Status|Docs', '', text)
return text.strip()
def _scrape(self, url: str, *args, **kwargs) -> str:
response = requests.get(url)
response.raise_for_status()
# For directory listings (tree URLs), use the API
if '/tree/' in url:
parts = url.replace("https://github.com/", "").split("/")
owner = parts[0]
repo = parts[1]
branch = parts[3] # usually 'main' or 'master'
path = "/".join(parts[4:]) if len(parts) > 4 else ""
api_url = f"https://api.github.com/repos/{owner}/{repo}/contents/{path}?ref={branch}"
api_response = requests.get(api_url)
api_response.raise_for_status()
contents = api_response.json()
if isinstance(contents, list):
files = [f"{item['name']} ({item['type']})" for item in contents]
return "Directory contents:\n" + "\n".join(files)
else:
return f"Error: Unexpected API response for {url}"
soup = BeautifulSoup(response.text, 'html.parser')
# For README and markdown files
readme_content = soup.find('article', class_='markdown-body')
if readme_content and hasattr(readme_content, 'get_text'):
return self.clean_text(readme_content.get_text())
# For code files
code_content = soup.find('table', class_='highlight')
if code_content and hasattr(code_content, 'get_text'):
return self.clean_text(code_content.get_text())
# For other content, get main content
main_content = soup.find('main')
if main_content and hasattr(main_content, 'get_text'):
return self.clean_text(main_content.get_text())
# Final fallback: get all text from soup
if hasattr(soup, 'get_text'):
return self.clean_text(soup.get_text())
else:
return self.clean_text(str(soup))
def load(self):
docs = []
for url in self.web_paths:
text = self._scrape(url)
docs.append(Document(page_content=text, metadata={"source": url}))
return docs
class RawContentLoader(WebBaseLoader):
"""Loader for raw content from GitHub (Python files, etc.)"""
def _scrape(self, url: str, *args, **kwargs) -> str:
response = requests.get(url)
response.raise_for_status()
return response.text
def load(self):
docs = []
for url in self.web_paths:
text = self._scrape(url)
docs.append(Document(page_content=text, metadata={"source": url}))
return docs
# Load documentation from urls
def load_docs():
# Get urls
urlsfile = open("urls.txt")
urls = urlsfile.readlines()
urls = [url.replace("\n","") for url in urls if not url.strip().startswith("#") and url.strip()]
urlsfile.close()
# Load documents from URLs
docs = []
for url in urls:
url = url.strip()
if not url:
continue
# Handle PDF files
if url.endswith('.pdf'):
print(f"Loading PDF: {url}")
try:
loader = PyPDFLoader(url)
pdf_docs = loader.load()
for doc in pdf_docs:
doc.metadata['source'] = url
docs.extend(pdf_docs)
except Exception as e:
print(f"Error loading PDF {url}: {str(e)}")
# Check if URL is a Jupyter notebook
elif url.endswith('.ipynb') and 'github.com' in url and '/blob/' in url:
print(f"Loading notebook: {url}")
notebook_docs = load_github_notebook(url)
docs.extend(notebook_docs)
# Handle raw content URLs (already in raw.githubusercontent.com format)
elif 'raw.githubusercontent.com' in url:
print(f"Loading raw content: {url}")
try:
loader = RawContentLoader([url])
web_docs = loader.load()
# Preserve original URL in metadata
for doc in web_docs:
doc.metadata['source'] = url
docs.extend(web_docs)
except Exception as e:
print(f"Error loading {url}: {str(e)}")
# Handle Python and Markdown files using raw content (convert from blob to raw)
elif url.endswith(('.py', '.md')) and 'github.com' in url and '/blob/' in url:
print(f"Loading raw content: {url}")
try:
raw_url = github_to_raw(url)
loader = RawContentLoader([raw_url])
web_docs = loader.load()
# Preserve original URL in metadata
for doc in web_docs:
doc.metadata['source'] = url
docs.extend(web_docs)
except Exception as e:
print(f"Error loading {url}: {str(e)}")
# Handle directory listings
elif '/tree/' in url and 'github.com' in url:
print(f"Loading directory: {url}")
try:
# Parse URL components
parts = url.replace("https://github.com/", "").split("/")
owner = parts[0]
repo = parts[1]
branch = parts[3] # usually 'main' or 'master'
path = "/".join(parts[4:]) if len(parts) > 4 else ""
# Construct API URL
api_url = f"https://api.github.com/repos/{owner}/{repo}/contents/{path}?ref={branch}"
response = requests.get(api_url)
response.raise_for_status()
# Parse directory listing
contents = response.json()
if isinstance(contents, list):
# Format directory contents
content = "Directory contents:\n" + "\n".join([f"{item['name']} ({item['type']})" for item in contents])
docs.append(Document(page_content=content, metadata={'source': url}))
else:
print(f"Error: Unexpected API response for {url}")
except Exception as e:
print(f"Error loading directory {url}: {str(e)}")
else:
print(f"Loading web page: {url}")
try:
loader = GitHubLoader([url]) # Use custom loader
web_docs = loader.load()
docs.extend(web_docs)
except Exception as e:
print(f"Error loading {url}: {str(e)}")
# Add source URLs as document names for reference
for i, doc in enumerate(docs):
if 'source' in doc.metadata:
doc.metadata['name'] = doc.metadata['source']
else:
doc.metadata['name'] = f"Document {i+1}"
print(f"Loaded {len(docs)} documents:")
for doc in docs:
print(f" - {doc.metadata.get('name')}")
return docs
def extract_reference(url):
"""Extract a reference keyword from the URL for display in citations."""
# Handle GitHub blob URLs
if "blob/main" in url:
return url.split("blob/main/")[-1]
# Handle GitHub tree URLs
elif "tree/main" in url:
return url.split("tree/main/")[-1] or "root"
# Handle raw.githubusercontent.com URLs
elif "raw.githubusercontent.com" in url:
# Example: https://raw.githubusercontent.com/user/repo/branch/path/to/file.py
parts = url.split("raw.githubusercontent.com/")[-1].split("/")
if len(parts) > 3:
# Remove user, repo, branch
return "/".join(parts[3:])
else:
return url
# For arXiv PDFs and other URLs, just use the filename
elif url.endswith('.pdf') or url.endswith('.ipynb') or url.endswith('.py') or url.endswith('.md'):
return url.split("/")[-1]
return url
# Join content pages for processing
def format_docs(docs):
formatted_docs = []
for doc in docs:
source = doc.metadata.get('source', 'Unknown source')
reference = f"[{extract_reference(source)}]"
content = doc.page_content
formatted_docs.append(f"{content}\n\nReference: {reference}")
return "\n\n---\n\n".join(formatted_docs)
# Create a RAG chain
def RAG(llm, docs, embeddings):
# Split text
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
splits = text_splitter.split_documents(docs)
# Create vector store
vectorstore = Chroma.from_documents(documents=splits, embedding=embeddings)
# Retrieve and generate using the relevant snippets of the documents
retriever = vectorstore.as_retriever()
# Prompt basis example for RAG systems
prompt = hub.pull("rlm/rag-prompt")
# Adding custom instructions to the prompt
template = prompt.messages[0].prompt.template
template_parts = template.split("\nQuestion: {question}")
combined_template = "You are an assistant for question-answering tasks. "\
+ "Use the following pieces of retrieved context to answer the question. "\
+ "If you don't know the answer, just say that you don't know. "\
+ "Try to keep the answer concise if possible. "\
+ "Write the names of the relevant functions from the retrived code and include code snippets to aid the user's understanding. "\
+ "Include the references used in square brackets at the end of your answer."\
+ template_parts[1]
prompt.messages[0].prompt.template = combined_template
# Create the chain
rag_chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
return rag_chain |