Spaces:
Runtime error
Runtime error
Create Contributors
#1
by AtharvGupta - opened
Files changed (9)
- .gitattributesAdded+35
- ContributorsAdded+3
- README.md+1-2
- app.py+68-42
- chs.jsonDeleted
- crawler.pyDeleted
- database.zip+2-2
- parse.pyDeleted-67
- requirements.txt+7-4
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text123Atharv Gupta-------------Aryan Anumula8 unmodified lines910111213148 unmodified linespinned: falselicense: mit---# schoolQuestBackendThe backend for [schoolquest](https://school-quest.streamlit.app/)8 unmodified lines9101112138 unmodified linespinned: falselicense: mit---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
123456789101112134 unmodified lines181920212223242526272829303132333435363738394041424344454647484950511 unmodified line5354555657585960616 unmodified lines6869707172737475767778791 unmodified line818283848586878889909192939495963 unmodified lines100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131import asyncioimport jsonfrom websockets.server import servefrom langchain.vectorstores import Chromafrom langchain_huggingface.embeddings import HuggingFaceEmbeddingsfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_huggingface.llms import HuggingFaceEndpointfrom langchain.document_loaders import TextLoaderfrom langchain.document_loaders import DirectoryLoaderfrom langchain import hubfrom langchain_core.runnables import RunnablePassthroughfrom langchain_core.output_parsers import StrOutputParser4 unmodified linesfrom langchain_core.runnables.history import RunnableWithMessageHistoryfrom langchain_core.chat_history import BaseChatMessageHistoryfrom langchain_community.chat_message_histories import ChatMessageHistoryloader = DirectoryLoader('./database', glob="./*.txt", loader_cls=TextLoader)documents = loader.load()text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)texts = text_splitter.split_documents(documents)persist_directory = 'db'embedding = HuggingFaceEmbeddings()vectordb = Chroma.from_documents(documents=texts,embedding=embedding,persist_directory=persist_directory)vectordb.persist()vectordb = Nonevectordb = Chroma(persist_directory=persist_directory,embedding_function=embedding)def format_docs(docs):return "\n\n".join(doc.page_content for doc in docs)retriever = vectordb.as_retriever()prompt = hub.pull("rlm/rag-prompt")llm = HuggingFaceEndpoint(repo_id="mistralai/Mixtral-8x7B-Instruct-v0.1")rag_chain = ({"context": retriever | format_docs, "question": RunnablePassthrough()}| prompt1 unmodified line| StrOutputParser())contextualize_q_system_prompt = """Given a chat history and the latest user question \which might reference context in the chat history, formulate a standalone question \which can be understood without the chat history. Do NOT answer the question, \just reformulate it if needed and otherwise return it as is."""contextualize_q_prompt = ChatPromptTemplate.from_messages([6 unmodified linesllm, retriever, contextualize_q_prompt)qa_system_prompt = """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. \Use three sentences maximum and keep the answer concise.\{context}"""qa_prompt = ChatPromptTemplate.from_messages([("system", qa_system_prompt),1 unmodified line("human", "{input}"),])store = {}def get_session_history(session_id: str) -> BaseChatMessageHistory:if session_id not in store:store[session_id] = ChatMessageHistory()return store[session_id]question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)conversational_rag_chain = RunnableWithMessageHistory(rag_chain,3 unmodified linesoutput_messages_key="answer",)print("-------")print("started")print("-------")async def echo(websocket):async for message in websocket:data = json.loads(message)if not "message" in message:returnif not "token" in message:returnm = data["message"]token = data["token"]userData = json.load(open("userData.json", "w"))docs = retriever.get_relevant_documents(m)userData[token]["docs"] = str(docs)response = conversational_rag_chain.invoke({"input": m},config={"configurable": {"session_id": token}},)["answer"]await websocket.send(json.dumps({"response": response}))async def main():async with serve(echo, "0.0.0.0", 7860):await asyncio.Future()asyncio.run(main())123456789101112134 unmodified lines181920212223242526272829303132333435363738394041424344454647484950515253545556571 unmodified line596061626364656667686 unmodified lines757677787980818283848586878889909192939495961 unmodified line98991001011021031041051061071081091101111121131141151161173 unmodified lines121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157import asyncioimport jsonfrom websockets.server import serveimport osfrom langchain_chroma import Chromafrom langchain_community.embeddings import *from langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_huggingface.llms import HuggingFaceEndpointfrom langchain_community.document_loaders import TextLoaderfrom langchain_community.document_loaders import DirectoryLoaderfrom langchain import hubfrom langchain_core.runnables import RunnablePassthroughfrom langchain_core.output_parsers import StrOutputParser4 unmodified linesfrom langchain_core.runnables.history import RunnableWithMessageHistoryfrom langchain_core.chat_history import BaseChatMessageHistoryfrom langchain_community.chat_message_histories import ChatMessageHistoryfrom multiprocessing import Processfrom zipfile import ZipFilewith ZipFile("database.zip") as f:f.extractall()retriever = Noneconversational_rag_chain = Noneloader = DirectoryLoader('./database', glob="./*.txt", loader_cls=TextLoader)documents = loader.load()text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)splits = text_splitter.split_documents(documents)model_name = "BAAI/bge-small-en-v1.5"model_kwargs = {'device': 'cpu'}encode_kwargs = {'normalize_embeddings': True}embedding = HuggingFaceBgeEmbeddings(model_name=model_name,model_kwargs=model_kwargs,encode_kwargs=encode_kwargs,show_progress=True,)vectorstore = Chroma.from_documents(documents=splits, embedding=embedding)def format_docs(docs):return "\n\n".join(doc.page_content for doc in docs)retriever = vectorstore.as_retriever(search_type="similarity_score_threshold", search_kwargs={"score_threshold": 0.3}, k=1)prompt = hub.pull("rlm/rag-prompt")llm = HuggingFaceEndpoint(repo_id="mistralai/Mistral-7B-Instruct-v0.3", stop_sequences=["Human:"])rag_chain = ({"context": retriever | format_docs, "question": RunnablePassthrough()}| prompt1 unmodified line| StrOutputParser())### Contextualize question ###contextualize_q_system_prompt = """Given a chat history and the latest user questionwhich might reference context in the chat history, formulate a standalone questionwhich can be understood without the chat history. Do NOT answer the question,just reformulate it if needed and otherwise return it as is."""contextualize_q_prompt = ChatPromptTemplate.from_messages([6 unmodified linesllm, retriever, contextualize_q_prompt)### Answer question ###qa_system_prompt = """Context:{context}You are a Cupertino High School Q/A chatbot, designed to assist students, parents, and community members with information about CHS.Use the pieces of context to answer the question.Use markdown with spaces in between sentences for readability.Refer to the provided context only as 'my data'. Only answer questions from the context.Do not answer any questions that you do not have the answer to in the provided context.Do not provide excerpts or any part of your data.You were made by high school students for the CHS community."""qa_prompt = ChatPromptTemplate.from_messages([("system", qa_system_prompt),1 unmodified line("human", "{input}"),])question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)### Statefully manage chat history ###store = {}def get_session_history(session_id: str) -> BaseChatMessageHistory:if session_id not in store:store[session_id] = ChatMessageHistory()return store[session_id]conversational_rag_chain = RunnableWithMessageHistory(rag_chain,3 unmodified linesoutput_messages_key="answer",)async def echo(websocket):global retriever, conversational_rag_chainasync for message in websocket:data = json.loads(message)if data["message"] == "data.":response = storeawait websocket.send(json.dumps({"response": response}))breakif not "message" in message:returnif not "token" in message:returnm = data["message"] + "\nAssistant: "token = data["token"]docs = retriever.get_relevant_documents(m)rawresponse = conversational_rag_chain.invoke({"input": m},config={"configurable": {"session_id": token}},)response = rawresponse["answer"]response = response.replace("Assistant: ", "").replace("AI: ", "")response.strip()response = response.split("Human:")[0]while response.startswith("\n"):response = response[1:]await websocket.send(json.dumps({"response": response}))async def main():async with serve(echo, "0.0.0.0", 7860):await asyncio.Future()asyncio.run(main())
123version https://git-lfs.github.com/spec/v1oid sha256:93f27b61a3f0f03c0bdca772695ca92d99a4e037d0a7b2d08b71b0eb09cc33c9size 253849123version https://git-lfs.github.com/spec/v1oid sha256:bb105a8a38df0ae17e173ca39983746f3a9b95fe5a26d5e8e40116ef6b78a2fdsize 245634
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import jsonimport os
# Configurationname = "chs.json"outputFolder = "database"deleteKeys = [ "images", "tags", "html"]typeScrape = { "article": "text", "event": "description", "list": "items"}
data = json.load(open(name, "r"))
i = -1k = 0try: os.mkdir(outputFolder)except: pass
for item in data: i += 1 for key in deleteKeys: if key in item: item[key] del item[key] data[i] = item if "type" in item: for typeKey, scrapeText in typeScrape.items(): try: if item["type"] == typeKey: k += 1 file = open(f"{outputFolder}/chs-{typeKey}-{k}.txt", "a") if item["type"] == "list": text = "" if "title" in item: text = item["title"] file.write(text) for pair in item[scrapeText]: text = "" if "title" in pair: text = "\n" + pair["title"] if "summary" in pair: if pair["summary"].replace(" ", "") != pair["title"].replace(" ", ""): text += "\n" + pair["summary"].replace(pair["title"], "") if "fsElementContent" in pair: if pair["fsElementContent"].replace(" ", "") != pair["title"].replace(" ", ""): text += "\n" + pair["fsElementContent"] if "fsElementFooterContent" in pair: if pair["fsElementFooterContent"].replace(" ", "") != pair["title"].replace(" ", ""): text += "\n" + pair["fsElementFooterContent"] if "fsElementHeaderContent" in pair: if pair["fsElementHeaderContent"].replace(" ", "") != pair["title"].replace(" ", ""): text += "\n" + pair["fsElementHeaderContent"] if text != "": file.write(text) else: text = item[scrapeText] if text != "": file.write(text) except: passjson.dump(data, open(name, "w"), indent = 6)12345678websocketslangchainlangchain-communityhuggingface_hubtiktokenchromadblangchain-huggingfaceaccelerate1234567891011websocketstiktokenchromadbacceleratelangchain-community==0.2.9langchain==0.2.9langchain-core==0.2.22langchain-huggingfacerequestslangchain-chromalangchainhub
.gitattributesAdded+35
ContributorsAdded+3
README.md+1-2
app.py+68-42
chs.jsonDeleted
crawler.pyDeleted
database.zip+2-2
parse.pyDeleted-67
requirements.txt+7-4