Rocky4516 commited on
Commit
bbb6cc2
·
verified ·
1 Parent(s): 27e768e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -52
app.py CHANGED
@@ -5,17 +5,40 @@ import time
5
  import os
6
  from pypdf import PdfReader, PdfWriter
7
 
8
- st.set_page_config(page_title="SSC 5-Tool Agent Pipeline", page_icon="🎓", layout="wide")
9
 
10
- st.title("🎓 SSC Maths Original 5-Tool Pipeline Engine (v5.9-Fixed)")
11
- st.write("यह इंजन आपके मूल 5-टूल आर्किटेक्चर पर काम करता है: इसमें LaTeX कोडिंग सिम्बल्स को पूरी तरह हटाकर नॉर्मल टेक्स्ट और डायनामिक एग्जाम हेडर को सेट कर दिया गया है।")
12
 
13
  # Sidebar
14
  with st.sidebar:
15
  st.header("🔑 Authentication & Config")
16
  api_key = st.text_input("Enter Gemini API Key", type="password", value="")
17
  header_keyword = st.text_input("Shift Header Keyword (🔑 शब्द)", value="Shift")
18
- st.info("यह वर्जन बिना किसी LaTeX कोडिंग के साफ-सुथरा साधारण टेक्स्ट आउटपुट जनरेट करता है।")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  if api_key:
21
  genai.configure(api_key=api_key.strip())
@@ -25,7 +48,7 @@ else:
25
  uploaded_file = st.file_uploader("Upload your SSC Maths PDF Book", type=["pdf"])
26
 
27
  if uploaded_file is not None and api_key:
28
- if st.button("🚀 Start 5-Tool Formatting Pipeline"):
29
 
30
  original_filename = uploaded_file.name
31
  base_name = os.path.splitext(original_filename)[0]
@@ -34,7 +57,7 @@ if uploaded_file is not None and api_key:
34
  # ==========================================
35
  # TOOL 1: Local Python Shift Splitter (pypdf)
36
  # ==========================================
37
- st.info("🕵️‍♂️ Tool 1 (Local Splitter) is analyzing text to divide by shifts...")
38
  pdf_data = uploaded_file.read()
39
  reader = PdfReader(io.BytesIO(pdf_data))
40
  total_pages = len(reader.pages)
@@ -49,21 +72,22 @@ if uploaded_file is not None and api_key:
49
  pass
50
 
51
  if not shift_start_pages:
52
- st.warning(f"Could not find keyword '{header_keyword}'. Splitting into stable 3-page chunks to prevent timeouts.")
53
  shift_start_pages = list(range(0, total_pages, 3))
54
  else:
55
  if shift_start_pages[0] != 0:
56
  shift_start_pages.insert(0, 0)
57
 
58
- st.success(f"🎯 Tool 1 successfully divided PDF into {len(shift_start_pages)} logical segments!")
59
 
60
  accumulated_text = ""
61
  progress_bar = st.progress(0)
62
  status_text = st.empty()
 
63
  total_segments = len(shift_start_pages)
64
  bt_fence = "```"
65
 
66
- # MASTER SHIFT LOOP
67
  for idx, start_p in enumerate(shift_start_pages):
68
  end_p = shift_start_pages[idx+1] if idx + 1 < total_segments else total_pages
69
 
@@ -81,32 +105,26 @@ if uploaded_file is not None and api_key:
81
  # ------------------------------------------
82
  # TOOL 2: AGENT 1 (Bilingual OCR Specialist)
83
  # ------------------------------------------
84
- status_text.markdown(f"⏳ **Segment {idx+1}/{total_segments}** -> Agent 1 (OCR) extracting text & headers...")
85
- ocr_out = ""
86
- for attempt in range(3):
87
- try:
88
- ocr_p = "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."
89
- ocr_out = model.generate_content([pdf_inline_object, ocr_p], request_options={'timeout': 600}).text
90
- break
91
- except Exception as e:
92
- ocr_out = f"[Agent 1 Error: {str(e)}]"
93
- time.sleep(5)
94
 
