File size: 2,571 Bytes
3447594
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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.")