CoolFace
Apppublic

Vaishnavi111/coversational_image_processing

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py185 linesDownload Raw Back to root
1import streamlit as st2import google.generativeai as genai3from PIL import Image4import yaml5from yaml.loader import SafeLoader6import os7 8# -------------------------------9# Streamlit Page Config10# -------------------------------11st.set_page_config(12    page_title="Electronics Troubleshooting Chatbot",13    page_icon="๐Ÿค–",14    layout="centered"15)16 17# -------------------------------18# Load Config19# -------------------------------20CONFIG_FILE = "config.yaml"21 22def load_config():23    with open(CONFIG_FILE) as file:24        return yaml.load(file, Loader=SafeLoader)25 26def save_config(config):27    with open(CONFIG_FILE, "w") as file:28        yaml.dump(config, file, default_flow_style=False)29 30config = load_config()31 32# -------------------------------33# Authentication and Registration34# -------------------------------35def authenticate():36    # Initialize auth session state37    if 'authenticated' not in st.session_state:38        st.session_state['authenticated'] = False39 40    if st.session_state['authenticated']:41        return True42 43    # Only show login/register if NOT authenticated44    auth_choice = st.sidebar.radio("Choose Action:", ["Login", "Register"])45 46    if auth_choice == "Register":47        st.subheader("๐Ÿ“ Create a New Account")48 49        with st.form("register_form"):50            new_username = st.text_input("Username")51            new_name = st.text_input("Full Name")52            new_email = st.text_input("Email")53            new_password = st.text_input("Password", type="password")54            confirm_password = st.text_input("Confirm Password", type="password")55            register_btn = st.form_submit_button("Register")56 57        if register_btn:58            if not new_username or not new_password or not new_email:59                st.error("โš ๏ธ Please fill in all required fields.")60            elif new_password != confirm_password:61                st.error("โŒ Passwords do not match.")62            elif new_username in config['credentials']['usernames']:63                st.error("โŒ Username already exists. Choose another.")64            else:65                config['credentials']['usernames'][new_username] = {66                    "email": new_email,67                    "name": new_name,68                    "password": new_password  # You can hash this if needed69                }70                save_config(config)71                st.success("โœ… Registration successful! Please login from the sidebar.")72 73    elif auth_choice == "Login":74        st.subheader("๐Ÿ”‘ Login")75 76        with st.form("login_form"):77            username = st.text_input("Username")78            password = st.text_input("Password", type="password")79            login_btn = st.form_submit_button("Login")80 81        if login_btn:82            if username in config['credentials']['usernames'] and config['credentials']['usernames'][username]["password"] == password:83                st.session_state['authenticated'] = True84                st.sidebar.success(f"โœ… Logged in as {username}")85                st.rerun()  # <--- this refreshes the UI to hide login form86            else:87                st.error("โŒ Invalid Username or Password")88 89    return False90 91# -------------------------------92# Main Content After Authentication93# -------------------------------94def chatbot_interface():95    # -------------------------------96    # API Key Config97    # -------------------------------98    if "GOOGLE_API_KEY" in st.secrets:99        api_key = st.secrets["GOOGLE_API_KEY"]100    else:101        api_key = st.text_input("Enter your Google API Key:", type="password")102 103    if not api_key:104        st.warning("Please provide your Google API Key to continue.")105        st.stop()106 107    # Configure Gemini client108    genai.configure(api_key=api_key)109 110    # -------------------------------111    # System Prompt112    # -------------------------------113    SYSTEM_PROMPT = """114    You are an expert in electronics troubleshooting.115 116    I face the provided the following issue:117    \"{question}\"118 119    Analyze the image (if provided), identify any visible issues, and provide:120    1. A diagnosis based on the description and/or image.121    2. Explanation of the problem.122    3. Suggested fix or faulty component.123    """124 125    # -------------------------------126    # Function to Get Response127    # -------------------------------128    def get_gemini_response(user_question, image=None):129        model = genai.GenerativeModel("gemini-1.5-flash")130        final_prompt = SYSTEM_PROMPT.format(question=user_question if user_question else "No text provided")131 132        if image:133            response = model.generate_content([final_prompt, image])134        else:135            response = model.generate_content(final_prompt)136 137        return response.text.strip()138 139    # -------------------------------140    # Chatbot UI141    # -------------------------------142    st.title("๐Ÿ”ง Electronics Troubleshooting Chatbot (Gemini Vision Pro)")143    st.markdown("Upload an image of your electronic circuit/device and ask a troubleshooting question.")144 145    user_question = st.text_input("๐Ÿ”Ž Describe your issue or question:", key="input")146 147    uploaded_image = st.file_uploader("๐Ÿ“ท Upload an image (optional)", type=["jpg", "jpeg", "png"])148 149    image_obj = None150    if uploaded_image:151        image_obj = Image.open(uploaded_image)152        st.image(image_obj, caption="Uploaded Image", use_column_width=True)153 154    if st.button("๐Ÿš€ Analyze & Troubleshoot"):155        with st.spinner("Analyzing... please wait"):156            try:157                response = get_gemini_response(user_question, image_obj)158                st.subheader("โœ… AI's Diagnosis & Suggestion:")159                st.write(response)160            except Exception as e:161                st.error(f"Error: {e}")162 163# -------------------------------164# Sidebar with Logout165# -------------------------------166def sidebar_logout():167    if st.session_state.get('authenticated', False):168        st.sidebar.button("Logout", on_click=logout)169 170def logout():171    st.session_state['authenticated'] = False172    st.session_state.clear()  # Clear session data173    st.experimental_rerun()  # Rerun the app to refresh everything174 175# -------------------------------176# Main Flow177# -------------------------------178if authenticate():179    # If logged in, display the chatbot interface180    sidebar_logout()  # Add logout button to the sidebar181    chatbot_interface()182else:183    # If not logged in, show the login or registration form184    sidebar_logout()  # In case of logout, hide the login/register form185