Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,217 +1,40 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
import
|
| 4 |
-
import streamlit as st
|
| 5 |
-
from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
|
| 6 |
-
from llama_index.llms.huggingface import HuggingFaceInferenceAPI
|
| 7 |
-
from dotenv import load_dotenv
|
| 8 |
-
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
| 9 |
-
import os
|
| 10 |
-
import base64
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
model_name="google/gemma-1.1-7b-it",
|
| 18 |
-
tokenizer_name="google/gemma-1.1-7b-it",
|
| 19 |
-
context_window=3000,
|
| 20 |
-
token=os.getenv("HF_TOKEN"),
|
| 21 |
-
max_new_tokens=512,
|
| 22 |
-
generate_kwargs={"temperature": 0.1},
|
| 23 |
-
)
|
| 24 |
-
Settings.embed_model = HuggingFaceEmbedding(
|
| 25 |
-
model_name="BAAI/bge-small-en-v1.5"
|
| 26 |
-
)
|
| 27 |
-
|
| 28 |
-
# Define the directory for persistent storage and data
|
| 29 |
-
PERSIST_DIR = "./db"
|
| 30 |
-
DATA_DIR = "data"
|
| 31 |
-
|
| 32 |
-
# Ensure data directory exists
|
| 33 |
-
os.makedirs(DATA_DIR, exist_ok=True)
|
| 34 |
-
os.makedirs(PERSIST_DIR, exist_ok=True)
|
| 35 |
-
|
| 36 |
-
def displayPDF(file):
|
| 37 |
-
with open(file, "rb") as f:
|
| 38 |
-
base64_pdf = base64.b64encode(f.read()).decode('utf-8')
|
| 39 |
-
pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>'
|
| 40 |
-
st.markdown(pdf_display, unsafe_allow_html=True)
|
| 41 |
-
|
| 42 |
-
def data_ingestion():
|
| 43 |
-
documents = SimpleDirectoryReader(DATA_DIR).load_data()
|
| 44 |
-
storage_context = StorageContext.from_defaults()
|
| 45 |
-
index = VectorStoreIndex.from_documents(documents)
|
| 46 |
-
index.storage_context.persist(persist_dir=PERSIST_DIR)
|
| 47 |
-
|
| 48 |
-
def handle_query(query):
|
| 49 |
-
storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
|
| 50 |
-
index = load_index_from_storage(storage_context)
|
| 51 |
-
chat_text_qa_msgs = [
|
| 52 |
-
(
|
| 53 |
-
"user",
|
| 54 |
-
"""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.
|
| 55 |
-
Context:
|
| 56 |
-
{context_str}
|
| 57 |
-
Question:
|
| 58 |
-
{query_str}
|
| 59 |
-
"""
|
| 60 |
-
)
|
| 61 |
-
]
|
| 62 |
-
text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
|
| 63 |
-
|
| 64 |
-
query_engine = index.as_query_engine(text_qa_template=text_qa_template)
|
| 65 |
-
answer = query_engine.query(query)
|
| 66 |
-
|
| 67 |
-
if hasattr(answer, 'response'):
|
| 68 |
-
return answer.response
|
| 69 |
-
elif isinstance(answer, dict) and 'response' in answer:
|
| 70 |
-
return answer['response']
|
| 71 |
-
else:
|
| 72 |
-
return "Sorry, I couldn't find an answer."
|
| 73 |
-
|
| 74 |
-
# Gradio part - Machine Health Prediction
|
| 75 |
-
def predict_status(air_temp, proc_temp, speed, torque, tool_wear):
|
| 76 |
-
# Load the saved model and feature columns
|
| 77 |
-
with open('logistic_regression_model.pkl', 'rb') as model_file:
|
| 78 |
-
model = pickle.load(model_file)
|
| 79 |
-
|
| 80 |
-
with open('feature_columns.pkl', 'rb') as col_file:
|
| 81 |
-
feature_columns = pickle.load(col_file)
|
| 82 |
-
|
| 83 |
-
# Prepare the input data
|
| 84 |
-
sample_input = {
|
| 85 |
-
"Air temperature [K]": air_temp,
|
| 86 |
-
"Process temperature [K]": proc_temp,
|
| 87 |
-
"Rotational speed [rpm]": speed,
|
| 88 |
-
"Torque [Nm]": torque,
|
| 89 |
-
"Tool wear [min]": tool_wear
|
| 90 |
-
}
|
| 91 |
-
|
| 92 |
-
# Convert the sample input to a DataFrame
|
| 93 |
-
sample_df = pd.DataFrame([sample_input])
|
| 94 |
-
|
| 95 |
-
# Ensure all columns from training data are present in the sample DataFrame
|
| 96 |
-
for col in feature_columns:
|
| 97 |
-
if col not in sample_df.columns:
|
| 98 |
-
sample_df[col] = 0 # Add missing columns and fill with 0
|
| 99 |
-
|
| 100 |
-
# Reorder columns to match the order in the training data
|
| 101 |
-
sample_df = sample_df[feature_columns]
|
| 102 |
-
|
| 103 |
-
# Make a prediction
|
| 104 |
-
prediction = model.predict(sample_df)[0]
|
| 105 |
-
|
| 106 |
-
# Initialize the reason list
|
| 107 |
-
reasons = []
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
"Process temperature [K]": (150, 500),
|
| 113 |
-
"Rotational speed [rpm]": (500, 1500),
|
| 114 |
-
"Torque [Nm]": (100, 800),
|
| 115 |
-
"Tool wear [min]": (50, 300)
|
| 116 |
-
}
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
reasons.append("• The air temperature is too low, which might be causing the machine to underperform.")
|
| 121 |
-
elif air_temp > 500:
|
| 122 |
-
reasons.append("• The air temperature is too high, which could be causing the machine to overheat.")
|
| 123 |
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
if speed < 500:
|
| 130 |
-
reasons.append("• The rotational speed is too low, causing the machine to operate inefficiently.")
|
| 131 |
-
elif speed > 1500:
|
| 132 |
-
reasons.append("• The rotational speed is too high, which might be causing excessive strain on the machine.")
|
| 133 |
-
|
| 134 |
-
if torque < 100:
|
| 135 |
-
reasons.append("• The torque is too low, which may indicate that the machine is not operating at its full capacity.")
|
| 136 |
-
elif torque > 800:
|
| 137 |
-
reasons.append("• The torque is too high, possibly putting excessive stress on the machine's components.")
|
| 138 |
-
|
| 139 |
-
if tool_wear < 50:
|
| 140 |
-
reasons.append("• The tool wear is minimal, but routine checks are still recommended to prevent future issues.")
|
| 141 |
-
elif tool_wear > 300:
|
| 142 |
-
reasons.append("• The tool wear is high, and the tool may need to be replaced soon to maintain optimal performance.")
|
| 143 |
-
|
| 144 |
-
# Generate the final result message
|
| 145 |
-
if prediction == 0:
|
| 146 |
-
result_message = "🔴 Machine is NOT working.\n" # First line for machine status
|
| 147 |
-
if reasons:
|
| 148 |
-
result_message += "\n".join(reasons) # Second row onward for reasons with bullet points
|
| 149 |
-
else:
|
| 150 |
-
result_message += "No specific reason identified." # In case no issues found
|
| 151 |
-
else:
|
| 152 |
-
result_message = "🟢 Machine is working fine."
|
| 153 |
-
|
| 154 |
-
return result_message
|
| 155 |
-
|
| 156 |
-
# Gradio interface setup
|
| 157 |
-
def create_gradio_app():
|
| 158 |
-
iface = gr.Interface(
|
| 159 |
-
fn=predict_status,
|
| 160 |
-
inputs=[
|
| 161 |
-
gr.Slider(label="Air Temperature (K)", minimum=0, maximum=1000, step=0.01, value=300),
|
| 162 |
-
gr.Slider(label="Process Temperature (K)", minimum=0, maximum=1000, step=0.01, value=300),
|
| 163 |
-
gr.Slider(label="Rotational Speed (rpm)", minimum=0, maximum=2000, step=1, value=1000),
|
| 164 |
-
gr.Slider(label="Torque (Nm)", minimum=0, maximum=1000, step=0.1, value=500),
|
| 165 |
-
gr.Slider(label="Tool Wear (min)", minimum=0, maximum=1000, step=1, value=100),
|
| 166 |
-
],
|
| 167 |
-
outputs="text",
|
| 168 |
-
title="Smart Machine Health Predictor",
|
| 169 |
-
description="Provide machine parameters to predict whether the machine is working or not."
|
| 170 |
-
)
|
| 171 |
-
return iface
|
| 172 |
-
|
| 173 |
-
# Streamlit app layout
|
| 174 |
-
st.title("Integrated Machine Health & PDF Q&A")
|
| 175 |
-
|
| 176 |
-
tab1, tab2 = st.tabs(["Machine Health Prediction", "PDF Chatbot"])
|
| 177 |
-
|
| 178 |
-
with tab1:
|
| 179 |
-
st.markdown("### Machine Health Prediction (Gradio App)")
|
| 180 |
-
# Embed Gradio app into Streamlit using iframe
|
| 181 |
-
gradio_app = create_gradio_app()
|
| 182 |
-
gradio_app.launch(share=True) # We need to launch Gradio in an iframe.
|
| 183 |
-
|
| 184 |
-
with tab2:
|
| 185 |
-
st.markdown("### PDF Chatbot by Vatsa Solution Pvt Ltd")
|
| 186 |
-
st.markdown("Upload a PDF and ask questions related to its content.")
|
| 187 |
-
|
| 188 |
-
if 'messages' not in st.session_state:
|
| 189 |
-
st.session_state.messages = [{'role': 'assistant', "content": 'Hello! Upload a PDF and ask me anything about its content.'}]
|
| 190 |
-
|
| 191 |
-
with st.sidebar:
|
| 192 |
-
st.title("Menu:")
|
| 193 |
-
uploaded_file = st.file_uploader("Upload your PDF Files and Click on the Submit & Process Button")
|
| 194 |
-
if st.button("Submit & Process"):
|
| 195 |
-
with st.spinner("Processing..."):
|
| 196 |
-
filepath = "data/saved_pdf.pdf"
|
| 197 |
-
with open(filepath, "wb") as f:
|
| 198 |
-
f.write(uploaded_file.getvalue())
|
| 199 |
-
displayPDF(filepath)
|
| 200 |
-
data_ingestion()
|
| 201 |
-
st.success("Data processed and saved to the database!")
|
| 202 |
-
|
| 203 |
-
st.markdown("#### Chat Interface:")
|
| 204 |
-
# Chat interface
|
| 205 |
-
for message in st.session_state.messages:
|
| 206 |
-
with st.chat_message(message["role"]):
|
| 207 |
-
st.markdown(message["content"])
|
| 208 |
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from llama_index_llms_huggingface_api import HuggingFaceInferenceAPI
|
| 3 |
+
from pydantic import BaseModel
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
# Define your Pydantic model with protected namespaces disabled
|
| 6 |
+
class ModelConfig(BaseModel):
|
| 7 |
+
model_id: str
|
| 8 |
+
model_name: str
|
| 9 |
|
| 10 |
+
class Config:
|
| 11 |
+
protected_namespaces = () # Disable protected namespaces warning
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
# Define Settings class
|
| 14 |
+
class Settings:
|
| 15 |
+
llm = None # Initialize the llm attribute
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
# Initialize FastAPI app
|
| 18 |
+
app = FastAPI()
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
+
# Set up the HuggingFaceInferenceAPI with the new class
|
| 21 |
+
Settings.llm = HuggingFaceInferenceAPI(
|
| 22 |
+
api_key="your_api_key", # Replace with your actual API key
|
| 23 |
+
model_name="your_model_name" # Replace with your actual model name
|
| 24 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
# Sample endpoint to test the LLM
|
| 27 |
+
@app.post("/predict/")
|
| 28 |
+
async def predict(input_text: str):
|
| 29 |
+
try:
|
| 30 |
+
response = Settings.llm.generate(input_text) # Replace with the appropriate method for your API
|
| 31 |
+
return {"prediction": response}
|
| 32 |
+
except Exception as e:
|
| 33 |
+
return {"error": str(e)}
|
| 34 |
+
|
| 35 |
+
# Sample endpoint to retrieve model configuration
|
| 36 |
+
@app.get("/model-config/")
|
| 37 |
+
async def get_model_config():
|
| 38 |
+
return {"model_id": Settings.llm.model_id, "model_name": Settings.llm.model_name}
|
| 39 |
+
|
| 40 |
+
# Run the app using: uvicorn app:app --reload
|