{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":112509,"databundleVersionId":14254895,"sourceType":"competition"}],"dockerImageVersionId":31192,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import streamlit as st\nimport pandas as pd\nfrom pathlib import Path\nfrom PIL import Image\nimport os\n\n# Page configuration\nst.set_page_config(layout=\"wide\", page_title=\"Image & CSV Viewer\")\n\n# Create a style for a paragraph with a smaller font size\nst.markdown(\n    \"\"\"\n    <style>\n    .small-font {\n        font-size: 12px;\n    }\n    </style>\n    \"\"\",\n    unsafe_allow_html=True\n)\n\n\n# Set paths (update these as needed..)\n#this script is more intended to be used with  locally downloaded images/data..\nimage_folder = \"/kaggle/input/csiro-biomass/train\"\ncsv_file = \"/kaggle/input/csiro-biomass/train.csv\"\n\n# Title\nst.title(\"Image and CSV Data Viewer\")\n\n# Load data\n@st.cache_data\ndef load_csv(file_path):\n    try:\n        df = pd.read_csv(file_path)\n        return df\n    except Exception as e:\n        st.error(f\"Error loading CSV: {e}\")\n        return None\n\n@st.cache_data\ndef get_image_files(folder_path):\n    try:\n        path = Path(folder_path)\n        if not path.exists():\n            return []\n        images = [f.name for f in path.glob(\"*.jpg\")]\n        #images.extend([f.name for f in path.glob(\"*.JPG\")])\n        return sorted(images)\n    except Exception as e:\n        st.error(f\"Error loading images: {e}\")\n        return []\n\n# Check if paths exist\nif os.path.exists(image_folder) and os.path.exists(csv_file):\n    # Load CSV data\n    df = load_csv(csv_file)\n    \n    # Get list of images\n    image_files = get_image_files(image_folder)\n    \n    if df is not None and len(image_files) > 0:\n        # Create two columns: left for list, right for display\n        col1, col2 = st.columns([1, 3])\n        \n        with col1:\n            st.subheader(\"Image List\")\n            \n            # Create a scrollable container for the image list\n            st.markdown(\"\"\"\n                <style>\n                    [data-testid=\"stVerticalBlock\"] > [style*=\"flex-direction: column;\"] > [data-testid=\"stVerticalBlock\"] {\n                        overflow-y: auto;\n                        max-height: 70vh;\n                    }\n                </style>\n            \"\"\", unsafe_allow_html=True)\n\n            # Initialize selected image\n            if 'selected_image' not in st.session_state:\n                st.session_state.selected_image = image_files[0]\n            srch_id = st.text_input('Enter ID')\n            if st.button('Search'):\n                st.session_state.selected_image =srch_id+'.jpg'\n                st.rerun()\n\n            with st.container(height=600):    \n                # Display clickable list of images\n                for img_file in image_files:\n                    is_selected = st.session_state.selected_image == img_file\n                    \n                    if st.button(\n                        f\"{'✓ ' if is_selected else ''}{img_file}\",\n                        key=img_file,\n                        use_container_width=True,\n                        type=\"primary\" if is_selected else \"secondary\"\n                    ):\n                        st.session_state.selected_image = img_file\n                        st.rerun()\n            \n        with col2:\n            selected_image = st.session_state.selected_image\n            \n            st.subheader(f\"Selected: {selected_image}\")\n            \n            # Display the image\n            image_path = os.path.join(image_folder, selected_image)\n            try:\n                img = Image.open(image_path)\n                st.image(img, use_container_width=True)\n            except Exception as e:\n                st.error(f\"Error loading image: {e}\")\n            \n            st.divider()\n            \n            # Display CSV details\n            #st.subheader(\"CSV Details\")\n            \n            # Extract image ID from selected image filename\n            image_id = os.path.splitext(selected_image)[0]\n            \n            # Determine which column contains the Image ID\n            possible_id_columns = ['sample_id','Image Id', 'ImageId', 'image_id', 'Image ID', \n                                  'id', 'ID', 'Id', 'filename', 'file_name']\n            \n            id_column = None\n            for col_name in possible_id_columns:\n                if col_name in df.columns:\n                    id_column = col_name\n                    break\n            \n            if id_column is None:\n                # If no standard column found, use the first column\n                id_column = df.columns[0]\n                st.info(f\"Using '{id_column}' as Image ID column\")\n            \n            print(image_id)\n            # Filter dataframe for the selected image ID\n            print(id_column)\n            filtered_df = df[df[id_column].str.startswith(image_id)]\n            \n            if not filtered_df.empty:\n                # Display as a formatted table\n                for column in filtered_df.columns:\n                    value = filtered_df[column].values[0]\n                    #st.text(f\"{column}: {value}\")\n                \n                #st.divider()\n                \n                # Also show as dataframe\n                st.dataframe(filtered_df, use_container_width=True)\n            else:\n                st.warning(f\"No data found for Image ID: {image_id}\")\n                st.info(f\"Sample IDs in CSV: {df[id_column].head(5).tolist()}\")\n    else:\n        if df is None:\n            st.error(\"Failed to load CSV file\")\n        if len(image_files) == 0:\n            st.error(\"No JPG images found in the specified folder\")\nelse:\n    st.warning(\"⚠️ Please ensure both image folder and CSV file paths are correct\")\n    st.info(f\"Image folder exists: {os.path.exists(image_folder)}\")\n    st.info(f\"CSV file exists: {os.path.exists(csv_file)}\")\n    \n    st.markdown(\"\"\"\n    ### Setup Instructions:\n    1. Update `image_folder` and `csv_file` paths at the top of the code\n    2. Ensure your CSV has a column containing image IDs that match your image filenames (without extension)\n    \n    ### Expected Format:\n    - **Images**: JPG files named like `image001.jpg`, `photo123.jpg`, etc.\n    - **CSV**: Must contain a column with IDs matching the image filenames (e.g., `image001`, `photo123`)\n    \"\"\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null}]}