# MetaDiscovery Agent - LOC API with Enhanced Completeness and Quality Analysis import requests import pandas as pd import numpy as np import streamlit as st import plotly.express as px from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity # Custom CSS for white background, styled sidebar, banner, and dark grey font st.markdown(""" """, unsafe_allow_html=True) # OPTION 1: Use an image from a URL for the banner st.image("https://cdn-uploads.huggingface.co/production/uploads/67351c643fe51cb1aa28f2e5/7ThcAOjbuM8ajrP85bGs4.jpeg", use_container_width=True) # Streamlit app header st.title("MetaDiscovery Agent for Library of Congress Collections") st.markdown(""" This tool connects to the LOC API, retrieves metadata from a selected collection, and performs an analysis of metadata completeness, suggests enhancements, and identifies authority gaps. """) # Updated collection URLs using the correct LOC API format collections = { "American Revolutionary War Maps": "american+revolutionary+war+maps", "Civil War Maps": "civil+war+maps", "Women's Suffrage": "women+suffrage", "World War I Posters": "world+war+posters" } # Sidebar for selecting collection #st.sidebar.markdown("## Settings") # Create empty metadata_df variable to ensure it exists before checking metadata_df = pd.DataFrame() # Add a key to the selectbox to ensure it refreshes properly selected = st.sidebar.selectbox("Select a collection", list(collections.keys()), key="collection_selector") search_query = collections[selected] # Define the collection URL collection_url = f"https://www.loc.gov/search/?q={search_query}&fo=json" # đ Quick Stats Section (styled) st.sidebar.markdown("""
Total Records: {len(metadata_df)}
", unsafe_allow_html=True) st.sidebar.markdown(f"Incomplete Records: {len(metadata_df[metadata_df.isnull().any(axis=1)])}
", unsafe_allow_html=True) st.sidebar.write(f"Incomplete Records: {len(metadata_df[metadata_df.isnull().any(axis=1)])}") # Utility functions for deeper metadata quality analysis def is_incomplete(value): return pd.isna(value) or value in ["", "N/A", "null", None] def is_valid_date(value): try: pd.to_datetime(value) return True except: return False if not metadata_df.empty: st.subheader("Retrieved Metadata Sample") st.dataframe(metadata_df.head()) # Metadata completeness analysis (enhanced) st.subheader("Metadata Completeness Analysis") completeness = metadata_df.map(lambda x: not is_incomplete(x)).mean() * 100 completeness_df = pd.DataFrame({"Field": completeness.index, "Completeness (%)": completeness.values}) fig = px.bar(completeness_df, x="Field", y="Completeness (%)", title="Metadata Completeness by Field") st.plotly_chart(fig) # Identify incomplete records incomplete_mask = metadata_df.map(is_incomplete).any(axis=1) incomplete_records = metadata_df[incomplete_mask] st.subheader("⨠Suggested Metadata Enhancements") incomplete_with_desc = incomplete_records[incomplete_records['description'].notnull()] reference_df = metadata_df[metadata_df['subject'].notnull() & metadata_df['description'].notnull()] tfidf = TfidfVectorizer(stop_words='english') if len(incomplete_with_desc) > 1 and len(reference_df) > 1: try: suggestions = [] tfidf_matrix = tfidf.fit_transform(reference_df['description']) for idx, row in incomplete_with_desc.iterrows(): if pd.isna(row['subject']) and pd.notna(row['description']): desc_vec = tfidf.transform([str(row['description'])]) sims = cosine_similarity(desc_vec, tfidf_matrix).flatten() top_idx = sims.argmax() suggested_subject = reference_df.iloc[top_idx]['subject'] if pd.notna(suggested_subject) and suggested_subject: suggestions.append((row['title'], suggested_subject)) if suggestions: suggestions_df = pd.DataFrame(suggestions, columns=["Title", "Suggested Subject"]) st.markdown("