yamanavijayavardhan commited on
Commit
bea66a9
·
1 Parent(s): 1de4963
Files changed (1) hide show
  1. main.py +65 -41
main.py CHANGED
@@ -134,14 +134,15 @@ def compute_marks():
134
 
135
  # Process files and create data structure
136
  data = {}
137
- parent_folder = os.path.join(cache_dir, 'student_answers') # Use temp directory
 
138
 
139
  # First, save uploaded files
140
  files = request.files.getlist('files[]')
141
  if not files:
142
  return jsonify({"error": "No files uploaded"}), 400
143
 
144
- # Save files to temporary directory
145
  for file in files:
146
  if file.filename.endswith(('.jpg', '.jpeg', '.png')):
147
  relative_path = file.filename.replace('\\', '/')
@@ -155,26 +156,19 @@ def compute_marks():
155
  student_dir = os.path.join(parent_folder, student_folder)
156
  os.makedirs(student_dir, exist_ok=True)
157
 
158
- # Save file
159
  save_path = os.path.join(student_dir, file_name)
160
  file.save(save_path)
161
- print(f"Saved file: {save_path}")
162
-
163
- print("Files saved, now processing folders...")
164
-
165
- # Process the saved files
166
- for student_folder in os.listdir(parent_folder):
167
- student_path = os.path.join(parent_folder, student_folder)
168
- if os.path.isdir(student_path):
169
- for image_file in os.listdir(student_path):
170
- if image_file.endswith(('.jpg', '.jpeg', '.png')):
171
- full_path = os.path.join(student_path, image_file).replace("\\", "/")
172
- if student_folder in data:
173
- data[student_folder].append(full_path)
174
- else:
175
- data[student_folder] = [full_path]
176
 
177
- print("Folder structure:", data)
178
 
179
  # Create vectors for reference answers
180
  sen_vec_answers = []
@@ -189,38 +183,65 @@ def compute_marks():
189
  word_vec_answers.append(temp_w)
190
 
191
  # Calculate marks
192
- s_marks = {}
193
- for student_folder in data:
194
- s_marks[student_folder] = []
195
- count = 0
196
- for image_path in sorted(data[student_folder]): # Sort to ensure consistent order
 
 
 
 
197
  try:
 
198
  s_answer = extract_text_from_image(image_path)
199
- print(f"\nProcessing {student_folder}'s answer {count + 1}:")
200
  print(f"Extracted answer: {s_answer}")
201
- print(f"Reference answer: {answers[count]}")
202
 
203
- if s_answer:
204
- tf_idf_word_values, max_tfidf = create_tfidf_values(answers[count])
205
- m = marks(s_answer, sen_vec_answers[count], word_vec_answers[count],
206
- tf_idf_word_values, max_tfidf, answers[count])
 
207
 
208
  if isinstance(m, torch.Tensor):
209
  m = m.item()
210
- m = round(float(m), 2)
 
 
211
  else:
212
- print(f"Warning: No text extracted from {image_path}")
213
- m = 0
 
 
 
 
 
 
214
 
215
- s_marks[student_folder].append(m)
216
- print(f"Marks awarded: {m}")
217
- count += 1
218
  except Exception as e:
219
  print(f"Error processing {image_path}: {str(e)}")
220
- s_marks[student_folder].append(0)
221
- count += 1
222
-
223
- print("\nFinal marks:", s_marks)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
  # Clean up temporary directory
226
  try:
@@ -230,7 +251,10 @@ def compute_marks():
230
  except Exception as e:
231
  print(f"Warning: Could not clean up temporary directory: {e}")
232
 
233
- return jsonify({"message": s_marks}), 200
 
 
 
234
 
235
  except Exception as e:
236
  print("Error in compute_marks:", str(e))
 
134
 
135
  # Process files and create data structure
136
  data = {}
137
+ parent_folder = os.path.join(cache_dir, 'student_answers')
138
+ os.makedirs(parent_folder, exist_ok=True)
139
 
140
  # First, save uploaded files
141
  files = request.files.getlist('files[]')
142
  if not files:
143
  return jsonify({"error": "No files uploaded"}), 400
144
 
145
+ # Save files to temporary directory with proper naming
146
  for file in files:
147
  if file.filename.endswith(('.jpg', '.jpeg', '.png')):
148
  relative_path = file.filename.replace('\\', '/')
 
156
  student_dir = os.path.join(parent_folder, student_folder)
157
  os.makedirs(student_dir, exist_ok=True)
158
 
159
+ # Save file with original name to maintain order
160
  save_path = os.path.join(student_dir, file_name)
161
  file.save(save_path)
162
+
163
+ # Store in data structure
164
+ if student_folder not in data:
165
+ data[student_folder] = []
166
+ data[student_folder].append({
167
+ 'path': save_path,
168
+ 'name': os.path.splitext(file_name)[0]
169
+ })
 
 
 
 
 
 
 
170
 
171
+ print("Initial data structure:", data)
172
 
173
  # Create vectors for reference answers
174
  sen_vec_answers = []
 
183
  word_vec_answers.append(temp_w)
184
 
185
  # Calculate marks
186
+ results = []
187
+ for student_folder, images in data.items():
188
+ student_total = 0
189
+ student_count = 0
190
+
191
+ # Sort images by name to maintain order
192
+ sorted_images = sorted(images, key=lambda x: x['name'])
193
+
194
+ for idx, image_info in enumerate(sorted_images):
195
  try:
196
+ image_path = image_info['path']
197
  s_answer = extract_text_from_image(image_path)
198
+ print(f"\nProcessing {student_folder}/{image_info['name']}:")
199
  print(f"Extracted answer: {s_answer}")
 
200
 
201
+ if s_answer and idx < len(answers):
202
+ print(f"Reference answer: {answers[idx]}")
203
+ tf_idf_word_values, max_tfidf = create_tfidf_values(answers[idx])
204
+ m = marks(s_answer, sen_vec_answers[idx], word_vec_answers[idx],
205
+ tf_idf_word_values, max_tfidf, answers[idx])
206
 
207
  if isinstance(m, torch.Tensor):
208
  m = m.item()
209
+ mark_value = round(float(m), 2)
210
+ student_total += mark_value
211
+ student_count += 1
212
  else:
213
+ mark_value = 0
214
+
215
+ results.append({
216
+ 'student': student_folder,
217
+ 'image_name': image_info['name'],
218
+ 'marks': mark_value
219
+ })
220
+ print(f"Marks awarded: {mark_value}")
221
 
 
 
 
222
  except Exception as e:
223
  print(f"Error processing {image_path}: {str(e)}")
224
+ results.append({
225
+ 'student': student_folder,
226
+ 'image_name': image_info['name'],
227
+ 'marks': 0
228
+ })
229
+
230
+ # Add average for student
231
+ if student_count > 0:
232
+ avg_mark = round(student_total / student_count, 2)
233
+ results.append({
234
+ 'student': student_folder,
235
+ 'image_name': 'AVERAGE',
236
+ 'marks': avg_mark
237
+ })
238
+
239
+ # Sort results
240
+ results.sort(key=lambda x: (x['student'], x['image_name']))
241
+
242
+ print("\nFinal Results:")
243
+ for r in results:
244
+ print(f"{r['student']}\t{r['image_name']}\t{r['marks']}")
245
 
246
  # Clean up temporary directory
247
  try:
 
251
  except Exception as e:
252
  print(f"Warning: Could not clean up temporary directory: {e}")
253
 
254
+ return jsonify({
255
+ "message": results,
256
+ "status": "success"
257
+ }), 200
258
 
259
  except Exception as e:
260
  print("Error in compute_marks:", str(e))