shahed125238 commited on
Commit
d2555b3
·
verified ·
1 Parent(s): 1d6cdc5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -51
app.py CHANGED
@@ -10,10 +10,10 @@ from llama_index.core import Settings
10
  import os
11
  import base64
12
 
13
- # Load environment variables for HuggingFace API
14
  load_dotenv()
15
 
16
- # Configure the Llama index settings
17
  Settings.llm = HuggingFaceInferenceAPI(
18
  model_name="google/gemma-1.1-7b-it",
19
  tokenizer_name="google/gemma-1.1-7b-it",
@@ -26,42 +26,29 @@ Settings.embed_model = HuggingFaceEmbedding(
26
  model_name="BAAI/bge-small-en-v1.5"
27
  )
28
 
29
- # Define directories for persistent storage and data
30
  PERSIST_DIR = "./db"
31
  DATA_DIR = "data"
32
 
33
- # Ensure data directory exists
34
  os.makedirs(DATA_DIR, exist_ok=True)
35
  os.makedirs(PERSIST_DIR, exist_ok=True)
36
 
37
- # Function to display PDF in Streamlit
38
- def displayPDF(file):
39
- with open(file, "rb") as f:
40
- base64_pdf = base64.b64encode(f.read()).decode('utf-8')
41
- pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>'
42
- st.markdown(pdf_display, unsafe_allow_html=True)
43
-
44
- # Function to handle PDF ingestion
45
  def data_ingestion():
46
  documents = SimpleDirectoryReader(DATA_DIR).load_data()
47
  storage_context = StorageContext.from_defaults()
48
  index = VectorStoreIndex.from_documents(documents)
49
  index.storage_context.persist(persist_dir=PERSIST_DIR)
50
 
51
- # Function to handle user queries
52
  def handle_query(query):
53
  storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
54
  index = load_index_from_storage(storage_context)
55
  chat_text_qa_msgs = [
56
- (
57
- "user",
58
- """You are a Q&A assistant named AskAI, created by Vatsa. You have a specific response programmed for when users ask about your creator, Suriya. The response is: "I was created by Suriya, an enthusiast in Artificial Intelligence."
59
- Context:
60
- {context_str}
61
- Question:
62
- {query_str}
63
- """
64
- )
65
  ]
66
  text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
67
 
@@ -75,40 +62,110 @@ def handle_query(query):
75
  else:
76
  return "Sorry, I couldn't find an answer."
77
 
78
- # Streamlit interface
79
- st.title("Integrated App: Gradio & Streamlit")
80
- st.markdown("### PDF Q&A + Machine Health Prediction")
 
 
 
 
81
 
82
- # Gradio App via iframe
83
- st.markdown("#### Machine Health Prediction App (Gradio)")
84
- gradio_app_url = "http://localhost:7860" # URL where Gradio app is running
85
- st.markdown(f'<iframe src="{gradio_app_url}" width="100%" height="800"></iframe>', unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
86
 
87
- # Streamlit section for PDF upload and chat
88
- st.markdown("#### PDF Chatbot App (Streamlit)")
 
 
 
 
 
 
89
 
90
- if 'messages' not in st.session_state:
91
- st.session_state.messages = [{'role': 'assistant', "content": 'Hello! Upload a PDF and ask me anything about its content.'}]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
- with st.sidebar:
94
- st.title("Menu:")
95
- uploaded_file = st.file_uploader("Upload your PDF Files and Click on the Submit & Process Button")
96
- if st.button("Submit & Process"):
97
- with st.spinner("Processing..."):
98
- filepath = "data/saved_pdf.pdf"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  with open(filepath, "wb") as f:
100
  f.write(uploaded_file.getbuffer())
101
- # displayPDF(filepath) # Display the uploaded PDF
102
- data_ingestion() # Process PDF every time new file is uploaded
103
- st.success("Done")
104
-
105
- user_prompt = st.chat_input("Ask me anything about the content of the PDF:")
106
- if user_prompt:
107
- st.session_state.messages.append({'role': 'user', "content": user_prompt})
108
- response = handle_query(user_prompt)
109
- st.session_state.messages.append({'role': 'assistant', "content": response})
110
 
111
- for message in st.session_state.messages:
112
- with st.chat_message(message['role']):
113
- st.write(message['content'])
 
114
 
 
 
 
10
  import os
11
  import base64
12
 
13
+ # Load environment variables for HuggingFace API tokens
14
  load_dotenv()
15
 
16
+ # Setup HuggingFace API for llama_index (used in the PDF chat functionality)
17
  Settings.llm = HuggingFaceInferenceAPI(
18
  model_name="google/gemma-1.1-7b-it",
19
  tokenizer_name="google/gemma-1.1-7b-it",
 
26
  model_name="BAAI/bge-small-en-v1.5"
27
  )
28
 
29
+ # Paths for file storage
30
  PERSIST_DIR = "./db"
31
  DATA_DIR = "data"
32
 
 
33
  os.makedirs(DATA_DIR, exist_ok=True)
34
  os.makedirs(PERSIST_DIR, exist_ok=True)
35
 
36
+ # PDF data ingestion function
 
 
 
 
 
 
 
37
  def data_ingestion():
38
  documents = SimpleDirectoryReader(DATA_DIR).load_data()
39
  storage_context = StorageContext.from_defaults()
40
  index = VectorStoreIndex.from_documents(documents)
41
  index.storage_context.persist(persist_dir=PERSIST_DIR)
42
 
43
+ # PDF query handler
44
  def handle_query(query):
45
  storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
46
  index = load_index_from_storage(storage_context)
47
  chat_text_qa_msgs = [
48
+ (
49
+ "user",
50
+ """You are a Q&A assistant named AskAI, created by Vatsa. You provide AI-powered answers to PDF documents."""
51
+ )
 
 
 
 
 
52
  ]
53
  text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
54
 
 
62
  else:
63
  return "Sorry, I couldn't find an answer."
64
 
65
+ # Machine Health Predictor Gradio App
66
+ def create_gradio_app():
67
+ with open('logistic_regression_model.pkl', 'rb') as model_file:
68
+ model = pickle.load(model_file)
69
+
70
+ with open('feature_columns.pkl', 'rb') as col_file:
71
+ feature_columns = pickle.load(col_file)
72
 
73
+ def predict_status(air_temp, proc_temp, speed, torque, tool_wear):
74
+ sample_input = {
75
+ "Air temperature [K]": air_temp,
76
+ "Process temperature [K]": proc_temp,
77
+ "Rotational speed [rpm]": speed,
78
+ "Torque [Nm]": torque,
79
+ "Tool wear [min]": tool_wear
80
+ }
81
+ sample_df = pd.DataFrame([sample_input])
82
+ for col in feature_columns:
83
+ if col not in sample_df.columns:
84
+ sample_df[col] = 0
85
+ sample_df = sample_df[feature_columns]
86
+ prediction = model.predict(sample_df)[0]
87
 
88
+ reasons = []
89
+ acceptable_ranges = {
90
+ "Air temperature [K]": (150, 500),
91
+ "Process temperature [K]": (150, 500),
92
+ "Rotational speed [rpm]": (500, 1500),
93
+ "Torque [Nm]": (100, 800),
94
+ "Tool wear [min]": (50, 300)
95
+ }
96
 
97
+ if air_temp < 150:
98
+ reasons.append("• The air temperature is too low.")
99
+ elif air_temp > 500:
100
+ reasons.append("• The air temperature is too high.")
101
+ if proc_temp < 150:
102
+ reasons.append("• The process temperature is below normal.")
103
+ elif proc_temp > 500:
104
+ reasons.append("• The process temperature is too high.")
105
+ if speed < 500:
106
+ reasons.append("• The rotational speed is too low.")
107
+ elif speed > 1500:
108
+ reasons.append("• The rotational speed is too high.")
109
+ if torque < 100:
110
+ reasons.append("• The torque is too low.")
111
+ elif torque > 800:
112
+ reasons.append("• The torque is too high.")
113
+ if tool_wear < 50:
114
+ reasons.append("• Tool wear is minimal.")
115
+ elif tool_wear > 300:
116
+ reasons.append("• Tool wear is high.")
117
 
118
+ if prediction == 0:
119
+ result_message = "🔴 Machine is NOT working.\n" + "\n".join(reasons) if reasons else "No specific reason."
120
+ else:
121
+ result_message = "🟢 Machine is working fine."
122
+
123
+ return result_message
124
+
125
+ return gr.Interface(
126
+ fn=predict_status,
127
+ inputs=[
128
+ gr.Slider(label="Air Temperature (K)", minimum=0, maximum=1000, step=0.01, value=300),
129
+ gr.Slider(label="Process Temperature (K)", minimum=0, maximum=1000, step=0.01, value=300),
130
+ gr.Slider(label="Rotational Speed (rpm)", minimum=0, maximum=2000, step=1, value=1000),
131
+ gr.Slider(label="Torque (Nm)", minimum=0, maximum=1000, step=0.1, value=500),
132
+ gr.Slider(label="Tool Wear (min)", minimum=0, maximum=1000, step=1, value=100)
133
+ ],
134
+ outputs="text",
135
+ title="Smart Machine Health Predictor",
136
+ description="Provide machine parameters to predict machine status."
137
+ )
138
+
139
+ # Display Gradio App in Streamlit
140
+ def run_gradio_app():
141
+ app = create_gradio_app()
142
+ app.launch(share=True)
143
+
144
+ # Streamlit Application - Combining Gradio and PDF Chatbot
145
+ def main():
146
+ st.title("Integrated Gradio & PDF Chat App")
147
+ st.sidebar.title("Choose Application")
148
+
149
+ app_choice = st.sidebar.selectbox("Select App", ("Machine Health Prediction (Gradio)", "PDF Chat (Streamlit)"))
150
+
151
+ if app_choice == "Machine Health Prediction (Gradio)":
152
+ st.write("Running the Machine Health Prediction app...")
153
+ run_gradio_app()
154
+ elif app_choice == "PDF Chat (Streamlit)":
155
+ st.write("PDF Chatbot Application")
156
+ uploaded_file = st.sidebar.file_uploader("Upload PDF")
157
+
158
+ if uploaded_file:
159
+ filepath = os.path.join(DATA_DIR, "saved_pdf.pdf")
160
  with open(filepath, "wb") as f:
161
  f.write(uploaded_file.getbuffer())
162
+ data_ingestion()
163
+ st.success("PDF processed.")
 
 
 
 
 
 
 
164
 
165
+ user_prompt = st.chat_input("Ask me anything about the PDF:")
166
+ if user_prompt:
167
+ response = handle_query(user_prompt)
168
+ st.write(response)
169
 
170
+ if __name__ == "__main__":
171
+ main()