Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files6 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485866 unmodified linesst.set_page_config(page_title="SaaS Media Vault", layout="wide")st.title("ποΈ SaaS Media Intelligence Vault")st.markdown("Analyze images and keep a running log of your media library assets.")# --- INITIALIZE SESSION STATE ---# This is our "Array" that lives as long as the app tab is openif "media_library" not in st.session_state:st.session_state.media_library = []# --- MODEL LOADING (Cached) ---@st.cache_resourcedef load_models():# CLIP for labelsclassifier = pipeline("zero-shot-image-classification",model="openai/clip-vit-base-patch32",device=-1)# CHANGE THIS: "image-to-text" -> "image-text-to-text"captioner = pipeline("image-text-to-text",model="Salesforce/blip-image-captioning-base",device=-1)return classifier, captionerclassifier, captioner = load_models()# --- SIDEBAR CONTROLS ---st.sidebar.header("Control Panel")labels_input = st.sidebar.text_input("Analysis Keywords", "professional, tech, lifestyle, nature")uploaded_file = st.sidebar.file_uploader("Add New Asset", type=["jpg", "png", "jpeg"])if uploaded_file:if st.sidebar.button("Process & Save to Vault"):image = Image.open(uploaded_file)with st.spinner("AI Processing..."):# 1. Get BLIP Descriptioncaption_out = captioner(image, max_new_tokens=30)description = caption_out[0]['generated_text']# 2. Get CLIP Top Labellabels = [l.strip() for l in labels_input.split(",")]clip_out = classifier(image, candidate_labels=labels)top_label = clip_out[0]['label']top_score = clip_out[0]['score']# 3. SAVE TO OUR ARRAY (Session State)asset_data = {"timestamp": datetime.datetime.now().strftime("%H:%M:%S"),"image": image,"description": description,"tag": top_label,"confidence": top_score}# Add to the start of the list so newest is firstst.session_state.media_library.insert(0, asset_data)st.sidebar.success("Asset Cataloged!")# --- MAIN DISPLAY: THE VAULT ---st.subheader(f"Current Vault Contents ({len(st.session_state.media_library)} items)")if not st.session_state.media_library:st.info("The vault is empty. Upload an image in the sidebar to start cataloging.")else:for idx, item in enumerate(st.session_state.media_library):with st.container():col1, col2 = st.columns([1, 3])with col1:st.image(item["image"], use_container_width=True)with col2:st.write(f"**π Captured at:** {item['timestamp']}")st.write(f"**π AI Description:** {item['description'].capitalize()}")st.write(f"**π·οΈ Primary Tag:** {item['tag']} ({round(item['confidence']*100, 1)}%)")st.divider()# --- EXPORT OPTION ---if st.session_state.media_library:if st.sidebar.button("Clear Vault Memory"):st.session_state.media_library = []st.rerun()6 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697986 unmodified linesst.set_page_config(page_title="SaaS Media Vault", layout="wide")st.title("ποΈ SaaS Media Intelligence Vault")st.markdown("Analyze, store, and **search** your media assets using AI-generated metadata.")# --- INITIALIZE SESSION STATE ---if "media_library" not in st.session_state:st.session_state.media_library = []# --- MODEL LOADING (Option 1: Auto-Detect Task) ---@st.cache_resourcedef load_models():# CLIP for matching labelsclassifier = pipeline("zero-shot-image-classification",model="openai/clip-vit-base-patch32",device=-1)# BLIP for generating descriptions (Auto-detects image-to-text)captioner = pipeline(model="Salesforce/blip-image-captioning-base",device=-1)return classifier, captionerclassifier, captioner = load_models()# --- SIDEBAR: UPLOAD & SETTINGS ---st.sidebar.header("π₯ Asset Management")labels_input = st.sidebar.text_input("Analysis Keywords", "professional, tech, lifestyle, nature")uploaded_file = st.sidebar.file_uploader("Add New Image", type=["jpg", "png", "jpeg"])if uploaded_file:if st.sidebar.button("Process & Index Asset"):image = Image.open(uploaded_file)with st.spinner("AI is thinking..."):# 1. BLIP Descriptioncaption_out = captioner(image, max_new_tokens=30)description = caption_out[0]['generated_text']# 2. CLIP Top Labellabels = [l.strip() for l in labels_input.split(",")]clip_out = classifier(image, candidate_labels=labels)top_label = clip_out[0]['label']top_score = clip_out[0]['score']# 3. SAVE TO ARRAYasset_data = {"id": len(st.session_state.media_library),"timestamp": datetime.datetime.now().strftime("%H:%M:%S"),"image": image,"description": description.lower(),"tag": top_label.lower(),"confidence": top_score}st.session_state.media_library.insert(0, asset_data)st.sidebar.success("Asset Cataloged!")# --- MAIN SECTION: SEARCH & RETRIEVAL ---st.subheader("π Intelligent Retrieval")search_query = st.text_input("Search the vault by keyword (e.g., 'dog', 'tech', 'landscape')", "").lower()# --- FILTER LOGIC ---if search_query:# We check if the search term is in the AI description or the chosen Tagfiltered_items = [item for item in st.session_state.media_libraryif search_query in item["description"] or search_query in item["tag"]]else:filtered_items = st.session_state.media_library# --- DISPLAY VAULT ---st.write(f"Showing {len(filtered_items)} of {len(st.session_state.media_library)} assets")if not filtered_items:st.info("No matching assets found in the vault.")else:for item in filtered_items:with st.container():col1, col2 = st.columns([1, 3])with col1:st.image(item["image"], use_container_width=True)with col2:st.write(f"**π Logged:** {item['timestamp']}")st.info(f"**AI Description:** {item['description'].capitalize()}")st.write(f"**π·οΈ Primary Tag:** `{item['tag']}` ({round(item['confidence']*100, 1)}%)")st.divider()# --- CLEAR UTILITY ---if st.sidebar.button("ποΈ Wipe Vault Memory"):st.session_state.media_library = []st.rerun()
src/streamlit_app.py+43-31