Update app.py
Browse files352 unmodified lines3533543553563573583593603613623633643 unmodified lines368369370371372373374375376377378379380381382383384385386387388389390391392393394352 unmodified linesexcept Exception as e:return f"An error occurred during summarization: {str(e)}"def get_response_from_gemini(query, context, file_type, num_calls=1, temperature=0.2):# Configure the Gemini APIgenai.configure(api_key=os.environ["GEMINI_API_KEY"])# Define the modelmodel = genai.GenerativeModel(model_name="gemini-1.5-flash",generation_config={"temperature": temperature,3 unmodified lines},)# Create the system instruction based on file typeif file_type == "excel":system_instruction = """You are a highly specialized data analyst with expertise in Excel spreadsheets.Your task is to analyze the provided Excel data and answer the user's query accurately and concisely.Focus on identifying key metrics, trends, and significant details relevant to the query.Do not make assumptions or include information not explicitly supported by the dataset."""elif file_type == "pdf":system_instruction = """You are a highly specialized document analyst with expertise in extracting information from PDF documents.Your task is to analyze the provided PDF content and answer the user's query accurately and comprehensively.Focus on key points, important details, and relevant information from the document.Ensure your response is strictly based on the provided context."""else:raise ValueError("Invalid file type. Use 'excel' or 'pdf'.")full_prompt = f"{system_instruction}\n\nContext:\n{context}\n\nUser query: {query}"full_response = ""for _ in range(num_calls):try:# Generate content with streaming enabledresponse = model.generate_content(full_prompt, stream=True)for chunk in response:if chunk.text:full_response += chunk.text352 unmodified lines3533543553563573583593603613623633643 unmodified lines368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422352 unmodified linesexcept Exception as e:return f"An error occurred during summarization: {str(e)}"def get_response_from_gemini(query, model, selected_docs, file_type, num_calls=1, temperature=0.2):# Configure the Gemini APIgenai.configure(api_key=os.environ["GEMINI_API_KEY"])# Define the modelgemini_model = genai.GenerativeModel(model_name="gemini-1.5-flash",generation_config={"temperature": temperature,3 unmodified lines},)if file_type == "excel":# Excel functionality remains the samesystem_instruction = """You are a highly specialized data analyst with expertise in Excel spreadsheets.Your task is to analyze the provided Excel data and answer the user's query accurately and concisely.Focus on identifying key metrics, trends, and significant details relevant to the query.Do not make assumptions or include information not explicitly supported by the dataset."""full_prompt = f"{system_instruction}\n\nContext:\n{selected_docs}\n\nUser query: {query}"elif file_type == "pdf":# PDF functionality similar to get_response_from_pdfembed = get_embeddings()if os.path.exists("faiss_database"):database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)else:yield "No documents available. Please upload PDF documents to answer questions."return# Pre-filter the documentsfiltered_docs = [doc for doc_id, doc in database.docstore._dict.items()if isinstance(doc, Document) and doc.metadata.get("source") in selected_docs]if not filtered_docs:yield "No relevant information found in the selected documents. Please try selecting different documents or rephrasing your query."return# Create a new FAISS index with only the selected documentsfiltered_db = FAISS.from_documents(filtered_docs, embed)retriever = filtered_db.as_retriever(search_kwargs={"k": 10})relevant_docs = retriever.get_relevant_documents(query)context_str = "\n".join([doc.page_content for doc in relevant_docs])system_instruction = """You are a highly specialized document analyst with expertise in extracting information from PDF documents.Your task is to analyze the provided PDF content and answer the user's query accurately and comprehensively.Focus on key points, important details, and relevant information from the document.Ensure your response is strictly based on the provided context."""full_prompt = f"{system_instruction}\n\nContext:\n{context_str}\n\nUser query: {query}\n\nPlease generate a step-by-step reasoning before arriving at a comprehensive and accurate summary addressing the question. Ensure your response is strictly based on the provided context, highlighting key metrics, trends, and significant details relevant to the query. Avoid any speculative or unverified information."else:raise ValueError("Invalid file type. Use 'excel' or 'pdf'.")full_response = ""for _ in range(num_calls):try:# Generate content with streaming enabledresponse = gemini_model.generate_content(full_prompt, stream=True)for chunk in response:if chunk.text:full_response += chunk.text
app.py+34-6