95
  time.sleep(2)
96
 
97
  # ------------------------------------------
98
  # TOOL 3: AGENT 2 (Graphics/HTML/SVG Converter)
99
  # ------------------------------------------
100
- status_text.markdown(f"⏳ **Segment {idx+1}/{total_segments}** -> Agent 2 (Graphics) rendering diagrams...")
101
- graph_out = ""
102
- for attempt in range(3):
103
- try:
104
- graph_p = "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'."
105
- graph_out = model.generate_content([pdf_inline_object, graph_p], request_options={'timeout': 600}).text
106
- break
107
- except Exception as e:
108
- graph_out = f"[Agent 2 Error: {str(e)}]"
109
- time.sleep(5)
110
  if "NO_GRAPHICS" in graph_out:
111
  graph_out = ""
112
 
@@ -115,23 +133,19 @@ if uploaded_file is not None and api_key:
115
  # ------------------------------------------
116
  # TOOL 4: AGENT 3 (Shortcut Solver)
117
  # ------------------------------------------
118
- status_text.markdown(f"⏳ **Segment {idx+1}/{total_segments}** -> Agent 3 (Shortcut Master) solving questions...")
119
- shortcut_out = ""
120
- for attempt in range(3):
121
- try:
122
- solver_p = 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 '/', '*', '=', '->')."
123
- shortcut_out = model.generate_content(solver_p, request_options={'timeout': 600}).text
124
- break
125
- except Exception as e:
126
- shortcut_out = f"[Agent 3 Error: {str(e)}]"
127
- time.sleep(5)
128
 
129
  time.sleep(2)
130
 
131
  # ------------------------------------------
132
  # TOOL 5: AGENT 4 (Final Layout Formatter)
133
  # ------------------------------------------
134
- status_text.markdown(f"⏳ **Segment {idx+1}/{total_segments}** -> Agent 4 (Final Formatter) binding layout structure...")
135
 
136
  formatter_p = f"""
137
  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.
@@ -160,7 +174,7 @@ if uploaded_file is not None and api_key:
160
  Hindi: [Clean Hindi trick solution from Agent 3 without any LaTeX markup]
161
 
162
  CRITICAL CONTROL RULES:
163
- - Absolutely NO LaTeX markup (never use backslashes, \\frac, \\implies, or \\times). Write fractions as a/b and equations cleanly using standard text.
164
  - Never output any asterisks (*), double stars (**), or markdown code blocks (```).
165
  - Inline any HTML tables or XML <svg> code directly inside the question body text where applicable.
166
  - Keep exactly one single leading space before the option letters (' A)', ' B)', ' C)', ' D)').
@@ -172,23 +186,18 @@ if uploaded_file is not None and api_key:
172
  - Shortcut Solutions: {shortcut_out}
173
  """
174
 
175
- chunk_final = ""
176
- for attempt in range(3):
177
- try:
178
- chunk_final = model.generate_content(formatter_p, request_options={'timeout': 600}).text
179
- break
180
- except Exception as e:
181
- chunk_final = f"[Agent 4 Assembly Error: {str(e)}]"
182
- time.sleep(5)
183
-
184
- if chunk_final:
185
  cleaned_output = chunk_final.replace(bt_fence + "html", "").replace(bt_fence, "").replace("**", "").strip()
186
  accumulated_text += f"\n\n\n==================== SEGMENT {idx+1} ====================\n" + cleaned_output
 
 
187
 
188
  time.sleep(3)
189
  progress_bar.progress((idx + 1) / total_segments)
190
 
191
- status_text.success("🎉 Process Complete with 5-Tool Formatting Pipeline!")
 
192
  st.text_area("Master Output Preview", accumulated_text, height=300)
193
 
194
  # Word Compilation layout
 
5
  import os
6
  from pypdf import PdfReader, PdfWriter
7
 
