yamanavijayavardhan commited on
Commit
43ce63b
·
1 Parent(s): 806c76a
Files changed (1) hide show
  1. main.py +49 -98
main.py CHANGED
@@ -198,127 +198,78 @@ def compute_marks():
198
  answers.append(ans)
199
  log_print(f"Processed answers structure: {answers}")
200
 
201
- # Process files and create data structure
202
  data = {}
203
- parent_folder = os.path.join(cache_dir, 'student_answers')
204
- os.makedirs(parent_folder, exist_ok=True)
205
 
206
- log_print("\n=== Processing Uploaded Files ===")
207
- files = request.files.getlist('files[]')
208
- if not files:
209
- log_print("No files uploaded", "ERROR")
210
- return jsonify({"error": "No files uploaded"}), 400
211
 
212
- log_print(f"Number of files received: {len(files)}")
213
-
214
- # File processing
215
- for file in files:
216
- if file.filename.endswith(('.jpg', '.jpeg', '.png')):
217
- relative_path = file.filename.replace('\\', '/')
218
- path_parts = relative_path.split('/')
219
-
220
- log_print(f"\nProcessing file: {file.filename}")
221
- log_print(f"Path parts: {path_parts}")
222
-
223
- if len(path_parts) >= 2:
224
- student_folder = path_parts[1]
225
- file_name = path_parts[-1]
226
-
227
- student_dir = os.path.join(parent_folder, student_folder)
228
- os.makedirs(student_dir, exist_ok=True)
229
-
230
- save_path = os.path.join(student_dir, file_name)
231
- file.save(save_path)
232
- log_print(f"Saved file: {save_path}")
233
-
234
- if student_folder not in data:
235
- data[student_folder] = []
236
- data[student_folder].append({
237
- 'path': save_path,
238
- 'name': os.path.splitext(file_name)[0]
239
- })
240
- else:
241
- log_print(f"WARNING: File {file.filename} doesn't have expected structure")
242
 
243
- # Log data structure
244
- log_print("\n=== Final Data Structure ===")
245
- for student, images in data.items():
246
- log_print(f"Student: {student}")
247
- for img in sorted(images, key=lambda x: x['name']):
248
- log_print(f" - {img['name']} ({img['path']})")
 
 
 
 
 
249
 
250
- # Calculate marks with logging
251
- results = []
252
- for student_folder, images in data.items():
253
- student_total = 0
254
- student_count = 0
255
-
256
- sorted_images = sorted(images, key=lambda x: x['name'])
257
-
258
- for idx, image_info in enumerate(sorted_images):
259
  try:
260
- image_path = image_info['path']
261
  s_answer = extract_text_from_image(image_path)
262
- log_print(f"\nProcessing {student_folder}/{image_info['name']}:")
263
  log_print(f"Extracted answer: {s_answer}")
264
 
265
- if s_answer and idx < len(answers):
266
- log_print(f"Reference answer: {answers[idx]}")
267
- tf_idf_word_values, max_tfidf = create_tfidf_values(answers[idx])
268
- m = marks(s_answer, sen_vec_answers[idx], word_vec_answers[idx],
269
- tf_idf_word_values, max_tfidf, answers[idx])
270
 
271
  if isinstance(m, torch.Tensor):
272
  m = m.item()
273
- mark_value = round(float(m), 2)
274
- student_total += mark_value
275
- student_count += 1
276
- log_print(f"Marks awarded: {mark_value}")
277
  else:
278
- mark_value = 0
279
- log_print(f"No text extracted or no reference answer for index {idx}", "WARNING")
280
 
281
- results.append({
282
- 'student': student_folder,
283
- 'image_name': image_info['name'],
284
- 'marks': mark_value
285
- })
286
 
287
  except Exception as e:
288
  log_print(f"Error processing {image_path}: {str(e)}", "ERROR")
289
- results.append({
290
- 'student': student_folder,
291
- 'image_name': image_info['name'],
292
- 'marks': 0
293
- })
294
-
295
- # Sort results
296
- results.sort(key=lambda x: (x['student'], x['image_name']))
297
 
298
  log_print("\nFinal Results:")
