shah1zil commited on
Commit
3447594
·
verified ·
1 Parent(s): ad1f8c5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ from PyPDF2 import PdfReader
4
+ import requests
5
+
6
+ # Set up the Streamlit app
7
+ st.title("Pakistani Constitution Q&A App")
8
+ st.write("Upload the Pakistani Constitution PDF, explore sections, and ask questions.")
9
+
10
+ # Upload PDF
11
+ uploaded_file = st.file_uploader("Upload PDF", type=["pdf"])
12
+
13
+ # Predefined sections of the Constitution
14
+ sections = {
15
+ "Preamble": (0, 1),
16
+ "Fundamental Rights": (2, 10),
17
+ # Add more sections with their page ranges here
18
+ }
19
+
20
+ # Groq API configuration
21
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY") # Read the API key from environment variables
22
+
23
+ if not GROQ_API_KEY:
24
+ st.error("Groq API key not found. Please set the 'GROQ_API_KEY' environment variable in Hugging Face Spaces settings.")
25
+
26
+ # Helper function to extract text from PDF
27
+ def extract_text_from_pdf(pdf_file, start_page, end_page):
28
+ try:
29
+ reader = PdfReader(pdf_file)
30
+ text = ""
31
+ for page in range(start_page, end_page + 1):
32
+ text += reader.pages[page].extract_text()
33
+ return text.strip()
34
+ except Exception as e:
35
+ st.error(f"Error extracting text from PDF: {e}")
36
+ return ""
37
+
38
+ # Section selection
39
+ if uploaded_file:
40
+ st.success("PDF uploaded successfully.")
41
+ selected_section = st.selectbox("Select a Section", list(sections.keys()))
42
+
43
+ if selected_section:
44
+ start_page, end_page = sections[selected_section]
45
+ section_text = extract_text_from_pdf(uploaded_file, start_page, end_page)
46
+
47
+ if section_text:
48
+ st.text_area("Selected Section Text", section_text, height=300)
49
+
50
+ # Question input
51
+ question = st.text_input("Ask a question about this section:")
52
+
53
+ if question:
54
+ # Make API call to Groq
55
+ try:
56
+ st.info("Querying Groq API...")
57
+ response = requests.post(
58
+ "https://api.groq.com/v1/ask",
59
+ headers={"Authorization": f"Bearer {GROQ_API_KEY}"},
60
+ json={"context": section_text, "question": question},
61
+ )
62
+
63
+ if response.status_code == 200:
64
+ answer = response.json().get("answer", "No answer found.")
65
+ st.success(f"Answer: {answer}")
66
+ else:
67
+ st.error(f"Error: {response.json().get('error', 'Unknown error occurred')}")
68
+ except Exception as e:
69
+ st.error(f"API call failed: {e}")
70
+ else:
71
+ st.warning("Please upload a PDF file to proceed.")