8
+ st.set_page_config(page_title="SSC 5-Tool Ultimate Pipeline", page_icon="🎓", layout="wide")
9
 
10
+ st.title("🎓 SSC Maths Original 5-Tool Pipeline (v7.0-Final-Proof)")
11
+ st.write("Yeh aapka original 5-tool system hai. Isme live countdown lagaya gaya hai taaki mobile browser freeze na ho aur Google 429 quota error ko bypass kiya ja sake.")
12
 
13
  # Sidebar
14
  with st.sidebar:
15
  st.header("🔑 Authentication & Config")
16
  api_key = st.text_input("Enter Gemini API Key", type="password", value="")
17
  header_keyword = st.text_input("Shift Header Keyword (🔑 शब्द)", value="Shift")
18
+ st.info("Yeh version live agent tracking aur safe auto-retry system ke saath aata hai.")
19
+
20
+ # -------------------------------------------------------------
21
+ # MASTER ANTI-429 COOLDOWN HELPER WITH LIVE UI COUNTDOWN
22
+ # -------------------------------------------------------------
23
+ def generate_with_quota_handler(model, prompt, content_obj=None, agent_name="Agent", retries=6):
24
+ """Google ke Rate Limit (429) ko handle karne aur mobile screen ko alive rakhne ka tool"""
25
+ for attempt in range(retries):
26
+ try:
27
+ inputs = [prompt] if content_obj is None else [content_obj, prompt]
28
+ response = model.generate_content(inputs, request_options={'timeout': 600})
29
+ return response.text
30
+ except Exception as e:
31
+ err_str = str(e)
32
+ if "429" in err_str or "quota" in err_str.lower() or "limit" in err_str.lower():
33
+ # Live countdown placeholder taaki browser active rahe
34
+ countdown_placeholder = st.empty()
35
+ for seconds_left in range(35, 0, -1):
36
+ countdown_placeholder.warning(f"⚠️ Google Rate Limit Hit on {agent_name}! Safe Cool-down: Re-trying in {seconds_left} seconds... Please do not close this tab.")
37
+ time.sleep(1)
38
+ countdown_placeholder.empty()
39
+ else:
40
+ time.sleep(4)
41
+ raise Exception(f"{agent_name} failed after multiple secure attempts due to server load.")
42
 
43
  if api_key:
44
  genai.configure(api_key=api_key.strip())
 
48
  uploaded_file = st.file_uploader("Upload your SSC Maths PDF Book", type=["pdf"])
49
 
50
  if uploaded_file is not None and api_key:
51
+ if st.button("🚀 Run Original 5-Tool Pipeline Process"):
52
 
53
  original_filename = uploaded_file.name
54
  base_name = os.path.splitext(original_filename)[0]
 
57
  # ==========================================
58
  # TOOL 1: Local Python Shift Splitter (pypdf)
59
  # ==========================================
60
+ st.info("🕵️‍♂️ Tool 1 (Local Splitter) is analyzing text structure...")
61
  pdf_data = uploaded_file.read()
62
  reader = PdfReader(io.BytesIO(pdf_data))
63
  total_pages = len(reader.pages)
 
72
  pass
73
 
74
  if not shift_start_pages:
75
+ st.warning(f"Keyword '{header_keyword}' not found in text. Splitting into stable 3-page batches for safety.")
76
  shift_start_pages = list(range(0, total_pages, 3))
77
  else:
78
  if shift_start_pages[0] != 0:
79
  shift_start_pages.insert(0, 0)
80
 
81
+ st.success(f"🎯 Tool 1 divided document into {len(shift_start_pages)} logical segments successfully!")
82
 
83
  accumulated_text = ""
84
  progress_bar = st.progress(0)
85
  status_text = st.empty()
86
+ live_log = st.empty()
87
  total_segments = len(shift_start_pages)
88
  bt_fence = "```"
89
 
90
+ # MASTER PIPELINE LOOP
91
  for idx, start_p in enumerate(shift_start_pages):
92
  end_p = shift_start_pages[idx+1] if idx + 1 < total_segments else total_pages
