File size: 5,884 Bytes
77f855f
 
 
7516733
77f855f
 
 
6523aaf
 
 
 
7516733
 
77f855f
 
 
6523aaf
 
 
 
 
77f855f
 
 
 
 
7516733
 
 
 
 
 
266f43b
 
 
 
 
7516733
 
 
 
 
 
 
 
 
77f855f
 
 
 
 
 
 
 
 
 
 
 
 
 
ef0b259
77f855f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef0b259
77f855f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334950f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import os
import streamlit as st
from supabase.client import create_client
from langchain_groq import ChatGroq
from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
from streamlit_mic_recorder import speech_to_text

# --- DIRECT ENVIRONMENT ACCESS (Bypasses st.secrets bug) ---
SUPABASE_URL = os.getenv("SUPABASE_URL")
SUPABASE_KEY = os.getenv("SUPABASE_KEY")
GEMINI_KEY = os.getenv("GEMINI_KEY")
# --- FETCH SECRETS ---
GROQ_API_KEY = os.getenv("GROQ_API_KEY")

# --- 1. SETTINGS & KEYS ---

# --- DEBUGGING UI (Temporary - helps us see what's wrong) ---
if not SUPABASE_URL:
    st.error("❌ SUPABASE_URL is missing from Environment Variables.")
    # Lists all variables to see if they are named differently (Safe for debugging)
    # st.write("Available keys:", list(os.environ.keys())) 
    st.stop()

# --- 2. INITIALIZE CLIENTS ---
# Using Gemini 3 Flash (Stable 2026 version) for the fastest industrial response
supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
#llm = ChatGoogleGenerativeAI(
#    model="gemini-2.5-flash-lite", # Exact name from your list
#    google_api_key=GEMINI_KEY,
#    temperature=0.1,
#   max_output_tokens=1000
#)
embeddings = GoogleGenerativeAIEmbeddings(
    model="models/gemini-embedding-001",
    google_api_key=GEMINI_KEY,
    task_type="retrieval_query" # Critical for the app search to work
)

# --- INITIALIZE GROQ LLM ---
# Llama 3.3 70B is the 'Pro' level model for complex industrial reasoning.
# Llama 3.1 8B is the 'Instant' model if you want lighting speed.
llm = ChatGroq(
    model_name="llama-3.3-70b-versatile", 
    groq_api_key=GROQ_API_KEY,
    temperature=0.1, # Low temperature for technical accuracy
    max_tokens=1024
)

# --- 3. UI SETUP ---
st.set_page_config(page_title="Industrial SOP Agent", page_icon="🔧", layout="wide")

# Custom CSS for a professional "Dark Mode" factory look
st.markdown("""
    <style>
    .main { background-color: #0e1117; }
    .stButton>button { width: 100%; border-radius: 5px; height: 3em; background-color: #ff4b4b; color: white; }
    </style>
    """, unsafe_allow_html=True)

st.title("👨‍🔧 Smart Factory SOP Assistant")
st.caption("Troubleshoot MCU installation, EBS, Siemens VFDs, Arduino, and more in real-time.")

# --- 4. SIDEBAR: THE MACHINE LIBRARY ---
st.sidebar.header("📚 Machine Library")

# Fetch unique manuals currently in your Supabase database
try:
    response = supabase.table("documents").select("metadata->manual").execute()
    # Extract unique names from metadata
    all_manuals = list(set([item['manual'] for item in response.data])) if response.data else []
except:
    all_manuals = []

selected_manual = st.sidebar.selectbox(
    "Which machine are you working on?",
    ["All Machines"] + all_manuals
)

target_language = st.sidebar.radio("Response Language", ["Hindi (हिंदी)", "English", "Spanish"])

st.sidebar.divider()
st.sidebar.info("Tip: Use the microphone icon to describe a fault code or sound.")

# --- 5. INPUT SECTION ---
st.write("### 🔍 What is the issue?")
col1, col2 = st.columns([0.85, 0.15])

with col2:
    # Voice input (Configured for Indian accents)
    voice_input = speech_to_text(
        language='hi-IN' if target_language != "English" else 'en-US',
        start_prompt="🎙️",
        stop_prompt="⏹️",
        key='speech'
    )

with col1:
    user_query = st.text_input(
        "Describe the fault (e.g., 'F0001 error on Siemens VFD')", 
        value=voice_input if voice_input else "",
        placeholder="Type or speak your issue here..."
    )

# --- 6. AGENT LOGIC ---
if user_query:
    with st.spinner("Consulting technical manuals..."):
        # A. Convert query to vector (3072 dimensions)
        q_vector = embeddings.embed_query(user_query)
        
        # B. Metadata Filtering logic
        search_filter = {} if selected_manual == "All Machines" else {"manual": selected_manual}
        
        # C. Search Database
		# Simplified RPC call if the first one fails
		# Simplified RPC call if the first one fails
        matches = supabase.rpc('match_documents', {
            'query_embedding': q_vector,
            'match_threshold': 0.25,
            'match_count': 4,
            'filter': search_filter if selected_manual != "All Machines" else {}
        }).execute()

        if not matches.data:
            st.warning("⚠️ No specific match found in the manuals. Try using the exact fault code.")
        else:
            # D. Compile Context
            context_text = ""
            for m in matches.data:
                source = m['metadata'].get('manual', 'Unknown')
                page = m['metadata'].get('page', '?')
                context_text += f"\n[Source: {source}, Page: {page}]\n{m['content']}\n"

            # E. Generate Engineering Response
            prompt = f"""
            You are a Senior Maintenance Engineer. 
            User Language: {target_language}
            Context from Manuals: {context_text}
            
            Worker's Issue: {user_query}
            
            INSTRUCTIONS:
            1. Provide the answer ONLY in {target_language}.
            2. Start with a '⚠️ SAFETY CHECK' if high voltage or mechanical danger is involved.
            3. Provide a clear, numbered 'Action Plan'.
            4. State which manual and page number you found the answer on.
            5. If the manual doesn't contain the answer, say "I cannot find this in our library."
            """
            
            result = llm.invoke(prompt)
            
            # F. Display Result
            st.markdown("---")
            st.markdown(f"### 🛠️ Solution for: *{selected_manual}*")
            st.write(result.content)

            # Show Sources for verification
            with st.expander("View Source Snippets (Audit Trail)"):
                st.text(context_text)