Okay, here's the frontend code tailored for Streamlit, designed to display the news data fetched from your backend API. This code assumes your backend is running and accessible at http://localhost:5000/api/news.
python
import streamlit as st
import requests
import pandas as pd
# Function to fetch news data from the backend
@st.cache_data # Cache the data to improve performance
def fetch_news():
try:
response = requests.get('http://localhost:5000/api/news')
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
return response.json()
except requests.exceptions.RequestException as e:
st.error(f"Error fetching news: {e}")
return []
# Streamlit app
def main():
st.title("📰 Clarity News")
news_data = fetch_news()
if news_data:
for article in news_data:
st.header(article['headline'])
st.write(article['summary'])
st.subheader("Sources:")
for source in article['sources']:
st.write(f"- [{source['title']}]({source['url']}) ({source['bias']})") # Markdown link
st.markdown("---") # Separator between articles
else:
st.warning("No news available. Check your backend server.")
if __name__ == "__main__":
main()
How to Run:
Save the code: Save the code as a Python file (e.g., clarity_streamlit.py).
Install Streamlit:
bash
pip install streamlit requests pandas
Run the Streamlit app:
bash
streamlit run clarity_streamlit.py
Explanation:
import streamlit as st: Imports the Streamlit library.
import requests: Imports the requests library for making HTTP requests to your backend.
import pandas as pd: Imports the pandas library for data manipulation (optional, but useful for more complex data display).
@st.cache_data: This decorator caches the fetch_news function's output. This means that Streamlit will only call the function once and reuse the result unless the function's code or inputs change. This significantly improves performance, especially when fetching data from an API.
fetch_news():
Fetches news data from your backend API (http://localhost:5000/api/news).
Handles potential errors using try...except and displays an error message in Streamlit if something goes wrong.
Returns the JSON response as a Python list of dictionaries.
main():
Sets the title of the Streamlit app.
Calls fetch_news() to get the news data.
Iterates through the news_data list:
Displays the headline as a header (st.header).
Displays the summary as text (st.write).
Displays the sources as a list of Markdown links (st.write). The Markdown link format [text](url) creates a clickable link.
Adds a separator line (st.markdown("---")) between articles.
If no news data is available, displays a warning message.
if __name__ == "__main__":: Ensures that the main() function is only called when the script is run directly (not when it's imported as a module).
Key Improvements & Considerations:
Error Handling: The try...except block in fetch_news() provides basic error handling. You can expand this to handle specific types of errors (e.g., connection errors, invalid JSON).
Caching: The @st.cache_data decorator significantly improves performance by caching the API response.
Markdown Links: Using Markdown links makes the source titles clickable, leading directly to the articles.
Clearer Display: The code uses Streamlit's st.header, st.write, and st.subheader functions to create a more structured and readable display.
Backend Dependency: This code assumes your backend is running and accessible at the specified URL. Make sure your backend is running before you run the Streamlit app.
Bias Display: The code displays the bias field from your backend data. Ensure your backend is providing this information.
Styling: You can customize the appearance of the Streamlit app using Streamlit's styling options (e.g., st.markdown with CSS).
Data Transformation: If your backend returns data in a different format, you may need to adjust the code to transform the data into a suitable format for display in Streamlit.
This Streamlit code provides a basic but functional frontend for your news app. You can expand it to include more features, such as filtering, searching, and more advanced data visualization.