shahed125238 commited on
Commit
aff3875
·
verified ·
1 Parent(s): 20716a2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +178 -0
app.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import pickle
4
+ import os
5
+ from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
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
+ # Load the saved model and feature columns for Machine Health Prediction
15
+ with open('logistic_regression_model.pkl', 'rb') as model_file:
16
+ model = pickle.load(model_file)
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
+ HuggingFaceInferenceAPI = 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
+ HuggingFaceEmbedding = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5")
31
+
32
+ # Define the directory for persistent storage and data
33
+ PERSIST_DIR = "./db"
34
+ DATA_DIR = "data"
35
+
36
+ # Ensure data directory exists
37
+ os.makedirs(DATA_DIR, exist_ok=True)
38
+ os.makedirs(PERSIST_DIR, exist_ok=True)
39
+
40
+ # Function to read the PDF from the predefined location
41
+ def read_pdf():
42
+ pdf_path = os.path.join(DATA_DIR, "machine_reasons_actions.pdf")
43
+ with open(pdf_path, "rb") as f:
44
+ base64_pdf = base64.b64encode(f.read()).decode('utf-8')
45
+ return f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>'
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 = {
51
+ "Air temperature [K]": air_temp,
52
+ "Process temperature [K]": proc_temp,
53
+ "Rotational speed [rpm]": speed,
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
+
69
+ # Make a prediction
70
+ prediction = model.predict(sample_df)[0]
71
+
72
+ # Initialize the reason list
73
+ reasons = []
74
+
75
+ # Define acceptable ranges for each feature with user-friendly feedback
76
+ acceptable_ranges = {
77
+ "Air temperature [K]": (150, 500),
78
+ "Process temperature [K]": (150, 500),
79
+ "Rotational speed [rpm]": (500, 1500),
80
+ "Torque [Nm]": (100, 800),
81
+ "Tool wear [min]": (50, 300)
82
+ }
83
+
84
+ # User-friendly reasons for each feature
85
+ if air_temp < 150:
86
+ reasons.append("• The air temperature is too low, which might be causing the machine to underperform.")
87
+ elif air_temp > 500:
88
+ reasons.append("• The air temperature is too high, which could be causing the machine to overheat.")
89
+
90
+ if proc_temp < 150:
91
+ reasons.append("• The process temperature is below the normal range, possibly affecting machine efficiency.")
92
+ elif proc_temp > 500:
93
+ reasons.append("• The process temperature is too high, which might lead to overheating.")
94
+
95
+ if speed < 500:
96
+ reasons.append("• The rotational speed is too low, causing the machine to operate inefficiently.")
97
+ elif speed > 1500:
98
+ reasons.append("• The rotational speed is too high, which might be causing excessive strain on the machine.")
99
+
100
+ if torque < 100:
101
+ reasons.append("• The torque is too low, which may indicate that the machine is not operating at its full capacity.")
102
+ elif torque > 800:
103
+ reasons.append("• The torque is too high, possibly putting excessive stress on the machine's components.")
104
+
105
+ if tool_wear < 50:
106
+ reasons.append("• The tool wear is minimal, but routine checks are still recommended to prevent future issues.")
107
+ elif tool_wear > 300:
108
+ reasons.append("• The tool wear is high, and the tool may need to be replaced soon to maintain optimal performance.")
109
+
110
+ # Generate the final result message
111
+ if prediction == 0:
112
+ result_message = "🔴 Machine is NOT working.\n" # First line for machine status
113
+ if reasons:
114
+ result_message += "\n".join(reasons) # Second row onward for reasons with bullet points
115
+ else:
116
+ result_message += "No specific reason identified." # In case no issues found
117
+ else:
118
+ result_message = "🟢 Machine is working fine."
119
+
120
+ return result_message, reasons
121
+
122
+ # PDF Reader logic
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
+ f"""You are a Q&A assistant named AskAI. Here are the actions based on the reason: {reason}. Provide answers based on this context."""
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
+ # Example query based on the machine status reason
139
+ answer = query_engine.query(reason)
140
+
141
+ return answer.response if hasattr(answer, 'response') else "Sorry, I couldn't find an answer."
142
+
143
+ # Combined Gradio interface
144
+ with gr.Blocks() as demo:
145
+ gr.Markdown("<h1 style='text-align: center;'>Smart Machine Health Predictor & PDF Chatbot</h1>")
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=lambda air, proc, spd, tq, wear: predict_status(air, proc, spd, tq, wear),
167
+ inputs=[air_temp, proc_temp, speed, torque, tool_wear],
168
+ outputs=output_status)
169
+
170
+ submit_btn.click(fn=lambda reason: handle_query(reason),
171
+ inputs=output_status,
172
+ outputs=response_box)
173
+
174
+ # Display the PDF content
175
+ gr.Markdown(read_pdf())
176
+
177
+ # Launch the app
178
+ demo.launch()