import os import streamlit as st import pandas as pd import pickle from PyPDF2 import PdfReader from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_google_genai import GoogleGenerativeAIEmbeddings import google.generativeai as genai from langchain.vectorstores import FAISS from langchain_google_genai import ChatGoogleGenerativeAI from langchain.chains.question_answering import load_qa_chain from langchain.prompts import PromptTemplate from dotenv import load_dotenv # Load environment variables load_dotenv() # Configure Google API genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) # Function to extract text from PDFs def get_pdf_text(pdf_docs): text = "" for pdf in pdf_docs: pdf_reader = PdfReader(pdf) for page in pdf_reader.pages: text += page.extract_text() return text # Function to split text into chunks def get_text_chunks(text): text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000) chunks = text_splitter.split_text(text) return chunks # Function to store text chunks in FAISS vector store def get_vector_store(text_chunks): embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001") vector_store = FAISS.from_texts(text_chunks, embedding=embeddings) vector_store.save_local("faiss_index") # Function to load the conversational chain for Q&A def get_conversational_chain(): prompt_template = """ Answer the question as detailed as possible from the provided context. Provide all details in English. If the answer is not in the provided context, just say, 'The answer is not available in the context.' Do not provide incorrect information. Context:\n{context}\n Question:\n{question}\n Answer: """ model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3) prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"]) chain = load_qa_chain(model, chain_type="stuff", prompt=prompt) return chain # Function to handle user input and provide answers def user_input(user_question): embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001") # Load the vector store with dangerous deserialization allowed new_db = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True) # Perform similarity search docs = new_db.similarity_search(user_question) # Load the conversational chain chain = get_conversational_chain() # Get the response based on the search response = chain({"input_documents": docs, "question": user_question}, return_only_outputs=True) # Print and display the response print(response) return response["output_text"] # Load the saved model and feature columns for the machine health predictor with open('logistic_regression_model.pkl', 'rb') as model_file: model = pickle.load(model_file) with open('feature_columns.pkl', 'rb') as col_file: feature_columns = pickle.load(col_file) def predict_status(air_temp, proc_temp, speed, torque, tool_wear): # Prepare the input data sample_input = { "Air temperature [K]": air_temp, "Process temperature [K]": proc_temp, "Rotational speed [rpm]": speed, "Torque [Nm]": torque, "Tool wear [min]": tool_wear } # Convert the sample input to a DataFrame sample_df = pd.DataFrame([sample_input]) # Ensure all columns from training data are present in the sample DataFrame for col in feature_columns: if col not in sample_df.columns: sample_df[col] = 0 # Add missing columns and fill with 0 # Reorder columns to match the order in the training data sample_df = sample_df[feature_columns] # Make a prediction prediction = model.predict(sample_df)[0] # Initialize the reason list reasons = [] # Define acceptable ranges for each feature with user-friendly feedback acceptable_ranges = { "Air temperature [K]": (150, 500), "Process temperature [K]": (150, 500), "Rotational speed [rpm]": (500, 1500), "Torque [Nm]": (100, 800), "Tool wear [min]": (50, 300) } # User-friendly reasons for each feature if air_temp < 150: reasons.append("• The air temperature is too low, which might be causing the machine to underperform.") elif air_temp > 500: reasons.append("• The air temperature is too high, which could be causing the machine to overheat.") if proc_temp < 150: reasons.append("• The process temperature is below the normal range, possibly affecting machine efficiency.") elif proc_temp > 500: reasons.append("• The process temperature is too high, which might lead to overheating.") if speed < 500: reasons.append("• The rotational speed is too low, causing the machine to operate inefficiently.") elif speed > 1500: reasons.append("• The rotational speed is too high, which might be causing excessive strain on the machine.") if torque < 100: reasons.append("• The torque is too low, which may indicate that the machine is not operating at its full capacity.") elif torque > 800: reasons.append("• The torque is too high, possibly putting excessive stress on the machine's components.") if tool_wear < 50: reasons.append("• The tool wear is minimal, but routine checks are still recommended to prevent future issues.") elif tool_wear > 300: reasons.append("• The tool wear is high, and the tool may need to be replaced soon to maintain optimal performance.") # Generate the final result message if prediction == 0: result_message = "🔴 Machine is NOT working.\n" # First line for machine status if reasons: result_message += "\n".join(reasons) # Second row onward for reasons with bullet points else: result_message += "No specific reason identified." # In case no issues found else: result_message = "🟢 Machine is working fine." return result_message # Main function for the Streamlit app def main(): st.set_page_config("Multi-PDF Chatbot & Machine Health Predictor", page_icon=":scroll:") # Sidebar for navigation st.sidebar.title("Navigation") app_mode = st.sidebar.radio("Choose an option", ["Combined Screen"]) # Define the PDF directory path pdf_directory = r"data" # Get all PDF files from the directory pdf_docs = [os.path.join(pdf_directory, file) for file in os.listdir(pdf_directory) if file.endswith('.pdf')] # Initialize session state for prediction message and user question if "prediction_message" not in st.session_state: st.session_state.prediction_message = "" if "user_question" not in st.session_state: st.session_state.user_question = "" # Slider defaults for machine health predictor if "air_temp" not in st.session_state: st.session_state.air_temp = 300 if "proc_temp" not in st.session_state: st.session_state.proc_temp = 300 if "speed" not in st.session_state: st.session_state.speed = 1000 if "torque" not in st.session_state: st.session_state.torque = 500 if "tool_wear" not in st.session_state: st.session_state.tool_wear = 100 # Combined Screen if app_mode == "Combined Screen": st.header("Smart Machine Health Predictor & PDF Chatbot") # Machine Health Predictor st.subheader("Machine Health Predictor") air_temp = st.slider("Air Temperature (K)", 0, 1000, st.session_state.air_temp, key='air_temp') proc_temp = st.slider("Process Temperature (K)", 0, 1000, st.session_state.proc_temp, key='proc_temp') speed = st.slider("Rotational Speed (rpm)", 0, 2000, st.session_state.speed, key='speed') torque = st.slider("Torque (Nm)", 0, 1000, st.session_state.torque, key='torque') tool_wear = st.slider("Tool Wear (min)", 0, 500, st.session_state.tool_wear, key='tool_wear') if st.button("Predict Machine Status"): result_message = predict_status(air_temp, proc_temp, speed, torque, tool_wear) st.session_state.prediction_message = result_message # Automatically populate the PDF Reader Chatbot input with the result message st.session_state.user_question = result_message # Set the question to the result st.markdown(st.session_state.prediction_message) # PDF Reader Chatbot st.subheader("Ask a question about the PDF documents:") user_question = st.text_input("Question:", value=st.session_state.user_question) # Set the input box to the prediction message if user_question: pdf_text = get_pdf_text(pdf_docs) text_chunks = get_text_chunks(pdf_text) get_vector_store(text_chunks) answer = user_input(user_question) st.success("Answer retrieved successfully!") st.write(answer) else: st.warning("Please enter a question.") # Run the app if __name__ == "__main__": main()