93
 
 
105
  # ------------------------------------------
106
  # TOOL 2: AGENT 1 (Bilingual OCR Specialist)
107
  # ------------------------------------------
108
+ status_text.markdown(f"⏳ **Segment {idx+1}/{total_segments}** -> Processing Tools...")
109
+ live_log.info(f"🔄 Run 1/4: Agent 1 (OCR) is parsing bilingual questions...")
110
+ try:
111
+ ocr_p = "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."
112
+ ocr_out = generate_with_quota_handler(model, ocr_p, pdf_inline_object, "Agent 1 (OCR)")
113
+ except Exception as e:
114
+ ocr_out = f"[Agent 1 Error: {str(e)}]"
 
 
 
115
 
116
  time.sleep(2)
117
 
118
  # ------------------------------------------
119
  # TOOL 3: AGENT 2 (Graphics/HTML/SVG Converter)
120
  # ------------------------------------------
121
+ live_log.info(f"🔄 Run 2/4: Agent 2 (Graphics) is rendering tables and vectors...")
122
+ try:
123
+ graph_p = "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'."
124
+ graph_out = generate_with_quota_handler(model, graph_p, pdf_inline_object, "Agent 2 (Graphics)")
125
+ except Exception as e:
126
+ graph_out = f"[Agent 2 Error: {str(e)}]"
127
+
 
 
 
128
  if "NO_GRAPHICS" in graph_out:
129
  graph_out = ""
130
 
 
133
  # ------------------------------------------
134
  # TOOL 4: AGENT 3 (Shortcut Solver)
135
  # ------------------------------------------
136
+ live_log.info(f"🔄 Run 3/4: Agent 3 (Shortcut Solver) is generating solutions...")
137
+ try:
138
+ solver_p = 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 '/', '*', '=', '->')."
139
+ shortcut_out = generate_with_quota_handler(model, solver_p, agent_name="Agent 3 (Solver)")
140
+ except Exception as e:
141
+ shortcut_out = f"[Agent 3 Error: {str(e)}]"
 
 
 
 
142
 
143
  time.sleep(2)
144
 
145
  # ------------------------------------------
146
  # TOOL 5: AGENT 4 (Final Layout Formatter)
147
  # ------------------------------------------
148
+ live_log.info(f"🔄 Run 4/4: Agent 4 (Final Formatter) is structuring presentation layout...")
149
 
150
  formatter_p = f"""
151
  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.
 
174
  Hindi: [Clean Hindi trick solution from Agent 3 without any LaTeX markup]
175
 
176
  CRITICAL CONTROL RULES:
177
+ - 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.
178
  - Never output any asterisks (*), double stars (**), or markdown code blocks (```).
179
  - Inline any HTML tables or XML <svg> code directly inside the question body text where applicable.
180
  - Keep exactly one single leading space before the option letters (' A)', ' B)', ' C)', ' D)').
 
186
  - Shortcut Solutions: {shortcut_out}
187
  """
188
 
189
+ try:
190
+ chunk_final = generate_with_quota_handler(model, formatter_p, agent_name="Agent 4 (Formatter)")
 
 
 
 
 
 
 
 
191
  cleaned_output = chunk_final.replace(bt_fence + "html", "").replace(bt_fence, "").replace("**", "").strip()
192
  accumulated_text += f"\n\n\n==================== SEGMENT {idx+1} ====================\n" + cleaned_output
193
+ except Exception as e:
194
+ accumulated_text += f"\n\n\n==================== SEGMENT {idx+1} ====================\n[Segment skipped due to critical error: {str(e)}]"
195
 
196
  time.sleep(3)
197
  progress_bar.progress((idx + 1) / total_segments)
198
 
199
+ live_log.empty()
200
+ status_text.success("🎉 Process Complete with 5-Tool Auto-Cooldown Pipeline!")
201
  st.text_area("Master Output Preview", accumulated_text, height=300)
202
 
203
  # Word Compilation layout