yamanavijayavardhan commited on
Commit
43bac4b
·
1 Parent(s): d7a1342

update_new

Browse files
Files changed (1) hide show
  1. main.py +64 -89
main.py CHANGED
@@ -12,7 +12,7 @@ from dotenv import load_dotenv
12
  load_dotenv()
13
 
14
  # Create directories in /tmp which is writable
15
- BASE_DIR = tempfile.gettempdir()
16
  log_dir = os.path.join(BASE_DIR, 'app_logs')
17
  cache_dir = os.path.join(BASE_DIR, 'app_cache')
18
 
@@ -22,7 +22,8 @@ try:
22
  except Exception as e:
23
  print(f"Warning: Could not create log directory: {e}")
24
  # Fallback to temp directory
25
- log_dir = tempfile.mkdtemp(prefix='app_logs_')
 
26
 
27
  # Create a log file with timestamp
28
  log_file = os.path.join(log_dir, f'app_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log')
@@ -62,26 +63,29 @@ def log_print(message, level="INFO"):
62
 
63
  # Set up all cache and data directories in /tmp
64
  try:
65
- nltk_data_dir = os.path.join(cache_dir, 'nltk_data')
66
- gensim_data_dir = os.path.join(cache_dir, 'gensim-data')
67
- upload_dir = os.path.join(cache_dir, 'uploads')
68
- ans_image_dir = os.path.join(cache_dir, 'ans_image')
69
- htr_images_dir = os.path.join(cache_dir, 'images')
70
 
71
  # Create directories with correct permissions
72
- for directory in [cache_dir, nltk_data_dir, gensim_data_dir, upload_dir, ans_image_dir, htr_images_dir]:
73
  os.makedirs(directory, exist_ok=True)
74
- # Ensure directory has write permissions
75
- os.chmod(directory, 0o777)
76
  except Exception as e:
77
  print(f"Warning: Could not create cache directories: {e}")
78
- # Fallback to temporary directories
79
- cache_dir = tempfile.mkdtemp(prefix='app_cache_')
80
- nltk_data_dir = tempfile.mkdtemp(prefix='nltk_data_')
81
- gensim_data_dir = tempfile.mkdtemp(prefix='gensim_data_')
82
- upload_dir = tempfile.mkdtemp(prefix='uploads_')
83
- ans_image_dir = tempfile.mkdtemp(prefix='ans_image_')
84
- htr_images_dir = tempfile.mkdtemp(prefix='htr_images_')
 
 
 
 
85
 
86
  # Set environment variables
87
  os.environ['HF_HOME'] = cache_dir
@@ -251,30 +255,6 @@ def compute_marks():
251
  log_print("Invalid JSON format in answers", "ERROR")
252
  return jsonify({"error": "Invalid JSON format in answers"}), 400
253
 
254
- # Add validation for answers
255
- def validate_answers(answers):
256
- try:
257
- if not isinstance(answers, list):
258
- return False
259
- # Check if each answer is a string or a list of strings
260
- for ans in answers:
261
- if isinstance(ans, str):
262
- continue
263
- elif isinstance(ans, list):
264
- if not all(isinstance(a, str) for a in ans):
265
- return False
266
- else:
267
- return False
268
- return True
269
- except Exception as e:
270
- log_print(f"Validation error: {str(e)}", "ERROR")
271
- return False
272
-
273
- if not validate_answers(answers):
274
- log_print("Invalid answer format", "ERROR")
275
- log_print(f"Received answer structure: {answers}", "ERROR")
276
- return jsonify({"error": "Invalid answer format"}), 400
277
-
278
  # Process answers to ensure consistent format
279
  processed_answers = []
280
  for ans in answers:
@@ -284,47 +264,40 @@ def compute_marks():
284
  processed_answers.append(ans)
285
  answers = processed_answers
286
 
287
- # Create HTR images directory if it doesn't exist
288
- os.makedirs(htr_images_dir, exist_ok=True)
289
- os.chmod(htr_images_dir, 0o777) # Ensure write permissions
290
-
291
- # Get files from the request
292
- files = request.files.getlist('files[]')
293
- if not files:
294
- log_print("No files were uploaded", "ERROR")
295
- return jsonify({"error": "No files were uploaded"}), 400
296
-
297
- # Create student folders and save files
298
- data = {}
299
- for file in files:
300
- if file and is_valid_image_file(file.filename):
301
- # Extract student folder from the path
302
- path_parts = file.filename.split('/')
303
- if len(path_parts) >= 2:
304
- student_folder = path_parts[-2] # Get the parent folder name
305
- filename = path_parts[-1] # Get the actual filename
306
-
307
- # Create student directory if it doesn't exist
308
- student_dir = os.path.join(ans_image_dir, student_folder)
309
- os.makedirs(student_dir, exist_ok=True)
310
- os.chmod(student_dir, 0o777) # Ensure write permissions
311
-
312
- # Save the file
313
- filepath = os.path.join(student_dir, filename)
314
- file.save(filepath)
315
- os.chmod(filepath, 0o666) # Ensure file is readable/writable
316
-
317
- # Create symlink in HTR images directory
318
- htr_filepath = os.path.join(htr_images_dir, f"{student_folder}_{filename}")
319
- if os.path.exists(htr_filepath):
320
- os.remove(htr_filepath)
321
- os.symlink(filepath, htr_filepath)
322
-
323
- # Add to data structure
324
- if student_folder not in data:
325
- data[student_folder] = []
326
- data[student_folder].append(htr_filepath.replace("\\", "/"))
327
- log_print(f"Saved file: {filepath} and linked to {htr_filepath}")
328
 
