Maths_agent / app.py
Rocky4516's picture
Update app.py
f4ad354 verified
Raw History Blame Contribute Delete
11.3 kB
import streamlit as st
import requests
import fitz # PyMuPDF
import os
import base64
import re
import io
st.set_page_config(page_title="SSC AI Portal", page_icon="πŸŽ“", layout="centered")
st.title("πŸŽ“ SSC Multi-Agent Expert Web Portal")
st.write("Aapka personal 4-Agent pipeline jo bina ruke automatic kaam karega.")
# πŸ”‘ DUAL API KEYS INPUT
with st.sidebar:
st.header("πŸ” API Configuration")
key_a = st.text_input("Google API Key - Account 1 (Agent 1 & 2)", type="password")
key_b = st.text_input("Google API Key - Account 2 (Agent 3 & 4)", type="password")
st.info("2 alag accounts ki key daalne se rate limit error nahi aayega.")
uploaded_file = st.file_uploader("Upload SSC Maths PDF", type=["pdf"])
if uploaded_file and key_a and key_b:
if st.button("πŸš€ Start 4-Agent Processing"):
with st.status("πŸ—οΈ Workflow Active... Processing with 4 Agents...", expanded=True) as status:
# Save temporary PDF
with open("temp.pdf", "wb") as f:
f.write(uploaded_file.getbuffer())
# --- AGENT 5 (System Task): Convert PDF Pages to Images ---
st.write("πŸ”„ System Task: Converting PDF pages to high-res images...")
doc = fitz.open("temp.pdf")
if not os.path.exists("temp_pages"):
os.makedirs("temp_pages")
page_images = []
for i in range(len(doc)):
p_path = f"temp_pages/page_{i+1}.png"
doc.load_page(i).get_pixmap(matrix=fitz.Matrix(1.5, 1.5)).save(p_path)
page_images.append(p_path)
b64_list = [base64.b64encode(open(p, "rb").read()).decode('utf-8') for p in page_images]
# -----------------------------------------------------------------
# πŸ€– AGENT 1: Bilingual OCR Specialist (Uses Account 1 - Key A)
# -----------------------------------------------------------------
st.write("πŸ€– Run 1/4: Agent 1 (OCR) extracting questions in English & Hindi...")
url_a = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={key_a}"
ocr_prompt = "You are Agent 1 (OCR Specialist). Extract all math questions from this document chunk. Crucial Rule 1: Read the top section header text of the document carefully and capture the actual Exam Name (e.g., GD, CHSL, CGL), actual Exam Date, and actual Shift Name. Crucial Rule 2: For every single question, you must completely extract and translate the full question text and all four options into BOTH English and Hindi. Never skip any text or use shortcuts. Output cleanly."
parts_a = [{"text": ocr_prompt}]
for b64 in b64_list:
parts_a.append({"inlineData": {"mimeType": "image/jpeg", "data": b64}})
res_a = requests.post(url_a, headers={"Content-Type": "application/json"}, json={"contents": [{"parts": parts_a}]})
ocr_out = res_a.json()['candidates'][0]['content']['parts'][0]['text']
# -----------------------------------------------------------------
# πŸ€– AGENT 2: Graphics/HTML/SVG Converter (Uses Account 1 - Key A)
# -----------------------------------------------------------------
st.write("πŸ€– Run 2/4: Agent 2 (Graphics) scanning for tables and charts...")
graph_prompt = "You are Agent 2 (Graphics Converter). If any question in this chunk has a data table/chart, output a clean native HTML table structure. If it has a geometry drawing, output raw XML <svg> vector tags. If no diagrams, reply with 'NO_GRAPHICS'."
parts_b = [{"text": graph_prompt}]
for b64 in b64_list:
parts_b.append({"inlineData": {"mimeType": "image/jpeg", "data": b64}})
res_b = requests.post(url_a, headers={"Content-Type": "application/json"}, json={"contents": [{"parts": parts_b}]})
graph_out = res_b.json()['candidates'][0]['content']['parts'][0]['text']
if "NO_GRAPHICS" in graph_out:
graph_out = ""
# -----------------------------------------------------------------
# πŸ€– AGENT 3: Shortcut Solver (Uses Account 2 - Key B)
# -----------------------------------------------------------------
st.write("πŸ€– Run 3/4: Agent 3 (Solver) generating exam-hall short tricks...")
url_b = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={key_b}"
solver_prompt = f"You are Agent 3 (Shortcut Solver). Review the extracted questions: {ocr_out}. For every question, provide premium short-trick solutions focusing entirely on exam-hall time-saving tricks like Ratio methods, Digital Root, Unit Digit, or Option Divisibility. Write the complete English solution text first, then immediately write the complete Hindi solution text right below it. STRICT BAN ON LATEX: Do NOT use any raw LaTeX coding style backslashes, formulas like \\frac, \\implies, \\times, etc. Write math expressions normally like a human would type on a standard keyboard (e.g., use '/', '*', '=', '->')."
res_c = requests.post(url_b, headers={"Content-Type": "application/json"}, json={"contents": [{"parts": [{"text": solver_prompt}]}]})
shortcut_out = res_c.json()['candidates'][0]['content']['parts'][0]['text']
# -----------------------------------------------------------------
# πŸ€– AGENT 4: Layout Formatter (Uses Account 2 - Key B)
# -----------------------------------------------------------------
st.write("πŸ€– Run 4/4: Agent 4 (Formatter) combining everything into clean presentation layout...")
formatter_prompt = f"""
You are Agent 4 (Final Layout Formatter). Your sole job is to take the raw inputs from Agent 1 (OCR Text), Agent 2 (Graphics), and Agent 3 (Solutions) and strictly assemble them into the exact presentation layout.
OFFICIAL COURSE CHAPTER LIST:
Classify the topic line exactly into one of these 30 chapters based on the math concept. If it doesn't fit, use 'Miscellaneous':
(1) Percentage, (2) Simple Interest, (3) Compound Interest, (4) Installments, (5) Profit and Loss, (6) Discount, (7) Ratio & proportion, (8) Partnership, (9) Average, (10) Weighted Average & Alligation, (11) Time and work, (12) Time and distance (Includes problem on trains, boats & streams, Races), (13) Number system, (14) HCF and LCM, (15) Data Interpretation, (16) Algebra, (17) Equations, (18) AP, GP, HP, (19) Surds & Indices, (20) Simplification, (21) Plane Geometry, (22) Mass Plane Geometry, (23) Mensuration 2D, (24) Mensuration 3D, (25) Trigonometry, (26) Height and Distance, (27) Coordinate Geometry, (28) Statistics, (29) Permutation & Combination, (30) Probability.
STRICT QUESTION LAYOUT FORMAT (Follow this layout EXACTLY for EACH and EVERY question. No asterisks, No bold markings, Absolutely NO LaTeX symbols like \\frac or \\implies):
Subject: MATHEMATICS
Topic: [Insert exact Chapter Name from the list above]
Q.[Original Question Number] [Question Text English]
[Question Text Hindi] [Exam: <Insert Real Extracted Exam Name like GD, CHSL, CGL from text header, fallback to SSC if not found> | Date: <Insert Real Extracted Exam Date from text header> | Shift: <Insert Real Extracted Shift Name from text header>]
A) [Option A English]
[Option A Hindi]
B) [Option B English]
[Option B Hindi]
C) [Option C English]
[Option C Hindi]
D) [Option D English]
[Option D Hindi]
Answer: [Correct Option Letter]
Tricks & Short Solution:
English: [Clean English trick solution from Agent 3 without any LaTeX markup]
Hindi: [Clean Hindi trick solution from Agent 3 without any LaTeX markup]
CRITICAL CONTROL RULES:
- Absolutely NO LaTeX markup (never use backslashes, \\frac, \\implies, or \\times). Write fractions as a/b and equations cleanly using standard text like human typing.
- Never output any asterisks (*), double stars (**), or markdown code blocks (```).
- Inline any HTML tables or XML <svg> code directly inside the question body text where applicable.
- Keep exactly one single leading space before the option letters (' A)', ' B)', ' C)', ' D)').
- The metadata bracket containing the real extracted Exam name, Date, and Shift must ONLY appear at the very end of the Hindi question line.
Data to assemble:
- Extracted Text & Options: {ocr_out}
- Graphics/Tables/SVG elements: {graph_out}
- Shortcut Solutions: {shortcut_out}
"""
res_d = requests.post(url_b, headers={"Content-Type": "application/json"}, json={"contents": [{"parts": [{"text": formatter_prompt}]}]})
final_output = res_d.json()['candidates'][0]['content']['parts'][0]['text']
cleaned_output = final_output.replace("```html", "").replace("```", "").replace("**", "").strip()
# -----------------------------------------------------------------
# ⬇️ FINAL COMPILATION (Kal Raat Wala Styled HTML Generation)
# -----------------------------------------------------------------
st.write("⬇️ System Compiling into Kal Raat's Best Presentation Template...")
html_lines = [line if any(t in line for t in ['<svg', '</svg>', '<table', '</table>', '<tr', '</tr>', '<td', '<td>', '<th', '</th>']) else line + "<br>" for line in cleaned_output.split('\n')]
final_html_body = "\n".join(html_lines)
# Kal raat wala professional formatting template
doc_html = "<html><head><style>body { font-family: 'Segoe UI', Arial, sans-serif; font-size: 11pt; color: #000000; line-height: 1.5; margin-left: 40px; padding-left: 10px; } table { border-collapse: collapse; margin: 12px 0; background-color: #ffffff; width: auto; } table, th, td { border: 1px solid #475569; padding: 8px 12px; text-align: center; font-size: 10pt; } th { background-color: #f1f5f9; font-weight: bold; color: #0f172a; } svg { margin: 15px 0; display: block; }</style></head><body><div>" + final_html_body + "</div></body></html>"
status.update(label="πŸŽ‰ Process Complete with 4-Agent Pipeline!", state="complete")
st.download_button(
label="πŸ“₯ Download Correct Layout Word File (.doc)",
data=doc_html.encode('utf-8'),
file_name=f"{os.path.splitext(uploaded_file.name)[0]}_Final.doc",
mime="application/msword"
)
else:
st.info("Kripya dono API Keys daal kar apni PDF file upload karein taaki 4-Agent system active ho sake.")