censAgent commited on
Commit
77f855f
·
verified ·
1 Parent(s): 0547ce1

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +155 -136
src/streamlit_app.py CHANGED
@@ -1,137 +1,156 @@
1
- import streamlit as st
2
- from supabase.client import create_client
3
- from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
4
- from streamlit_mic_recorder import speech_to_text
5
-
6
- # --- 1. SETTINGS & KEYS ---
7
- # --- 1. CONFIG FROM HUGGING FACE SECRETS ---
8
- SUPABASE_URL = st.secrets["SUPABASE_URL"]
9
- SUPABASE_KEY = st.secrets["SUPABASE_KEY"]
10
- GEMINI_KEY = st.secrets["GEMINI_KEY"]
11
-
12
-
13
- # --- 2. INITIALIZE CLIENTS ---
14
- # Using Gemini 3 Flash (Stable 2026 version) for the fastest industrial response
15
- supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
16
- llm = ChatGoogleGenerativeAI(
17
- model="gemini-2.5-flash-lite", # Exact name from your list
18
- google_api_key=GEMINI_KEY,
19
- temperature=0.1,
20
- max_output_tokens=1000
21
- )
22
- embeddings = GoogleGenerativeAIEmbeddings(
23
- model="models/gemini-embedding-001",
24
- google_api_key=GEMINI_KEY,
25
- task_type="retrieval_query" # Critical for the app search to work
26
- )
27
-
28
- # --- 3. UI SETUP ---
29
- st.set_page_config(page_title="Industrial SOP Agent", page_icon="🔧", layout="wide")
30
-
31
- # Custom CSS for a professional "Dark Mode" factory look
32
- st.markdown("""
33
- <style>
34
- .main { background-color: #0e1117; }
35
- .stButton>button { width: 100%; border-radius: 5px; height: 3em; background-color: #ff4b4b; color: white; }
36
- </style>
37
- """, unsafe_allow_html=True)
38
-
39
- st.title("👨‍🔧 Smart Factory SOP Assistant")
40
- st.caption("Troubleshoot Siemens VFDs, ESP32 Controllers, and more in real-time.")
41
-
42
- # --- 4. SIDEBAR: THE MACHINE LIBRARY ---
43
- st.sidebar.header("📚 Machine Library")
44
-
45
- # Fetch unique manuals currently in your Supabase database
46
- try:
47
- response = supabase.table("documents").select("metadata->manual").execute()
48
- # Extract unique names from metadata
49
- all_manuals = list(set([item['manual'] for item in response.data])) if response.data else []
50
- except:
51
- all_manuals = []
52
-
53
- selected_manual = st.sidebar.selectbox(
54
- "Which machine are you working on?",
55
- ["All Machines"] + all_manuals
56
- )
57
-
58
- target_language = st.sidebar.radio("Response Language", ["Hindi (हिंदी)", "English", "Marathi (मराठी)"])
59
-
60
- st.sidebar.divider()
61
- st.sidebar.info("Tip: Use the microphone icon to describe a fault code or sound.")
62
-
63
- # --- 5. INPUT SECTION ---
64
- st.write("### 🔍 What is the issue?")
65
- col1, col2 = st.columns([0.85, 0.15])
66
-
67
- with col2:
68
- # Voice input (Configured for Indian accents)
69
- voice_input = speech_to_text(
70
- language='hi-IN' if target_language != "English" else 'en-US',
71
- start_prompt="🎙️",
72
- stop_prompt="⏹️",
73
- key='speech'
74
- )
75
-
76
- with col1:
77
- user_query = st.text_input(
78
- "Describe the fault (e.g., 'F0001 error on Siemens VFD')",
79
- value=voice_input if voice_input else "",
80
- placeholder="Type or speak your issue here..."
81
- )
82
-
83
- # --- 6. AGENT LOGIC ---
84
- if user_query:
85
- with st.spinner("Consulting technical manuals..."):
86
- # A. Convert query to vector (3072 dimensions)
87
- q_vector = embeddings.embed_query(user_query)
88
-
89
- # B. Metadata Filtering logic
90
- search_filter = {} if selected_manual == "All Machines" else {"manual": selected_manual}
91
-
92
- # C. Search Database
93
- # Simplified RPC call if the first one fails
94
- # Simplified RPC call if the first one fails
95
- matches = supabase.rpc('match_documents', {
96
- 'query_embedding': q_vector,
97
- 'match_threshold': 0.25,
98
- 'match_count': 4,
99
- 'filter': search_filter if selected_manual != "All Machines" else {}
100
- }).execute()
101
-
102
- if not matches.data:
103
- st.warning("⚠️ No specific match found in the manuals. Try using the exact fault code.")
104
- else:
105
- # D. Compile Context
106
- context_text = ""
107
- for m in matches.data:
108
- source = m['metadata'].get('manual', 'Unknown')
109
- page = m['metadata'].get('page', '?')
110
- context_text += f"\n[Source: {source}, Page: {page}]\n{m['content']}\n"
111
-
112
- # E. Generate Engineering Response
113
- prompt = f"""
114
- You are a Senior Maintenance Engineer.
115
- User Language: {target_language}
116
- Context from Manuals: {context_text}
117
-
118
- Worker's Issue: {user_query}
119
-
120
- INSTRUCTIONS:
121
- 1. Provide the answer ONLY in {target_language}.
122
- 2. Start with a '⚠️ SAFETY CHECK' if high voltage or mechanical danger is involved.
123
- 3. Provide a clear, numbered 'Action Plan'.
124
- 4. State which manual and page number you found the answer on.
125
- 5. If the manual doesn't contain the answer, say "I cannot find this in our library."
126
- """
127
-
128
- result = llm.invoke(prompt)
129
-
130
- # F. Display Result
131
- st.markdown("---")
132
- st.markdown(f"### 🛠️ Solution for: *{selected_manual}*")
133
- st.write(result.content)
134
-
135
- # Show Sources for verification
136
- with st.expander("View Source Snippets (Audit Trail)"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  st.text(context_text)
 
1
+ import os
2
+ import streamlit as st
3
+ from supabase.client import create_client
4
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
5
+ from streamlit_mic_recorder import speech_to_text
6
+
7
+ # Helper function to get secrets from HF or Streamlit
8
+ def get_secret(key):
9
+ # 1. Try environment variables (Hugging Face default)
10
+ value = os.environ.get(key)
11
+ if value:
12
+ return value
13
+ # 2. Try Streamlit Secrets (Hugging Face / Streamlit fallback)
14
+ try:
15
+ return st.secrets[key]
16
+ except Exception:
17
+ return None
18
+
19
+ # --- 1. SETTINGS & KEYS ---
20
+ # --- 1. CONFIG FROM HUGGING FACE SECRETS ---
21
+ SUPABASE_URL = st.secrets["SUPABASE_URL"]
22
+ SUPABASE_KEY = st.secrets["SUPABASE_KEY"]
23
+ GEMINI_KEY = st.secrets["GEMINI_KEY"]
24
+
25
+
26
+ # Safety Check: If any are missing, show a clear message in the UI
27
+ if not all([SUPABASE_URL, SUPABASE_KEY, GEMINI_KEY]):
28
+ st.error("🚨 Configuration Error: Secrets not found in Hugging Face Settings.")
29
+ st.info("Check 'Settings -> Variables and secrets' and ensure names match EXACTLY.")
30
+ st.stop()
31
+
32
+ # --- 2. INITIALIZE CLIENTS ---
33
+ # Using Gemini 3 Flash (Stable 2026 version) for the fastest industrial response
34
+ supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
35
+ llm = ChatGoogleGenerativeAI(
36
+ model="gemini-2.5-flash-lite", # Exact name from your list
37
+ google_api_key=GEMINI_KEY,
38
+ temperature=0.1,
39
+ max_output_tokens=1000
40
+ )
41
+ embeddings = GoogleGenerativeAIEmbeddings(
42
+ model="models/gemini-embedding-001",
43
+ google_api_key=GEMINI_KEY,
44
+ task_type="retrieval_query" # Critical for the app search to work
45
+ )
46
+
47
+ # --- 3. UI SETUP ---
48
+ st.set_page_config(page_title="Industrial SOP Agent", page_icon="🔧", layout="wide")
49
+
50
+ # Custom CSS for a professional "Dark Mode" factory look
51
+ st.markdown("""
52
+ <style>
53
+ .main { background-color: #0e1117; }
54
+ .stButton>button { width: 100%; border-radius: 5px; height: 3em; background-color: #ff4b4b; color: white; }
55
+ </style>
56
+ """, unsafe_allow_html=True)
57
+
58
+ st.title("👨‍🔧 Smart Factory SOP Assistant")
59
+ st.caption("Troubleshoot Siemens VFDs, ESP32 Controllers, and more in real-time.")
60
+
61
+ # --- 4. SIDEBAR: THE MACHINE LIBRARY ---
62
+ st.sidebar.header("📚 Machine Library")
63
+
64
+ # Fetch unique manuals currently in your Supabase database
65
+ try:
66
+ response = supabase.table("documents").select("metadata->manual").execute()
67
+ # Extract unique names from metadata
68
+ all_manuals = list(set([item['manual'] for item in response.data])) if response.data else []
69
+ except:
70
+ all_manuals = []
71
+
72
+ selected_manual = st.sidebar.selectbox(
73
+ "Which machine are you working on?",
74
+ ["All Machines"] + all_manuals
75
+ )
76
+
77
+ target_language = st.sidebar.radio("Response Language", ["Hindi (हिंदी)", "English", "Marathi (मराठी)"])
78
+
79
+ st.sidebar.divider()
80
+ st.sidebar.info("Tip: Use the microphone icon to describe a fault code or sound.")
81
+
82
+ # --- 5. INPUT SECTION ---
83
+ st.write("### 🔍 What is the issue?")
84
+ col1, col2 = st.columns([0.85, 0.15])
85
+
86
+ with col2:
87
+ # Voice input (Configured for Indian accents)
88
+ voice_input = speech_to_text(
89
+ language='hi-IN' if target_language != "English" else 'en-US',
90
+ start_prompt="🎙️",
91
+ stop_prompt="⏹️",
92
+ key='speech'
93
+ )
94
+
95
+ with col1:
96
+ user_query = st.text_input(
97
+ "Describe the fault (e.g., 'F0001 error on Siemens VFD')",
98
+ value=voice_input if voice_input else "",
99
+ placeholder="Type or speak your issue here..."
100
+ )
101
+
102
+ # --- 6. AGENT LOGIC ---
103
+ if user_query:
104
+ with st.spinner("Consulting technical manuals..."):
105
+ # A. Convert query to vector (3072 dimensions)
106
+ q_vector = embeddings.embed_query(user_query)
107
+
108
+ # B. Metadata Filtering logic
109
+ search_filter = {} if selected_manual == "All Machines" else {"manual": selected_manual}
110
+
111
+ # C. Search Database
112
+ # Simplified RPC call if the first one fails
113
+ # Simplified RPC call if the first one fails
114
+ matches = supabase.rpc('match_documents', {
115
+ 'query_embedding': q_vector,
116
+ 'match_threshold': 0.25,
117
+ 'match_count': 4,
118
+ 'filter': search_filter if selected_manual != "All Machines" else {}
119
+ }).execute()
120
+
121
+ if not matches.data:
122
+ st.warning("⚠️ No specific match found in the manuals. Try using the exact fault code.")
123
+ else:
124
+ # D. Compile Context
125
+ context_text = ""
126
+ for m in matches.data:
127
+ source = m['metadata'].get('manual', 'Unknown')
128
+ page = m['metadata'].get('page', '?')
129
+ context_text += f"\n[Source: {source}, Page: {page}]\n{m['content']}\n"
130
+
131
+ # E. Generate Engineering Response
132
+ prompt = f"""
133
+ You are a Senior Maintenance Engineer.
134
+ User Language: {target_language}
135
+ Context from Manuals: {context_text}
136
+
137
+ Worker's Issue: {user_query}
138
+
139
+ INSTRUCTIONS:
140
+ 1. Provide the answer ONLY in {target_language}.
141
+ 2. Start with a '⚠️ SAFETY CHECK' if high voltage or mechanical danger is involved.
142
+ 3. Provide a clear, numbered 'Action Plan'.
143
+ 4. State which manual and page number you found the answer on.
144
+ 5. If the manual doesn't contain the answer, say "I cannot find this in our library."
145
+ """
146
+
147
+ result = llm.invoke(prompt)
148
+
149
+ # F. Display Result
150
+ st.markdown("---")
151
+ st.markdown(f"### 🛠️ Solution for: *{selected_manual}*")
152
+ st.write(result.content)
153
+
154
+ # Show Sources for verification
155
+ with st.expander("View Source Snippets (Audit Trail)"):
156
  st.text(context_text)