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(""" """, 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)