Hkoradiya123 commited on
Commit
7e6ee3b
·
1 Parent(s): 9a10d7c

Add Cloudinary uploads for materials and PDFs

Browse files
Backend/requirements.txt CHANGED
@@ -4,6 +4,7 @@ PyPDF2
4
  python-docx
5
  reportlab
6
  python-dotenv
 
7
  flask-cors
8
  pydantic
9
  supabase
 
4
  python-docx
5
  reportlab
6
  python-dotenv
7
+ cloudinary
8
  flask-cors
9
  pydantic
10
  supabase
Backend/routes/generate.py CHANGED
@@ -7,6 +7,7 @@ from .auth_utils import token_required, supabase
7
  from utils.extractor import get_text_from_file
8
  from utils.ai_generator import generate_questions, regenerate_single_question
9
  from utils.pdf_generator import create_pdf
 
10
 
11
  generate_bp = Blueprint('generate', __name__)
12
 
@@ -35,21 +36,39 @@ def upload_file(user_id):
35
  # with open(filepath, "rb") as f:
36
  # bucket.upload(filename, f.read())
37
 
 
 
 
 
 
 
38
  if supabase:
 
 
 
 
 
 
 
 
39
  try:
40
- supabase.table('materials').insert({
41
- "user_id": user_id,
42
- "file_name": file.filename,
43
- "file_size": os.path.getsize(filepath),
44
- "storage_path": filename
45
- }).execute()
46
  except Exception as e:
47
- print(f"Failed to record material in DB: {e}")
 
 
 
 
 
 
 
 
48
 
49
  return jsonify({
50
  "message": "File uploaded and processed",
51
  "content_preview": text[:500],
52
- "file_id": filename
 
53
  })
54
 
55
  @generate_bp.route('/generate', methods=['POST'])
@@ -120,6 +139,10 @@ def download():
120
  filepath = os.path.join(UPLOAD_FOLDER, filename)
121
 
122
  create_pdf(data, filepath, password=password)
 
 
 
 
123
  return send_file(filepath, as_attachment=True)
124
 
125
  @generate_bp.route('/regenerate-question', methods=['POST'])
 
7
  from utils.extractor import get_text_from_file
8
  from utils.ai_generator import generate_questions, regenerate_single_question
9
  from utils.pdf_generator import create_pdf
10
+ from utils.cloudinary_uploader import upload_file
11
 
12
  generate_bp = Blueprint('generate', __name__)
13
 
 
36
  # with open(filepath, "rb") as f:
37
  # bucket.upload(filename, f.read())
38
 
39
+ cloudinary_info = None
40
+ try:
41
+ cloudinary_info = upload_file(filepath, folder="examcraft/materials")
42
+ except Exception as e:
43
+ print(f"Cloudinary upload failed: {e}")
44
+
45
  if supabase:
46
+ payload = {
47
+ "user_id": user_id,
48
+ "file_name": file.filename,
49
+ "file_size": os.path.getsize(filepath),
50
+ "storage_path": filename,
51
+ "cloudinary_url": cloudinary_info.get("url") if cloudinary_info else None,
52
+ "cloudinary_public_id": cloudinary_info.get("public_id") if cloudinary_info else None
53
+ }
54
  try:
55
+ supabase.table('materials').insert(payload).execute()
 
 
 
 
 
56
  except Exception as e:
57
+ print(f"Failed to record material in DB (with cloudinary fields): {e}")
58
+ try:
59
+ fallback_payload = {
60
+ k: v for k, v in payload.items()
61
+ if k not in ("cloudinary_url", "cloudinary_public_id")
62
+ }
63
+ supabase.table('materials').insert(fallback_payload).execute()
64
+ except Exception as e2:
65
+ print(f"Failed to record material in DB (fallback): {e2}")
66
 
67
  return jsonify({
68
  "message": "File uploaded and processed",
69
  "content_preview": text[:500],
70
+ "file_id": filename,
71
+ "cloudinary_url": cloudinary_info.get("url") if cloudinary_info else None
72
  })
73
 
74
  @generate_bp.route('/generate', methods=['POST'])
 
139
  filepath = os.path.join(UPLOAD_FOLDER, filename)
140
 
141
  create_pdf(data, filepath, password=password)
142
+ try:
143
+ upload_file(filepath, folder="examcraft/generated_pdfs")
144
+ except Exception as e:
145
+ print(f"Cloudinary PDF upload failed: {e}")
146
  return send_file(filepath, as_attachment=True)
147
 
148
  @generate_bp.route('/regenerate-question', methods=['POST'])
Backend/scripts/upload_existing_to_cloudinary.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ from utils.cloudinary_uploader import upload_file
4
+
5
+
6
+ def main():
7
+ uploads_dir = Path(__file__).resolve().parents[1] / "uploads"
8
+ if not uploads_dir.exists():
9
+ print(f"Uploads directory not found: {uploads_dir}")
10
+ return
11
+
12
+ uploaded = 0
13
+ for path in uploads_dir.rglob("*"):
14
+ if not path.is_file():
15
+ continue
16
+ try:
17
+ result = upload_file(str(path), folder="examcraft/legacy_uploads")
18
+ if result and result.get("url"):
19
+ uploaded += 1
20
+ print(f"Uploaded: {path} -> {result.get('url')}")
21
+ else:
22
+ print(f"Skipped (no config?): {path}")
23
+ except Exception as e:
24
+ print(f"Failed: {path} ({e})")
25
+
26
+ print(f"Done. Uploaded {uploaded} files.")
27
+
28
+
29
+ if __name__ == "__main__":
30
+ main()
Backend/utils/cloudinary_uploader.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import mimetypes
3
+ import cloudinary
4
+ import cloudinary.uploader
5
+
6
+
7
+ def _is_configured():
8
+ return bool(os.getenv("CLOUDINARY_URL"))
9
+
10
+
11
+ def _resource_type_for(path):
12
+ mime_type, _ = mimetypes.guess_type(path)
13
+ if mime_type and mime_type.startswith("image/"):
14
+ return "image"
15
+ return "raw"
16
+
17
+
18
+ def upload_file(path, folder="examcraft", public_id=None, tags=None):
19
+ if not _is_configured():
20
+ return None
21
+
22
+ resource_type = _resource_type_for(path)
23
+ options = {
24
+ "folder": folder,
25
+ "resource_type": resource_type,
26
+ }
27
+ if public_id:
28
+ options["public_id"] = public_id
29
+ if tags:
30
+ options["tags"] = tags
31
+
32
+ result = cloudinary.uploader.upload(path, **options)
33
+ return {
34
+ "url": result.get("secure_url") or result.get("url"),
35
+ "public_id": result.get("public_id"),
36
+ "resource_type": result.get("resource_type"),
37
+ }