censAgent commited on
Commit
334950f
·
verified ·
1 Parent(s): bb7b4ee

Upload 2 files

Browse files
Files changed (2) hide show
  1. src/app.py +137 -0
  2. src/requirements.txt +5 -0
src/app.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
src/requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ streamlit
2
+ supabase
3
+ langchain-google-genai
4
+ streamlit-mic-recorder
5
+ google-generativeai