joshuarauh commited on
Commit
bfc1cf6
·
verified ·
1 Parent(s): d4d9036

Add initial app.py with math test generator

Browse files
Files changed (1) hide show
  1. app.py +138 -0
app.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import os
3
+ import gradio as gr
4
+ from anthropic import Anthropic
5
+ from datetime import datetime, timedelta
6
+ from collections import deque
7
+
8
+ # Initialize Anthropic client - will use the secret key from HuggingFace
9
+ anthropic = Anthropic(
10
+ api_key=os.environ.get('ANTHROPIC_API_KEY')
11
+ )
12
+
13
+ # Request tracking
14
+ MAX_REQUESTS_PER_DAY = 25 # Conservative limit to start
15
+ request_history = deque(maxlen=1000)
16
+
17
+ def check_api_key():
18
+ """Verify API key is configured"""
19
+ if not os.environ.get('ANTHROPIC_API_KEY'):
20
+ raise ValueError("Anthropic API key not found. Please configure it in HuggingFace Spaces settings.")
21
+
22
+ def check_rate_limit():
23
+ """Check if we're within rate limits"""
24
+ now = datetime.now()
25
+ # Remove requests older than 24 hours
26
+ while request_history and (now - request_history[0]) > timedelta(days=1):
27
+ request_history.popleft()
28
+ return len(request_history) < MAX_REQUESTS_PER_DAY
29
+
30
+ def clean_latex(text):
31
+ """Simple LaTeX cleaning"""
32
+ text = text.replace('\n', '\n\n')
33
+ return text
34
+
35
+ def generate_test(subject):
36
+ """Generate a math test with error handling and rate limiting"""
37
+ try:
38
+ # Check API key
39
+ check_api_key()
40
+
41
+ # Check rate limit
42
+ if not check_rate_limit():
43
+ return "Daily request limit reached. Please try again tomorrow."
44
+
45
+ # Record request
46
+ request_history.append(datetime.now())
47
+
48
+ system_prompt = """You will write math exam questions. Follow these requirements EXACTLY:
49
+ 1. Write exactly 3 challenging university-level questions
50
+ 2. For LaTeX math formatting:
51
+ - Use $ for simple inline math
52
+ - For equations and solution steps, use $$ on separate lines
53
+ - For multi-step solutions, put each step on its own line in $$ $$
54
+ - DO NOT use \\begin{aligned} or any other environments
55
+ 3. Number each question as 1), 2), 3)
56
+ 4. Include solutions after each question
57
+ 5. Keep formatting simple and clear"""
58
+
59
+ message = anthropic.messages.create(
60
+ model="claude-3-opus-20240229",
61
+ max_tokens=1500,
62
+ temperature=0.7,
63
+ messages=[{
64
+ "role": "user",
65
+ "content": f"{system_prompt}\n\nWrite an exam for {subject}."
66
+ }]
67
+ )
68
+
69
+ # Extract usage information
70
+ input_tokens = message.usage.input_tokens
71
+ output_tokens = message.usage.output_tokens
72
+ input_cost = (input_tokens / 1000) * 0.015
73
+ output_cost = (output_tokens / 1000) * 0.075
74
+ total_cost = input_cost + output_cost
75
+
76
+ usage_stats = f"""
77
+ \n---\nUsage Statistics:
78
+ • Input Tokens: {input_tokens:,}
79
+ • Output Tokens: {output_tokens:,}
80
+ • Total Tokens: {input_tokens + output_tokens:,}
81
+
82
+ Cost Breakdown:
83
+ • Input Cost: ${input_cost:.4f}
84
+ • Output Cost: ${output_cost:.4f}
85
+ • Total Cost: ${total_cost:.4f}
86
+ """
87
+
88
+ if hasattr(message, 'content') and len(message.content) > 0:
89
+ response_text = message.content[0].text
90
+ formatted_response = clean_latex(response_text) + usage_stats
91
+ return formatted_response
92
+ else:
93
+ return "Error: No content in response"
94
+
95
+ except ValueError as e:
96
+ return f"Configuration Error: {str(e)}"
97
+ except Exception as e:
98
+ return f"Error: {str(e)}"
99
+
100
+ # Subject choices
101
+ subjects = [
102
+ "Single Variable Calculus",
103
+ "Multivariable Calculus",
104
+ "Linear Algebra",
105
+ "Differential Equations",
106
+ "Real Analysis",
107
+ "Complex Analysis",
108
+ "Abstract Algebra",
109
+ "Probability Theory",
110
+ "Numerical Analysis",
111
+ "Topology"
112
+ ]
113
+
114
+ # Create Gradio interface
115
+ interface = gr.Interface(
116
+ fn=generate_test,
117
+ inputs=gr.Dropdown(
118
+ choices=subjects,
119
+ label="Select Mathematics Subject",
120
+ info="Choose a subject for the exam questions"
121
+ ),
122
+ outputs=gr.Markdown(
123
+ label="Generated Test",
124
+ latex_delimiters=[
125
+ {"left": "$$", "right": "$$", "display": True"},
126
+ {"left": "$", "right": "$", "display": False}
127
+ ]
128
+ ),
129
+ title="Advanced Mathematics Test Generator",
130
+ description="""Generates university-level mathematics exam questions with solutions using Claude 3 Opus.
131
+ Limited to 25 requests per day. Please use responsibly.""",
132
+ theme="default",
133
+ allow_flagging="never"
134
+ )
135
+
136
+ # Launch the interface
137
+ if __name__ == "__main__":
138
+ interface.launch()