archives.py 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920
  1. import io
  2. import logging
  3. import zipfile
  4. from pathlib import Path
  5. from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, UploadFile
  6. from fastapi.responses import FileResponse, Response
  7. from sqlalchemy import func, select
  8. from sqlalchemy.ext.asyncio import AsyncSession
  9. from backend.app.core.config import settings
  10. from backend.app.core.database import get_db
  11. from backend.app.models.archive import PrintArchive
  12. from backend.app.models.filament import Filament
  13. from backend.app.schemas.archive import ArchiveResponse, ArchiveStats, ArchiveUpdate
  14. from backend.app.services.archive import ArchiveService
  15. logger = logging.getLogger(__name__)
  16. router = APIRouter(prefix="/archives", tags=["archives"])
  17. def compute_time_accuracy(archive: PrintArchive) -> dict:
  18. """Compute actual print time and accuracy for an archive.
  19. Returns dict with actual_time_seconds and time_accuracy.
  20. time_accuracy = (estimated / actual) * 100
  21. - 100% = perfect estimate
  22. - >100% = print was faster than estimated
  23. - <100% = print took longer than estimated
  24. """
  25. result = {"actual_time_seconds": None, "time_accuracy": None}
  26. if archive.started_at and archive.completed_at and archive.status == "completed":
  27. actual_seconds = int((archive.completed_at - archive.started_at).total_seconds())
  28. if actual_seconds > 0:
  29. result["actual_time_seconds"] = actual_seconds
  30. if archive.print_time_seconds and archive.print_time_seconds > 0:
  31. # Calculate accuracy as percentage
  32. accuracy = (archive.print_time_seconds / actual_seconds) * 100
  33. result["time_accuracy"] = round(accuracy, 1)
  34. return result
  35. def archive_to_response(
  36. archive: PrintArchive,
  37. duplicates: list[dict] | None = None,
  38. duplicate_count: int = 0,
  39. ) -> dict:
  40. """Convert archive model to response dict with computed fields."""
  41. data = {
  42. "id": archive.id,
  43. "printer_id": archive.printer_id,
  44. "project_id": archive.project_id,
  45. "project_name": archive.project.name if archive.project else None,
  46. "filename": archive.filename,
  47. "file_path": archive.file_path,
  48. "file_size": archive.file_size,
  49. "content_hash": archive.content_hash,
  50. "thumbnail_path": archive.thumbnail_path,
  51. "timelapse_path": archive.timelapse_path,
  52. "source_3mf_path": archive.source_3mf_path,
  53. "duplicates": duplicates,
  54. "duplicate_count": duplicate_count if duplicates is None else len(duplicates),
  55. "print_name": archive.print_name,
  56. "print_time_seconds": archive.print_time_seconds,
  57. "filament_used_grams": archive.filament_used_grams,
  58. "filament_type": archive.filament_type,
  59. "filament_color": archive.filament_color,
  60. "layer_height": archive.layer_height,
  61. "total_layers": archive.total_layers,
  62. "nozzle_diameter": archive.nozzle_diameter,
  63. "bed_temperature": archive.bed_temperature,
  64. "nozzle_temperature": archive.nozzle_temperature,
  65. "status": archive.status,
  66. "started_at": archive.started_at,
  67. "completed_at": archive.completed_at,
  68. "extra_data": archive.extra_data,
  69. "makerworld_url": archive.makerworld_url,
  70. "designer": archive.designer,
  71. "is_favorite": archive.is_favorite,
  72. "tags": archive.tags,
  73. "notes": archive.notes,
  74. "cost": archive.cost,
  75. "photos": archive.photos,
  76. "failure_reason": archive.failure_reason,
  77. "created_at": archive.created_at,
  78. }
  79. # Add computed time accuracy fields
  80. accuracy_data = compute_time_accuracy(archive)
  81. data.update(accuracy_data)
  82. return data
  83. @router.get("/", response_model=list[ArchiveResponse])
  84. async def list_archives(
  85. printer_id: int | None = None,
  86. project_id: int | None = None,
  87. limit: int = 50,
  88. offset: int = 0,
  89. db: AsyncSession = Depends(get_db),
  90. ):
  91. """List archived prints."""
  92. service = ArchiveService(db)
  93. archives = await service.list_archives(
  94. printer_id=printer_id,
  95. project_id=project_id,
  96. limit=limit,
  97. offset=offset,
  98. )
  99. # Get set of hashes that have duplicates (efficient single query)
  100. duplicate_hashes = await service.get_duplicate_hashes()
  101. # Mark archives that have duplicates
  102. result = []
  103. for a in archives:
  104. has_duplicate = a.content_hash in duplicate_hashes if a.content_hash else False
  105. result.append(archive_to_response(a, duplicate_count=1 if has_duplicate else 0))
  106. return result
  107. @router.get("/search", response_model=list[ArchiveResponse])
  108. async def search_archives(
  109. q: str = Query(..., min_length=2, description="Search query"),
  110. printer_id: int | None = None,
  111. project_id: int | None = None,
  112. status: str | None = None,
  113. limit: int = 50,
  114. offset: int = 0,
  115. db: AsyncSession = Depends(get_db),
  116. ):
  117. """Full-text search across archives.
  118. Searches print_name, filename, tags, notes, designer, and filament_type fields.
  119. Supports partial matches with wildcards (e.g., 'vor*' matches 'voron').
  120. """
  121. from sqlalchemy import text
  122. from sqlalchemy.orm import selectinload
  123. # Prepare search query - add wildcard for partial matches
  124. search_term = q.strip()
  125. if not search_term.endswith("*"):
  126. search_term = f"{search_term}*"
  127. # Build the FTS query
  128. # Using MATCH for FTS5 full-text search
  129. fts_query = text("""
  130. SELECT rowid FROM archive_fts
  131. WHERE archive_fts MATCH :search_term
  132. ORDER BY rank
  133. LIMIT :limit OFFSET :offset
  134. """)
  135. try:
  136. result = await db.execute(fts_query, {"search_term": search_term, "limit": limit + 100, "offset": 0})
  137. matched_ids = [row[0] for row in result.fetchall()]
  138. except Exception as e:
  139. logger.warning(f"FTS search failed, falling back to LIKE search: {e}")
  140. # Fallback to LIKE search if FTS fails
  141. like_pattern = f"%{q}%"
  142. query = (
  143. select(PrintArchive)
  144. .options(selectinload(PrintArchive.project))
  145. .where(
  146. (PrintArchive.print_name.ilike(like_pattern))
  147. | (PrintArchive.filename.ilike(like_pattern))
  148. | (PrintArchive.tags.ilike(like_pattern))
  149. | (PrintArchive.notes.ilike(like_pattern))
  150. | (PrintArchive.designer.ilike(like_pattern))
  151. | (PrintArchive.filament_type.ilike(like_pattern))
  152. )
  153. .order_by(PrintArchive.created_at.desc())
  154. )
  155. if printer_id:
  156. query = query.where(PrintArchive.printer_id == printer_id)
  157. if project_id:
  158. query = query.where(PrintArchive.project_id == project_id)
  159. if status:
  160. query = query.where(PrintArchive.status == status)
  161. query = query.limit(limit).offset(offset)
  162. result = await db.execute(query)
  163. archives = result.scalars().all()
  164. return [archive_to_response(a) for a in archives]
  165. if not matched_ids:
  166. return []
  167. # Fetch full archive records for matched IDs
  168. query = select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id.in_(matched_ids))
  169. # Apply additional filters
  170. if printer_id:
  171. query = query.where(PrintArchive.printer_id == printer_id)
  172. if project_id:
  173. query = query.where(PrintArchive.project_id == project_id)
  174. if status:
  175. query = query.where(PrintArchive.status == status)
  176. result = await db.execute(query)
  177. archives_dict = {a.id: a for a in result.scalars().all()}
  178. # Preserve FTS ranking order and apply pagination
  179. ordered_archives = [archives_dict[id] for id in matched_ids if id in archives_dict]
  180. paginated = ordered_archives[offset : offset + limit]
  181. return [archive_to_response(a) for a in paginated]
  182. @router.post("/search/rebuild-index")
  183. async def rebuild_search_index(db: AsyncSession = Depends(get_db)):
  184. """Rebuild the full-text search index from existing archives.
  185. Use this if search results seem incomplete or incorrect.
  186. """
  187. from sqlalchemy import text
  188. try:
  189. # Clear and rebuild the FTS index
  190. await db.execute(text("DELETE FROM archive_fts"))
  191. # Repopulate from print_archives
  192. await db.execute(
  193. text("""
  194. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  195. SELECT id, print_name, filename, tags, notes, designer, filament_type
  196. FROM print_archives
  197. """)
  198. )
  199. await db.commit()
  200. # Count entries
  201. result = await db.execute(text("SELECT COUNT(*) FROM archive_fts"))
  202. count = result.scalar() or 0
  203. return {"message": f"Search index rebuilt with {count} entries"}
  204. except Exception as e:
  205. logger.error(f"Failed to rebuild search index: {e}")
  206. raise HTTPException(status_code=500, detail=f"Failed to rebuild index: {str(e)}")
  207. @router.get("/analysis/failures")
  208. async def analyze_failures(
  209. days: int = 30,
  210. printer_id: int | None = None,
  211. project_id: int | None = None,
  212. db: AsyncSession = Depends(get_db),
  213. ):
  214. """Analyze failure patterns across prints.
  215. Returns failure statistics including:
  216. - Overall failure rate
  217. - Failures by reason, filament type, printer
  218. - Time of day distribution
  219. - Recent failures
  220. - Weekly trend
  221. """
  222. from backend.app.services.failure_analysis import FailureAnalysisService
  223. service = FailureAnalysisService(db)
  224. return await service.analyze_failures(
  225. days=days,
  226. printer_id=printer_id,
  227. project_id=project_id,
  228. )
  229. @router.get("/compare")
  230. async def compare_archives(
  231. archive_ids: str = Query(..., description="Comma-separated archive IDs (2-5)"),
  232. db: AsyncSession = Depends(get_db),
  233. ):
  234. """Compare multiple archives side by side.
  235. Compares print settings, filament usage, and print times.
  236. Also analyzes correlation between settings and success/failure.
  237. Args:
  238. archive_ids: Comma-separated list of 2-5 archive IDs to compare
  239. """
  240. from backend.app.services.archive_comparison import ArchiveComparisonService
  241. # Parse and validate archive IDs
  242. try:
  243. ids = [int(id.strip()) for id in archive_ids.split(",")]
  244. except ValueError:
  245. raise HTTPException(400, "Invalid archive IDs format")
  246. if len(ids) < 2:
  247. raise HTTPException(400, "At least 2 archives required for comparison")
  248. if len(ids) > 5:
  249. raise HTTPException(400, "Maximum 5 archives can be compared at once")
  250. service = ArchiveComparisonService(db)
  251. try:
  252. return await service.compare_archives(ids)
  253. except ValueError as e:
  254. raise HTTPException(400, str(e))
  255. @router.get("/export")
  256. async def export_archives(
  257. format: str = Query("csv", description="Export format: csv or xlsx"),
  258. fields: str | None = Query(None, description="Comma-separated field names"),
  259. printer_id: int | None = None,
  260. project_id: int | None = None,
  261. status: str | None = None,
  262. date_from: str | None = Query(None, description="Start date (ISO format)"),
  263. date_to: str | None = Query(None, description="End date (ISO format)"),
  264. search: str | None = None,
  265. db: AsyncSession = Depends(get_db),
  266. ):
  267. """Export archives to CSV or Excel format.
  268. Returns a downloadable file with archive data.
  269. """
  270. from datetime import datetime
  271. from fastapi.responses import StreamingResponse
  272. from backend.app.services.export import ExportService
  273. if format not in ("csv", "xlsx"):
  274. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  275. # Parse fields
  276. field_list = None
  277. if fields:
  278. field_list = [f.strip() for f in fields.split(",")]
  279. # Parse dates
  280. date_from_dt = None
  281. date_to_dt = None
  282. if date_from:
  283. try:
  284. date_from_dt = datetime.fromisoformat(date_from)
  285. except ValueError:
  286. raise HTTPException(400, "Invalid date_from format")
  287. if date_to:
  288. try:
  289. date_to_dt = datetime.fromisoformat(date_to)
  290. except ValueError:
  291. raise HTTPException(400, "Invalid date_to format")
  292. service = ExportService(db)
  293. try:
  294. file_bytes, filename, content_type = await service.export_archives(
  295. format=format,
  296. fields=field_list,
  297. printer_id=printer_id,
  298. project_id=project_id,
  299. status=status,
  300. date_from=date_from_dt,
  301. date_to=date_to_dt,
  302. search=search,
  303. )
  304. except ImportError as e:
  305. raise HTTPException(500, str(e))
  306. return StreamingResponse(
  307. io.BytesIO(file_bytes),
  308. media_type=content_type,
  309. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  310. )
  311. @router.get("/stats/export")
  312. async def export_stats(
  313. format: str = Query("csv", description="Export format: csv or xlsx"),
  314. days: int = 30,
  315. printer_id: int | None = None,
  316. project_id: int | None = None,
  317. db: AsyncSession = Depends(get_db),
  318. ):
  319. """Export statistics summary to CSV or Excel format."""
  320. from fastapi.responses import StreamingResponse
  321. from backend.app.services.export import ExportService
  322. if format not in ("csv", "xlsx"):
  323. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  324. service = ExportService(db)
  325. try:
  326. file_bytes, filename, content_type = await service.export_stats(
  327. format=format,
  328. days=days,
  329. printer_id=printer_id,
  330. project_id=project_id,
  331. )
  332. except ImportError as e:
  333. raise HTTPException(500, str(e))
  334. return StreamingResponse(
  335. io.BytesIO(file_bytes),
  336. media_type=content_type,
  337. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  338. )
  339. @router.get("/stats", response_model=ArchiveStats)
  340. async def get_archive_stats(db: AsyncSession = Depends(get_db)):
  341. """Get statistics across all archives."""
  342. # Total counts
  343. total_result = await db.execute(select(func.count(PrintArchive.id)))
  344. total_prints = total_result.scalar() or 0
  345. successful_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "completed"))
  346. successful_prints = successful_result.scalar() or 0
  347. failed_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "failed"))
  348. failed_prints = failed_result.scalar() or 0
  349. # Totals
  350. time_result = await db.execute(select(func.sum(PrintArchive.print_time_seconds)))
  351. total_time = (time_result.scalar() or 0) / 3600 # Convert to hours
  352. filament_result = await db.execute(select(func.sum(PrintArchive.filament_used_grams)))
  353. total_filament = filament_result.scalar() or 0
  354. cost_result = await db.execute(select(func.sum(PrintArchive.cost)))
  355. total_cost = cost_result.scalar() or 0
  356. # By filament type (split comma-separated values for multi-material prints)
  357. filament_type_result = await db.execute(
  358. select(PrintArchive.filament_type).where(PrintArchive.filament_type.isnot(None))
  359. )
  360. prints_by_filament: dict[str, int] = {}
  361. for (filament_types,) in filament_type_result.all():
  362. # Split by comma and count each type
  363. for ftype in filament_types.split(","):
  364. ftype = ftype.strip()
  365. if ftype:
  366. prints_by_filament[ftype] = prints_by_filament.get(ftype, 0) + 1
  367. # By printer
  368. printer_result = await db.execute(
  369. select(PrintArchive.printer_id, func.count(PrintArchive.id)).group_by(PrintArchive.printer_id)
  370. )
  371. prints_by_printer = {str(k): v for k, v in printer_result.all()}
  372. # Time accuracy statistics
  373. # Get all completed archives with both estimated and actual times
  374. accuracy_result = await db.execute(
  375. select(PrintArchive)
  376. .where(PrintArchive.status == "completed")
  377. .where(PrintArchive.print_time_seconds.isnot(None))
  378. .where(PrintArchive.started_at.isnot(None))
  379. .where(PrintArchive.completed_at.isnot(None))
  380. )
  381. archives_with_times = list(accuracy_result.scalars().all())
  382. average_accuracy = None
  383. accuracy_by_printer: dict[str, float] = {}
  384. if archives_with_times:
  385. accuracies = []
  386. printer_accuracies: dict[str, list[float]] = {}
  387. for archive in archives_with_times:
  388. acc_data = compute_time_accuracy(archive)
  389. if acc_data["time_accuracy"] is not None:
  390. accuracies.append(acc_data["time_accuracy"])
  391. # Group by printer
  392. printer_key = str(archive.printer_id) if archive.printer_id else "unknown"
  393. if printer_key not in printer_accuracies:
  394. printer_accuracies[printer_key] = []
  395. printer_accuracies[printer_key].append(acc_data["time_accuracy"])
  396. if accuracies:
  397. average_accuracy = round(sum(accuracies) / len(accuracies), 1)
  398. # Calculate per-printer averages
  399. for printer_key, accs in printer_accuracies.items():
  400. accuracy_by_printer[printer_key] = round(sum(accs) / len(accs), 1)
  401. # Energy totals - check which mode to use
  402. from backend.app.api.routes.settings import get_setting
  403. energy_tracking_mode = await get_setting(db, "energy_tracking_mode") or "total"
  404. energy_cost_per_kwh_str = await get_setting(db, "energy_cost_per_kwh")
  405. energy_cost_per_kwh = float(energy_cost_per_kwh_str) if energy_cost_per_kwh_str else 0.15
  406. if energy_tracking_mode == "total":
  407. # Total mode: sum up 'total' counter from all smart plugs (lifetime consumption)
  408. from backend.app.models.smart_plug import SmartPlug
  409. from backend.app.services.tasmota import tasmota_service
  410. plugs_result = await db.execute(select(SmartPlug))
  411. plugs = list(plugs_result.scalars().all())
  412. total_energy_kwh = 0.0
  413. for plug in plugs:
  414. energy = await tasmota_service.get_energy(plug)
  415. if energy and energy.get("total") is not None:
  416. total_energy_kwh += energy["total"]
  417. total_energy_kwh = round(total_energy_kwh, 3)
  418. total_energy_cost = round(total_energy_kwh * energy_cost_per_kwh, 2)
  419. else:
  420. # Print mode: sum up per-print energy from archives
  421. energy_kwh_result = await db.execute(select(func.sum(PrintArchive.energy_kwh)))
  422. total_energy_kwh = energy_kwh_result.scalar() or 0
  423. energy_cost_result = await db.execute(select(func.sum(PrintArchive.energy_cost)))
  424. total_energy_cost = energy_cost_result.scalar() or 0
  425. return ArchiveStats(
  426. total_prints=total_prints,
  427. successful_prints=successful_prints,
  428. failed_prints=failed_prints,
  429. total_print_time_hours=round(total_time, 1),
  430. total_filament_grams=round(total_filament, 1),
  431. total_cost=round(total_cost, 2),
  432. prints_by_filament_type=prints_by_filament,
  433. prints_by_printer=prints_by_printer,
  434. average_time_accuracy=average_accuracy,
  435. time_accuracy_by_printer=accuracy_by_printer if accuracy_by_printer else None,
  436. total_energy_kwh=round(total_energy_kwh, 3),
  437. total_energy_cost=round(total_energy_cost, 2),
  438. )
  439. @router.get("/{archive_id}", response_model=ArchiveResponse)
  440. async def get_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  441. """Get a specific archive."""
  442. service = ArchiveService(db)
  443. archive = await service.get_archive(archive_id)
  444. if not archive:
  445. raise HTTPException(404, "Archive not found")
  446. # Find duplicates
  447. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  448. duplicates = await service.find_duplicates(
  449. archive_id=archive.id,
  450. content_hash=archive.content_hash,
  451. print_name=archive.print_name,
  452. makerworld_model_id=makerworld_id,
  453. )
  454. return archive_to_response(archive, duplicates)
  455. @router.get("/{archive_id}/similar")
  456. async def find_similar_archives(
  457. archive_id: int,
  458. limit: int = 10,
  459. db: AsyncSession = Depends(get_db),
  460. ):
  461. """Find archives with similar settings for comparison.
  462. Returns archives that match by:
  463. - Same print name (highest priority)
  464. - Same file content hash
  465. - Same filament type
  466. """
  467. from backend.app.services.archive_comparison import ArchiveComparisonService
  468. service = ArchiveComparisonService(db)
  469. try:
  470. return await service.find_similar_archives(archive_id, limit=limit)
  471. except ValueError as e:
  472. raise HTTPException(404, str(e))
  473. @router.patch("/{archive_id}", response_model=ArchiveResponse)
  474. async def update_archive(
  475. archive_id: int,
  476. update_data: ArchiveUpdate,
  477. db: AsyncSession = Depends(get_db),
  478. ):
  479. """Update archive metadata (tags, notes, cost, is_favorite, project_id)."""
  480. from sqlalchemy.orm import selectinload
  481. result = await db.execute(
  482. select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id == archive_id)
  483. )
  484. archive = result.scalar_one_or_none()
  485. if not archive:
  486. raise HTTPException(404, "Archive not found")
  487. for field, value in update_data.model_dump(exclude_unset=True).items():
  488. setattr(archive, field, value)
  489. await db.commit()
  490. # Re-fetch with project relationship loaded after commit
  491. result = await db.execute(
  492. select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id == archive_id)
  493. )
  494. archive = result.scalar_one_or_none()
  495. return archive_to_response(archive)
  496. @router.post("/{archive_id}/favorite", response_model=ArchiveResponse)
  497. async def toggle_favorite(
  498. archive_id: int,
  499. db: AsyncSession = Depends(get_db),
  500. ):
  501. """Toggle favorite status for an archive."""
  502. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  503. archive = result.scalar_one_or_none()
  504. if not archive:
  505. raise HTTPException(404, "Archive not found")
  506. archive.is_favorite = not archive.is_favorite
  507. await db.commit()
  508. await db.refresh(archive)
  509. return archive
  510. @router.post("/{archive_id}/rescan", response_model=ArchiveResponse)
  511. async def rescan_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  512. """Rescan the 3MF file and update metadata."""
  513. from backend.app.services.archive import ThreeMFParser
  514. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  515. archive = result.scalar_one_or_none()
  516. if not archive:
  517. raise HTTPException(404, "Archive not found")
  518. file_path = settings.base_dir / archive.file_path
  519. if not file_path.exists():
  520. raise HTTPException(404, "Archive file not found")
  521. # Parse the 3MF file
  522. parser = ThreeMFParser(file_path)
  523. metadata = parser.parse()
  524. # Update fields from metadata
  525. if metadata.get("filament_type"):
  526. archive.filament_type = metadata["filament_type"]
  527. if metadata.get("filament_color"):
  528. archive.filament_color = metadata["filament_color"]
  529. if metadata.get("print_time_seconds"):
  530. archive.print_time_seconds = metadata["print_time_seconds"]
  531. if metadata.get("filament_used_grams"):
  532. archive.filament_used_grams = metadata["filament_used_grams"]
  533. if metadata.get("layer_height"):
  534. archive.layer_height = metadata["layer_height"]
  535. if metadata.get("nozzle_diameter"):
  536. archive.nozzle_diameter = metadata["nozzle_diameter"]
  537. if metadata.get("bed_temperature"):
  538. archive.bed_temperature = metadata["bed_temperature"]
  539. if metadata.get("nozzle_temperature"):
  540. archive.nozzle_temperature = metadata["nozzle_temperature"]
  541. if metadata.get("makerworld_url"):
  542. archive.makerworld_url = metadata["makerworld_url"]
  543. if metadata.get("designer"):
  544. archive.designer = metadata["designer"]
  545. # Calculate cost based on filament usage and type
  546. if archive.filament_used_grams and archive.filament_type:
  547. primary_type = archive.filament_type.split(",")[0].strip()
  548. filament_result = await db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  549. filament = filament_result.scalar_one_or_none()
  550. if filament:
  551. archive.cost = round((archive.filament_used_grams / 1000) * filament.cost_per_kg, 2)
  552. else:
  553. archive.cost = round((archive.filament_used_grams / 1000) * 25.0, 2)
  554. await db.commit()
  555. await db.refresh(archive)
  556. return archive
  557. @router.post("/recalculate-costs")
  558. async def recalculate_all_costs(db: AsyncSession = Depends(get_db)):
  559. """Recalculate costs for all archives based on filament usage and prices."""
  560. result = await db.execute(select(PrintArchive))
  561. archives = list(result.scalars().all())
  562. # Load all filaments for lookup
  563. filament_result = await db.execute(select(Filament))
  564. filaments = {f.type: f.cost_per_kg for f in filament_result.scalars().all()}
  565. default_cost_per_kg = 25.0
  566. updated = 0
  567. for archive in archives:
  568. if archive.filament_used_grams and archive.filament_type:
  569. primary_type = archive.filament_type.split(",")[0].strip()
  570. cost_per_kg = filaments.get(primary_type, default_cost_per_kg)
  571. new_cost = round((archive.filament_used_grams / 1000) * cost_per_kg, 2)
  572. if archive.cost != new_cost:
  573. archive.cost = new_cost
  574. updated += 1
  575. await db.commit()
  576. return {"message": f"Recalculated costs for {updated} archives", "updated": updated}
  577. @router.post("/rescan-all")
  578. async def rescan_all_archives(db: AsyncSession = Depends(get_db)):
  579. """Rescan all archives and update their metadata."""
  580. from backend.app.services.archive import ThreeMFParser
  581. result = await db.execute(select(PrintArchive))
  582. archives = list(result.scalars().all())
  583. updated = 0
  584. errors = []
  585. for archive in archives:
  586. try:
  587. file_path = settings.base_dir / archive.file_path
  588. if not file_path.exists():
  589. errors.append({"id": archive.id, "error": "File not found"})
  590. continue
  591. parser = ThreeMFParser(file_path)
  592. metadata = parser.parse()
  593. if metadata.get("filament_type"):
  594. archive.filament_type = metadata["filament_type"]
  595. if metadata.get("filament_color"):
  596. archive.filament_color = metadata["filament_color"]
  597. if metadata.get("print_time_seconds"):
  598. archive.print_time_seconds = metadata["print_time_seconds"]
  599. if metadata.get("filament_used_grams"):
  600. archive.filament_used_grams = metadata["filament_used_grams"]
  601. if metadata.get("layer_height"):
  602. archive.layer_height = metadata["layer_height"]
  603. if metadata.get("nozzle_diameter"):
  604. archive.nozzle_diameter = metadata["nozzle_diameter"]
  605. if metadata.get("makerworld_url"):
  606. archive.makerworld_url = metadata["makerworld_url"]
  607. if metadata.get("designer"):
  608. archive.designer = metadata["designer"]
  609. updated += 1
  610. except Exception as e:
  611. errors.append({"id": archive.id, "error": str(e)})
  612. await db.commit()
  613. return {"updated": updated, "errors": errors}
  614. @router.get("/{archive_id}/duplicates")
  615. async def get_archive_duplicates(archive_id: int, db: AsyncSession = Depends(get_db)):
  616. """Get duplicates for a specific archive."""
  617. service = ArchiveService(db)
  618. archive = await service.get_archive(archive_id)
  619. if not archive:
  620. raise HTTPException(404, "Archive not found")
  621. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  622. duplicates = await service.find_duplicates(
  623. archive_id=archive.id,
  624. content_hash=archive.content_hash,
  625. print_name=archive.print_name,
  626. makerworld_model_id=makerworld_id,
  627. )
  628. return {"duplicates": duplicates, "count": len(duplicates)}
  629. @router.post("/backfill-hashes")
  630. async def backfill_content_hashes(db: AsyncSession = Depends(get_db)):
  631. """Compute and store content hashes for all archives missing them."""
  632. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash.is_(None)))
  633. archives = list(result.scalars().all())
  634. updated = 0
  635. errors = []
  636. for archive in archives:
  637. try:
  638. file_path = settings.base_dir / archive.file_path
  639. if not file_path.exists():
  640. errors.append({"id": archive.id, "error": "File not found"})
  641. continue
  642. archive.content_hash = ArchiveService.compute_file_hash(file_path)
  643. updated += 1
  644. except Exception as e:
  645. errors.append({"id": archive.id, "error": str(e)})
  646. await db.commit()
  647. return {"updated": updated, "errors": errors}
  648. @router.delete("/{archive_id}")
  649. async def delete_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  650. """Delete an archive."""
  651. service = ArchiveService(db)
  652. if not await service.delete_archive(archive_id):
  653. raise HTTPException(404, "Archive not found")
  654. return {"status": "deleted"}
  655. @router.get("/{archive_id}/download")
  656. async def download_archive(
  657. archive_id: int,
  658. inline: bool = False,
  659. db: AsyncSession = Depends(get_db),
  660. ):
  661. """Download the 3MF file."""
  662. service = ArchiveService(db)
  663. archive = await service.get_archive(archive_id)
  664. if not archive:
  665. raise HTTPException(404, "Archive not found")
  666. file_path = settings.base_dir / archive.file_path
  667. if not file_path.exists():
  668. raise HTTPException(404, "File not found")
  669. # Use inline disposition to let browser/OS handle file association
  670. content_disposition = "inline" if inline else "attachment"
  671. return FileResponse(
  672. path=file_path,
  673. filename=archive.filename,
  674. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  675. content_disposition_type=content_disposition,
  676. )
  677. @router.get("/{archive_id}/file/{filename}")
  678. async def download_archive_with_filename(
  679. archive_id: int,
  680. filename: str,
  681. db: AsyncSession = Depends(get_db),
  682. ):
  683. """Download the 3MF file with filename in URL (for Bambu Studio protocol)."""
  684. service = ArchiveService(db)
  685. archive = await service.get_archive(archive_id)
  686. if not archive:
  687. raise HTTPException(404, "Archive not found")
  688. file_path = settings.base_dir / archive.file_path
  689. if not file_path.exists():
  690. raise HTTPException(404, "File not found")
  691. return FileResponse(
  692. path=file_path,
  693. filename=archive.filename,
  694. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  695. )
  696. @router.get("/{archive_id}/thumbnail")
  697. async def get_thumbnail(archive_id: int, db: AsyncSession = Depends(get_db)):
  698. """Get the thumbnail image."""
  699. service = ArchiveService(db)
  700. archive = await service.get_archive(archive_id)
  701. if not archive or not archive.thumbnail_path:
  702. raise HTTPException(404, "Thumbnail not found")
  703. thumb_path = settings.base_dir / archive.thumbnail_path
  704. if not thumb_path.exists():
  705. raise HTTPException(404, "Thumbnail file not found")
  706. return FileResponse(path=thumb_path, media_type="image/png")
  707. @router.get("/{archive_id}/timelapse")
  708. async def get_timelapse(archive_id: int, db: AsyncSession = Depends(get_db)):
  709. """Get the timelapse video."""
  710. service = ArchiveService(db)
  711. archive = await service.get_archive(archive_id)
  712. if not archive or not archive.timelapse_path:
  713. raise HTTPException(404, "Timelapse not found")
  714. timelapse_path = settings.base_dir / archive.timelapse_path
  715. if not timelapse_path.exists():
  716. raise HTTPException(404, "Timelapse file not found")
  717. return FileResponse(
  718. path=timelapse_path,
  719. media_type="video/mp4",
  720. filename=f"{archive.print_name or 'timelapse'}.mp4",
  721. )
  722. @router.post("/{archive_id}/timelapse/scan")
  723. async def scan_timelapse(
  724. archive_id: int,
  725. db: AsyncSession = Depends(get_db),
  726. ):
  727. """Scan printer for timelapse matching this archive and attach it."""
  728. from backend.app.models.printer import Printer
  729. from backend.app.services.bambu_ftp import download_file_bytes_async, list_files_async
  730. service = ArchiveService(db)
  731. archive = await service.get_archive(archive_id)
  732. if not archive:
  733. raise HTTPException(404, "Archive not found")
  734. if archive.timelapse_path:
  735. return {"status": "exists", "message": "Timelapse already attached"}
  736. if not archive.printer_id:
  737. raise HTTPException(400, "Archive has no associated printer")
  738. # Get printer
  739. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  740. printer = result.scalar_one_or_none()
  741. if not printer:
  742. raise HTTPException(404, "Printer not found")
  743. # Get base name from archive filename (without .3mf extension)
  744. base_name = Path(archive.filename).stem
  745. # Scan timelapse directory on printer
  746. # Try both /timelapse and /timelapse/video (different printer models use different paths)
  747. files = []
  748. for timelapse_path in ["/timelapse", "/timelapse/video"]:
  749. try:
  750. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_path)
  751. if files:
  752. break
  753. except Exception:
  754. continue
  755. if not files:
  756. raise HTTPException(500, "Failed to connect to printer or no timelapse directory found")
  757. # Look for matching timelapse
  758. matching_file = None
  759. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  760. # Strategy 1: Match by print name in filename
  761. for f in mp4_files:
  762. fname = f.get("name", "")
  763. if base_name.lower() in fname.lower():
  764. matching_file = f
  765. break
  766. # Strategy 2: Match by timestamp proximity
  767. # Bambu timelapse filename uses the print START time (when recording began)
  768. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  769. import re
  770. from datetime import datetime, timedelta
  771. # Prefer started_at since video filename is the print start time
  772. # Fall back to completed_at or created_at if started_at is not available
  773. archive_start = archive.started_at
  774. archive_end = archive.completed_at or archive.created_at
  775. best_match = None
  776. best_diff = timedelta(hours=24) # Max 24 hour difference
  777. for f in mp4_files:
  778. fname = f.get("name", "")
  779. # Parse timestamp from filename like "video_2025-11-24_03-17-40.mp4"
  780. match = re.search(r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})", fname)
  781. if match:
  782. try:
  783. file_time = datetime.strptime(match.group(1), "%Y-%m-%d_%H-%M-%S")
  784. # Try multiple timezone offsets since printer timezone can vary
  785. # Common cases: local time (0), CST/UTC+8 (+8), or UTC (-local offset)
  786. for hour_offset in [0, 8, -8, 7, -7, 1, -1]:
  787. adjusted_file_time = file_time - timedelta(hours=hour_offset)
  788. # Check against start time (video filename = print start)
  789. if archive_start:
  790. diff = abs(adjusted_file_time - archive_start)
  791. if diff < best_diff:
  792. best_diff = diff
  793. best_match = f
  794. logger.debug(
  795. f"Timelapse match candidate: {fname} with offset {hour_offset}h, "
  796. f"diff from start: {diff}"
  797. )
  798. # Also check against end time with a buffer
  799. # (video timestamp should be BEFORE completion time)
  800. if archive_end:
  801. # The video timestamp should be within the print duration before completion
  802. if adjusted_file_time < archive_end:
  803. diff = archive_end - adjusted_file_time
  804. # Reasonable print duration: up to 48 hours
  805. if diff < timedelta(hours=48) and diff < best_diff:
  806. best_diff = diff
  807. best_match = f
  808. logger.debug(
  809. f"Timelapse match candidate (from end): {fname} with offset {hour_offset}h, "
  810. f"diff: {diff}"
  811. )
  812. except ValueError:
  813. continue
  814. # Accept match within 4 hours (more lenient for timezone issues)
  815. if best_match and best_diff < timedelta(hours=4):
  816. matching_file = best_match
  817. logger.info(f"Matched timelapse by timestamp: {best_match.get('name')} (diff: {best_diff})")
  818. # Strategy 3: Use file modification time from FTP listing
  819. # This handles cases where printer's filename timestamp is wrong but file mtime is correct
  820. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  821. from datetime import datetime, timedelta
  822. archive_start = archive.started_at
  823. archive_end = archive.completed_at or archive.created_at
  824. best_match = None
  825. best_diff = timedelta(hours=24)
  826. for f in mp4_files:
  827. mtime = f.get("mtime")
  828. if mtime:
  829. # Timelapse file should be modified during or shortly after the print
  830. # The mtime should be close to completion time (video finishes when print ends)
  831. if archive_end:
  832. diff = abs(mtime - archive_end)
  833. if diff < best_diff:
  834. best_diff = diff
  835. best_match = f
  836. logger.debug(
  837. f"Timelapse mtime match candidate: {f.get('name')}, mtime: {mtime}, diff from end: {diff}"
  838. )
  839. if best_match and best_diff < timedelta(hours=2):
  840. matching_file = best_match
  841. logger.info(f"Matched timelapse by file mtime: {best_match.get('name')} (diff: {best_diff})")
  842. # Strategy 4: If only one timelapse exists and archive was recently completed, use it
  843. # This handles cases where printer clock is wrong or timezone issues exist
  844. if not matching_file and len(mp4_files) == 1:
  845. from datetime import datetime, timedelta
  846. archive_completed = archive.completed_at or archive.created_at
  847. if archive_completed:
  848. time_since_completion = datetime.now() - archive_completed
  849. # If archive was completed within the last hour, assume the single timelapse is for it
  850. if time_since_completion < timedelta(hours=1):
  851. matching_file = mp4_files[0]
  852. logger.info(f"Using single timelapse file as fallback: {mp4_files[0].get('name')}")
  853. # Note: We intentionally don't use a "most recent file" fallback because
  854. # we can't verify if timelapse was actually enabled for this print.
  855. # Instead, return the list of available files for manual selection.
  856. if not matching_file:
  857. # Return available files for manual selection
  858. available_files = [
  859. {
  860. "name": f.get("name"),
  861. "path": f.get("path"),
  862. "size": f.get("size"),
  863. "mtime": f.get("mtime").isoformat() if f.get("mtime") else None,
  864. }
  865. for f in mp4_files
  866. ]
  867. # Sort by mtime descending (most recent first)
  868. available_files.sort(key=lambda x: x.get("mtime") or "", reverse=True)
  869. return {
  870. "status": "not_found",
  871. "message": "No matching timelapse found - please select manually",
  872. "available_files": available_files,
  873. }
  874. # Download the timelapse - use the full path from the file listing
  875. remote_path = matching_file.get("path") or f"/timelapse/{matching_file['name']}"
  876. timelapse_data = await download_file_bytes_async(printer.ip_address, printer.access_code, remote_path)
  877. if not timelapse_data:
  878. raise HTTPException(500, "Failed to download timelapse")
  879. # Attach timelapse to archive
  880. success = await service.attach_timelapse(archive_id, timelapse_data, matching_file["name"])
  881. if not success:
  882. raise HTTPException(500, "Failed to attach timelapse")
  883. return {
  884. "status": "attached",
  885. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  886. "filename": matching_file["name"],
  887. }
  888. @router.post("/{archive_id}/timelapse/select")
  889. async def select_timelapse(
  890. archive_id: int,
  891. filename: str = Query(..., description="Timelapse filename to attach"),
  892. db: AsyncSession = Depends(get_db),
  893. ):
  894. """Manually select a timelapse from the printer to attach."""
  895. from backend.app.models.printer import Printer
  896. from backend.app.services.bambu_ftp import download_file_bytes_async, list_files_async
  897. service = ArchiveService(db)
  898. archive = await service.get_archive(archive_id)
  899. if not archive:
  900. raise HTTPException(404, "Archive not found")
  901. if not archive.printer_id:
  902. raise HTTPException(400, "Archive has no associated printer")
  903. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  904. printer = result.scalar_one_or_none()
  905. if not printer:
  906. raise HTTPException(404, "Printer not found")
  907. # Find the file on the printer
  908. files = []
  909. remote_path = None
  910. for timelapse_dir in ["/timelapse", "/timelapse/video"]:
  911. try:
  912. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_dir)
  913. for f in files:
  914. if f.get("name") == filename:
  915. remote_path = f.get("path") or f"{timelapse_dir}/{filename}"
  916. break
  917. if remote_path:
  918. break
  919. except Exception:
  920. continue
  921. if not remote_path:
  922. raise HTTPException(404, f"Timelapse '{filename}' not found on printer")
  923. # Download and attach
  924. timelapse_data = await download_file_bytes_async(printer.ip_address, printer.access_code, remote_path)
  925. if not timelapse_data:
  926. raise HTTPException(500, "Failed to download timelapse")
  927. success = await service.attach_timelapse(archive_id, timelapse_data, filename)
  928. if not success:
  929. raise HTTPException(500, "Failed to attach timelapse")
  930. return {
  931. "status": "attached",
  932. "message": f"Timelapse '{filename}' attached successfully",
  933. "filename": filename,
  934. }
  935. @router.post("/{archive_id}/timelapse/upload")
  936. async def upload_timelapse(
  937. archive_id: int,
  938. file: UploadFile = File(...),
  939. db: AsyncSession = Depends(get_db),
  940. ):
  941. """Manually upload a timelapse video to an archive."""
  942. service = ArchiveService(db)
  943. archive = await service.get_archive(archive_id)
  944. if not archive:
  945. raise HTTPException(404, "Archive not found")
  946. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  947. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  948. content = await file.read()
  949. success = await service.attach_timelapse(archive_id, content, file.filename)
  950. if not success:
  951. raise HTTPException(500, "Failed to attach timelapse")
  952. return {"status": "attached", "filename": file.filename}
  953. # ============================================
  954. # Photo Endpoints
  955. # ============================================
  956. @router.post("/{archive_id}/photos")
  957. async def upload_photo(
  958. archive_id: int,
  959. file: UploadFile = File(...),
  960. db: AsyncSession = Depends(get_db),
  961. ):
  962. """Upload a photo of the printed result."""
  963. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  964. archive = result.scalar_one_or_none()
  965. if not archive:
  966. raise HTTPException(404, "Archive not found")
  967. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  968. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  969. # Get archive directory
  970. file_path = settings.base_dir / archive.file_path
  971. archive_dir = file_path.parent
  972. photos_dir = archive_dir / "photos"
  973. photos_dir.mkdir(exist_ok=True)
  974. # Generate unique filename
  975. import uuid
  976. ext = Path(file.filename).suffix.lower()
  977. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  978. photo_path = photos_dir / photo_filename
  979. # Save file
  980. content = await file.read()
  981. photo_path.write_bytes(content)
  982. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  983. photos = list(archive.photos or [])
  984. photos.append(photo_filename)
  985. archive.photos = photos
  986. await db.commit()
  987. await db.refresh(archive)
  988. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  989. @router.get("/{archive_id}/photos/{filename}")
  990. async def get_photo(
  991. archive_id: int,
  992. filename: str,
  993. db: AsyncSession = Depends(get_db),
  994. ):
  995. """Get a specific photo."""
  996. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  997. archive = result.scalar_one_or_none()
  998. if not archive:
  999. raise HTTPException(404, "Archive not found")
  1000. file_path = settings.base_dir / archive.file_path
  1001. photo_path = file_path.parent / "photos" / filename
  1002. if not photo_path.exists():
  1003. raise HTTPException(404, "Photo not found")
  1004. # Determine media type
  1005. ext = Path(filename).suffix.lower()
  1006. media_types = {
  1007. ".jpg": "image/jpeg",
  1008. ".jpeg": "image/jpeg",
  1009. ".png": "image/png",
  1010. ".webp": "image/webp",
  1011. }
  1012. media_type = media_types.get(ext, "image/jpeg")
  1013. return FileResponse(path=photo_path, media_type=media_type)
  1014. @router.delete("/{archive_id}/photos/{filename}")
  1015. async def delete_photo(
  1016. archive_id: int,
  1017. filename: str,
  1018. db: AsyncSession = Depends(get_db),
  1019. ):
  1020. """Delete a photo."""
  1021. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1022. archive = result.scalar_one_or_none()
  1023. if not archive:
  1024. raise HTTPException(404, "Archive not found")
  1025. if not archive.photos or filename not in archive.photos:
  1026. raise HTTPException(404, "Photo not found")
  1027. # Delete file
  1028. file_path = settings.base_dir / archive.file_path
  1029. photo_path = file_path.parent / "photos" / filename
  1030. if photo_path.exists():
  1031. photo_path.unlink()
  1032. # Update archive photos list
  1033. photos = [p for p in archive.photos if p != filename]
  1034. archive.photos = photos if photos else None
  1035. await db.commit()
  1036. return {"status": "deleted", "photos": archive.photos}
  1037. # ============================================
  1038. # QR Code Endpoint
  1039. # ============================================
  1040. @router.get("/{archive_id}/qrcode")
  1041. async def get_qrcode(
  1042. archive_id: int,
  1043. request: Request,
  1044. size: int = 200,
  1045. db: AsyncSession = Depends(get_db),
  1046. ):
  1047. """Generate a QR code that links to this archive."""
  1048. import qrcode
  1049. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1050. archive = result.scalar_one_or_none()
  1051. if not archive:
  1052. raise HTTPException(404, "Archive not found")
  1053. # Build URL to archive detail page
  1054. base_url = str(request.base_url).rstrip("/")
  1055. archive_url = f"{base_url}/archives?id={archive_id}"
  1056. # Generate QR code
  1057. qr = qrcode.QRCode(
  1058. version=1,
  1059. error_correction=qrcode.constants.ERROR_CORRECT_M,
  1060. box_size=10,
  1061. border=2,
  1062. )
  1063. qr.add_data(archive_url)
  1064. qr.make(fit=True)
  1065. img = qr.make_image(fill_color="black", back_color="white")
  1066. # Resize if needed
  1067. if size != 200:
  1068. img = img.resize((size, size))
  1069. # Convert to bytes
  1070. buffer = io.BytesIO()
  1071. img.save(buffer, format="PNG")
  1072. buffer.seek(0)
  1073. return Response(
  1074. content=buffer.getvalue(),
  1075. media_type="image/png",
  1076. headers={"Content-Disposition": f'inline; filename="qr_{archive.print_name or archive_id}.png"'},
  1077. )
  1078. @router.get("/{archive_id}/capabilities")
  1079. async def get_archive_capabilities(archive_id: int, db: AsyncSession = Depends(get_db)):
  1080. """Check what viewing capabilities are available for this 3MF file."""
  1081. import json
  1082. service = ArchiveService(db)
  1083. archive = await service.get_archive(archive_id)
  1084. if not archive:
  1085. raise HTTPException(404, "Archive not found")
  1086. file_path = settings.base_dir / archive.file_path
  1087. if not file_path.exists():
  1088. raise HTTPException(404, "File not found")
  1089. has_model = False
  1090. has_gcode = False
  1091. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  1092. try:
  1093. with zipfile.ZipFile(file_path, "r") as zf:
  1094. names = zf.namelist()
  1095. # Check for G-code
  1096. has_gcode = any(n.startswith("Metadata/") and n.endswith(".gcode") for n in names)
  1097. # Check for 3D model - need to look for actual mesh data
  1098. for name in names:
  1099. if name.endswith(".model"):
  1100. try:
  1101. content = zf.read(name).decode("utf-8")
  1102. # Check if this model file contains actual mesh vertices
  1103. if "<vertex" in content or "<mesh" in content:
  1104. has_model = True
  1105. break
  1106. except Exception:
  1107. pass
  1108. # Extract build volume from project settings
  1109. if "Metadata/project_settings.config" in names:
  1110. try:
  1111. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1112. config_data = json.loads(config_content)
  1113. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  1114. printable_area = config_data.get("printable_area", [])
  1115. if printable_area and len(printable_area) >= 3:
  1116. # Get max X and Y from the corner coordinates
  1117. max_x = 0
  1118. max_y = 0
  1119. for coord in printable_area:
  1120. if "x" in coord:
  1121. parts = coord.split("x")
  1122. if len(parts) == 2:
  1123. try:
  1124. x, y = int(parts[0]), int(parts[1])
  1125. max_x = max(max_x, x)
  1126. max_y = max(max_y, y)
  1127. except ValueError:
  1128. pass
  1129. if max_x > 0 and max_y > 0:
  1130. build_volume["x"] = max_x
  1131. build_volume["y"] = max_y
  1132. # Parse printable_height
  1133. printable_height = config_data.get("printable_height")
  1134. if printable_height:
  1135. try:
  1136. build_volume["z"] = int(printable_height)
  1137. except (ValueError, TypeError):
  1138. pass
  1139. except Exception:
  1140. pass
  1141. except zipfile.BadZipFile:
  1142. raise HTTPException(400, "Invalid 3MF file")
  1143. return {
  1144. "has_model": has_model,
  1145. "has_gcode": has_gcode,
  1146. "build_volume": build_volume,
  1147. }
  1148. @router.get("/{archive_id}/gcode")
  1149. async def get_gcode(archive_id: int, db: AsyncSession = Depends(get_db)):
  1150. """Extract and return G-code from the 3MF file."""
  1151. service = ArchiveService(db)
  1152. archive = await service.get_archive(archive_id)
  1153. if not archive:
  1154. raise HTTPException(404, "Archive not found")
  1155. file_path = settings.base_dir / archive.file_path
  1156. if not file_path.exists():
  1157. raise HTTPException(404, "File not found")
  1158. try:
  1159. with zipfile.ZipFile(file_path, "r") as zf:
  1160. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  1161. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  1162. if not gcode_files:
  1163. raise HTTPException(
  1164. 404,
  1165. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  1166. )
  1167. # Get the first plate's G-code (usually plate_1.gcode)
  1168. gcode_content = zf.read(gcode_files[0]).decode("utf-8")
  1169. return Response(content=gcode_content, media_type="text/plain")
  1170. except zipfile.BadZipFile:
  1171. raise HTTPException(400, "Invalid 3MF file")
  1172. except HTTPException:
  1173. raise
  1174. except Exception as e:
  1175. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  1176. @router.post("/upload")
  1177. async def upload_archive(
  1178. file: UploadFile = File(...),
  1179. printer_id: int | None = None,
  1180. db: AsyncSession = Depends(get_db),
  1181. ):
  1182. """Manually upload a 3MF file to archive."""
  1183. if not file.filename or not file.filename.endswith(".3mf"):
  1184. raise HTTPException(400, "File must be a .3mf file")
  1185. # Save uploaded file temporarily
  1186. temp_path = settings.archive_dir / "temp" / file.filename
  1187. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1188. try:
  1189. content = await file.read()
  1190. temp_path.write_bytes(content)
  1191. service = ArchiveService(db)
  1192. archive = await service.archive_print(
  1193. printer_id=printer_id,
  1194. source_file=temp_path,
  1195. )
  1196. if not archive:
  1197. raise HTTPException(400, "Failed to archive file")
  1198. return ArchiveResponse.model_validate(archive)
  1199. finally:
  1200. if temp_path.exists():
  1201. temp_path.unlink()
  1202. @router.post("/upload-bulk")
  1203. async def upload_archives_bulk(
  1204. files: list[UploadFile] = File(...),
  1205. printer_id: int | None = None,
  1206. db: AsyncSession = Depends(get_db),
  1207. ):
  1208. """Bulk upload multiple 3MF files to archive."""
  1209. results = []
  1210. errors = []
  1211. for file in files:
  1212. if not file.filename or not file.filename.endswith(".3mf"):
  1213. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  1214. continue
  1215. temp_path = settings.archive_dir / "temp" / file.filename
  1216. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1217. try:
  1218. content = await file.read()
  1219. temp_path.write_bytes(content)
  1220. service = ArchiveService(db)
  1221. archive = await service.archive_print(
  1222. printer_id=printer_id,
  1223. source_file=temp_path,
  1224. )
  1225. if archive:
  1226. results.append(
  1227. {
  1228. "filename": file.filename,
  1229. "id": archive.id,
  1230. "status": "success",
  1231. }
  1232. )
  1233. else:
  1234. errors.append({"filename": file.filename, "error": "Failed to process"})
  1235. except Exception as e:
  1236. errors.append({"filename": file.filename, "error": str(e)})
  1237. finally:
  1238. if temp_path.exists():
  1239. temp_path.unlink()
  1240. return {
  1241. "uploaded": len(results),
  1242. "failed": len(errors),
  1243. "results": results,
  1244. "errors": errors,
  1245. }
  1246. @router.post("/{archive_id}/reprint")
  1247. async def reprint_archive(
  1248. archive_id: int,
  1249. printer_id: int,
  1250. db: AsyncSession = Depends(get_db),
  1251. ):
  1252. """Send an archived 3MF file to a printer and start printing."""
  1253. from backend.app.main import register_expected_print
  1254. from backend.app.models.printer import Printer
  1255. from backend.app.services.bambu_ftp import upload_file_async
  1256. from backend.app.services.printer_manager import printer_manager
  1257. # Get archive
  1258. service = ArchiveService(db)
  1259. archive = await service.get_archive(archive_id)
  1260. if not archive:
  1261. raise HTTPException(404, "Archive not found")
  1262. # Get printer
  1263. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1264. printer = result.scalar_one_or_none()
  1265. if not printer:
  1266. raise HTTPException(404, "Printer not found")
  1267. # Check printer is connected
  1268. if not printer_manager.is_connected(printer_id):
  1269. raise HTTPException(400, "Printer is not connected")
  1270. # Get the sliced 3MF file path
  1271. file_path = settings.base_dir / archive.file_path
  1272. if not file_path.exists():
  1273. raise HTTPException(404, "Archive file not found")
  1274. # Upload file to printer via FTP
  1275. from backend.app.services.bambu_ftp import delete_file_async
  1276. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  1277. # The printer might reject filenames with unusual extensions
  1278. base_name = archive.filename
  1279. if base_name.endswith(".gcode.3mf"):
  1280. base_name = base_name[:-10] # Remove .gcode.3mf
  1281. elif base_name.endswith(".3mf"):
  1282. base_name = base_name[:-4] # Remove .3mf
  1283. remote_filename = f"{base_name}.3mf"
  1284. remote_path = f"/{remote_filename}"
  1285. # Delete existing file if present (avoids 553 error)
  1286. await delete_file_async(
  1287. printer.ip_address,
  1288. printer.access_code,
  1289. remote_path,
  1290. )
  1291. uploaded = await upload_file_async(
  1292. printer.ip_address,
  1293. printer.access_code,
  1294. file_path,
  1295. remote_path,
  1296. )
  1297. if not uploaded:
  1298. raise HTTPException(500, "Failed to upload file to printer")
  1299. # Register this as an expected print so we don't create a duplicate archive
  1300. register_expected_print(printer_id, remote_filename, archive_id)
  1301. # Detect plate ID from 3MF file
  1302. plate_id = 1
  1303. try:
  1304. with zipfile.ZipFile(file_path, "r") as zf:
  1305. for name in zf.namelist():
  1306. if name.startswith("Metadata/plate_") and name.endswith(".gcode"):
  1307. # Extract plate number from "Metadata/plate_X.gcode"
  1308. plate_str = name[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1309. plate_id = int(plate_str)
  1310. break
  1311. except Exception:
  1312. pass # Default to plate 1 if detection fails
  1313. logger.info(f"Reprint archive {archive_id}: using plate_id={plate_id}")
  1314. # Start the print
  1315. started = printer_manager.start_print(printer_id, remote_filename, plate_id)
  1316. if not started:
  1317. raise HTTPException(500, "Failed to start print")
  1318. return {
  1319. "status": "printing",
  1320. "printer_id": printer_id,
  1321. "archive_id": archive_id,
  1322. "filename": archive.filename,
  1323. }
  1324. # =============================================================================
  1325. # Project Page API
  1326. # =============================================================================
  1327. @router.get("/{archive_id}/project-page")
  1328. async def get_project_page(archive_id: int, db: AsyncSession = Depends(get_db)):
  1329. """Get the project page data from the 3MF file."""
  1330. from backend.app.schemas.archive import ProjectPageResponse
  1331. from backend.app.services.archive import ProjectPageParser
  1332. service = ArchiveService(db)
  1333. archive = await service.get_archive(archive_id)
  1334. if not archive:
  1335. raise HTTPException(404, "Archive not found")
  1336. file_path = settings.base_dir / archive.file_path
  1337. if not file_path.exists():
  1338. raise HTTPException(404, "Archive file not found")
  1339. parser = ProjectPageParser(file_path)
  1340. data = parser.parse(archive_id)
  1341. return ProjectPageResponse(**data)
  1342. @router.patch("/{archive_id}/project-page")
  1343. async def update_project_page(
  1344. archive_id: int,
  1345. update_data: dict,
  1346. db: AsyncSession = Depends(get_db),
  1347. ):
  1348. """Update project page metadata in the 3MF file."""
  1349. from backend.app.services.archive import ProjectPageParser
  1350. service = ArchiveService(db)
  1351. archive = await service.get_archive(archive_id)
  1352. if not archive:
  1353. raise HTTPException(404, "Archive not found")
  1354. file_path = settings.base_dir / archive.file_path
  1355. if not file_path.exists():
  1356. raise HTTPException(404, "Archive file not found")
  1357. parser = ProjectPageParser(file_path)
  1358. success = parser.update_metadata(update_data)
  1359. if not success:
  1360. raise HTTPException(500, "Failed to update project page")
  1361. # Return updated data
  1362. data = parser.parse(archive_id)
  1363. return data
  1364. @router.get("/{archive_id}/project-image/{image_path:path}")
  1365. async def get_project_image(
  1366. archive_id: int,
  1367. image_path: str,
  1368. db: AsyncSession = Depends(get_db),
  1369. ):
  1370. """Get an image from the 3MF project page."""
  1371. from backend.app.services.archive import ProjectPageParser
  1372. service = ArchiveService(db)
  1373. archive = await service.get_archive(archive_id)
  1374. if not archive:
  1375. raise HTTPException(404, "Archive not found")
  1376. file_path = settings.base_dir / archive.file_path
  1377. if not file_path.exists():
  1378. raise HTTPException(404, "Archive file not found")
  1379. parser = ProjectPageParser(file_path)
  1380. result = parser.get_image(image_path)
  1381. if not result:
  1382. raise HTTPException(404, "Image not found in 3MF file")
  1383. image_data, content_type = result
  1384. return Response(
  1385. content=image_data,
  1386. media_type=content_type,
  1387. headers={"Cache-Control": "max-age=3600"},
  1388. )
  1389. # =============================================================================
  1390. # Source 3MF API (Original Project Files)
  1391. # =============================================================================
  1392. @router.post("/{archive_id}/source")
  1393. async def upload_source_3mf(
  1394. archive_id: int,
  1395. file: UploadFile = File(...),
  1396. db: AsyncSession = Depends(get_db),
  1397. ):
  1398. """Upload the original source 3MF project file for an archive."""
  1399. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1400. archive = result.scalar_one_or_none()
  1401. if not archive:
  1402. raise HTTPException(404, "Archive not found")
  1403. if not file.filename or not file.filename.endswith(".3mf"):
  1404. raise HTTPException(400, "File must be a .3mf file")
  1405. # Get archive directory and create source subdirectory
  1406. file_path = settings.base_dir / archive.file_path
  1407. archive_dir = file_path.parent
  1408. source_dir = archive_dir / "source"
  1409. source_dir.mkdir(exist_ok=True)
  1410. # Delete old source file if exists
  1411. if archive.source_3mf_path:
  1412. old_source_path = settings.base_dir / archive.source_3mf_path
  1413. if old_source_path.exists():
  1414. old_source_path.unlink()
  1415. # Save the source 3MF file - preserve original filename
  1416. source_filename = file.filename
  1417. source_path = source_dir / source_filename
  1418. content = await file.read()
  1419. source_path.write_bytes(content)
  1420. # Update archive with source path (relative to base_dir)
  1421. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  1422. await db.commit()
  1423. await db.refresh(archive)
  1424. return {
  1425. "status": "uploaded",
  1426. "source_3mf_path": archive.source_3mf_path,
  1427. "filename": source_filename,
  1428. }
  1429. @router.get("/{archive_id}/source")
  1430. async def download_source_3mf(
  1431. archive_id: int,
  1432. db: AsyncSession = Depends(get_db),
  1433. ):
  1434. """Download the source 3MF project file."""
  1435. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1436. archive = result.scalar_one_or_none()
  1437. if not archive:
  1438. raise HTTPException(404, "Archive not found")
  1439. if not archive.source_3mf_path:
  1440. raise HTTPException(404, "No source 3MF attached to this archive")
  1441. source_path = settings.base_dir / archive.source_3mf_path
  1442. if not source_path.exists():
  1443. raise HTTPException(404, "Source 3MF file not found on disk")
  1444. # Use the actual filename from the path
  1445. filename = source_path.name
  1446. return FileResponse(
  1447. path=source_path,
  1448. filename=filename,
  1449. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1450. )
  1451. @router.get("/{archive_id}/source/{filename}")
  1452. async def download_source_3mf_for_slicer(
  1453. archive_id: int,
  1454. filename: str,
  1455. db: AsyncSession = Depends(get_db),
  1456. ):
  1457. """Download source 3MF with filename in URL (for Bambu Studio compatibility)."""
  1458. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1459. archive = result.scalar_one_or_none()
  1460. if not archive:
  1461. raise HTTPException(404, "Archive not found")
  1462. if not archive.source_3mf_path:
  1463. raise HTTPException(404, "No source 3MF attached to this archive")
  1464. source_path = settings.base_dir / archive.source_3mf_path
  1465. if not source_path.exists():
  1466. raise HTTPException(404, "Source 3MF file not found on disk")
  1467. return FileResponse(
  1468. path=source_path,
  1469. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  1470. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1471. )
  1472. @router.post("/upload-source")
  1473. async def upload_source_3mf_by_name(
  1474. file: UploadFile = File(...),
  1475. print_name: str = Query(None, description="Match archive by print name"),
  1476. db: AsyncSession = Depends(get_db),
  1477. ):
  1478. """Upload source 3MF and match to archive by print name.
  1479. This endpoint is designed for slicer post-processing scripts.
  1480. It finds the most recent archive matching the print name and attaches the source.
  1481. """
  1482. if not file.filename or not file.filename.endswith(".3mf"):
  1483. raise HTTPException(400, "File must be a .3mf file")
  1484. # Derive print name from filename if not provided
  1485. if not print_name:
  1486. # Remove .3mf extension and common suffixes
  1487. print_name = file.filename.rsplit(".3mf", 1)[0]
  1488. # Remove _source suffix if present
  1489. if print_name.endswith("_source"):
  1490. print_name = print_name[:-7]
  1491. # Find matching archive - try exact match first, then fuzzy
  1492. result = await db.execute(
  1493. select(PrintArchive)
  1494. .where(PrintArchive.print_name == print_name)
  1495. .order_by(PrintArchive.created_at.desc())
  1496. .limit(1)
  1497. )
  1498. archive = result.scalar_one_or_none()
  1499. if not archive:
  1500. # Try matching filename without .gcode.3mf
  1501. result = await db.execute(
  1502. select(PrintArchive)
  1503. .where(PrintArchive.filename.like(f"{print_name}%"))
  1504. .order_by(PrintArchive.created_at.desc())
  1505. .limit(1)
  1506. )
  1507. archive = result.scalar_one_or_none()
  1508. if not archive:
  1509. # Try case-insensitive partial match on print_name
  1510. result = await db.execute(
  1511. select(PrintArchive)
  1512. .where(PrintArchive.print_name.ilike(f"%{print_name}%"))
  1513. .order_by(PrintArchive.created_at.desc())
  1514. .limit(1)
  1515. )
  1516. archive = result.scalar_one_or_none()
  1517. if not archive:
  1518. raise HTTPException(404, f"No archive found matching '{print_name}'")
  1519. # Get archive directory and create source subdirectory
  1520. file_path = settings.base_dir / archive.file_path
  1521. archive_dir = file_path.parent
  1522. source_dir = archive_dir / "source"
  1523. source_dir.mkdir(exist_ok=True)
  1524. # Delete old source file if exists
  1525. if archive.source_3mf_path:
  1526. old_source_path = settings.base_dir / archive.source_3mf_path
  1527. if old_source_path.exists():
  1528. old_source_path.unlink()
  1529. # Save the source 3MF file - preserve original filename
  1530. source_filename = file.filename
  1531. source_path = source_dir / source_filename
  1532. content = await file.read()
  1533. source_path.write_bytes(content)
  1534. # Update archive with source path
  1535. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  1536. await db.commit()
  1537. await db.refresh(archive)
  1538. return {
  1539. "status": "uploaded",
  1540. "archive_id": archive.id,
  1541. "archive_name": archive.print_name or archive.filename,
  1542. "source_3mf_path": archive.source_3mf_path,
  1543. "filename": source_filename,
  1544. }
  1545. @router.delete("/{archive_id}/source")
  1546. async def delete_source_3mf(
  1547. archive_id: int,
  1548. db: AsyncSession = Depends(get_db),
  1549. ):
  1550. """Delete the source 3MF project file from an archive."""
  1551. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1552. archive = result.scalar_one_or_none()
  1553. if not archive:
  1554. raise HTTPException(404, "Archive not found")
  1555. if not archive.source_3mf_path:
  1556. raise HTTPException(404, "No source 3MF attached to this archive")
  1557. # Delete the file
  1558. source_path = settings.base_dir / archive.source_3mf_path
  1559. if source_path.exists():
  1560. source_path.unlink()
  1561. # Clear the path in database
  1562. archive.source_3mf_path = None
  1563. await db.commit()
  1564. return {"status": "deleted"}