Harishkhawaja commited on
Commit
d9d3f7f
·
verified ·
1 Parent(s): a5fa065

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -0
app.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pdfplumber
3
+ import pytesseract
4
+ from PIL import Image
5
+ import io
6
+ import requests
7
+
8
+ # Constants
9
+ GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
10
+ GROQ_API_KEY = st.secrets["GROQ_API_KEY"]
11
+ MODEL = "mixtral-8x7b-32768" # or llama3, gemma, etc.
12
+
13
+ # Extract text from PDF
14
+ def extract_text_from_pdf(uploaded_file):
15
+ text = ""
16
+ with pdfplumber.open(uploaded_file) as pdf:
17
+ for page in pdf.pages:
18
+ text += page.extract_text() + "\n"
19
+ return text
20
+
21
+ # Extract text from image
22
+ def extract_text_from_image(uploaded_file):
23
+ image = Image.open(uploaded_file)
24
+ text = pytesseract.image_to_string(image)
25
+ return text
26
+
27
+ # Call Groq API
28
+ def get_answers_from_groq(text):
29
+ prompt = (
30
+ "You are a helpful assistant. The user provides a set of multiple-choice questions. "
31
+ "For each question, choose the most appropriate answer and give a 1-line explanation.\n\n"
32
+ f"Questions:\n{text}\n\n"
33
+ "Format your response as:\n\nQ1: Answer - Explanation\nQ2: Answer - Explanation\n..."
34
+ )
35
+
36
+ headers = {
37
+ "Authorization": f"Bearer {GROQ_API_KEY}",
38
+ "Content-Type": "application/json"
39
+ }
40
+ payload = {
41
+ "model": MODEL,
42
+ "messages": [{"role": "user", "content": prompt}],
43
+ "temperature": 0.3
44
+ }
45
+
46
+ response = requests.post(GROQ_API_URL, headers=headers, json=payload)
47
+ result = response.json()
48
+ return result["choices"][0]["message"]["content"]
49
+
50
+ # Streamlit UI
51
+ st.set_page_config(page_title="Quiz Solver", layout="centered")
52
+ st.title("🧠 Quiz Solver App")
53
+ st.write("Upload a PDF or image containing multiple-choice questions. The app will return the answers with explanations.")
54
+
55
+ uploaded_file = st.file_uploader("Upload PDF or Image", type=["pdf", "png", "jpg", "jpeg"])
56
+
57
+ if uploaded_file:
58
+ file_type = uploaded_file.type
59
+ with st.spinner("Extracting text..."):
60
+ if "pdf" in file_type:
61
+ extracted_text = extract_text_from_pdf(uploaded_file)
62
+ else:
63
+ extracted_text = extract_text_from_image(uploaded_file)
64
+
65
+ st.subheader("Extracted Text")
66
+ st.text_area("Preview", extracted_text, height=300)
67
+
68
+ if st.button("Get Answers"):
69
+ with st.spinner("Getting answers from Groq..."):
70
+ try:
71
+ answers = get_answers_from_groq(extracted_text)
72
+ st.subheader("Answers and Explanations")
73
+ st.markdown(f"```text\n{answers}\n```")
74
+ except Exception as e:
75
+ st.error(f"Error: {e}")