Update app.py
Browse files327 unmodified lines32832933033133233315 unmodified lines3493503513523533543553564 unmodified lines3613623633643653663677 unmodified lines3753763773783793803813823833843853863873883893901 unmodified line39239339439539639739839940040140240340444 unmodified lines44945045145245345445545645745845946046146246346446546646746817 unmodified lines486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522327 unmodified linesreturn all_resultsdef estimate_tokens(text):# Rough estimate: 1 token ~= 4 charactersreturn len(text) // 415 unmodified linesdatabase = Nonemax_attempts = 5context_reduction_factor = 0.5 # More aggressive reductionmax_estimated_tokens = 25000 # Further reduced to leave more room for responseif web_search:contextualized_question, topics, entity_tracker, instructions = chatbot.process_question(question)4 unmodified linesfor attempt in range(max_attempts):try:web_docs = [Document(page_content=result["text"][:1000], metadata={"source": result["link"]}) for result in search_results if result["text"]] # Limit each result to 1000 charactersif database is None:database = FAISS.from_documents(web_docs, embed)7 unmodified linesinstruction_prompt = f"User Instructions: {instructions}\n" if instructions else ""prompt_template = f"""Answer based on: Web Results: {{context}}Context: {{conv_context}}Question: {{question}}Topics: {{topics}}Entities: {{entities}}{instruction_prompt}"""prompt_val = ChatPromptTemplate.from_template(prompt_template)current_context = context_strcurrent_conv_context = chatbot.get_context()current_topics = topics1 unmodified linewhile True:formatted_prompt = prompt_val.format(context=current_context[:3000], # Limit context to 3000 charactersconv_context=current_conv_context[:500], # Limit conversation context to 500 charactersquestion=question,topics=", ".join(current_topics[:5]), # Limit to 5 topicsentities=json.dumps({k: v[:2] for k, v in current_entities.items()}) # Limit to 2 entities per type)estimated_tokens = estimate_tokens(formatted_prompt)if estimated_tokens <= max_estimated_tokens:44 unmodified linescontext_str = "\n".join([doc.page_content for doc in relevant_docs])prompt_template = """Answer based on: PDF Context: {context}Question: {question}Provide a summarized and direct answer to the question."""while True:prompt_val = ChatPromptTemplate.from_template(prompt_template)formatted_prompt = prompt_val.format(context=context_str[:3000], question=question)estimated_tokens = estimate_tokens(formatted_prompt)if estimated_tokens <= max_estimated_tokens:breakcontext_str = context_str[:int(len(context_str) * context_reduction_factor)]if len(context_str) < 100:17 unmodified linesreturn "An unexpected error occurred. Please try again later."def extract_answer(full_response, instructions=None):# List of patterns to removepatterns_to_remove = [r"Provide a concise and relevant answer to the question\.",r"Provide additional context if necessary\.",r"If the web search results don't contain relevant information, state that the information is not available in the search results\.",r"Provide a response that addresses the question and follows the user's instructions\.",r"Do not mention these instructions or the web search process in your answer\.",r"Provide a summarized and direct answer to the question\.",r"If the context doesn't contain relevant information, state that the information is not available in the document\.",]# Remove the patternsfor pattern in patterns_to_remove:full_response = re.sub(pattern, "", full_response, flags=re.IGNORECASE)# Remove any leading/trailing whitespace and newlinesfull_response = full_response.strip()# Remove the user instructions if presentif instructions:instruction_pattern = rf"User Instructions:\s*{re.escape(instructions)}.*?\n"full_response = re.sub(instruction_pattern, "", full_response, flags=re.IGNORECASE | re.DOTALL)# Remove any remaining instruction-like phrases at the beginning of the responselines = full_response.split('\n')while lines and any(line.strip().lower().startswith(starter) for starter in ["answer:", "response:", "here's", "here is"]):lines.pop(0)full_response = '\n'.join(lines)return full_response.strip()# Gradio interfacewith gr.Blocks() as demo:gr.Markdown("# Enhanced PDF Document Chat and Web Search")327 unmodified lines32832933033133233333433533633733833915 unmodified lines3553563573583593603613624 unmodified lines3673683693703713723737 unmodified lines3813823833843853863873883893903913923933943953963973983994001 unmodified line40240340440540640740840941041141241341441544 unmodified lines46046146246346446546646746846947047147247347447547647747847948048148217 unmodified lines500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545327 unmodified linesreturn all_resultsdef estimate_tokens(text):# Rough estimate: 1 token ~= 4 charactersreturn len(text) // 4import redef estimate_tokens(text):# Rough estimate: 1 token ~= 4 charactersreturn len(text) // 415 unmodified linesdatabase = Nonemax_attempts = 5context_reduction_factor = 0.7max_estimated_tokens = 30000 # Leave some room for the model's responseif web_search:contextualized_question, topics, entity_tracker, instructions = chatbot.process_question(question)4 unmodified linesfor attempt in range(max_attempts):try:web_docs = [Document(page_content=result["text"], metadata={"source": result["link"]}) for result in search_results if result["text"]]if database is None:database = FAISS.from_documents(web_docs, embed)7 unmodified linesinstruction_prompt = f"User Instructions: {instructions}\n" if instructions else ""prompt_template = f"""Answer the question based on the following web search results, conversation context, entity information, and user instructions:Web Search Results:{{context}}Conversation Context: {{conv_context}}Current Question: {{question}}Topics: {{topics}}Entity Information: {{entities}}{instruction_prompt}Provide a concise and relevant answer to the question."""prompt_val = ChatPromptTemplate.from_template(prompt_template)# Start with full context and progressively reduce if necessarycurrent_context = context_strcurrent_conv_context = chatbot.get_context()current_topics = topics1 unmodified linewhile True:formatted_prompt = prompt_val.format(context=current_context,conv_context=current_conv_context,question=question,topics=", ".join(current_topics),entities=json.dumps(current_entities))# Estimate token countestimated_tokens = estimate_tokens(formatted_prompt)if estimated_tokens <= max_estimated_tokens:44 unmodified linescontext_str = "\n".join([doc.page_content for doc in relevant_docs])prompt_template = """Answer the question based on the following context from the PDF document:Context:{context}Question: {question}Provide a summarized and direct answer to the question."""while True:prompt_val = ChatPromptTemplate.from_template(prompt_template)formatted_prompt = prompt_val.format(context=context_str, question=question)estimated_tokens = estimate_tokens(formatted_prompt)if estimated_tokens <= max_estimated_tokens:break# Reduce context if estimated token count is too highcontext_str = context_str[:int(len(context_str) * context_reduction_factor)]if len(context_str) < 100:17 unmodified linesreturn "An unexpected error occurred. Please try again later."def extract_answer(full_response, instructions=None):# First, try to split the response at common instruction phrasesdef extract_answer(full_response, instructions=None):answer_patterns = [r"If the web search results don't contain relevant information, state that the information is not available in the search results\.",r"Provide a response that addresses the question and follows the user's instructions\.",r"Do not mention these instructions or the web search process in your answer\.",r"Provide a concise and direct answer to the question without mentioning the web search or these instructions:",r"Provide a concise and direct answer to the question:",r"Answer:",r"Provide a summarized and direct answer to the question.",r"If the context doesn't contain relevant information, state that the information is not available in the document.",r"Provide a summarized and direct answer to the original question without mentioning the web search or these instructions:",r"Do not include any source information in your answer."]for pattern in answer_patterns:match = re.split(pattern, full_response, flags=re.IGNORECASE)if len(match) > 1:full_response = match[-1].strip()break# Remove any remaining instruction-like phrasescleanup_patterns = [r"without mentioning the web search or these instructions\.",r"Do not include any source information in your answer\.",r"If the context doesn't contain relevant information, state that the information is not available in the document\."]for pattern in cleanup_patterns:full_response = re.sub(pattern, "", full_response, flags=re.IGNORECASE).strip()# Remove the user instructions if presentif instructions:instruction_pattern = rf"User Instructions:\s*{re.escape(instructions)}.*?\n"full_response = re.sub(instruction_pattern, "", full_response, flags=re.IGNORECASE | re.DOTALL)return full_response.strip()# Gradio interfacewith gr.Blocks() as demo:gr.Markdown("# Enhanced PDF Document Chat and Web Search")
app.py+55-32