import os import tempfile import json import streamlit as st from PIL import Image import pandas as pd try: from gradio_client import Client, handle_file except ImportError: # pragma: no cover - optional dependency Client = None SPACE_ID = "BARATH0070/plate-detector" # Try common Gradio API endpoint names COMMON_API_NAMES = [ "/detect_and_save", # Function name "/query_database", # Function name "/predict", # Default Gradio names "/predict_0", "/predict_1", "/run", # Run endpoint "/run_0", "/run_1", ] # Initialize session state for API names if "detect_api" not in st.session_state: st.session_state.detect_api = "/predict_0" if "query_api" not in st.session_state: st.session_state.query_api = "/predict_1" if "query_input" not in st.session_state: st.session_state.query_input = "" # Example queries for testing EXAMPLE_QUERIES = [ "Show TN vehicles", "How many cars detected?", "Show all trucks", "Count bikes in database", "Show latest 10 detections", "Vehicles from adyar", "Top detected plates", "Vehicle type distribution", "Show vehicles with high confidence", "Traffic by hour" ] def find_api_endpoints(): """Try to find available API endpoints""" if Client is None: return [] try: client = Client(SPACE_ID) # Try to get API info available = [] for api_name in COMMON_API_NAMES: try: # Just check if the endpoint exists by attempting a view available.append(api_name) except: pass return available except Exception as e: print(f"Error finding APIs: {e}") return [] def get_available_apis(): """Get list of available API functions from the Space""" try: if Client is None: return None client = Client(SPACE_ID) # Try to view API info = client.view_api() return info except Exception as e: return None def call_space(pil_image): if Client is None: raise RuntimeError("gradio_client is not installed.") client = Client(SPACE_ID) with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp: pil_image.save(tmp.name) tmp_path = tmp.name try: image_input = handle_file(tmp_path) # Try the configured API try: print(f"Trying detection API: {st.session_state.detect_api}") return client.predict(image_input, api_name=st.session_state.detect_api) except Exception as e: error_msg = str(e) print(f"Error with {st.session_state.detect_api}: {error_msg}") # Try other common names for api_name in ["/predict_0", "/predict", "/run"]: try: print(f"Trying {api_name}...") result = client.predict(image_input, api_name=api_name) st.session_state.detect_api = api_name st.success(f"β Found working endpoint: {api_name}") return result except: continue raise RuntimeError(f"Could not find working detection endpoint.\n\nTried: {COMMON_API_NAMES}") finally: if os.path.exists(tmp_path): os.remove(tmp_path) def query_space(user_query): """Call the NLP-to-SQL query function from the Space""" if Client is None: raise RuntimeError("gradio_client is not installed.") client = Client(SPACE_ID) try: print(f"Trying query API: {st.session_state.query_api}") result = client.predict(user_query, api_name=st.session_state.query_api) return result except Exception as e: error_msg = str(e) print(f"Error with {st.session_state.query_api}: {error_msg}") # Try other common names for api_name in ["/predict_1", "/predict", "/run"]: try: print(f"Trying {api_name}...") result = client.predict(user_query, api_name=api_name) st.session_state.query_api = api_name st.success(f"β Found working endpoint: {api_name}") return result except: continue return {"error": f"Could not find working query endpoint.\n\nTried: {COMMON_API_NAMES}"} # Page configuration st.set_page_config( page_title="Vehicle Intelligence System", page_icon="π", layout="wide", initial_sidebar_state="expanded" ) # Custom CSS for better styling st.markdown(""" """, unsafe_allow_html=True) # Header st.markdown("# π Vehicle Intelligence System") st.markdown("### Advanced License Plate Detection & NLP Database Query") st.markdown("---") # Sidebar with st.sidebar: st.markdown("## βοΈ Configuration") api_status = st.checkbox("Show API Status", value=True) if api_status: st.markdown("### π‘ API Status") col1, col2 = st.columns(2) with col1: st.metric("Space ID", SPACE_ID.split("/")[1]) with col2: if Client is not None: st.success("β Client Ready") else: st.error("β Client Error") st.markdown("### π API Names (auto-discovering)") st.info(f""" **Current API Names (auto-discovering):** - Detection: `{st.session_state.detect_api}` - Query: `{st.session_state.query_api}` If you see API errors, the app will automatically try other endpoints! """) # Show available APIs if st.button("π Show Available APIs"): try: apis = get_available_apis() if apis: st.json(apis) else: st.warning("Could not retrieve API list") except Exception as e: st.error(f"Error: {e}") st.markdown("---") st.markdown("### π Quick Links") st.markdown(""" - [HF Spaces](https://huggingface.co/spaces) - [Documentation](#) - [Report Issue](#) """) # Main content area tab1, tab2, tab3 = st.tabs(["π₯ Detection", "π Database Query", "π Analytics"]) # ============= TAB 1: DETECTION ============= with tab1: st.markdown("## License Plate Detection") st.markdown("Upload a vehicle image to detect license plates and classify vehicle type.") col_upload, col_preview = st.columns([1, 1]) with col_upload: st.markdown("### π€ Upload Image") uploaded = st.file_uploader( "Choose an image file", type=["jpg", "jpeg", "png"], key="detection_upload" ) if uploaded is None: st.info("π Upload a vehicle image to get started") else: st.success(f"β File loaded: {uploaded.name}") with col_preview: if uploaded is not None: pil_image = Image.open(uploaded).convert("RGB") st.markdown("### πΈ Preview") st.image(pil_image, use_container_width=True) # Detection button and results if uploaded is not None: if Client is None: st.error("β gradio_client is not installed. Run: pip install gradio_client") else: col_detect, col_clear = st.columns([3, 1]) with col_detect: detect_clicked = st.button( "π Detect License Plate", use_container_width=True, key="detect_btn" ) with col_clear: if st.button("π Clear", use_container_width=True): st.rerun() if detect_clicked: with st.spinner("π Detecting license plate..."): try: result = call_space(pil_image) if isinstance(result, (list, tuple)): text_output = result[0] if len(result) > 0 else "" json_output = result[1] if len(result) > 1 else {} else: text_output = str(result) json_output = {} # Display results in columns col_text, col_json = st.columns([1, 1]) with col_text: st.markdown("### π Detection Result") st.markdown('