import gradio as gr import pandas as pd import json from langchain.document_loaders import DataFrameLoader from langchain.text_splitter import CharacterTextSplitter from langchain.llms import HuggingFaceHub from langchain.embeddings import HuggingFaceEmbeddings from langchain.vectorstores import Chroma from langchain.chains import RetrievalQA from trafilatura import fetch_url, extract from trafilatura.spider import focused_crawler from trafilatura.settings import use_config def loading_website(): return "Loading..." def url_changes(url, pages_to_visit, urls_to_scrape, repo_id): to_visit, links = focused_crawler(url, max_seen_urls=pages_to_visit, max_known_urls=urls_to_scrape) print(f"{len(links)} to be crawled") config = use_config() config.set("DEFAULT", "EXTRACTION_TIMEOUT", "0") results_df = pd.DataFrame() for url in links: downloaded = fetch_url(url) if downloaded: result = extract(downloaded, output_format='json', config=config) result = json.loads(result) results_df = pd.concat([results_df, pd.DataFrame.from_records([result])]) loader = DataFrameLoader(results_df, page_content_column="text") documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=200) texts = text_splitter.split_documents(documents) emb_model = "snunlp/KR-SBERT-V40K-klueNLI-augSTS" embeddings = HuggingFaceEmbeddings( model_name=emb_model ) db = Chroma.from_documents(texts, embeddings) retriever = db.as_retriever() llm = HuggingFaceHub(repo_id=repo_id, model_kwargs={"temperature":0.1, "max_new_tokens":250}) global qa qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever, return_source_documents=True) return "Ready" def add_text(history, text): history = history + [(text, None)] return history, "" def bot(history): response = infer(history[-1][0]) history[-1][1] = response['result'] return history def infer(question): query = question result = qa({"query": query}) return result css=""" #col-container {max-width: 700px; margin-left: auto; margin-right: auto;} """ title = """
Enter target URL, click the "Load website to LangChain" button