files.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import os
  2. import uuid
  3. import hashlib
  4. from fastapi import APIRouter, UploadFile, File
  5. from typing import List
  6. import db
  7. import config
  8. import preview_utils
  9. router = APIRouter(prefix="/files", tags=["files"])
  10. @router.post("/upload")
  11. async def upload_files(files: List[UploadFile] = File(...)):
  12. if not files: return {"uploaded": []}
  13. uploaded_data = []
  14. for file in files:
  15. if not file.filename: continue
  16. file_ext = os.path.splitext(file.filename)[1]
  17. unique_filename = f"{uuid.uuid4()}{file_ext}"
  18. file_path = os.path.join(config.UPLOAD_DIR, unique_filename)
  19. db_file_path = f"uploads/{unique_filename}"
  20. sha256_hash = hashlib.sha256()
  21. with open(file_path, "wb") as buffer:
  22. while chunk := file.file.read(8192):
  23. sha256_hash.update(chunk)
  24. buffer.write(chunk)
  25. file_hash = sha256_hash.hexdigest()
  26. # --- CACHE CHECK (Hash based) ---
  27. filament_g = None
  28. print_time = None
  29. cached_record = db.execute_query(
  30. "SELECT filament_g, print_time FROM order_files WHERE file_hash = %s AND print_time IS NOT NULL LIMIT 1",
  31. (file_hash,)
  32. )
  33. if cached_record:
  34. filament_g = cached_record[0]['filament_g']
  35. print_time = cached_record[0]['print_time']
  36. # Only slice if not cached
  37. if not print_time and config.SYNC_SLICING_ON_UPLOAD and file_ext.lower() == ".stl":
  38. import slicer_utils
  39. result = slicer_utils.slice_model(file_path)
  40. if result and result.get('success'):
  41. filament_g = result.get('filament_g')
  42. print_time = result.get('print_time_str')
  43. preview_path = None
  44. db_preview_path = None
  45. if file_ext.lower() == ".stl":
  46. preview_filename = f"{uuid.uuid4()}.png"
  47. preview_path = os.path.join(config.PREVIEW_DIR, preview_filename)
  48. db_preview_path = f"uploads/previews/{preview_filename}"
  49. preview_utils.generate_stl_preview(file_path, preview_path)
  50. query = "INSERT INTO order_files (order_id, filename, file_path, file_size, quantity, file_hash, print_time, filament_g, preview_path) VALUES (NULL, %s, %s, %s, 1, %s, %s, %s, %s)"
  51. f_id = db.execute_commit(query, (file.filename, db_file_path, file.size, file_hash, print_time, filament_g, db_preview_path))
  52. uploaded_data.append({
  53. "id": f_id, "filename": file.filename, "size": file.size,
  54. "print_time": print_time, "filament_g": filament_g, "preview_path": db_preview_path
  55. })
  56. return {"uploaded": uploaded_data}