Scraping websites contents and retrieve data via prompting experience
Recently I was testing out the real scenarios of how to minic ChatGPT experience to provide myself similar experience to retrieve info based on my own data source.
I started to scrape some websites via python libs, e.g. bs4 and create bunch of pdf files which maps to each of the sub pages of the websites.
import requests
from bs4 import BeautifulSoup
from pyhtml2pdf import converter
url = 'https://xxxx'
baseurl = 'https://yyy'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.find_all('a', href=True))
external_links = []
for link in soup.find_all('a', href=True):
if link['href'].startswith('/'):
print(baseurl+link['href'])
print(link['href'].replace("/", "-") + ".pdf")
filename = link['href'].replace("/", "-") + ".pdf"
converter.convert(baseurl+link['href'], filename)
external_links.append(baseurl+link['href'])
response_sub = requests.get(baseurl+link['href'])
soup_sub = BeautifulSoup(response_sub.text, 'html.parser')
for link_sub in soup_sub.find_all('a', href=True):
if link_sub['href'].startswith('/path1*'):
print(baseurl+link_sub['href'])
print(link_sub['href'].replace("/", "-") + ".pdf")
filename_sub = link_sub['href'].replace("/", "-") + ".pdf"
converter.convert(baseurl+link_sub['href'], filename_sub)
external_links.append(baseurl+link_sub['href'])
# this is based on your site structures
print(external_links)
Easily to import the pdf contents into my ChatGPT retrieve data folder to ask questions
Below is an example of how i use the python Openai Libs to allow myself use prompting to retrieve answers
import os
import sys
import openai
from langchain.chains import ConversationalRetrievalChain, RetrievalQA
from langchain.chat_models import ChatOpenAI
from langchain.document_loaders import DirectoryLoader, TextLoader
from langchain.embeddings import OpenAIEmbeddings
from langchain.indexes import VectorstoreIndexCreator
from langchain.indexes.vectorstore import VectorStoreIndexWrapper
from langchain.llms import OpenAI
from langchain.vectorstores import Chroma
import constants
os.environ["OPENAI_API_KEY"] = constants.APIKEY
# Enable to save to disk & reuse the model (for repeated queries on the same data)
PERSIST = False
query = None
if len(sys.argv) > 1:
query = sys.argv[1]
if PERSIST and os.path.exists("persist"):
print("Reusing index...\n")
vectorstore = Chroma(persist_directory="persist", embedding_function=OpenAIEmbeddings())
index = VectorStoreIndexWrapper(vectorstore=vectorstore)
else:
#loader = TextLoader("data/data.txt") # Use this line if you only need data.txt
loader = DirectoryLoader("data/")
if PERSIST:
index = VectorstoreIndexCreator(vectorstore_kwargs={"persist_directory":"persist"}).from_loaders([loader])
else:
index = VectorstoreIndexCreator().from_loaders([loader])
chain = ConversationalRetrievalChain.from_llm(
llm=ChatOpenAI(model="gpt-3.5-turbo"),
retriever=index.vectorstore.as_retriever(search_kwargs={"k": 1}),
)
chat_history = []
while True:
if not query:
query = input("Prompt: ")
if query in ['quit', 'q', 'exit']:
sys.exit()
result = chain({"question": query, "chat_history": chat_history})
print(result['answer'])
chat_history.append((query, result['answer']))
query = None
Data Source, Q&A


Comments
Post a Comment