Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,9 +4,6 @@ from anthropic import Anthropic
|
|
| 4 |
from datetime import datetime, timedelta
|
| 5 |
from collections import deque
|
| 6 |
import random
|
| 7 |
-
import tempfile
|
| 8 |
-
import subprocess
|
| 9 |
-
from pathlib import Path
|
| 10 |
|
| 11 |
# Initialize Anthropic client
|
| 12 |
anthropic = Anthropic(
|
|
@@ -37,47 +34,41 @@ def clean_latex(text):
|
|
| 37 |
def create_latex_document(content, questions_only=False):
|
| 38 |
"""Create a complete LaTeX document"""
|
| 39 |
latex_header = r"""\documentclass{article}
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
| 44 |
latex_footer = r"\end{document}"
|
| 45 |
|
| 46 |
if questions_only:
|
| 47 |
# Extract only the questions (everything before "Solution:")
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
| 51 |
continue
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
return f"{latex_header}\n{content}\n{latex_footer}"
|
| 56 |
|
| 57 |
-
def
|
| 58 |
-
"""
|
| 59 |
-
with tempfile.TemporaryDirectory() as tmpdir:
|
| 60 |
-
tex_path = Path(tmpdir) / "output.tex"
|
| 61 |
-
with open(tex_path, "w", encoding="utf-8") as f:
|
| 62 |
-
f.write(latex_content)
|
| 63 |
-
|
| 64 |
-
# Run pdflatex twice to resolve references
|
| 65 |
-
subprocess.run(["pdflatex", "-interaction=nonstopmode", str(tex_path)],
|
| 66 |
-
cwd=tmpdir, capture_output=True)
|
| 67 |
-
subprocess.run(["pdflatex", "-interaction=nonstopmode", str(tex_path)],
|
| 68 |
-
cwd=tmpdir, capture_output=True)
|
| 69 |
-
|
| 70 |
-
pdf_path = Path(tmpdir) / "output.pdf"
|
| 71 |
-
if pdf_path.exists():
|
| 72 |
-
return pdf_path.read_bytes()
|
| 73 |
-
return None
|
| 74 |
-
|
| 75 |
-
def generate_test_with_format(subject, output_format):
|
| 76 |
-
"""Generate a math test with specified output format"""
|
| 77 |
try:
|
| 78 |
check_api_key()
|
| 79 |
if not check_rate_limit():
|
| 80 |
-
return "Daily request limit reached. Please try again tomorrow."
|
| 81 |
|
| 82 |
request_history.append(datetime.now())
|
| 83 |
|
|
@@ -111,12 +102,10 @@ def generate_test_with_format(subject, output_format):
|
|
| 111 |
|
| 112 |
Important: Every question must require mathematical computation or proof. Do not ask for explanations, descriptions, or concepts."""
|
| 113 |
|
| 114 |
-
temperature = 0.7
|
| 115 |
-
|
| 116 |
message = anthropic.messages.create(
|
| 117 |
model="claude-3-opus-20240229",
|
| 118 |
max_tokens=1500,
|
| 119 |
-
temperature=
|
| 120 |
messages=[{
|
| 121 |
"role": "user",
|
| 122 |
"content": f"{system_prompt}\n\nWrite an exam for {subject}."
|
|
@@ -125,29 +114,18 @@ def generate_test_with_format(subject, output_format):
|
|
| 125 |
|
| 126 |
if hasattr(message, 'content') and len(message.content) > 0:
|
| 127 |
response_text = message.content[0].text
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
else:
|
| 130 |
-
return "Error: No content in response"
|
| 131 |
|
| 132 |
except Exception as e:
|
| 133 |
-
return f"Error: {str(e)}"
|
| 134 |
-
|
| 135 |
-
def create_download_files(test_content):
|
| 136 |
-
"""Create downloadable files in different formats"""
|
| 137 |
-
# Full test (questions and solutions)
|
| 138 |
-
full_latex = create_latex_document(test_content, questions_only=False)
|
| 139 |
-
full_pdf = latex_to_pdf(full_latex)
|
| 140 |
-
|
| 141 |
-
# Questions only
|
| 142 |
-
questions_latex = create_latex_document(test_content, questions_only=True)
|
| 143 |
-
questions_pdf = latex_to_pdf(questions_latex)
|
| 144 |
-
|
| 145 |
-
return {
|
| 146 |
-
"full_latex": full_latex,
|
| 147 |
-
"full_pdf": full_pdf,
|
| 148 |
-
"questions_latex": questions_latex,
|
| 149 |
-
"questions_pdf": questions_pdf
|
| 150 |
-
}
|
| 151 |
|
| 152 |
subjects = [
|
| 153 |
"Single Variable Calculus",
|
|
@@ -162,10 +140,6 @@ subjects = [
|
|
| 162 |
"Topology"
|
| 163 |
]
|
| 164 |
|
| 165 |
-
def download_handler(file_content, filename):
|
| 166 |
-
"""Handle file downloads"""
|
| 167 |
-
return file_content
|
| 168 |
-
|
| 169 |
# Create Gradio interface
|
| 170 |
with gr.Blocks() as interface:
|
| 171 |
gr.Markdown("# Advanced Mathematics Test Generator")
|
|
@@ -190,45 +164,24 @@ with gr.Blocks() as interface:
|
|
| 190 |
|
| 191 |
with gr.Row():
|
| 192 |
with gr.Column():
|
| 193 |
-
gr.Markdown("### Download
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
with gr.Column():
|
| 198 |
-
gr.Markdown("### Download Full Test with Solutions")
|
| 199 |
-
full_latex_btn = gr.Button("Download Full Test (LaTeX)")
|
| 200 |
-
full_pdf_btn = gr.Button("Download Full Test (PDF)")
|
| 201 |
-
|
| 202 |
-
# Hidden components for downloads
|
| 203 |
-
questions_latex_output = gr.File(label="Questions LaTeX", visible=False)
|
| 204 |
-
questions_pdf_output = gr.File(label="Questions PDF", visible=False)
|
| 205 |
-
full_latex_output = gr.File(label="Full LaTeX", visible=False)
|
| 206 |
-
full_pdf_output = gr.File(label="Full PDF", visible=False)
|
| 207 |
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
files
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
(files["full_latex"], "full_test.tex"),
|
| 217 |
-
(files["full_pdf"], "full_test.pdf")
|
| 218 |
-
)
|
| 219 |
|
| 220 |
generate_btn.click(
|
| 221 |
-
|
| 222 |
inputs=[subject_dropdown],
|
| 223 |
-
outputs=[output_text,
|
| 224 |
-
full_latex_output, full_pdf_output]
|
| 225 |
)
|
| 226 |
-
|
| 227 |
-
# Download button clicks
|
| 228 |
-
questions_latex_btn.click(lambda: questions_latex_output.value)
|
| 229 |
-
questions_pdf_btn.click(lambda: questions_pdf_output.value)
|
| 230 |
-
full_latex_btn.click(lambda: full_latex_output.value)
|
| 231 |
-
full_pdf_btn.click(lambda: full_pdf_output.value)
|
| 232 |
|
| 233 |
if __name__ == "__main__":
|
| 234 |
interface.launch()
|
|
|
|
| 4 |
from datetime import datetime, timedelta
|
| 5 |
from collections import deque
|
| 6 |
import random
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
# Initialize Anthropic client
|
| 9 |
anthropic = Anthropic(
|
|
|
|
| 34 |
def create_latex_document(content, questions_only=False):
|
| 35 |
"""Create a complete LaTeX document"""
|
| 36 |
latex_header = r"""\documentclass{article}
|
| 37 |
+
\usepackage{amsmath,amssymb}
|
| 38 |
+
\usepackage[margin=1in]{geometry}
|
| 39 |
+
\begin{document}
|
| 40 |
+
\title{Mathematics Test}
|
| 41 |
+
\maketitle
|
| 42 |
+
"""
|
| 43 |
latex_footer = r"\end{document}"
|
| 44 |
|
| 45 |
if questions_only:
|
| 46 |
# Extract only the questions (everything before "Solution:")
|
| 47 |
+
processed_content = []
|
| 48 |
+
current_question = []
|
| 49 |
+
for line in content.split('\n'):
|
| 50 |
+
if 'Solution:' in line:
|
| 51 |
+
processed_content.append('\n'.join(current_question))
|
| 52 |
+
current_question = []
|
| 53 |
continue
|
| 54 |
+
if any(line.startswith(f"{i})") for i in range(1, 4)):
|
| 55 |
+
if current_question:
|
| 56 |
+
processed_content.append('\n'.join(current_question))
|
| 57 |
+
current_question = [line]
|
| 58 |
+
elif current_question:
|
| 59 |
+
current_question.append(line)
|
| 60 |
+
if current_question:
|
| 61 |
+
processed_content.append('\n'.join(current_question))
|
| 62 |
+
content = '\n\n'.join(processed_content)
|
| 63 |
|
| 64 |
return f"{latex_header}\n{content}\n{latex_footer}"
|
| 65 |
|
| 66 |
+
def generate_test(subject):
|
| 67 |
+
"""Generate a math test"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
try:
|
| 69 |
check_api_key()
|
| 70 |
if not check_rate_limit():
|
| 71 |
+
return "Daily request limit reached. Please try again tomorrow.", None, None
|
| 72 |
|
| 73 |
request_history.append(datetime.now())
|
| 74 |
|
|
|
|
| 102 |
|
| 103 |
Important: Every question must require mathematical computation or proof. Do not ask for explanations, descriptions, or concepts."""
|
| 104 |
|
|
|
|
|
|
|
| 105 |
message = anthropic.messages.create(
|
| 106 |
model="claude-3-opus-20240229",
|
| 107 |
max_tokens=1500,
|
| 108 |
+
temperature=0.7,
|
| 109 |
messages=[{
|
| 110 |
"role": "user",
|
| 111 |
"content": f"{system_prompt}\n\nWrite an exam for {subject}."
|
|
|
|
| 114 |
|
| 115 |
if hasattr(message, 'content') and len(message.content) > 0:
|
| 116 |
response_text = message.content[0].text
|
| 117 |
+
cleaned_text = clean_latex(response_text)
|
| 118 |
+
|
| 119 |
+
# Create both versions of the LaTeX document
|
| 120 |
+
full_latex = create_latex_document(cleaned_text, questions_only=False)
|
| 121 |
+
questions_latex = create_latex_document(cleaned_text, questions_only=True)
|
| 122 |
+
|
| 123 |
+
return cleaned_text, questions_latex, full_latex
|
| 124 |
else:
|
| 125 |
+
return "Error: No content in response", None, None
|
| 126 |
|
| 127 |
except Exception as e:
|
| 128 |
+
return f"Error: {str(e)}", None, None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
subjects = [
|
| 131 |
"Single Variable Calculus",
|
|
|
|
| 140 |
"Topology"
|
| 141 |
]
|
| 142 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
# Create Gradio interface
|
| 144 |
with gr.Blocks() as interface:
|
| 145 |
gr.Markdown("# Advanced Mathematics Test Generator")
|
|
|
|
| 164 |
|
| 165 |
with gr.Row():
|
| 166 |
with gr.Column():
|
| 167 |
+
gr.Markdown("### Download LaTeX Files")
|
| 168 |
+
questions_file = gr.File(label="Questions Only (LaTeX)")
|
| 169 |
+
full_file = gr.File(label="Full Test with Solutions (LaTeX)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
def generate_and_prepare_files(subject):
|
| 172 |
+
preview, questions_latex, full_latex = generate_test(subject)
|
| 173 |
+
|
| 174 |
+
# Create temporary files for download
|
| 175 |
+
questions_file = {"content": questions_latex.encode(), "name": "questions.tex"}
|
| 176 |
+
full_file = {"content": full_latex.encode(), "name": "full_test.tex"}
|
| 177 |
+
|
| 178 |
+
return preview, questions_file, full_file
|
|
|
|
|
|
|
|
|
|
| 179 |
|
| 180 |
generate_btn.click(
|
| 181 |
+
generate_and_prepare_files,
|
| 182 |
inputs=[subject_dropdown],
|
| 183 |
+
outputs=[output_text, questions_file, full_file]
|
|
|
|
| 184 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
if __name__ == "__main__":
|
| 187 |
interface.launch()
|