Spaces:
Sleeping
Sleeping
Download app.py from tbels89/Prometheus: direct link, hf CLI and curl.
- Browser
- Download file 6.3 kB
-
https://huggingface.co/spaces/tbels89/Prometheus/resolve/main/app.py
- Command line
-
hf download hf://spaces/tbels89/Prometheus/app.py
-
curl -L -o app.py https://huggingface.co/spaces/tbels89/Prometheus/resolve/main/app.py
6.3 kB
| # app.py | |
| # v1.0 - modular | |
| # External | |
| import streamlit as st | |
| import sqlite3 | |
| from datetime import datetime | |
| # Internal | |
| from logging_config import logger | |
| from database import init_db, add_message, load_messages, DB_NAME | |
| from retriever import load_retriever, TOP_K | |
| from prompt import build_prompt | |
| from api_client import send_query_to_llm | |
| from get_csv import get_db_contents_as_csv | |
| from session import get_session_id | |
| # ----------------------- | |
| # Configuration and Setup | |
| # ----------------------- | |
| # Setup logging | |
| logger.info(f"Logging setup initialized successfully at {datetime.now().isoformat()}.") | |
| # ----------------------- | |
| # Streamlit UI | |
| # ----------------------- | |
| try: | |
| init_db(DB_NAME) # Ensure DB is ready | |
| logger.info("DB initialized successfully.") | |
| # Initialize session state | |
| session_id = get_session_id() | |
| # Load retriever | |
| retriever = load_retriever() | |
| logger.info("Retriever initialized successfully.") | |
| # ----------------------- | |
| # Download Chat History as CSV button | |
| # ----------------------- | |
| st.sidebar.header("Download Your Chat History") | |
| if st.sidebar.button("Download History as CSV"): | |
| csv = get_db_contents_as_csv(session_id) | |
| if csv: | |
| st.sidebar.download_button( | |
| label="Download as CSV", | |
| data=csv, | |
| file_name="chat_history.csv", | |
| mime="text/csv" | |
| ) | |
| else: | |
| st.sidebar.warning("No chat history available for download.") | |
| logger.info("No chat history available for download.") | |
| logger.info("Download History as CSV button initialized successfully.") | |
| # ----------------------- | |
| st.title("Prometheus v1.0 - Personalized Canadian History Tutor") | |
| logger.info("Streamlit title initialized successfully.") | |
| # Instructions | |
| with st.expander("📋 Instructions", expanded=True): | |
| st.write( | |
| """ | |
| - Press **Enter** to submit your query. | |
| - Type **'quit'** to clear the conversation history. | |
| - Use the sidebar button to download conversation history as a CSV file. | |
| - Textbook sources retrieved available in the sidebar. | |
| """ | |
| ) | |
| logger.info("Instructions expanded successfully.") | |
| # Chat-like UI for conversation history | |
| st.subheader("💬 Conversation History") | |
| messages = load_messages(session_id) | |
| if not messages: | |
| # Add initial assistant message | |
| initial_message = { | |
| "role": "assistant", | |
| "content": ( | |
| "Hello, I'm Prometheus, your AI-powered personal tutor. " | |
| "I'm here to guide you through your learning journey using a step-by-step approach and Socratic progression to help you think critically, master concepts, and achieve your academic goals." | |
| ) | |
| } | |
| add_message("assistant", initial_message["content"], session_id) | |
| messages = load_messages(session_id) | |
| logger.info("Initial assistant message added to conversation history.") | |
| for m in messages: | |
| with st.chat_message(m['role']): | |
| st.markdown(m['content']) | |
| logger.info("Conversation history UI initialized successfully.") | |
| # Input area for user query | |
| if prompt := st.chat_input("Ask Prometheus... Type 'quit' to clear history."): | |
| # If user inputs 'quit', clear conversation history | |
| if prompt.strip().lower() == 'quit': | |
| try: | |
| conn = sqlite3.connect(DB_NAME) | |
| c = conn.cursor() | |
| c.execute("DELETE FROM conversations") | |
| conn.commit() | |
| logger.info("Conversation history cleared.") | |
| st.success("Conversation history cleared.") | |
| except sqlite3.Error as e: | |
| logger.error(f"Error clearing conversation history: {e}") | |
| st.error("Failed to clear conversation history.") | |
| finally: | |
| conn.close() | |
| logger.info("DB connection closed.") | |
| else: | |
| # Immediately display user message in the UI | |
| messages.append({"role": "user", "content": prompt.strip()}) | |
| with st.chat_message("user"): | |
| st.markdown(prompt.strip()) | |
| logger.info(f"User message displayed in UI") | |
| # Add user message to DB | |
| add_message("user", prompt.strip(), session_id) | |
| logger.info(f"User message added to DB") | |
| # Retrieve chunks | |
| if retriever: | |
| results = retriever.retrieve(prompt.strip(), k=TOP_K) | |
| logger.info(f"Retrieved {len(results)} chunks for query: '{prompt.strip()}'") | |
| else: | |
| results = [] | |
| logger.warning("Retriever is not available.") | |
| # Load updated messages (including user query) | |
| messages = load_messages(session_id) | |
| logger.info("Updated messages loaded, including user query") | |
| # Build prompt | |
| llm_prompt = build_prompt(prompt.strip(), results, messages) | |
| logger.info("Prompt built for api client") | |
| # Call LLM | |
| assistant_response = send_query_to_llm(llm_prompt) | |
| logger.info("API client response received") | |
| # Add assistant response to DB | |
| add_message("assistant", assistant_response, session_id) | |
| logger.info("Assistant response added to DB") | |
| # Display assistant response | |
| with st.chat_message("assistant"): | |
| st.markdown(assistant_response) | |
| logger.info("Assistant response displayed in UI") | |
| # Display retrieved sources in the sidebar | |
| with st.sidebar: | |
| st.header("📖 Sources") | |
| if results: | |
| for i, res in enumerate(results): | |
| st.markdown(f"- **Result {i+1}:** Page {res['page_num']}") | |
| st.code(res['content']) | |
| logger.info(f"Sources displayed in sidebar") | |
| else: | |
| st.warning("No relevant sources found.") | |
| logger.info("No relevant sources found.") | |
| except Exception as e: | |
| logger.error(f"Failed to initialize DB: {e}") | |
| raise ValueError("Failed to initialize DB.") |