import os import streamlit as st from PyPDF2 import PdfReader import requests # Set up the Streamlit app st.title("Pakistani Constitution Q&A App") st.write("Upload the Pakistani Constitution PDF, explore sections, and ask questions.") # Upload PDF uploaded_file = st.file_uploader("Upload PDF", type=["pdf"]) # Predefined sections of the Constitution sections = { "Preamble": (0, 1), "Fundamental Rights": (2, 10), # Add more sections with their page ranges here } # Groq API configuration GROQ_API_KEY = os.getenv("GROQ_API_KEY") # Read the API key from environment variables if not GROQ_API_KEY: st.error("Groq API key not found. Please set the 'GROQ_API_KEY' environment variable in Hugging Face Spaces settings.") # Helper function to extract text from PDF def extract_text_from_pdf(pdf_file, start_page, end_page): try: reader = PdfReader(pdf_file) text = "" for page in range(start_page, end_page + 1): text += reader.pages[page].extract_text() return text.strip() except Exception as e: st.error(f"Error extracting text from PDF: {e}") return "" # Section selection if uploaded_file: st.success("PDF uploaded successfully.") selected_section = st.selectbox("Select a Section", list(sections.keys())) if selected_section: start_page, end_page = sections[selected_section] section_text = extract_text_from_pdf(uploaded_file, start_page, end_page) if section_text: st.text_area("Selected Section Text", section_text, height=300) # Question input question = st.text_input("Ask a question about this section:") if question: # Make API call to Groq try: st.info("Querying Groq API...") response = requests.post( "https://api.groq.com/v1/ask", headers={"Authorization": f"Bearer {GROQ_API_KEY}"}, json={"context": section_text, "question": question}, ) if response.status_code == 200: answer = response.json().get("answer", "No answer found.") st.success(f"Answer: {answer}") else: st.error(f"Error: {response.json().get('error', 'Unknown error occurred')}") except Exception as e: st.error(f"API call failed: {e}") else: st.warning("Please upload a PDF file to proceed.")