Spaces:
Sleeping
Sleeping
Update backend.py
Browse files- backend.py +66 -95
backend.py
CHANGED
|
@@ -2,63 +2,55 @@ import os
|
|
| 2 |
import re
|
| 3 |
import json
|
| 4 |
import requests
|
| 5 |
-
from flask import Flask, request, jsonify,
|
| 6 |
from flask_cors import CORS
|
| 7 |
from fpdf import FPDF
|
| 8 |
-
import tempfile
|
| 9 |
|
| 10 |
app = Flask(__name__)
|
| 11 |
CORS(app)
|
| 12 |
|
| 13 |
-
# Secure Claude
|
| 14 |
CLAUDE_API_KEY = os.environ["CLAUDE_API_KEY"]
|
| 15 |
|
| 16 |
-
#
|
| 17 |
def extract_final_answer(text):
|
| 18 |
if not text:
|
| 19 |
return None
|
| 20 |
|
| 21 |
-
#
|
| 22 |
-
|
| 23 |
-
if match_full:
|
| 24 |
-
answer = match_full.group(1).strip()
|
| 25 |
-
if answer: return answer
|
| 26 |
-
|
| 27 |
-
# ✅ Match LaTeX-style $$...$$ if used alone
|
| 28 |
-
match_dollars = re.search(r'\$\$(.+?)\$\$', text)
|
| 29 |
if match_dollars:
|
| 30 |
return match_dollars.group(1).strip()
|
| 31 |
|
| 32 |
-
#
|
| 33 |
-
match_dollar = re.search(r'\$(.+?)\$', text)
|
| 34 |
if match_dollar:
|
| 35 |
return match_dollar.group(1).strip()
|
| 36 |
|
| 37 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
fallback = re.findall(r'\b\d+\.?\d*\b', text)
|
| 39 |
return fallback[-1].strip() if fallback else None
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
# Claude API call function
|
| 44 |
def call_claude(prompt):
|
| 45 |
headers = {
|
| 46 |
"x-api-key": CLAUDE_API_KEY,
|
| 47 |
"Content-Type": "application/json",
|
| 48 |
"anthropic-version": "2023-06-01"
|
| 49 |
}
|
| 50 |
-
|
| 51 |
body = {
|
| 52 |
"model": "claude-3-opus-20240229",
|
| 53 |
"max_tokens": 1024,
|
| 54 |
"temperature": 0.5,
|
| 55 |
"system": (
|
| 56 |
"You are a helpful and clear Year 5–10 maths tutor. "
|
| 57 |
-
"Provide accurate, step-by-step explanations
|
| 58 |
-
"
|
| 59 |
-
"Use natural teacher-style explanations. "
|
| 60 |
-
"Use LaTeX formatting for mathematical expressions inside $...$ or $$...$$. "
|
| 61 |
-
"At the end, clearly write: Final Answer: $[answer]$"
|
| 62 |
),
|
| 63 |
"messages": [{"role": "user", "content": prompt}]
|
| 64 |
}
|
|
@@ -72,7 +64,40 @@ def call_claude(prompt):
|
|
| 72 |
except Exception as e:
|
| 73 |
return f"❌ Claude API call failed: {e}"
|
| 74 |
|
| 75 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
@app.route("/solve", methods=["POST"])
|
| 77 |
def solve():
|
| 78 |
data = request.get_json()
|
|
@@ -80,83 +105,29 @@ def solve():
|
|
| 80 |
if not question.strip():
|
| 81 |
return jsonify({"error": "No question provided."}), 400
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
f"Your previous answer was unclear.\n\n"
|
| 90 |
-
f"❓ Question: {question}\n"
|
| 91 |
-
f"❌ Response: {first_response}\n"
|
| 92 |
-
f"Please retry with clear steps and end with: Final Answer: $[answer]$"
|
| 93 |
-
)
|
| 94 |
-
retry_response = call_claude(retry_prompt)
|
| 95 |
-
retry_answer = extract_final_answer(retry_response)
|
| 96 |
-
return jsonify({
|
| 97 |
-
"steps": retry_response,
|
| 98 |
-
"final_answer": retry_answer or "Not found"
|
| 99 |
-
})
|
| 100 |
|
| 101 |
return jsonify({
|
| 102 |
-
"steps":
|
| 103 |
"final_answer": final_answer
|
| 104 |
})
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
def export_to_pdf():
|
| 112 |
-
data = request.get_json()
|
| 113 |
-
question = data.get("question", "")
|
| 114 |
-
steps = data.get("steps", "")
|
| 115 |
-
final_answer = data.get("final_answer", "")
|
| 116 |
-
|
| 117 |
-
pdf = FPDF()
|
| 118 |
-
pdf.add_page()
|
| 119 |
-
pdf.set_auto_page_break(auto=True, margin=15)
|
| 120 |
-
|
| 121 |
-
# Title
|
| 122 |
-
pdf.set_font("Arial", 'B', 16)
|
| 123 |
-
pdf.cell(0, 10, "Math Problem Solution", ln=True, align='C')
|
| 124 |
-
pdf.ln(10)
|
| 125 |
-
|
| 126 |
-
# Question
|
| 127 |
-
pdf.set_font("Arial", 'B', 12)
|
| 128 |
-
pdf.cell(0, 10, "Problem:", ln=True)
|
| 129 |
-
pdf.set_font("Arial", '', 12)
|
| 130 |
-
pdf.multi_cell(0, 10, question)
|
| 131 |
-
pdf.ln(5)
|
| 132 |
-
|
| 133 |
-
# Steps
|
| 134 |
-
pdf.set_font("Arial", 'B', 12)
|
| 135 |
-
pdf.cell(0, 10, "Step-by-Step Solution:", ln=True)
|
| 136 |
-
pdf.set_font("Arial", '', 12)
|
| 137 |
-
for i, step in enumerate(steps.split("\n")):
|
| 138 |
-
if step.strip():
|
| 139 |
-
pdf.multi_cell(0, 10, f"{i+1}. {step.strip()}")
|
| 140 |
-
pdf.ln(5)
|
| 141 |
-
|
| 142 |
-
# Final Answer
|
| 143 |
-
pdf.set_font("Arial", 'B', 12)
|
| 144 |
-
pdf.cell(0, 10, "Final Answer:", ln=True)
|
| 145 |
-
pdf.set_font("Arial", '', 12)
|
| 146 |
-
pdf.multi_cell(0, 10, final_answer)
|
| 147 |
-
pdf.ln(5)
|
| 148 |
-
|
| 149 |
-
# Save to a temporary file
|
| 150 |
-
temp = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
|
| 151 |
-
pdf.output(temp.name)
|
| 152 |
-
|
| 153 |
-
return send_file(temp.name, mimetype='application/pdf', as_attachment=True, download_name="math_solution.pdf")
|
| 154 |
-
|
| 155 |
|
| 156 |
-
# Serve
|
| 157 |
@app.route("/", methods=["GET"])
|
| 158 |
-
def
|
| 159 |
-
return
|
| 160 |
|
|
|
|
| 161 |
if __name__ == "__main__":
|
| 162 |
app.run(host="0.0.0.0", port=7860)
|
|
|
|
| 2 |
import re
|
| 3 |
import json
|
| 4 |
import requests
|
| 5 |
+
from flask import Flask, request, jsonify, send_file
|
| 6 |
from flask_cors import CORS
|
| 7 |
from fpdf import FPDF
|
|
|
|
| 8 |
|
| 9 |
app = Flask(__name__)
|
| 10 |
CORS(app)
|
| 11 |
|
| 12 |
+
# Secure Claude key (from secrets)
|
| 13 |
CLAUDE_API_KEY = os.environ["CLAUDE_API_KEY"]
|
| 14 |
|
| 15 |
+
# === Final Answer Extractor ===
|
| 16 |
def extract_final_answer(text):
|
| 17 |
if not text:
|
| 18 |
return None
|
| 19 |
|
| 20 |
+
# LaTeX $$...$$
|
| 21 |
+
match_dollars = re.search(r'final answer[:\-]?\s*\$\$(.+?)\$\$', text, re.IGNORECASE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
if match_dollars:
|
| 23 |
return match_dollars.group(1).strip()
|
| 24 |
|
| 25 |
+
# LaTeX $...$
|
| 26 |
+
match_dollar = re.search(r'final answer[:\-]?\s*\$(.+?)\$', text, re.IGNORECASE)
|
| 27 |
if match_dollar:
|
| 28 |
return match_dollar.group(1).strip()
|
| 29 |
|
| 30 |
+
# Plain
|
| 31 |
+
match_plain = re.search(r'final answer[:\-]?\s*(.+)', text, re.IGNORECASE)
|
| 32 |
+
if match_plain:
|
| 33 |
+
return match_plain.group(1).strip()
|
| 34 |
+
|
| 35 |
+
# Fallback: last number
|
| 36 |
fallback = re.findall(r'\b\d+\.?\d*\b', text)
|
| 37 |
return fallback[-1].strip() if fallback else None
|
| 38 |
|
| 39 |
+
# === Claude Prompting Logic ===
|
|
|
|
|
|
|
| 40 |
def call_claude(prompt):
|
| 41 |
headers = {
|
| 42 |
"x-api-key": CLAUDE_API_KEY,
|
| 43 |
"Content-Type": "application/json",
|
| 44 |
"anthropic-version": "2023-06-01"
|
| 45 |
}
|
|
|
|
| 46 |
body = {
|
| 47 |
"model": "claude-3-opus-20240229",
|
| 48 |
"max_tokens": 1024,
|
| 49 |
"temperature": 0.5,
|
| 50 |
"system": (
|
| 51 |
"You are a helpful and clear Year 5–10 maths tutor. "
|
| 52 |
+
"Provide accurate, step-by-step explanations using plain English and structure. "
|
| 53 |
+
"End with: Final Answer: [answer]"
|
|
|
|
|
|
|
|
|
|
| 54 |
),
|
| 55 |
"messages": [{"role": "user", "content": prompt}]
|
| 56 |
}
|
|
|
|
| 64 |
except Exception as e:
|
| 65 |
return f"❌ Claude API call failed: {e}"
|
| 66 |
|
| 67 |
+
# === Generate PDF with Nice Formatting ===
|
| 68 |
+
def generate_pdf(problem, steps_text, final_answer):
|
| 69 |
+
pdf = FPDF()
|
| 70 |
+
pdf.add_page()
|
| 71 |
+
pdf.set_font("Arial", "B", 14)
|
| 72 |
+
pdf.cell(0, 10, "LoopBreakers Math AI – Step-by-Step Solution", ln=True)
|
| 73 |
+
|
| 74 |
+
pdf.set_font("Arial", size=12)
|
| 75 |
+
pdf.ln(5)
|
| 76 |
+
pdf.cell(0, 10, f"Problem:", ln=True)
|
| 77 |
+
pdf.set_font("Arial", "I", 12)
|
| 78 |
+
pdf.multi_cell(0, 10, problem)
|
| 79 |
+
|
| 80 |
+
pdf.ln(5)
|
| 81 |
+
pdf.set_font("Arial", size=12)
|
| 82 |
+
pdf.cell(0, 10, "Working:", ln=True)
|
| 83 |
+
|
| 84 |
+
# Format each step with bullets
|
| 85 |
+
steps = steps_text.split("\n")
|
| 86 |
+
for step in steps:
|
| 87 |
+
clean = step.strip("0123456789. ").strip()
|
| 88 |
+
if clean:
|
| 89 |
+
pdf.set_font("Arial", size=11)
|
| 90 |
+
pdf.multi_cell(0, 8, f"- {clean}")
|
| 91 |
+
|
| 92 |
+
pdf.ln(4)
|
| 93 |
+
pdf.set_font("Arial", "B", 12)
|
| 94 |
+
pdf.cell(0, 10, f"Final Answer: {final_answer}", ln=True)
|
| 95 |
+
|
| 96 |
+
output_path = "/mnt/data/loopbreakers_solution_clean.pdf"
|
| 97 |
+
pdf.output(output_path)
|
| 98 |
+
return output_path
|
| 99 |
+
|
| 100 |
+
# === API Endpoint: Solve ===
|
| 101 |
@app.route("/solve", methods=["POST"])
|
| 102 |
def solve():
|
| 103 |
data = request.get_json()
|
|
|
|
| 105 |
if not question.strip():
|
| 106 |
return jsonify({"error": "No question provided."}), 400
|
| 107 |
|
| 108 |
+
# Claude call
|
| 109 |
+
steps_text = call_claude(question)
|
| 110 |
+
final_answer = extract_final_answer(steps_text)
|
| 111 |
+
|
| 112 |
+
# Save for download
|
| 113 |
+
generate_pdf(question, steps_text, final_answer or "Not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
return jsonify({
|
| 116 |
+
"steps": steps_text,
|
| 117 |
"final_answer": final_answer
|
| 118 |
})
|
| 119 |
|
| 120 |
+
# === API Endpoint: Download PDF ===
|
| 121 |
+
@app.route("/download", methods=["GET"])
|
| 122 |
+
def download_pdf():
|
| 123 |
+
path = "/mnt/data/loopbreakers_solution_clean.pdf"
|
| 124 |
+
return send_file(path, as_attachment=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
+
# === Serve index.html locally if needed ===
|
| 127 |
@app.route("/", methods=["GET"])
|
| 128 |
+
def serve_frontend():
|
| 129 |
+
return send_file("index.html")
|
| 130 |
|
| 131 |
+
# === Run ===
|
| 132 |
if __name__ == "__main__":
|
| 133 |
app.run(host="0.0.0.0", port=7860)
|