329
  if not data:
330
  log_print("No valid image files were found in the upload", "ERROR")
@@ -454,13 +427,15 @@ def allowed_file(filename, allowed_extensions):
454
 
455
  def cleanup_temp_files():
456
  try:
457
- import shutil
458
- temp_dirs = [ans_image_dir, upload_dir, htr_images_dir]
459
- for directory in temp_dirs:
460
- if os.path.exists(directory):
461
- shutil.rmtree(directory)
462
- os.makedirs(directory, exist_ok=True)
463
- os.chmod(directory, 0o777) # Ensure write permissions
 
 
464
  log_print("Successfully cleaned up temporary files")
465
  except Exception as e:
466
  log_print(f"Error cleaning up temporary files: {e}", "ERROR")
 
12
  load_dotenv()
13
 
14
  # Create directories in /tmp which is writable
15
+ BASE_DIR = '/tmp' # Use direct /tmp path for Hugging Face
16
  log_dir = os.path.join(BASE_DIR, 'app_logs')
17
  cache_dir = os.path.join(BASE_DIR, 'app_cache')
18
 
 
22
  except Exception as e:
23
  print(f"Warning: Could not create log directory: {e}")
24
  # Fallback to temp directory
25
+ log_dir = os.path.join(BASE_DIR, 'app_logs')
26
+ os.makedirs(log_dir, exist_ok=True)
27
 
28
  # Create a log file with timestamp
29
  log_file = os.path.join(log_dir, f'app_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log')
 
63
 
64
  # Set up all cache and data directories in /tmp
65
  try:
66
+ nltk_data_dir = os.path.join(BASE_DIR, 'nltk_data')
67
+ gensim_data_dir = os.path.join(BASE_DIR, 'gensim-data')
68
+ upload_dir = os.path.join(BASE_DIR, 'uploads')
69
+ ans_image_dir = os.path.join(BASE_DIR, 'ans_image')
70
+ images_dir = os.path.join(BASE_DIR, 'images') # Direct in /tmp for HTR
71
 
72
  # Create directories with correct permissions
73
+ for directory in [cache_dir, nltk_data_dir, gensim_data_dir, upload_dir, ans_image_dir, images_dir]:
74
  os.makedirs(directory, exist_ok=True)
75
+
 
76
  except Exception as e:
77
  print(f"Warning: Could not create cache directories: {e}")
78
+ # Don't use tempfile in Hugging Face environment
79
+ cache_dir = os.path.join(BASE_DIR, 'cache')
80
+ nltk_data_dir = os.path.join(BASE_DIR, 'nltk_data')
81
+ gensim_data_dir = os.path.join(BASE_DIR, 'gensim_data')
82
+ upload_dir = os.path.join(BASE_DIR, 'uploads')
83
+ ans_image_dir = os.path.join(BASE_DIR, 'ans_image')
84
+ images_dir = os.path.join(BASE_DIR, 'images')
85
+
86
+ # Create directories
87
+ for directory in [cache_dir, nltk_data_dir, gensim_data_dir, upload_dir, ans_image_dir, images_dir]:
88
+ os.makedirs(directory, exist_ok=True)
89
 
90
  # Set environment variables
91
  os.environ['HF_HOME'] = cache_dir
 
255
  log_print("Invalid JSON format in answers", "ERROR")
256
  return jsonify({"error": "Invalid JSON format in answers"}), 400
257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
258
  # Process answers to ensure consistent format
259
  processed_answers = []
260
  for ans in answers:
 
264
  processed_answers.append(ans)
265
  answers = processed_answers
266
 
267
+ # Create necessary directories
268
+ try:
269
+ # Ensure the images directory exists in the HTR expected location
270
+ os.makedirs(images_dir, exist_ok=True)
271
+
272
+ # Get files from the request
273
+ files = request.files.getlist('files[]')
274
+ if not files:
275
+ log_print("No files were uploaded", "ERROR")
276
+ return jsonify({"error": "No files were uploaded"}), 400
277
+
278
+ # Create student folders and save files
279
+ data = {}
280
+
281
+ for file in files:
282
+ if file and is_valid_image_file(file.filename):
283
+ # Extract student folder from the path
284
+ path_parts = file.filename.split('/')
285
+ if len(path_parts) >= 2:
286
+ student_folder = path_parts[-2] # Get the parent folder name
287
+ filename = path_parts[-1] # Get the actual filename
288
+
289
+ # Save directly to the images directory with a unique name
290
+ htr_filename = f"{student_folder}_{filename}"
291
+ htr_filepath = os.path.join(images_dir, htr_filename)
292
+
293
+ # Save the file
294
+ file.save(htr_filepath)
295
+ log_print(f"Saved file: {htr_filepath}")
296
+
297
+ # Add to data structure
298
+ if student_folder not in data:
299
+ data[student_folder] = []
300
+ data[student_folder].append(htr_filepath)
 
 
 
 
 
 
 
301
 
302
  if not data:
303
  log_print("No valid image files were found in the upload", "ERROR")
 
427
 
428
  def cleanup_temp_files():
429
  try:
430
+ # Clean up only the images directory
431
+ if os.path.exists(images_dir):
432
+ for file in os.listdir(images_dir):
433
+ file_path = os.path.join(images_dir, file)
434
+ try:
435
+ if os.path.isfile(file_path):
436
+ os.unlink(file_path)
437
+ except Exception as e:
438
+ log_print(f"Error deleting file {file_path}: {e}", "ERROR")
439
  log_print("Successfully cleaned up temporary files")
440
  except Exception as e:
441
  log_print(f"Error cleaning up temporary files: {e}", "ERROR")