bhagwandas commited on
Commit
c966df4
Β·
verified Β·
1 Parent(s): 055e613

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -29
app.py CHANGED
@@ -4,25 +4,35 @@ import matplotlib.pyplot as plt
4
  import seaborn as sns
5
  from sklearn.ensemble import IsolationForest
6
  from sklearn.preprocessing import StandardScaler
7
- import openai
8
- import os
9
-
10
- # Set your OpenAI key here or use Hugging Face Secrets Manager
11
- openai.api_key = os.getenv("OPENAI_API_KEY")
12
 
13
  st.set_page_config(page_title="Smart Factory RAG Assistant", layout="wide")
14
 
15
- st.title("🏭 Industry 5.0 | Smart Factory RAG Assistant")
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  # File Upload
18
- uploaded_file = st.file_uploader("πŸ“€ Upload your factory CSV data", type=["csv"])
19
 
20
  if uploaded_file:
21
  df = pd.read_csv(uploaded_file)
22
  st.success("βœ… File uploaded and loaded!")
23
 
24
  # Basic Preview
25
- st.subheader("πŸ“„ Data Preview")
26
  st.dataframe(df.head())
27
 
28
  # Descriptive Stats
@@ -48,13 +58,13 @@ if uploaded_file:
48
  st.write(f"Detected {len(anomalies)} anomalies")
49
  st.dataframe(anomalies.head(10))
50
 
51
- # Prepare context for GPT
52
  st.subheader("🧠 Role-Based Decision Assistant")
53
  role = st.selectbox("Select your role", ["Engineer", "Operator"])
54
  question = st.text_input("Ask a question based on the data analysis")
55
 
56
  if question:
57
- with st.spinner("Thinking..."):
58
  summary = df.describe().to_string()
59
  corr_text = corr.to_string()
60
  anomaly_count = len(anomalies)
@@ -74,27 +84,21 @@ ANOMALY DETECTION:
74
  {anomaly_count} anomalies detected using Isolation Forest method.
75
 
76
  Based on this context, answer the following question in a clear, technically accurate manner and suggest best decisions from the point of view of a {role}.
77
- """
78
 
79
- final_prompt = f"""{context}
80
  QUESTION: {question}
81
- ANSWER:"""
82
-
83
- try:
84
- response = openai.ChatCompletion.create(
85
- model="gpt-4",
86
- messages=[
87
- {"role": "system", "content": f"You are an expert {role} in a smart factory."},
88
- {"role": "user", "content": final_prompt}
89
- ],
90
- temperature=0.5,
91
- max_tokens=500
92
- )
93
- answer = response['choices'][0]['message']['content']
94
- st.success("βœ… Recommendation:")
95
- st.markdown(f"**{answer}**")
96
- except Exception as e:
97
- st.error(f"⚠️ Error calling GPT API: {str(e)}")
98
 
99
  else:
100
  st.info("πŸ“‚ Please upload a factory CSV data file to begin analysis.")
 
4
  import seaborn as sns
5
  from sklearn.ensemble import IsolationForest
6
  from sklearn.preprocessing import StandardScaler
7
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
8
+ import torch
 
 
 
9
 
10
  st.set_page_config(page_title="Smart Factory RAG Assistant", layout="wide")
11
 
12
+ st.title("🏠 Industry 5.0 | Smart Factory RAG Assistant (Open Source)")
13
+
14
+ # Load the open-source model (Mistral-7B-Instruct)
15
+ @st.cache_resource(show_spinner=True)
16
+ def load_model():
17
+ tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.2")
18
+ model = AutoModelForCausalLM.from_pretrained(
19
+ "mistralai/Mistral-7B-Instruct-v0.2",
20
+ torch_dtype=torch.float16,
21
+ device_map="auto"
22
+ )
23
+ return pipeline("text-generation", model=model, tokenizer=tokenizer)
24
+
25
+ nlp = load_model()
26
 
27
  # File Upload
28
+ uploaded_file = st.file_uploader("πŸ“„ Upload your factory CSV data", type=["csv"])
29
 
30
  if uploaded_file:
31
  df = pd.read_csv(uploaded_file)
32
  st.success("βœ… File uploaded and loaded!")
33
 
34
  # Basic Preview
35
+ st.subheader("πŸ“ƒ Data Preview")
36
  st.dataframe(df.head())
37
 
38
  # Descriptive Stats
 
58
  st.write(f"Detected {len(anomalies)} anomalies")
59
  st.dataframe(anomalies.head(10))
60
 
61
+ # Role-based Assistant
62
  st.subheader("🧠 Role-Based Decision Assistant")
63
  role = st.selectbox("Select your role", ["Engineer", "Operator"])
64
  question = st.text_input("Ask a question based on the data analysis")
65
 
66
  if question:
67
+ with st.spinner("Generating insights..."):
68
  summary = df.describe().to_string()
69
  corr_text = corr.to_string()
70
  anomaly_count = len(anomalies)
 
84
  {anomaly_count} anomalies detected using Isolation Forest method.
85
 
86
  Based on this context, answer the following question in a clear, technically accurate manner and suggest best decisions from the point of view of a {role}.
 
87
 
 
88
  QUESTION: {question}
89
+ ANSWER:
90
+ """
91
+ prompt = f"<s>[INST] {context} [/INST]"
92
+ output = nlp(prompt, max_new_tokens=512, do_sample=True, temperature=0.5)[0]['generated_text']
93
+
94
+ # Clean up response
95
+ if '[/INST]' in output:
96
+ answer = output.split('[/INST]')[-1].strip()
97
+ else:
98
+ answer = output.strip()
99
+
100
+ st.success("βœ… Recommendation:")
101
+ st.markdown(f"**{answer}**")
 
 
 
 
102
 
103
  else:
104
  st.info("πŸ“‚ Please upload a factory CSV data file to begin analysis.")