Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,32 +2,27 @@ import gradio as gr
|
|
| 2 |
import pandas as pd
|
| 3 |
import pickle
|
| 4 |
import os
|
| 5 |
-
|
|
|
|
| 6 |
from llama_index.llms.huggingface import HuggingFaceInferenceAPI
|
| 7 |
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
| 8 |
from dotenv import load_dotenv
|
| 9 |
-
import base64
|
| 10 |
|
| 11 |
# Load environment variables
|
| 12 |
load_dotenv()
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
with open('feature_columns.pkl', 'rb') as col_file:
|
| 19 |
-
feature_columns = pickle.load(col_file)
|
| 20 |
-
|
| 21 |
-
# Configure the Llama index settings for the PDF Reader
|
| 22 |
-
hf_api = HuggingFaceInferenceAPI(
|
| 23 |
-
model_name="google/gemma-1.1-7b-it",
|
| 24 |
tokenizer_name="google/gemma-1.1-7b-it",
|
| 25 |
context_window=3000,
|
| 26 |
token=os.getenv("HF_TOKEN"),
|
| 27 |
max_new_tokens=512,
|
| 28 |
-
generate_kwargs={"temperature": 0.1}
|
|
|
|
|
|
|
|
|
|
| 29 |
)
|
| 30 |
-
hf_embedding = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5")
|
| 31 |
|
| 32 |
# Define the directory for persistent storage and data
|
| 33 |
PERSIST_DIR = "./db"
|
|
@@ -37,14 +32,13 @@ DATA_DIR = "data"
|
|
| 37 |
os.makedirs(DATA_DIR, exist_ok=True)
|
| 38 |
os.makedirs(PERSIST_DIR, exist_ok=True)
|
| 39 |
|
| 40 |
-
#
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
|
| 47 |
-
# Machine Health Prediction function
|
| 48 |
def predict_status(air_temp, proc_temp, speed, torque, tool_wear):
|
| 49 |
# Prepare the input data
|
| 50 |
sample_input = {
|
|
@@ -54,15 +48,15 @@ def predict_status(air_temp, proc_temp, speed, torque, tool_wear):
|
|
| 54 |
"Torque [Nm]": torque,
|
| 55 |
"Tool wear [min]": tool_wear
|
| 56 |
}
|
| 57 |
-
|
| 58 |
# Convert the sample input to a DataFrame
|
| 59 |
sample_df = pd.DataFrame([sample_input])
|
| 60 |
-
|
| 61 |
# Ensure all columns from training data are present in the sample DataFrame
|
| 62 |
for col in feature_columns:
|
| 63 |
if col not in sample_df.columns:
|
| 64 |
sample_df[col] = 0 # Add missing columns and fill with 0
|
| 65 |
-
|
| 66 |
# Reorder columns to match the order in the training data
|
| 67 |
sample_df = sample_df[feature_columns]
|
| 68 |
|
|
@@ -117,62 +111,72 @@ def predict_status(air_temp, proc_temp, speed, torque, tool_wear):
|
|
| 117 |
else:
|
| 118 |
result_message = "🟢 Machine is working fine."
|
| 119 |
|
| 120 |
-
return result_message
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
-
|
| 123 |
-
def handle_query(reason):
|
| 124 |
storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
|
| 125 |
index = load_index_from_storage(storage_context)
|
| 126 |
-
|
| 127 |
-
# Set up the query context for the chatbot
|
| 128 |
chat_text_qa_msgs = [
|
| 129 |
(
|
| 130 |
"user",
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
)
|
| 133 |
]
|
| 134 |
text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
|
| 135 |
|
| 136 |
query_engine = index.as_query_engine(text_qa_template=text_qa_template)
|
|
|
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
-
#
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
with gr.Row():
|
| 148 |
-
with gr.Column():
|
| 149 |
-
gr.Markdown("### Machine Health Prediction")
|
| 150 |
-
air_temp = gr.Slider(label="Air Temperature (K)", minimum=0, maximum=1000, step=0.01, value=300)
|
| 151 |
-
proc_temp = gr.Slider(label="Process Temperature (K)", minimum=0, maximum=1000, step=0.01, value=300)
|
| 152 |
-
speed = gr.Slider(label="Rotational Speed (rpm)", minimum=0, maximum=2000, step=1, value=1000)
|
| 153 |
-
torque = gr.Slider(label="Torque (Nm)", minimum=0, maximum=1000, step=0.1, value=500)
|
| 154 |
-
tool_wear = gr.Slider(label="Tool Wear (min)", minimum=0, maximum=1000, step=1, value=100)
|
| 155 |
-
|
| 156 |
-
predict_button = gr.Button("Predict Machine Status")
|
| 157 |
-
output_status = gr.Markdown(label="Machine Status & Reasons")
|
| 158 |
-
|
| 159 |
-
with gr.Column():
|
| 160 |
-
gr.Markdown("### PDF Chatbot")
|
| 161 |
-
chat_box = gr.Textbox(label="Ask me anything about the PDF content:", placeholder="Type your question here...", lines=3)
|
| 162 |
-
submit_btn = gr.Button("Send")
|
| 163 |
-
response_box = gr.Markdown(label="Chatbot Response")
|
| 164 |
-
|
| 165 |
-
# Define button actions
|
| 166 |
-
predict_button.click(fn=predict_status,
|
| 167 |
-
inputs=[air_temp, proc_temp, speed, torque, tool_wear],
|
| 168 |
-
outputs=[output_status])
|
| 169 |
-
|
| 170 |
-
submit_btn.click(fn=handle_query,
|
| 171 |
-
inputs=chat_box,
|
| 172 |
-
outputs=response_box)
|
| 173 |
-
|
| 174 |
-
# Display the PDF content
|
| 175 |
-
gr.Markdown(read_pdf())
|
| 176 |
-
|
| 177 |
-
# Launch the app
|
| 178 |
-
demo.launch()
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
import pickle
|
| 4 |
import os
|
| 5 |
+
import base64
|
| 6 |
+
from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
|
| 7 |
from llama_index.llms.huggingface import HuggingFaceInferenceAPI
|
| 8 |
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
| 9 |
from dotenv import load_dotenv
|
|
|
|
| 10 |
|
| 11 |
# Load environment variables
|
| 12 |
load_dotenv()
|
| 13 |
|
| 14 |
+
# Configure the Llama index settings
|
| 15 |
+
Settings.llm = HuggingFaceInferenceAPI(
|
| 16 |
+
model_name="google/gemma-1.1-7b-it",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
tokenizer_name="google/gemma-1.1-7b-it",
|
| 18 |
context_window=3000,
|
| 19 |
token=os.getenv("HF_TOKEN"),
|
| 20 |
max_new_tokens=512,
|
| 21 |
+
generate_kwargs={"temperature": 0.1},
|
| 22 |
+
)
|
| 23 |
+
Settings.embed_model = HuggingFaceEmbedding(
|
| 24 |
+
model_name="BAAI/bge-small-en-v1.5"
|
| 25 |
)
|
|
|
|
| 26 |
|
| 27 |
# Define the directory for persistent storage and data
|
| 28 |
PERSIST_DIR = "./db"
|
|
|
|
| 32 |
os.makedirs(DATA_DIR, exist_ok=True)
|
| 33 |
os.makedirs(PERSIST_DIR, exist_ok=True)
|
| 34 |
|
| 35 |
+
# Load the saved model and feature columns for the machine health predictor
|
| 36 |
+
with open('logistic_regression_model.pkl', 'rb') as model_file:
|
| 37 |
+
model = pickle.load(model_file)
|
| 38 |
+
|
| 39 |
+
with open('feature_columns.pkl', 'rb') as col_file:
|
| 40 |
+
feature_columns = pickle.load(col_file)
|
| 41 |
|
|
|
|
| 42 |
def predict_status(air_temp, proc_temp, speed, torque, tool_wear):
|
| 43 |
# Prepare the input data
|
| 44 |
sample_input = {
|
|
|
|
| 48 |
"Torque [Nm]": torque,
|
| 49 |
"Tool wear [min]": tool_wear
|
| 50 |
}
|
| 51 |
+
|
| 52 |
# Convert the sample input to a DataFrame
|
| 53 |
sample_df = pd.DataFrame([sample_input])
|
| 54 |
+
|
| 55 |
# Ensure all columns from training data are present in the sample DataFrame
|
| 56 |
for col in feature_columns:
|
| 57 |
if col not in sample_df.columns:
|
| 58 |
sample_df[col] = 0 # Add missing columns and fill with 0
|
| 59 |
+
|
| 60 |
# Reorder columns to match the order in the training data
|
| 61 |
sample_df = sample_df[feature_columns]
|
| 62 |
|
|
|
|
| 111 |
else:
|
| 112 |
result_message = "🟢 Machine is working fine."
|
| 113 |
|
| 114 |
+
return result_message
|
| 115 |
+
|
| 116 |
+
def displayPDF():
|
| 117 |
+
# Load and display the PDF content from the data folder
|
| 118 |
+
filepath = os.path.join(DATA_DIR, "saved_pdf.pdf")
|
| 119 |
+
with open(filepath, "rb") as f:
|
| 120 |
+
base64_pdf = base64.b64encode(f.read()).decode('utf-8')
|
| 121 |
+
pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>'
|
| 122 |
+
return pdf_display
|
| 123 |
+
|
| 124 |
+
def data_ingestion():
|
| 125 |
+
documents = SimpleDirectoryReader(DATA_DIR).load_data()
|
| 126 |
+
storage_context = StorageContext.from_defaults()
|
| 127 |
+
index = VectorStoreIndex.from_documents(documents)
|
| 128 |
+
index.storage_context.persist(persist_dir=PERSIST_DIR)
|
| 129 |
|
| 130 |
+
def handle_query(query):
|
|
|
|
| 131 |
storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
|
| 132 |
index = load_index_from_storage(storage_context)
|
|
|
|
|
|
|
| 133 |
chat_text_qa_msgs = [
|
| 134 |
(
|
| 135 |
"user",
|
| 136 |
+
"""You are a Q&A assistant named AskAI, created by Vatsa. You have a specific response programmed for when users specifically ask about your creator, Suriya. The response is: "I was created by Suriya, an enthusiast in Artificial Intelligence. He is dedicated to solving complex problems and delivering innovative solutions. With a strong focus on machine learning, deep learning, Python, generative AI, NLP, and computer vision, Suriya is passionate about pushing the boundaries of AI to explore new possibilities." For all other inquiries, your main goal is to provide answers as accurately as possible, based on the instructions and context you have been given. If a question does not match the provided context or is outside the scope of the document, kindly advise the user to ask questions within the context of the document.
|
| 137 |
+
Context:
|
| 138 |
+
{context_str}
|
| 139 |
+
Question:
|
| 140 |
+
{query_str}
|
| 141 |
+
"""
|
| 142 |
)
|
| 143 |
]
|
| 144 |
text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
|
| 145 |
|
| 146 |
query_engine = index.as_query_engine(text_qa_template=text_qa_template)
|
| 147 |
+
answer = query_engine.query(query)
|
| 148 |
|
| 149 |
+
if hasattr(answer, 'response'):
|
| 150 |
+
return answer.response
|
| 151 |
+
elif isinstance(answer, dict) and 'response' in answer:
|
| 152 |
+
return answer['response']
|
| 153 |
+
else:
|
| 154 |
+
return "Sorry, I couldn't find an answer."
|
| 155 |
+
|
| 156 |
+
# Define the Gradio interface
|
| 157 |
+
iface = gr.Interface(
|
| 158 |
+
fn=lambda air_temp, proc_temp, speed, torque, tool_wear, user_query: (
|
| 159 |
+
predict_status(air_temp, proc_temp, speed, torque, tool_wear),
|
| 160 |
+
displayPDF(),
|
| 161 |
+
handle_query(user_query)
|
| 162 |
+
),
|
| 163 |
+
inputs=[
|
| 164 |
+
gr.Slider(label="Air Temperature (K)", minimum=0, maximum=1000, step=0.01, value=300),
|
| 165 |
+
gr.Slider(label="Process Temperature (K)", minimum=0, maximum=1000, step=0.01, value=300),
|
| 166 |
+
gr.Slider(label="Rotational Speed (rpm)", minimum=0, maximum=2000, step=1, value=1000),
|
| 167 |
+
gr.Slider(label="Torque (Nm)", minimum=0, maximum=1000, step=0.1, value=500),
|
| 168 |
+
gr.Slider(label="Tool Wear (min)", minimum=0, maximum=1000, step=1, value=100),
|
| 169 |
+
gr.Textbox(label="Ask me anything about the PDF:", placeholder="Type your question here...")
|
| 170 |
+
],
|
| 171 |
+
outputs=[
|
| 172 |
+
"text", # For machine health prediction
|
| 173 |
+
"html", # For PDF display
|
| 174 |
+
"text" # For query response
|
| 175 |
+
],
|
| 176 |
+
title="Integrated Machine Health and PDF Query Predictor",
|
| 177 |
+
description="Provide machine parameters to predict whether the machine is working or not, and ask questions about the PDF content.",
|
| 178 |
+
)
|
| 179 |
|
| 180 |
+
# Launch the Gradio app
|
| 181 |
+
if __name__ == "__main__":
|
| 182 |
+
iface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|