Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234567845691011121314151617181920212223242526272829303132333435363738394041424344454647481112131415164950515253545518565758593 unmodified lines636465286667686970717273327475343576777879388081824243444546474849505152535455565758598384858687888990919293949596979899100101import gradio as grfrom huggingface_hub import InferenceClientfrom typing import List, Tupleimport fitz # PyMuPDFfrom sentence_transformers import SentenceTransformer, utilimport numpy as npimport faiss
"""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")
# Placeholder for the app's stateclass MyApp: def __init__(self) -> None: self.documents = [] self.embeddings = None self.index = None self.load_pdf("Realestate.pdf") # Replace with the actual PDF filename self.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, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p, message: str, history: List[Tuple[str, str]], system_message: str, max_tokens: int, temperature: float, top_p: float,): messages = [{"role": "system", "content": system_message}] 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 lines
messages.append({"role": "user", "content": message})
response = "" # RAG - Retrieve relevant documents retrieved_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=max_tokens, max_tokens=100, stream=True, temperature=temperature, top_p=top_p, temperature=0.7, top_p=0.9, ): token = message.choices[0].delta.content
response += token yield 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)", ), ],)demo = 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