sunbal7 commited on
Commit
fdd5bb4
Β·
verified Β·
1 Parent(s): cd5aa8b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -7
app.py CHANGED
@@ -6,9 +6,10 @@ import fitz # PyMuPDF
6
  import io
7
  import requests
8
  import re
 
9
 
10
  # --- Config ---
11
- API_KEY = "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"
12
  API_URL = "https://openrouter.ai/api/v1/chat/completions"
13
  MODEL = "mistralai/mistral-7b-instruct"
14
 
@@ -66,6 +67,19 @@ st.markdown("""
66
  margin: 15px 0;
67
  border-radius: 0 8px 8px 0;
68
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  </style>
70
  """, unsafe_allow_html=True)
71
 
@@ -80,6 +94,15 @@ st.markdown("""
80
  </div>
81
  """, unsafe_allow_html=True)
82
 
 
 
 
 
 
 
 
 
 
83
  # Features in columns
84
  col1, col2, col3 = st.columns(3)
85
  with col1:
@@ -134,7 +157,7 @@ if uploaded_file:
134
  lab_text = st.text_area("", lab_text, height=300, label_visibility="collapsed")
135
 
136
  # --- AI Evaluation ---
137
- if lab_text.strip():
138
  # -- AI Evaluation Prompt --
139
  full_prompt = f"""You are a science teacher evaluating a student's lab report. Please provide a comprehensive analysis:
140
 
@@ -171,9 +194,9 @@ if lab_text.strip():
171
  Be concise but thorough in your analysis.
172
  """
173
 
174
- def query_ai(prompt):
175
  headers = {
176
- "Authorization": f"Bearer {API_KEY}",
177
  "Content-Type": "application/json"
178
  }
179
  payload = {
@@ -187,20 +210,23 @@ if lab_text.strip():
187
  response = requests.post(API_URL, headers=headers, json=payload, timeout=120)
188
  response.raise_for_status()
189
  return response.json()['choices'][0]['message']['content']
 
 
 
190
  except Exception as e:
191
  st.error(f"Error connecting to AI service: {str(e)}")
192
  return None
193
 
194
  if st.button("πŸ§ͺ Analyze Report", use_container_width=True):
195
  with st.spinner("πŸ” Analyzing report with AI. This may take 20-30 seconds..."):
196
- result = query_ai(full_prompt)
197
 
198
  if result:
199
  st.success("βœ… Analysis Complete!")
200
  st.balloons()
201
 
202
  # Extract score using regex
203
- score_match = re.search(r"Completeness Score:\s*(\d+)/10", result)
204
  score = int(score_match.group(1)) if score_match else None
205
 
206
  # Display score in a card
@@ -305,11 +331,13 @@ if lab_text.strip():
305
  Answer the question based on the lab report. If the question can't be answered from the report,
306
  suggest what information the student should add to answer it.
307
  """
308
- followup_response = query_ai(followup_prompt)
309
 
310
  if followup_response:
311
  st.markdown("### πŸ’¬ AI Response")
312
  st.markdown(f'<div class="tip-box">{followup_response}</div>', unsafe_allow_html=True)
 
 
313
  else:
314
  # Show sample report if no file uploaded
315
  st.markdown("---")
 
6
  import io
7
  import requests
8
  import re
9
+ import os
10
 
11
  # --- Config ---
12
+ DEFAULT_API_KEY = "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"
13
  API_URL = "https://openrouter.ai/api/v1/chat/completions"
14
  MODEL = "mistralai/mistral-7b-instruct"
15
 
 
67
  margin: 15px 0;
68
  border-radius: 0 8px 8px 0;
69
  }
70
+ .error-box {
71
+ background-color: #fdecea;
72
+ border-left: 5px solid #e74c3c;
73
+ padding: 15px;
74
+ margin: 15px 0;
75
+ border-radius: 0 8px 8px 0;
76
+ }
77
+ .api-container {
78
+ background-color: #eaf2f8;
79
+ border-radius: 10px;
80
+ padding: 15px;
81
+ margin: 15px 0;
82
+ }
83
  </style>
84
  """, unsafe_allow_html=True)
85
 
 
94
  </div>
95
  """, unsafe_allow_html=True)
96
 
97
+ # API Key Setup
98
+ st.markdown("---")
99
+ st.markdown("### πŸ”‘ API Configuration")
100
+ st.info("You need an API key from [OpenRouter](https://openrouter.ai/) to use this tool. Get a free key and paste it below.")
101
+
102
+ api_key = st.text_input("Enter your OpenRouter API Key:", type="password",
103
+ help="Get your API key from https://openrouter.ai/keys",
104
+ value=os.getenv("OPENROUTER_API_KEY", DEFAULT_API_KEY))
105
+
106
  # Features in columns
107
  col1, col2, col3 = st.columns(3)
108
  with col1:
 
157
  lab_text = st.text_area("", lab_text, height=300, label_visibility="collapsed")
158
 
159
  # --- AI Evaluation ---
160
+ if lab_text.strip() and api_key:
161
  # -- AI Evaluation Prompt --
162
  full_prompt = f"""You are a science teacher evaluating a student's lab report. Please provide a comprehensive analysis:
163
 
 
194
  Be concise but thorough in your analysis.
195
  """
196
 
197
+ def query_ai(prompt, api_key):
198
  headers = {
199
+ "Authorization": f"Bearer {api_key}",
200
  "Content-Type": "application/json"
201
  }
202
  payload = {
 
210
  response = requests.post(API_URL, headers=headers, json=payload, timeout=120)
211
  response.raise_for_status()
212
  return response.json()['choices'][0]['message']['content']
213
+ except requests.exceptions.HTTPError as err:
214
+ st.error(f"API Error: {err.response.status_code} - {err.response.text}")
215
+ return None
216
  except Exception as e:
217
  st.error(f"Error connecting to AI service: {str(e)}")
218
  return None
219
 
220
  if st.button("πŸ§ͺ Analyze Report", use_container_width=True):
221
  with st.spinner("πŸ” Analyzing report with AI. This may take 20-30 seconds..."):
222
+ result = query_ai(full_prompt, api_key)
223
 
224
  if result:
225
  st.success("βœ… Analysis Complete!")
226
  st.balloons()
227
 
228
  # Extract score using regex
229
+ score_match = re.search(r"Completeness Score:\s*(\d+)/10", result, re.IGNORECASE)
230
  score = int(score_match.group(1)) if score_match else None
231
 
232
  # Display score in a card
 
331
  Answer the question based on the lab report. If the question can't be answered from the report,
332
  suggest what information the student should add to answer it.
333
  """
334
+ followup_response = query_ai(followup_prompt, api_key)
335
 
336
  if followup_response:
337
  st.markdown("### πŸ’¬ AI Response")
338
  st.markdown(f'<div class="tip-box">{followup_response}</div>', unsafe_allow_html=True)
339
+ elif lab_text.strip() and not api_key:
340
+ st.error("⚠️ Please enter a valid OpenRouter API key to analyze your report")
341
  else:
342
  # Show sample report if no file uploaded
343
  st.markdown("---")