Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234567891011121314151617181920213 unmodified lines252627282930313233343536373839404142434445464748495051525354555657585960616263import gradio as grfrom huggingface_hub import InferenceClient"""For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference"""client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")def respond(message,history: list[tuple[str, str]],system_message,max_tokens,temperature,top_p,):messages = [{"role": "system", "content": system_message}]for val in history:if val[0]:3 unmodified linesmessages.append({"role": "user", "content": message})response = ""for message in client.chat_completion(messages,max_tokens=max_tokens,stream=True,temperature=temperature,top_p=top_p,):token = message.choices[0].delta.contentresponse += tokenyield response"""For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface"""demo = gr.ChatInterface(respond,additional_inputs=[gr.Textbox(value="You are a friendly Chatbot.", label="System message"),gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),gr.Slider(minimum=0.1,maximum=1.0,value=0.95,step=0.05,label="Top-p (nucleus sampling)",),],)if __name__ == "__main__":demo.launch()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758593 unmodified lines63646566676869707172737475767778798081828384858687888990919293949596979899100101import gradio as grfrom huggingface_hub import InferenceClientfrom typing import List, Tupleimport fitz # PyMuPDFfrom sentence_transformers import SentenceTransformer, utilimport numpy as npimport faissclient = InferenceClient("HuggingFaceH4/zephyr-7b-beta")# Placeholder for the app's stateclass MyApp:def __init__(self) -> None:self.documents = []self.embeddings = Noneself.index = Noneself.load_pdf("Realestate.pdf") # Replace with the actual PDF filenameself.build_vector_db()def load_pdf(self, file_path: str) -> None:"""Extracts text from a PDF file and stores it in the app's documents."""doc = fitz.open(file_path)self.documents = []for page_num in range(len(doc)):page = doc[page_num]text = page.get_text()self.documents.append({"page": page_num + 1, "content": text})print("PDF processed successfully!")def build_vector_db(self) -> None:"""Builds a vector database using the content of the PDF."""model = SentenceTransformer('all-MiniLM-L6-v2')self.embeddings = model.encode([doc["content"] for doc in self.documents])self.index = faiss.IndexFlatL2(self.embeddings.shape[1])self.index.add(np.array(self.embeddings))print("Vector database built successfully!")def search_documents(self, query: str, k: int = 3) -> List[str]:"""Searches for relevant documents using vector similarity."""model = SentenceTransformer('all-MiniLM-L6-v2')query_embedding = model.encode([query])D, I = self.index.search(np.array(query_embedding), k)results = [self.documents[i]["content"] for i in I[0]]return results if results else ["No relevant documents found."]app = MyApp()def respond(message: str,history: List[Tuple[str, str]],system_message: str,max_tokens: int,temperature: float,top_p: float,):system_message = "You are a very good adviser regarding property deals based on Realestae guide. By approaching property deals with knowledge, preparation, and strategic thinking, you always make the best decisions that align with your goals and maximize your investment potential in real estate."for val in history:if val[0]:3 unmodified linesmessages.append({"role": "user", "content": message})# RAG - Retrieve relevant documentsretrieved_docs = app.search_documents(message)context = "\n".join(retrieved_docs)messages.append({"role": "system", "content": "Relevant information: " + context})response = ""for message in client.chat_completion(messages,max_tokens=100,stream=True,temperature=0.7,top_p=0.9,):token = message.choices[0].delta.contentresponse += tokenyield responsedemo = gr.Blocks()with demo:gr.Markdown("‼️Disclaimer: This chatbot is based on Realestate guide and is intended for givinf Knowledge based on property .‼️")chatbot = gr.ChatInterface(respond,examples=[["Do you have what it takes to be a Millionaire?"],["What is a good deal?"],["Explain 10/10/10 Rule"],],title='The real estate agent')if __name__ == "__main__":demo.launch()
app.py+71-33