def main(): st.title("🤗 Streamlit App with Secrets") st.write("This application demonstrates how to access secret API keys securely on Hugging Face Spaces.") # Accessing secrets # On Hugging Face Spaces, go to 'Settings' > 'Variables and secrets' to add your key. # In Streamlit, these are accessible via st.secrets SECRET_KEY_NAME = "MY_NEW_SECRET" try: # Check if the key exists in secrets if SECRET_KEY_NAME in st.secrets: api_key = st.secrets[MY_NEW_SECRET] st.success(f"Successfully loaded secret: `{SECRET_KEY_NAME}`") # Display a masked version of the key for verification (NEVER print the full key in a real app) masked_key = f"{api_key[:4]}{'*' * (len(api_key) - 4)}" if len(api_key) > 4 else "****" st.code(f"Key Value: {masked_key}", language="text") st.info("You can now use this variable `api_key` to make authenticated requests.") else: st.warning(f"Secret `{MY_NEW_SECRET}` not found.") st.markdown(""" **How to fix:** 1. Go to your Hugging Face Space **Settings**. 2. Scroll to **Variables and secrets**. 3. Click **New secret**. 4. Name: `MY_API_KEY`. 5. Value: *Your actual API key*. """) except FileNotFoundError: # This handles local development if .streamlit/secrets.toml is missing st.error("Secrets configuration not found.") st.markdown("If running locally, ensure you have a `.streamlit/secrets.toml` file.") if __name__ == "__main__": main()