299
- for r in results:
300
- log_print(f"{r['student']}\t{r['image_name']}\t{r['marks']}")
301
-
302
- # Clean up temporary directory
303
- try:
304
- import shutil
305
- shutil.rmtree(parent_folder)
306
- log_print(f"Cleaned up temporary directory: {parent_folder}")
307
- except Exception as e:
308
- log_print(f"Warning: Could not clean up temporary directory: {e}", "WARNING")
309
 
310
- return jsonify({
311
- "message": results,
312
- "status": "success"
313
- }), 200
314
 
315
  except Exception as e:
316
  log_print(f"Error in compute_marks: {str(e)}", "ERROR")
317
- try:
318
- import shutil
319
- shutil.rmtree(parent_folder)
320
- except:
321
- pass
322
  return jsonify({"error": str(e)}), 500
323
 
324
  def marks(answer, sen_vec_answers, word_vec_answers, tf_idf_word_values, max_tfidf, correct_answers):
 
198
  answers.append(ans)
199
  log_print(f"Processed answers structure: {answers}")
200
 
201
+ # Initialize data structure and parent folder
202
  data = {}
203
+ parent_folder = "ans_image" # Changed from cache_dir to match reference code
 
204
 
205
+ # Check if answers exist
206
+ if not answers:
207
+ log_print("No answers found", "ERROR")
208
+ return jsonify({"error": "Missing required files"}), 400
 
209
 
210
+ # Process student folders and images
211
+ for student_folder in os.listdir(parent_folder):
212
+ student_path = os.path.join(parent_folder, student_folder)
213
+ if os.path.isdir(student_path):
214
+ for image_file in os.listdir(student_path):
215
+ if image_file.endswith(('.jpg')): # Changed to match reference code
216
+ full_path = os.path.join(student_path, image_file).replace("\\", "/")
217
+ if student_folder in data:
218
+ data[student_folder].append(full_path)
219
+ else:
220
+ data[student_folder] = [full_path]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
+ # Initialize vectors for answers
223
+ sen_vec_answers = []
224
+ word_vec_answers = []
225
+ for i in answers:
226
+ temp_v = []
227
+ temp_w = []
228
+ for j in i:
229
+ temp_v.append(question_vector_sentence(j))
230
+ temp_w.append(question_vector_word(j))
231
+ sen_vec_answers.append(temp_v)
232
+ word_vec_answers.append(temp_w)
233
 
234
+ # Calculate marks
235
+ s_marks = {}
236
+ for student_folder in data:
237
+ s_marks[student_folder] = []
238
+ count = 0
239
+ for image_path in data[student_folder]:
 
 
 
240
  try:
 
241
  s_answer = extract_text_from_image(image_path)
242
+ log_print(f"\nProcessing {student_folder}/{os.path.basename(image_path)}:")
243
  log_print(f"Extracted answer: {s_answer}")
244
 
245
+ if s_answer and count < len(answers):
246
+ log_print(f"Reference answer: {answers[count]}")
247
+ tf_idf_word_values, max_tfidf = create_tfidf_values(answers[count])
248
+ m = marks(s_answer, sen_vec_answers[count], word_vec_answers[count],
249
+ tf_idf_word_values, max_tfidf, answers[count])
250
 
251
  if isinstance(m, torch.Tensor):
252
  m = m.item()
253
+ s_marks[student_folder].append(round(float(m), 2))
254
+ log_print(f"Marks awarded: {m}")
 
 
255
  else:
256
+ s_marks[student_folder].append(0)
257
+ log_print(f"No text extracted or no reference answer for index {count}", "WARNING")
258
 
259
+ count += 1
 
 
 
 
260
 
261
  except Exception as e:
262
  log_print(f"Error processing {image_path}: {str(e)}", "ERROR")
263
+ s_marks[student_folder].append(0)
 
 
 
 
 
 
 
264
 
265
  log_print("\nFinal Results:")
266
+ for student, marks_list in s_marks.items():
267
+ log_print(f"{student}: {marks_list}")
 
 
 
 
 
 
 
 
268
 
269
+ return jsonify({"message": s_marks}), 200
 
 
 
270
 
271
  except Exception as e:
272
  log_print(f"Error in compute_marks: {str(e)}", "ERROR")
 
 
 
 
 
273
  return jsonify({"error": str(e)}), 500
274
 
275
  def marks(answer, sen_vec_answers, word_vec_answers, tf_idf_word_values, max_tfidf, correct_answers):