Spaces:
Running
Running
File size: 6,440 Bytes
6e812cd 0beed35 c5936cd 0beed35 c5936cd bb4f66e 0beed35 c5936cd 0beed35 c5936cd 0beed35 ab0189e c5936cd 0a4996a c5936cd 6b3c370 c5936cd 0a4996a c5936cd 6e812cd c5936cd 8d18428 6e812cd 0a4996a 6e812cd 8d18428 0beed35 6e812cd 8d18428 c5936cd d884ff4 3caae59 c5936cd 3caae59 c5936cd d884ff4 c5936cd 0beed35 c5936cd 0beed35 c5936cd ab0189e c5936cd 0beed35 8d18428 0beed35 8d18428 0beed35 587a001 0beed35 587a001 c5936cd cf437f7 0beed35 c5936cd 587a001 d94b965 03b98ec 587a001 c5936cd cb1b91f cf437f7 c5936cd 587a001 c5936cd 587a001 61f90d6 587a001 c5936cd 587a001 61f90d6 587a001 61f90d6 cb1b91f cf437f7 c5936cd cc59a7b c5936cd 0673283 c5936cd cf437f7 0beed35 cc59a7b 0beed35 cf437f7 |
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 |
import subprocess
from pathlib import Path
from typing import List, Tuple
import streamlit as st
from dotenv import load_dotenv
from haystack.components.builders import AnswerBuilder, PromptBuilder
from haystack.components.converters import TextFileToDocument
from haystack.components.generators.openai import OpenAIGenerator
from haystack.components.preprocessors import (
DocumentCleaner,
DocumentSplitter,
)
from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
from haystack.components.writers import DocumentWriter
from haystack.core.pipeline import Pipeline
from haystack.dataclasses import GeneratedAnswer
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack.document_stores.types import DuplicatePolicy
# Load the environment variables, we're going to need it for OpenAI
load_dotenv()
# This is the list of documentation that we're going to fetch
DOCUMENTATIONS = [
(
"DocArray",
"https://github.com/docarray/docarray",
"./docs/**/*.md",
),
(
"Streamlit",
"https://github.com/streamlit/docs",
"./content/**/*.md",
),
(
"Jinja",
"https://github.com/pallets/jinja",
"./docs/**/*.rst",
),
(
"Pandas",
"https://github.com/pandas-dev/pandas",
"./doc/source/**/*.rst",
),
(
"Elasticsearch",
"https://github.com/elastic/elasticsearch",
"./docs/**/*.asciidoc",
),
(
"NumPy",
"https://github.com/numpy/numpy",
"./doc/**/*.rst",
),
]
DOCS_PATH = Path(__file__).parent / "downloaded_docs"
@st.cache_data(show_spinner=False)
def fetch(documentations: List[Tuple[str, str, str]]):
files = []
# Create the docs path if it doesn't exist
DOCS_PATH.mkdir(parents=True, exist_ok=True)
for name, url, pattern in documentations:
st.write(f"Fetching {name} repository")
repo = DOCS_PATH / name
# Attempt cloning only if it doesn't exist
if not repo.exists():
subprocess.run(["git", "clone", "--depth", "1", url, str(repo)], check=True)
res = subprocess.run(
["git", "rev-parse", "--abbrev-ref", "HEAD"],
check=True,
capture_output=True,
encoding="utf-8",
cwd=repo,
)
branch = res.stdout.strip()
for p in repo.glob(pattern):
data = {
"path": p,
"meta": {
"url_source": f"{url}/tree/{branch}/{p.relative_to(repo)}",
"suffix": p.suffix,
},
}
files.append(data)
return files
@st.cache_resource(show_spinner=False)
def document_store(index: str = "documentation"):
# We're going to store the processed documents in here
return InMemoryDocumentStore(index=index)
@st.cache_resource(show_spinner=False)
def index_files(files):
# We create some components
text_converter = TextFileToDocument()
document_cleaner = DocumentCleaner()
document_splitter = DocumentSplitter()
document_writer = DocumentWriter(
document_store=document_store(), policy=DuplicatePolicy.OVERWRITE
)
# And our pipeline
indexing_pipeline = Pipeline()
indexing_pipeline.add_component("converter", text_converter)
indexing_pipeline.add_component("cleaner", document_cleaner)
indexing_pipeline.add_component("splitter", document_splitter)
indexing_pipeline.add_component("writer", document_writer)
indexing_pipeline.connect("converter", "cleaner")
indexing_pipeline.connect("cleaner", "splitter")
indexing_pipeline.connect("splitter", "writer")
# And now we save the documentation in our InMemoryDocumentStore
paths = []
meta = []
for f in files:
paths.append(f["path"])
meta.append(f["meta"])
indexing_pipeline.run(
{
"converter": {
"sources": paths,
"meta": meta,
}
}
)
def search(question: str) -> GeneratedAnswer:
retriever = InMemoryBM25Retriever(document_store=document_store(), top_k=5)
template = (
"Using the information contained in the context, give a comprehensive answer to the question."
"If the answer cannot be deduced from the context, do not give an answer."
"Context: {{ documents|map(attribute='content')|join(';')|replace('\n', ' ') }}"
"Question: {{ query }}"
"Answer:"
)
prompt_builder = PromptBuilder(template)
generator = OpenAIGenerator(model="gpt-4o")
answer_builder = AnswerBuilder()
query_pipeline = Pipeline()
query_pipeline.add_component("docs_retriever", retriever)
query_pipeline.add_component("prompt_builder", prompt_builder)
query_pipeline.add_component("llm", generator)
query_pipeline.add_component("answer_builder", answer_builder)
query_pipeline.connect("docs_retriever.documents", "prompt_builder.documents")
query_pipeline.connect("prompt_builder.prompt", "llm.prompt")
query_pipeline.connect("docs_retriever.documents", "answer_builder.documents")
query_pipeline.connect("llm.replies", "answer_builder.replies")
res = query_pipeline.run({"query": question})
return res["answer_builder"]["answers"][0]
with st.status(
"Downloading documentation files...",
expanded=st.session_state.get("expanded", True),
) as status:
files = fetch(DOCUMENTATIONS)
status.update(label="Indexing documentation...")
index_files(files)
status.update(
label="Download and indexing complete!", state="complete", expanded=False
)
st.session_state["expanded"] = False
st.header("π Documentation finder", divider="rainbow")
st.caption(
f"Use this to search answers for {', '.join([d[0] for d in DOCUMENTATIONS])}"
)
if question := st.text_input(
label="What do you need to know?", placeholder="What is a DataFrame?"
):
with st.spinner("Waiting"):
answer = search(question)
if not st.session_state.get("run_once", False):
st.balloons()
st.session_state["run_once"] = True
st.markdown(answer.data)
with st.expander("See sources:"):
for document in answer.documents:
url_source = document.meta.get("url_source", "")
st.write(url_source)
st.text(document.content)
st.divider()
|