archives.py 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479
  1. import io
  2. import logging
  3. import zipfile
  4. from pathlib import Path
  5. from fastapi import APIRouter, Depends, File, Form, 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, ReprintRequest
  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. # Sanity check: skip unreasonable values (e.g., manually changed status)
  34. # Valid range: 5% to 500% (print took 20x longer to 5x faster than estimated)
  35. if 5 <= accuracy <= 500:
  36. result["time_accuracy"] = round(accuracy, 1)
  37. return result
  38. def archive_to_response(
  39. archive: PrintArchive,
  40. duplicates: list[dict] | None = None,
  41. duplicate_count: int = 0,
  42. ) -> dict:
  43. """Convert archive model to response dict with computed fields."""
  44. data = {
  45. "id": archive.id,
  46. "printer_id": archive.printer_id,
  47. "project_id": archive.project_id,
  48. "project_name": archive.project.name if archive.project else None,
  49. "filename": archive.filename,
  50. "file_path": archive.file_path,
  51. "file_size": archive.file_size,
  52. "content_hash": archive.content_hash,
  53. "thumbnail_path": archive.thumbnail_path,
  54. "timelapse_path": archive.timelapse_path,
  55. "source_3mf_path": archive.source_3mf_path,
  56. "duplicates": duplicates,
  57. "duplicate_count": duplicate_count if duplicates is None else len(duplicates),
  58. "print_name": archive.print_name,
  59. "print_time_seconds": archive.print_time_seconds,
  60. "filament_used_grams": archive.filament_used_grams,
  61. "filament_type": archive.filament_type,
  62. "filament_color": archive.filament_color,
  63. "layer_height": archive.layer_height,
  64. "total_layers": archive.total_layers,
  65. "nozzle_diameter": archive.nozzle_diameter,
  66. "bed_temperature": archive.bed_temperature,
  67. "nozzle_temperature": archive.nozzle_temperature,
  68. "status": archive.status,
  69. "started_at": archive.started_at,
  70. "completed_at": archive.completed_at,
  71. "extra_data": archive.extra_data,
  72. "makerworld_url": archive.makerworld_url,
  73. "designer": archive.designer,
  74. "is_favorite": archive.is_favorite,
  75. "tags": archive.tags,
  76. "notes": archive.notes,
  77. "cost": archive.cost,
  78. "photos": archive.photos,
  79. "failure_reason": archive.failure_reason,
  80. "quantity": archive.quantity,
  81. "energy_kwh": archive.energy_kwh,
  82. "energy_cost": archive.energy_cost,
  83. "created_at": archive.created_at,
  84. }
  85. # Add computed time accuracy fields
  86. accuracy_data = compute_time_accuracy(archive)
  87. data.update(accuracy_data)
  88. return data
  89. @router.get("/", response_model=list[ArchiveResponse])
  90. async def list_archives(
  91. printer_id: int | None = None,
  92. project_id: int | None = None,
  93. limit: int = 50,
  94. offset: int = 0,
  95. db: AsyncSession = Depends(get_db),
  96. ):
  97. """List archived prints."""
  98. service = ArchiveService(db)
  99. archives = await service.list_archives(
  100. printer_id=printer_id,
  101. project_id=project_id,
  102. limit=limit,
  103. offset=offset,
  104. )
  105. # Get set of hashes that have duplicates (efficient single query)
  106. duplicate_hashes = await service.get_duplicate_hashes()
  107. # Mark archives that have duplicates
  108. result = []
  109. for a in archives:
  110. has_duplicate = a.content_hash in duplicate_hashes if a.content_hash else False
  111. result.append(archive_to_response(a, duplicate_count=1 if has_duplicate else 0))
  112. return result
  113. @router.get("/search", response_model=list[ArchiveResponse])
  114. async def search_archives(
  115. q: str = Query(..., min_length=2, description="Search query"),
  116. printer_id: int | None = None,
  117. project_id: int | None = None,
  118. status: str | None = None,
  119. limit: int = 50,
  120. offset: int = 0,
  121. db: AsyncSession = Depends(get_db),
  122. ):
  123. """Full-text search across archives.
  124. Searches print_name, filename, tags, notes, designer, and filament_type fields.
  125. Supports partial matches with wildcards (e.g., 'vor*' matches 'voron').
  126. """
  127. from sqlalchemy import text
  128. from sqlalchemy.orm import selectinload
  129. # Prepare search query - add wildcard for partial matches
  130. search_term = q.strip()
  131. if not search_term.endswith("*"):
  132. search_term = f"{search_term}*"
  133. # Build the FTS query
  134. # Using MATCH for FTS5 full-text search
  135. fts_query = text("""
  136. SELECT rowid FROM archive_fts
  137. WHERE archive_fts MATCH :search_term
  138. ORDER BY rank
  139. LIMIT :limit OFFSET :offset
  140. """)
  141. try:
  142. result = await db.execute(fts_query, {"search_term": search_term, "limit": limit + 100, "offset": 0})
  143. matched_ids = [row[0] for row in result.fetchall()]
  144. except Exception as e:
  145. logger.warning(f"FTS search failed, falling back to LIKE search: {e}")
  146. # Fallback to LIKE search if FTS fails
  147. like_pattern = f"%{q}%"
  148. query = (
  149. select(PrintArchive)
  150. .options(selectinload(PrintArchive.project))
  151. .where(
  152. (PrintArchive.print_name.ilike(like_pattern))
  153. | (PrintArchive.filename.ilike(like_pattern))
  154. | (PrintArchive.tags.ilike(like_pattern))
  155. | (PrintArchive.notes.ilike(like_pattern))
  156. | (PrintArchive.designer.ilike(like_pattern))
  157. | (PrintArchive.filament_type.ilike(like_pattern))
  158. )
  159. .order_by(PrintArchive.created_at.desc())
  160. )
  161. if printer_id:
  162. query = query.where(PrintArchive.printer_id == printer_id)
  163. if project_id:
  164. query = query.where(PrintArchive.project_id == project_id)
  165. if status:
  166. query = query.where(PrintArchive.status == status)
  167. query = query.limit(limit).offset(offset)
  168. result = await db.execute(query)
  169. archives = result.scalars().all()
  170. return [archive_to_response(a) for a in archives]
  171. if not matched_ids:
  172. return []
  173. # Fetch full archive records for matched IDs
  174. query = select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id.in_(matched_ids))
  175. # Apply additional filters
  176. if printer_id:
  177. query = query.where(PrintArchive.printer_id == printer_id)
  178. if project_id:
  179. query = query.where(PrintArchive.project_id == project_id)
  180. if status:
  181. query = query.where(PrintArchive.status == status)
  182. result = await db.execute(query)
  183. archives_dict = {a.id: a for a in result.scalars().all()}
  184. # Preserve FTS ranking order and apply pagination
  185. ordered_archives = [archives_dict[id] for id in matched_ids if id in archives_dict]
  186. paginated = ordered_archives[offset : offset + limit]
  187. return [archive_to_response(a) for a in paginated]
  188. @router.post("/search/rebuild-index")
  189. async def rebuild_search_index(db: AsyncSession = Depends(get_db)):
  190. """Rebuild the full-text search index from existing archives.
  191. Use this if search results seem incomplete or incorrect.
  192. """
  193. from sqlalchemy import text
  194. try:
  195. # Clear and rebuild the FTS index
  196. await db.execute(text("DELETE FROM archive_fts"))
  197. # Repopulate from print_archives
  198. await db.execute(
  199. text("""
  200. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  201. SELECT id, print_name, filename, tags, notes, designer, filament_type
  202. FROM print_archives
  203. """)
  204. )
  205. await db.commit()
  206. # Count entries
  207. result = await db.execute(text("SELECT COUNT(*) FROM archive_fts"))
  208. count = result.scalar() or 0
  209. return {"message": f"Search index rebuilt with {count} entries"}
  210. except Exception as e:
  211. logger.error(f"Failed to rebuild search index: {e}")
  212. raise HTTPException(status_code=500, detail=f"Failed to rebuild index: {str(e)}")
  213. @router.get("/analysis/failures")
  214. async def analyze_failures(
  215. days: int = 30,
  216. printer_id: int | None = None,
  217. project_id: int | None = None,
  218. db: AsyncSession = Depends(get_db),
  219. ):
  220. """Analyze failure patterns across prints.
  221. Returns failure statistics including:
  222. - Overall failure rate
  223. - Failures by reason, filament type, printer
  224. - Time of day distribution
  225. - Recent failures
  226. - Weekly trend
  227. """
  228. from backend.app.services.failure_analysis import FailureAnalysisService
  229. service = FailureAnalysisService(db)
  230. return await service.analyze_failures(
  231. days=days,
  232. printer_id=printer_id,
  233. project_id=project_id,
  234. )
  235. @router.get("/compare")
  236. async def compare_archives(
  237. archive_ids: str = Query(..., description="Comma-separated archive IDs (2-5)"),
  238. db: AsyncSession = Depends(get_db),
  239. ):
  240. """Compare multiple archives side by side.
  241. Compares print settings, filament usage, and print times.
  242. Also analyzes correlation between settings and success/failure.
  243. Args:
  244. archive_ids: Comma-separated list of 2-5 archive IDs to compare
  245. """
  246. from backend.app.services.archive_comparison import ArchiveComparisonService
  247. # Parse and validate archive IDs
  248. try:
  249. ids = [int(id.strip()) for id in archive_ids.split(",")]
  250. except ValueError:
  251. raise HTTPException(400, "Invalid archive IDs format")
  252. if len(ids) < 2:
  253. raise HTTPException(400, "At least 2 archives required for comparison")
  254. if len(ids) > 5:
  255. raise HTTPException(400, "Maximum 5 archives can be compared at once")
  256. service = ArchiveComparisonService(db)
  257. try:
  258. return await service.compare_archives(ids)
  259. except ValueError as e:
  260. raise HTTPException(400, str(e))
  261. @router.get("/export")
  262. async def export_archives(
  263. format: str = Query("csv", description="Export format: csv or xlsx"),
  264. fields: str | None = Query(None, description="Comma-separated field names"),
  265. printer_id: int | None = None,
  266. project_id: int | None = None,
  267. status: str | None = None,
  268. date_from: str | None = Query(None, description="Start date (ISO format)"),
  269. date_to: str | None = Query(None, description="End date (ISO format)"),
  270. search: str | None = None,
  271. db: AsyncSession = Depends(get_db),
  272. ):
  273. """Export archives to CSV or Excel format.
  274. Returns a downloadable file with archive data.
  275. """
  276. from datetime import datetime
  277. from fastapi.responses import StreamingResponse
  278. from backend.app.services.export import ExportService
  279. if format not in ("csv", "xlsx"):
  280. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  281. # Parse fields
  282. field_list = None
  283. if fields:
  284. field_list = [f.strip() for f in fields.split(",")]
  285. # Parse dates
  286. date_from_dt = None
  287. date_to_dt = None
  288. if date_from:
  289. try:
  290. date_from_dt = datetime.fromisoformat(date_from)
  291. except ValueError:
  292. raise HTTPException(400, "Invalid date_from format")
  293. if date_to:
  294. try:
  295. date_to_dt = datetime.fromisoformat(date_to)
  296. except ValueError:
  297. raise HTTPException(400, "Invalid date_to format")
  298. service = ExportService(db)
  299. try:
  300. file_bytes, filename, content_type = await service.export_archives(
  301. format=format,
  302. fields=field_list,
  303. printer_id=printer_id,
  304. project_id=project_id,
  305. status=status,
  306. date_from=date_from_dt,
  307. date_to=date_to_dt,
  308. search=search,
  309. )
  310. except ImportError as e:
  311. raise HTTPException(500, str(e))
  312. return StreamingResponse(
  313. io.BytesIO(file_bytes),
  314. media_type=content_type,
  315. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  316. )
  317. @router.get("/stats/export")
  318. async def export_stats(
  319. format: str = Query("csv", description="Export format: csv or xlsx"),
  320. days: int = 30,
  321. printer_id: int | None = None,
  322. project_id: int | None = None,
  323. db: AsyncSession = Depends(get_db),
  324. ):
  325. """Export statistics summary to CSV or Excel format."""
  326. from fastapi.responses import StreamingResponse
  327. from backend.app.services.export import ExportService
  328. if format not in ("csv", "xlsx"):
  329. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  330. service = ExportService(db)
  331. try:
  332. file_bytes, filename, content_type = await service.export_stats(
  333. format=format,
  334. days=days,
  335. printer_id=printer_id,
  336. project_id=project_id,
  337. )
  338. except ImportError as e:
  339. raise HTTPException(500, str(e))
  340. return StreamingResponse(
  341. io.BytesIO(file_bytes),
  342. media_type=content_type,
  343. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  344. )
  345. @router.get("/stats", response_model=ArchiveStats)
  346. async def get_archive_stats(db: AsyncSession = Depends(get_db)):
  347. """Get statistics across all archives."""
  348. # Total counts
  349. total_result = await db.execute(select(func.count(PrintArchive.id)))
  350. total_prints = total_result.scalar() or 0
  351. successful_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "completed"))
  352. successful_prints = successful_result.scalar() or 0
  353. failed_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "failed"))
  354. failed_prints = failed_result.scalar() or 0
  355. # Totals
  356. time_result = await db.execute(select(func.sum(PrintArchive.print_time_seconds)))
  357. total_time = (time_result.scalar() or 0) / 3600 # Convert to hours
  358. filament_result = await db.execute(select(func.sum(PrintArchive.filament_used_grams)))
  359. total_filament = filament_result.scalar() or 0
  360. cost_result = await db.execute(select(func.sum(PrintArchive.cost)))
  361. total_cost = cost_result.scalar() or 0
  362. # By filament type (split comma-separated values for multi-material prints)
  363. filament_type_result = await db.execute(
  364. select(PrintArchive.filament_type).where(PrintArchive.filament_type.isnot(None))
  365. )
  366. prints_by_filament: dict[str, int] = {}
  367. for (filament_types,) in filament_type_result.all():
  368. # Split by comma and count each type
  369. for ftype in filament_types.split(","):
  370. ftype = ftype.strip()
  371. if ftype:
  372. prints_by_filament[ftype] = prints_by_filament.get(ftype, 0) + 1
  373. # By printer
  374. printer_result = await db.execute(
  375. select(PrintArchive.printer_id, func.count(PrintArchive.id)).group_by(PrintArchive.printer_id)
  376. )
  377. prints_by_printer = {str(k): v for k, v in printer_result.all()}
  378. # Time accuracy statistics
  379. # Get all completed archives with both estimated and actual times
  380. accuracy_result = await db.execute(
  381. select(PrintArchive)
  382. .where(PrintArchive.status == "completed")
  383. .where(PrintArchive.print_time_seconds.isnot(None))
  384. .where(PrintArchive.started_at.isnot(None))
  385. .where(PrintArchive.completed_at.isnot(None))
  386. )
  387. archives_with_times = list(accuracy_result.scalars().all())
  388. average_accuracy = None
  389. accuracy_by_printer: dict[str, float] = {}
  390. if archives_with_times:
  391. accuracies = []
  392. printer_accuracies: dict[str, list[float]] = {}
  393. for archive in archives_with_times:
  394. acc_data = compute_time_accuracy(archive)
  395. if acc_data["time_accuracy"] is not None:
  396. accuracies.append(acc_data["time_accuracy"])
  397. # Group by printer
  398. printer_key = str(archive.printer_id) if archive.printer_id else "unknown"
  399. if printer_key not in printer_accuracies:
  400. printer_accuracies[printer_key] = []
  401. printer_accuracies[printer_key].append(acc_data["time_accuracy"])
  402. if accuracies:
  403. average_accuracy = round(sum(accuracies) / len(accuracies), 1)
  404. # Calculate per-printer averages
  405. for printer_key, accs in printer_accuracies.items():
  406. accuracy_by_printer[printer_key] = round(sum(accs) / len(accs), 1)
  407. # Energy totals - check which mode to use
  408. from backend.app.api.routes.settings import get_setting
  409. energy_tracking_mode = await get_setting(db, "energy_tracking_mode") or "total"
  410. energy_cost_per_kwh_str = await get_setting(db, "energy_cost_per_kwh")
  411. energy_cost_per_kwh = float(energy_cost_per_kwh_str) if energy_cost_per_kwh_str else 0.15
  412. if energy_tracking_mode == "total":
  413. # Total mode: sum up 'total' counter from all smart plugs (lifetime consumption)
  414. from backend.app.models.smart_plug import SmartPlug
  415. from backend.app.services.tasmota import tasmota_service
  416. plugs_result = await db.execute(select(SmartPlug))
  417. plugs = list(plugs_result.scalars().all())
  418. total_energy_kwh = 0.0
  419. for plug in plugs:
  420. energy = await tasmota_service.get_energy(plug)
  421. if energy and energy.get("total") is not None:
  422. total_energy_kwh += energy["total"]
  423. total_energy_kwh = round(total_energy_kwh, 3)
  424. total_energy_cost = round(total_energy_kwh * energy_cost_per_kwh, 2)
  425. else:
  426. # Print mode: sum up per-print energy from archives
  427. energy_kwh_result = await db.execute(select(func.sum(PrintArchive.energy_kwh)))
  428. total_energy_kwh = energy_kwh_result.scalar() or 0
  429. energy_cost_result = await db.execute(select(func.sum(PrintArchive.energy_cost)))
  430. total_energy_cost = energy_cost_result.scalar() or 0
  431. return ArchiveStats(
  432. total_prints=total_prints,
  433. successful_prints=successful_prints,
  434. failed_prints=failed_prints,
  435. total_print_time_hours=round(total_time, 1),
  436. total_filament_grams=round(total_filament, 1),
  437. total_cost=round(total_cost, 2),
  438. prints_by_filament_type=prints_by_filament,
  439. prints_by_printer=prints_by_printer,
  440. average_time_accuracy=average_accuracy,
  441. time_accuracy_by_printer=accuracy_by_printer if accuracy_by_printer else None,
  442. total_energy_kwh=round(total_energy_kwh, 3),
  443. total_energy_cost=round(total_energy_cost, 2),
  444. )
  445. @router.get("/{archive_id}", response_model=ArchiveResponse)
  446. async def get_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  447. """Get a specific archive."""
  448. service = ArchiveService(db)
  449. archive = await service.get_archive(archive_id)
  450. if not archive:
  451. raise HTTPException(404, "Archive not found")
  452. # Find duplicates
  453. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  454. duplicates = await service.find_duplicates(
  455. archive_id=archive.id,
  456. content_hash=archive.content_hash,
  457. print_name=archive.print_name,
  458. makerworld_model_id=makerworld_id,
  459. )
  460. return archive_to_response(archive, duplicates)
  461. @router.get("/{archive_id}/similar")
  462. async def find_similar_archives(
  463. archive_id: int,
  464. limit: int = 10,
  465. db: AsyncSession = Depends(get_db),
  466. ):
  467. """Find archives with similar settings for comparison.
  468. Returns archives that match by:
  469. - Same print name (highest priority)
  470. - Same file content hash
  471. - Same filament type
  472. """
  473. from backend.app.services.archive_comparison import ArchiveComparisonService
  474. service = ArchiveComparisonService(db)
  475. try:
  476. return await service.find_similar_archives(archive_id, limit=limit)
  477. except ValueError as e:
  478. raise HTTPException(404, str(e))
  479. @router.patch("/{archive_id}", response_model=ArchiveResponse)
  480. async def update_archive(
  481. archive_id: int,
  482. update_data: ArchiveUpdate,
  483. db: AsyncSession = Depends(get_db),
  484. ):
  485. """Update archive metadata (tags, notes, cost, is_favorite, project_id)."""
  486. from sqlalchemy.orm import selectinload
  487. result = await db.execute(
  488. select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id == archive_id)
  489. )
  490. archive = result.scalar_one_or_none()
  491. if not archive:
  492. raise HTTPException(404, "Archive not found")
  493. for field, value in update_data.model_dump(exclude_unset=True).items():
  494. setattr(archive, field, value)
  495. await db.commit()
  496. # Re-fetch with project relationship loaded after commit
  497. result = await db.execute(
  498. select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id == archive_id)
  499. )
  500. archive = result.scalar_one_or_none()
  501. return archive_to_response(archive)
  502. @router.post("/{archive_id}/favorite", response_model=ArchiveResponse)
  503. async def toggle_favorite(
  504. archive_id: int,
  505. db: AsyncSession = Depends(get_db),
  506. ):
  507. """Toggle favorite status for an archive."""
  508. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  509. archive = result.scalar_one_or_none()
  510. if not archive:
  511. raise HTTPException(404, "Archive not found")
  512. archive.is_favorite = not archive.is_favorite
  513. await db.commit()
  514. await db.refresh(archive)
  515. return archive
  516. @router.post("/{archive_id}/rescan", response_model=ArchiveResponse)
  517. async def rescan_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  518. """Rescan the 3MF file and update metadata."""
  519. from backend.app.services.archive import ThreeMFParser
  520. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  521. archive = result.scalar_one_or_none()
  522. if not archive:
  523. raise HTTPException(404, "Archive not found")
  524. file_path = settings.base_dir / archive.file_path
  525. if not file_path.exists():
  526. raise HTTPException(404, "Archive file not found")
  527. # Parse the 3MF file
  528. parser = ThreeMFParser(file_path)
  529. metadata = parser.parse()
  530. # Update fields from metadata
  531. if metadata.get("filament_type"):
  532. archive.filament_type = metadata["filament_type"]
  533. if metadata.get("filament_color"):
  534. archive.filament_color = metadata["filament_color"]
  535. if metadata.get("print_time_seconds"):
  536. archive.print_time_seconds = metadata["print_time_seconds"]
  537. if metadata.get("filament_used_grams"):
  538. archive.filament_used_grams = metadata["filament_used_grams"]
  539. if metadata.get("layer_height"):
  540. archive.layer_height = metadata["layer_height"]
  541. if metadata.get("nozzle_diameter"):
  542. archive.nozzle_diameter = metadata["nozzle_diameter"]
  543. if metadata.get("bed_temperature"):
  544. archive.bed_temperature = metadata["bed_temperature"]
  545. if metadata.get("nozzle_temperature"):
  546. archive.nozzle_temperature = metadata["nozzle_temperature"]
  547. if metadata.get("makerworld_url"):
  548. archive.makerworld_url = metadata["makerworld_url"]
  549. if metadata.get("designer"):
  550. archive.designer = metadata["designer"]
  551. # Calculate cost based on filament usage and type
  552. if archive.filament_used_grams and archive.filament_type:
  553. primary_type = archive.filament_type.split(",")[0].strip()
  554. filament_result = await db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  555. filament = filament_result.scalar_one_or_none()
  556. if filament:
  557. archive.cost = round((archive.filament_used_grams / 1000) * filament.cost_per_kg, 2)
  558. else:
  559. archive.cost = round((archive.filament_used_grams / 1000) * 25.0, 2)
  560. await db.commit()
  561. await db.refresh(archive)
  562. return archive
  563. @router.post("/recalculate-costs")
  564. async def recalculate_all_costs(db: AsyncSession = Depends(get_db)):
  565. """Recalculate costs for all archives based on filament usage and prices."""
  566. result = await db.execute(select(PrintArchive))
  567. archives = list(result.scalars().all())
  568. # Load all filaments for lookup
  569. filament_result = await db.execute(select(Filament))
  570. filaments = {f.type: f.cost_per_kg for f in filament_result.scalars().all()}
  571. default_cost_per_kg = 25.0
  572. updated = 0
  573. for archive in archives:
  574. if archive.filament_used_grams and archive.filament_type:
  575. primary_type = archive.filament_type.split(",")[0].strip()
  576. cost_per_kg = filaments.get(primary_type, default_cost_per_kg)
  577. new_cost = round((archive.filament_used_grams / 1000) * cost_per_kg, 2)
  578. if archive.cost != new_cost:
  579. archive.cost = new_cost
  580. updated += 1
  581. await db.commit()
  582. return {"message": f"Recalculated costs for {updated} archives", "updated": updated}
  583. @router.post("/rescan-all")
  584. async def rescan_all_archives(db: AsyncSession = Depends(get_db)):
  585. """Rescan all archives and update their metadata."""
  586. from backend.app.services.archive import ThreeMFParser
  587. result = await db.execute(select(PrintArchive))
  588. archives = list(result.scalars().all())
  589. updated = 0
  590. errors = []
  591. for archive in archives:
  592. try:
  593. file_path = settings.base_dir / archive.file_path
  594. if not file_path.exists():
  595. errors.append({"id": archive.id, "error": "File not found"})
  596. continue
  597. parser = ThreeMFParser(file_path)
  598. metadata = parser.parse()
  599. if metadata.get("filament_type"):
  600. archive.filament_type = metadata["filament_type"]
  601. if metadata.get("filament_color"):
  602. archive.filament_color = metadata["filament_color"]
  603. if metadata.get("print_time_seconds"):
  604. archive.print_time_seconds = metadata["print_time_seconds"]
  605. if metadata.get("filament_used_grams"):
  606. archive.filament_used_grams = metadata["filament_used_grams"]
  607. if metadata.get("layer_height"):
  608. archive.layer_height = metadata["layer_height"]
  609. if metadata.get("nozzle_diameter"):
  610. archive.nozzle_diameter = metadata["nozzle_diameter"]
  611. if metadata.get("makerworld_url"):
  612. archive.makerworld_url = metadata["makerworld_url"]
  613. if metadata.get("designer"):
  614. archive.designer = metadata["designer"]
  615. updated += 1
  616. except Exception as e:
  617. errors.append({"id": archive.id, "error": str(e)})
  618. await db.commit()
  619. return {"updated": updated, "errors": errors}
  620. @router.get("/{archive_id}/duplicates")
  621. async def get_archive_duplicates(archive_id: int, db: AsyncSession = Depends(get_db)):
  622. """Get duplicates for a specific archive."""
  623. service = ArchiveService(db)
  624. archive = await service.get_archive(archive_id)
  625. if not archive:
  626. raise HTTPException(404, "Archive not found")
  627. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  628. duplicates = await service.find_duplicates(
  629. archive_id=archive.id,
  630. content_hash=archive.content_hash,
  631. print_name=archive.print_name,
  632. makerworld_model_id=makerworld_id,
  633. )
  634. return {"duplicates": duplicates, "count": len(duplicates)}
  635. @router.post("/backfill-hashes")
  636. async def backfill_content_hashes(db: AsyncSession = Depends(get_db)):
  637. """Compute and store content hashes for all archives missing them."""
  638. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash.is_(None)))
  639. archives = list(result.scalars().all())
  640. updated = 0
  641. errors = []
  642. for archive in archives:
  643. try:
  644. file_path = settings.base_dir / archive.file_path
  645. if not file_path.exists():
  646. errors.append({"id": archive.id, "error": "File not found"})
  647. continue
  648. archive.content_hash = ArchiveService.compute_file_hash(file_path)
  649. updated += 1
  650. except Exception as e:
  651. errors.append({"id": archive.id, "error": str(e)})
  652. await db.commit()
  653. return {"updated": updated, "errors": errors}
  654. @router.delete("/{archive_id}")
  655. async def delete_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  656. """Delete an archive."""
  657. service = ArchiveService(db)
  658. if not await service.delete_archive(archive_id):
  659. raise HTTPException(404, "Archive not found")
  660. return {"status": "deleted"}
  661. @router.get("/{archive_id}/download")
  662. async def download_archive(
  663. archive_id: int,
  664. inline: bool = False,
  665. db: AsyncSession = Depends(get_db),
  666. ):
  667. """Download the 3MF file."""
  668. service = ArchiveService(db)
  669. archive = await service.get_archive(archive_id)
  670. if not archive:
  671. raise HTTPException(404, "Archive not found")
  672. file_path = settings.base_dir / archive.file_path
  673. if not file_path.exists():
  674. raise HTTPException(404, "File not found")
  675. # Use inline disposition to let browser/OS handle file association
  676. content_disposition = "inline" if inline else "attachment"
  677. return FileResponse(
  678. path=file_path,
  679. filename=archive.filename,
  680. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  681. content_disposition_type=content_disposition,
  682. )
  683. @router.get("/{archive_id}/file/{filename}")
  684. async def download_archive_with_filename(
  685. archive_id: int,
  686. filename: str,
  687. db: AsyncSession = Depends(get_db),
  688. ):
  689. """Download the 3MF file with filename in URL (for Bambu Studio protocol)."""
  690. service = ArchiveService(db)
  691. archive = await service.get_archive(archive_id)
  692. if not archive:
  693. raise HTTPException(404, "Archive not found")
  694. file_path = settings.base_dir / archive.file_path
  695. if not file_path.exists():
  696. raise HTTPException(404, "File not found")
  697. return FileResponse(
  698. path=file_path,
  699. filename=archive.filename,
  700. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  701. )
  702. @router.get("/{archive_id}/thumbnail")
  703. async def get_thumbnail(archive_id: int, db: AsyncSession = Depends(get_db)):
  704. """Get the thumbnail image."""
  705. service = ArchiveService(db)
  706. archive = await service.get_archive(archive_id)
  707. if not archive or not archive.thumbnail_path:
  708. raise HTTPException(404, "Thumbnail not found")
  709. thumb_path = settings.base_dir / archive.thumbnail_path
  710. if not thumb_path.exists():
  711. raise HTTPException(404, "Thumbnail file not found")
  712. # Use file modification time as ETag to bust cache
  713. mtime = int(thumb_path.stat().st_mtime)
  714. return FileResponse(
  715. path=thumb_path,
  716. media_type="image/png",
  717. headers={
  718. "Cache-Control": "no-cache, must-revalidate",
  719. "ETag": f'"{mtime}"',
  720. },
  721. )
  722. @router.get("/{archive_id}/timelapse")
  723. async def get_timelapse(archive_id: int, db: AsyncSession = Depends(get_db)):
  724. """Get the timelapse video."""
  725. service = ArchiveService(db)
  726. archive = await service.get_archive(archive_id)
  727. if not archive or not archive.timelapse_path:
  728. raise HTTPException(404, "Timelapse not found")
  729. timelapse_path = settings.base_dir / archive.timelapse_path
  730. if not timelapse_path.exists():
  731. raise HTTPException(404, "Timelapse file not found")
  732. # Use file modification time as ETag to bust cache after processing
  733. mtime = int(timelapse_path.stat().st_mtime)
  734. return FileResponse(
  735. path=timelapse_path,
  736. media_type="video/mp4",
  737. filename=f"{archive.print_name or 'timelapse'}.mp4",
  738. headers={
  739. "Cache-Control": "no-cache, must-revalidate",
  740. "ETag": f'"{mtime}"',
  741. },
  742. )
  743. @router.post("/{archive_id}/timelapse/scan")
  744. async def scan_timelapse(
  745. archive_id: int,
  746. db: AsyncSession = Depends(get_db),
  747. ):
  748. """Scan printer for timelapse matching this archive and attach it."""
  749. from backend.app.models.printer import Printer
  750. from backend.app.services.bambu_ftp import (
  751. download_file_bytes_async,
  752. get_ftp_retry_settings,
  753. list_files_async,
  754. with_ftp_retry,
  755. )
  756. service = ArchiveService(db)
  757. archive = await service.get_archive(archive_id)
  758. if not archive:
  759. raise HTTPException(404, "Archive not found")
  760. if archive.timelapse_path:
  761. return {"status": "exists", "message": "Timelapse already attached"}
  762. if not archive.printer_id:
  763. raise HTTPException(400, "Archive has no associated printer")
  764. # Get printer
  765. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  766. printer = result.scalar_one_or_none()
  767. if not printer:
  768. raise HTTPException(404, "Printer not found")
  769. # Get base name from archive filename (without .3mf extension)
  770. base_name = Path(archive.filename).stem
  771. # Scan timelapse directory on printer
  772. # Try both /timelapse and /timelapse/video (different printer models use different paths)
  773. files = []
  774. for timelapse_path in ["/timelapse", "/timelapse/video"]:
  775. try:
  776. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_path)
  777. if files:
  778. break
  779. except Exception:
  780. continue
  781. if not files:
  782. raise HTTPException(500, "Failed to connect to printer or no timelapse directory found")
  783. # Look for matching timelapse
  784. matching_file = None
  785. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  786. # Strategy 1: Match by print name in filename
  787. for f in mp4_files:
  788. fname = f.get("name", "")
  789. if base_name.lower() in fname.lower():
  790. matching_file = f
  791. break
  792. # Strategy 2: Match by timestamp proximity
  793. # Bambu timelapse filename uses the print START time (when recording began)
  794. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  795. import re
  796. from datetime import datetime, timedelta
  797. # Prefer started_at since video filename is the print start time
  798. # Fall back to completed_at or created_at if started_at is not available
  799. archive_start = archive.started_at
  800. archive_end = archive.completed_at or archive.created_at
  801. best_match = None
  802. best_diff = timedelta(hours=24) # Max 24 hour difference
  803. for f in mp4_files:
  804. fname = f.get("name", "")
  805. # Parse timestamp from filename like "video_2025-11-24_03-17-40.mp4"
  806. match = re.search(r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})", fname)
  807. if match:
  808. try:
  809. file_time = datetime.strptime(match.group(1), "%Y-%m-%d_%H-%M-%S")
  810. # Try multiple timezone offsets since printer timezone can vary
  811. # Common cases: local time (0), CST/UTC+8 (+8), or UTC (-local offset)
  812. for hour_offset in [0, 8, -8, 7, -7, 1, -1]:
  813. adjusted_file_time = file_time - timedelta(hours=hour_offset)
  814. # Check against start time (video filename = print start)
  815. if archive_start:
  816. diff = abs(adjusted_file_time - archive_start)
  817. if diff < best_diff:
  818. best_diff = diff
  819. best_match = f
  820. logger.debug(
  821. f"Timelapse match candidate: {fname} with offset {hour_offset}h, "
  822. f"diff from start: {diff}"
  823. )
  824. # Also check against end time with a buffer
  825. # (video timestamp should be BEFORE completion time)
  826. if archive_end:
  827. # The video timestamp should be within the print duration before completion
  828. if adjusted_file_time < archive_end:
  829. diff = archive_end - adjusted_file_time
  830. # Reasonable print duration: up to 48 hours
  831. if diff < timedelta(hours=48) and diff < best_diff:
  832. best_diff = diff
  833. best_match = f
  834. logger.debug(
  835. f"Timelapse match candidate (from end): {fname} with offset {hour_offset}h, "
  836. f"diff: {diff}"
  837. )
  838. except ValueError:
  839. continue
  840. # Accept match within 4 hours (more lenient for timezone issues)
  841. if best_match and best_diff < timedelta(hours=4):
  842. matching_file = best_match
  843. logger.info(f"Matched timelapse by timestamp: {best_match.get('name')} (diff: {best_diff})")
  844. # Strategy 3: Use file modification time from FTP listing
  845. # This handles cases where printer's filename timestamp is wrong but file mtime is correct
  846. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  847. from datetime import datetime, timedelta
  848. archive_start = archive.started_at
  849. archive_end = archive.completed_at or archive.created_at
  850. best_match = None
  851. best_diff = timedelta(hours=24)
  852. for f in mp4_files:
  853. mtime = f.get("mtime")
  854. if mtime:
  855. # Timelapse file should be modified during or shortly after the print
  856. # The mtime should be close to completion time (video finishes when print ends)
  857. if archive_end:
  858. diff = abs(mtime - archive_end)
  859. if diff < best_diff:
  860. best_diff = diff
  861. best_match = f
  862. logger.debug(
  863. f"Timelapse mtime match candidate: {f.get('name')}, mtime: {mtime}, diff from end: {diff}"
  864. )
  865. if best_match and best_diff < timedelta(hours=2):
  866. matching_file = best_match
  867. logger.info(f"Matched timelapse by file mtime: {best_match.get('name')} (diff: {best_diff})")
  868. # Strategy 4: If only one timelapse exists and archive was recently completed, use it
  869. # This handles cases where printer clock is wrong or timezone issues exist
  870. if not matching_file and len(mp4_files) == 1:
  871. from datetime import datetime, timedelta
  872. archive_completed = archive.completed_at or archive.created_at
  873. if archive_completed:
  874. time_since_completion = datetime.now() - archive_completed
  875. # If archive was completed within the last hour, assume the single timelapse is for it
  876. if time_since_completion < timedelta(hours=1):
  877. matching_file = mp4_files[0]
  878. logger.info(f"Using single timelapse file as fallback: {mp4_files[0].get('name')}")
  879. # Note: We intentionally don't use a "most recent file" fallback because
  880. # we can't verify if timelapse was actually enabled for this print.
  881. # Instead, return the list of available files for manual selection.
  882. if not matching_file:
  883. # Return available files for manual selection
  884. available_files = [
  885. {
  886. "name": f.get("name"),
  887. "path": f.get("path"),
  888. "size": f.get("size"),
  889. "mtime": f.get("mtime").isoformat() if f.get("mtime") else None,
  890. }
  891. for f in mp4_files
  892. ]
  893. # Sort by mtime descending (most recent first)
  894. available_files.sort(key=lambda x: x.get("mtime") or "", reverse=True)
  895. return {
  896. "status": "not_found",
  897. "message": "No matching timelapse found - please select manually",
  898. "available_files": available_files,
  899. }
  900. # Download the timelapse - use the full path from the file listing
  901. remote_path = matching_file.get("path") or f"/timelapse/{matching_file['name']}"
  902. # Get FTP retry settings
  903. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  904. if ftp_retry_enabled:
  905. timelapse_data = await with_ftp_retry(
  906. download_file_bytes_async,
  907. printer.ip_address,
  908. printer.access_code,
  909. remote_path,
  910. socket_timeout=ftp_timeout,
  911. printer_model=printer.model,
  912. max_retries=ftp_retry_count,
  913. retry_delay=ftp_retry_delay,
  914. operation_name=f"Download timelapse {matching_file['name']}",
  915. )
  916. else:
  917. timelapse_data = await download_file_bytes_async(
  918. printer.ip_address,
  919. printer.access_code,
  920. remote_path,
  921. socket_timeout=ftp_timeout,
  922. printer_model=printer.model,
  923. )
  924. if not timelapse_data:
  925. raise HTTPException(500, "Failed to download timelapse")
  926. # Attach timelapse to archive
  927. success = await service.attach_timelapse(archive_id, timelapse_data, matching_file["name"])
  928. if not success:
  929. raise HTTPException(500, "Failed to attach timelapse")
  930. return {
  931. "status": "attached",
  932. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  933. "filename": matching_file["name"],
  934. }
  935. @router.post("/{archive_id}/timelapse/select")
  936. async def select_timelapse(
  937. archive_id: int,
  938. filename: str = Query(..., description="Timelapse filename to attach"),
  939. db: AsyncSession = Depends(get_db),
  940. ):
  941. """Manually select a timelapse from the printer to attach."""
  942. from backend.app.models.printer import Printer
  943. from backend.app.services.bambu_ftp import (
  944. download_file_bytes_async,
  945. get_ftp_retry_settings,
  946. list_files_async,
  947. with_ftp_retry,
  948. )
  949. service = ArchiveService(db)
  950. archive = await service.get_archive(archive_id)
  951. if not archive:
  952. raise HTTPException(404, "Archive not found")
  953. if not archive.printer_id:
  954. raise HTTPException(400, "Archive has no associated printer")
  955. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  956. printer = result.scalar_one_or_none()
  957. if not printer:
  958. raise HTTPException(404, "Printer not found")
  959. # Find the file on the printer
  960. files = []
  961. remote_path = None
  962. for timelapse_dir in ["/timelapse", "/timelapse/video"]:
  963. try:
  964. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_dir)
  965. for f in files:
  966. if f.get("name") == filename:
  967. remote_path = f.get("path") or f"{timelapse_dir}/{filename}"
  968. break
  969. if remote_path:
  970. break
  971. except Exception:
  972. continue
  973. if not remote_path:
  974. raise HTTPException(404, f"Timelapse '{filename}' not found on printer")
  975. # Download and attach
  976. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  977. if ftp_retry_enabled:
  978. timelapse_data = await with_ftp_retry(
  979. download_file_bytes_async,
  980. printer.ip_address,
  981. printer.access_code,
  982. remote_path,
  983. socket_timeout=ftp_timeout,
  984. printer_model=printer.model,
  985. max_retries=ftp_retry_count,
  986. retry_delay=ftp_retry_delay,
  987. operation_name=f"Download timelapse {filename}",
  988. )
  989. else:
  990. timelapse_data = await download_file_bytes_async(
  991. printer.ip_address,
  992. printer.access_code,
  993. remote_path,
  994. socket_timeout=ftp_timeout,
  995. printer_model=printer.model,
  996. )
  997. if not timelapse_data:
  998. raise HTTPException(500, "Failed to download timelapse")
  999. success = await service.attach_timelapse(archive_id, timelapse_data, filename)
  1000. if not success:
  1001. raise HTTPException(500, "Failed to attach timelapse")
  1002. return {
  1003. "status": "attached",
  1004. "message": f"Timelapse '{filename}' attached successfully",
  1005. "filename": filename,
  1006. }
  1007. @router.post("/{archive_id}/timelapse/upload")
  1008. async def upload_timelapse(
  1009. archive_id: int,
  1010. file: UploadFile = File(...),
  1011. db: AsyncSession = Depends(get_db),
  1012. ):
  1013. """Manually upload a timelapse video to an archive."""
  1014. service = ArchiveService(db)
  1015. archive = await service.get_archive(archive_id)
  1016. if not archive:
  1017. raise HTTPException(404, "Archive not found")
  1018. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  1019. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  1020. content = await file.read()
  1021. success = await service.attach_timelapse(archive_id, content, file.filename)
  1022. if not success:
  1023. raise HTTPException(500, "Failed to attach timelapse")
  1024. return {"status": "attached", "filename": file.filename}
  1025. @router.get("/{archive_id}/timelapse/info")
  1026. async def get_timelapse_info(archive_id: int, db: AsyncSession = Depends(get_db)):
  1027. """Get timelapse video metadata for editor."""
  1028. from backend.app.schemas.timelapse import TimelapseInfoResponse
  1029. from backend.app.services.timelapse_processor import TimelapseProcessor
  1030. service = ArchiveService(db)
  1031. archive = await service.get_archive(archive_id)
  1032. if not archive or not archive.timelapse_path:
  1033. raise HTTPException(404, "Timelapse not found")
  1034. timelapse_path = settings.base_dir / archive.timelapse_path
  1035. if not timelapse_path.exists():
  1036. raise HTTPException(404, "Timelapse file not found")
  1037. try:
  1038. processor = TimelapseProcessor(timelapse_path)
  1039. info = await processor.get_info()
  1040. return TimelapseInfoResponse(**info)
  1041. except Exception as e:
  1042. logger.error(f"Failed to get timelapse info: {e}")
  1043. raise HTTPException(500, f"Failed to get video info: {str(e)}")
  1044. @router.get("/{archive_id}/timelapse/thumbnails")
  1045. async def get_timelapse_thumbnails(
  1046. archive_id: int,
  1047. count: int = Query(10, ge=1, le=30),
  1048. width: int = Query(160, ge=80, le=320),
  1049. db: AsyncSession = Depends(get_db),
  1050. ):
  1051. """Generate timeline thumbnail frames for visual scrubbing."""
  1052. import base64
  1053. from backend.app.schemas.timelapse import ThumbnailResponse
  1054. from backend.app.services.timelapse_processor import TimelapseProcessor
  1055. service = ArchiveService(db)
  1056. archive = await service.get_archive(archive_id)
  1057. if not archive or not archive.timelapse_path:
  1058. raise HTTPException(404, "Timelapse not found")
  1059. timelapse_path = settings.base_dir / archive.timelapse_path
  1060. if not timelapse_path.exists():
  1061. raise HTTPException(404, "Timelapse file not found")
  1062. try:
  1063. processor = TimelapseProcessor(timelapse_path)
  1064. thumbnails = await processor.generate_thumbnails(count, width)
  1065. return ThumbnailResponse(
  1066. thumbnails=[base64.b64encode(data).decode() for _, data in thumbnails],
  1067. timestamps=[ts for ts, _ in thumbnails],
  1068. )
  1069. except Exception as e:
  1070. logger.error(f"Failed to generate thumbnails: {e}")
  1071. raise HTTPException(500, f"Failed to generate thumbnails: {str(e)}")
  1072. @router.post("/{archive_id}/timelapse/process")
  1073. async def process_timelapse(
  1074. archive_id: int,
  1075. trim_start: float = Form(0),
  1076. trim_end: float = Form(None),
  1077. speed: float = Form(1.0),
  1078. save_mode: str = Form("new"),
  1079. output_filename: str = Form(None),
  1080. audio: UploadFile = File(None),
  1081. db: AsyncSession = Depends(get_db),
  1082. ):
  1083. """Process timelapse with trim, speed, and optional audio overlay."""
  1084. import shutil
  1085. import tempfile
  1086. from backend.app.schemas.timelapse import ProcessResponse
  1087. from backend.app.services.timelapse_processor import TimelapseProcessor
  1088. # Validate speed
  1089. if not 0.25 <= speed <= 4.0:
  1090. raise HTTPException(400, "Speed must be between 0.25 and 4.0")
  1091. if save_mode not in ("replace", "new"):
  1092. raise HTTPException(400, "save_mode must be 'replace' or 'new'")
  1093. service = ArchiveService(db)
  1094. archive = await service.get_archive(archive_id)
  1095. if not archive or not archive.timelapse_path:
  1096. raise HTTPException(404, "Timelapse not found")
  1097. timelapse_path = settings.base_dir / archive.timelapse_path
  1098. if not timelapse_path.exists():
  1099. raise HTTPException(404, "Timelapse file not found")
  1100. archive_dir = timelapse_path.parent
  1101. # Handle audio file
  1102. audio_temp_path = None
  1103. if audio and audio.filename:
  1104. # Validate audio file extension
  1105. if not audio.filename.lower().endswith((".mp3", ".wav", ".m4a", ".aac", ".ogg")):
  1106. raise HTTPException(400, "Audio must be .mp3, .wav, .m4a, .aac, or .ogg")
  1107. audio_content = await audio.read()
  1108. suffix = Path(audio.filename).suffix
  1109. audio_temp_path = Path(tempfile.gettempdir()) / f"audio_{archive_id}{suffix}"
  1110. audio_temp_path.write_bytes(audio_content)
  1111. try:
  1112. processor = TimelapseProcessor(timelapse_path)
  1113. # Determine output path
  1114. if save_mode == "replace":
  1115. # Process to temp file first, then replace
  1116. temp_output = Path(tempfile.gettempdir()) / f"processed_{archive_id}.mp4"
  1117. output_path = temp_output
  1118. else:
  1119. # Save as new file alongside original
  1120. filename = output_filename or f"{archive.print_name or 'timelapse'}_edited.mp4"
  1121. # Sanitize filename
  1122. filename = "".join(c for c in filename if c.isalnum() or c in "._- ")
  1123. if not filename.endswith(".mp4"):
  1124. filename += ".mp4"
  1125. output_path = archive_dir / filename
  1126. success = await processor.process(
  1127. output_path=output_path,
  1128. trim_start=trim_start,
  1129. trim_end=trim_end,
  1130. speed=speed,
  1131. audio_path=audio_temp_path,
  1132. )
  1133. if not success:
  1134. raise HTTPException(500, "Video processing failed")
  1135. # Handle save mode
  1136. if save_mode == "replace":
  1137. # Replace original file
  1138. shutil.move(str(output_path), str(timelapse_path))
  1139. final_path = archive.timelapse_path
  1140. message = "Timelapse replaced successfully"
  1141. else:
  1142. final_path = str(output_path.relative_to(settings.base_dir))
  1143. message = f"Saved as {output_path.name}"
  1144. return ProcessResponse(
  1145. status="completed",
  1146. output_path=final_path,
  1147. message=message,
  1148. )
  1149. except HTTPException:
  1150. raise
  1151. except Exception as e:
  1152. logger.error(f"Timelapse processing failed: {e}")
  1153. raise HTTPException(500, f"Processing failed: {str(e)}")
  1154. finally:
  1155. # Cleanup temp audio file
  1156. if audio_temp_path and audio_temp_path.exists():
  1157. audio_temp_path.unlink()
  1158. # ============================================
  1159. # Photo Endpoints
  1160. # ============================================
  1161. @router.post("/{archive_id}/photos")
  1162. async def upload_photo(
  1163. archive_id: int,
  1164. file: UploadFile = File(...),
  1165. db: AsyncSession = Depends(get_db),
  1166. ):
  1167. """Upload a photo of the printed result."""
  1168. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1169. archive = result.scalar_one_or_none()
  1170. if not archive:
  1171. raise HTTPException(404, "Archive not found")
  1172. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  1173. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  1174. # Get archive directory
  1175. file_path = settings.base_dir / archive.file_path
  1176. archive_dir = file_path.parent
  1177. photos_dir = archive_dir / "photos"
  1178. photos_dir.mkdir(exist_ok=True)
  1179. # Generate unique filename
  1180. import uuid
  1181. ext = Path(file.filename).suffix.lower()
  1182. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  1183. photo_path = photos_dir / photo_filename
  1184. # Save file
  1185. content = await file.read()
  1186. photo_path.write_bytes(content)
  1187. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  1188. photos = list(archive.photos or [])
  1189. photos.append(photo_filename)
  1190. archive.photos = photos
  1191. await db.commit()
  1192. await db.refresh(archive)
  1193. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  1194. @router.get("/{archive_id}/photos/{filename}")
  1195. async def get_photo(
  1196. archive_id: int,
  1197. filename: str,
  1198. db: AsyncSession = Depends(get_db),
  1199. ):
  1200. """Get a specific photo."""
  1201. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1202. archive = result.scalar_one_or_none()
  1203. if not archive:
  1204. raise HTTPException(404, "Archive not found")
  1205. file_path = settings.base_dir / archive.file_path
  1206. photo_path = file_path.parent / "photos" / filename
  1207. if not photo_path.exists():
  1208. raise HTTPException(404, "Photo not found")
  1209. # Determine media type
  1210. ext = Path(filename).suffix.lower()
  1211. media_types = {
  1212. ".jpg": "image/jpeg",
  1213. ".jpeg": "image/jpeg",
  1214. ".png": "image/png",
  1215. ".webp": "image/webp",
  1216. }
  1217. media_type = media_types.get(ext, "image/jpeg")
  1218. return FileResponse(path=photo_path, media_type=media_type)
  1219. @router.delete("/{archive_id}/photos/{filename}")
  1220. async def delete_photo(
  1221. archive_id: int,
  1222. filename: str,
  1223. db: AsyncSession = Depends(get_db),
  1224. ):
  1225. """Delete a photo."""
  1226. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1227. archive = result.scalar_one_or_none()
  1228. if not archive:
  1229. raise HTTPException(404, "Archive not found")
  1230. if not archive.photos or filename not in archive.photos:
  1231. raise HTTPException(404, "Photo not found")
  1232. # Delete file
  1233. file_path = settings.base_dir / archive.file_path
  1234. photo_path = file_path.parent / "photos" / filename
  1235. if photo_path.exists():
  1236. photo_path.unlink()
  1237. # Update archive photos list
  1238. photos = [p for p in archive.photos if p != filename]
  1239. archive.photos = photos if photos else None
  1240. await db.commit()
  1241. return {"status": "deleted", "photos": archive.photos}
  1242. # ============================================
  1243. # QR Code Endpoint
  1244. # ============================================
  1245. @router.get("/{archive_id}/qrcode")
  1246. async def get_qrcode(
  1247. archive_id: int,
  1248. request: Request,
  1249. size: int = 200,
  1250. db: AsyncSession = Depends(get_db),
  1251. ):
  1252. """Generate a QR code that links to this archive."""
  1253. try:
  1254. import qrcode
  1255. from PIL import Image as PILImage
  1256. except ImportError:
  1257. raise HTTPException(500, "QR code generation not available - qrcode package not installed")
  1258. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1259. archive = result.scalar_one_or_none()
  1260. if not archive:
  1261. raise HTTPException(404, "Archive not found")
  1262. # Build URL to archive download
  1263. base_url = str(request.base_url).rstrip("/")
  1264. archive_url = f"{base_url}/api/v1/archives/{archive_id}/download"
  1265. # Generate QR code
  1266. qr = qrcode.QRCode(
  1267. version=1,
  1268. error_correction=qrcode.constants.ERROR_CORRECT_M,
  1269. box_size=10,
  1270. border=2,
  1271. )
  1272. qr.add_data(archive_url)
  1273. qr.make(fit=True)
  1274. img = qr.make_image(fill_color="black", back_color="white")
  1275. # Convert to PIL Image for resizing
  1276. pil_img = img.get_image()
  1277. # Resize if needed
  1278. if size != 200:
  1279. pil_img = pil_img.resize((size, size), PILImage.Resampling.LANCZOS)
  1280. # Convert to bytes
  1281. buffer = io.BytesIO()
  1282. pil_img.save(buffer, format="PNG")
  1283. buffer.seek(0)
  1284. return Response(
  1285. content=buffer.getvalue(),
  1286. media_type="image/png",
  1287. headers={"Content-Disposition": f'inline; filename="qr_{archive.print_name or archive_id}.png"'},
  1288. )
  1289. @router.get("/{archive_id}/capabilities")
  1290. async def get_archive_capabilities(archive_id: int, db: AsyncSession = Depends(get_db)):
  1291. """Check what viewing capabilities are available for this 3MF file."""
  1292. import json
  1293. import xml.etree.ElementTree as ET
  1294. service = ArchiveService(db)
  1295. archive = await service.get_archive(archive_id)
  1296. if not archive:
  1297. raise HTTPException(404, "Archive not found")
  1298. file_path = settings.base_dir / archive.file_path
  1299. if not file_path.exists():
  1300. raise HTTPException(404, "File not found")
  1301. has_model = False
  1302. has_gcode = False
  1303. has_source = False
  1304. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  1305. filament_colors: list[str] = []
  1306. # Check if source 3MF exists - this is where actual mesh data typically lives
  1307. source_path = None
  1308. if archive.source_3mf_path:
  1309. source_path = settings.base_dir / archive.source_3mf_path
  1310. if source_path.exists():
  1311. has_source = True
  1312. # Helper function to check for mesh data and extract colors from a 3MF file
  1313. def extract_3mf_info(zf_path: Path) -> tuple[bool, list[str], dict]:
  1314. """Extract mesh presence, colors, and build volume from a 3MF file."""
  1315. found_mesh = False
  1316. colors: list[str] = []
  1317. volume = {"x": 256, "y": 256, "z": 256}
  1318. try:
  1319. with zipfile.ZipFile(zf_path, "r") as zf:
  1320. names = zf.namelist()
  1321. # Check for 3D model - look for actual mesh data
  1322. for name in names:
  1323. if name.endswith(".model"):
  1324. try:
  1325. content = zf.read(name).decode("utf-8")
  1326. if "<vertex" in content or "<mesh" in content:
  1327. found_mesh = True
  1328. break
  1329. except Exception:
  1330. pass
  1331. # Extract filament colors from project_settings.config
  1332. if "Metadata/project_settings.config" in names:
  1333. try:
  1334. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1335. config_data = json.loads(config_content)
  1336. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  1337. printable_area = config_data.get("printable_area", [])
  1338. if printable_area and len(printable_area) >= 3:
  1339. max_x = 0
  1340. max_y = 0
  1341. for coord in printable_area:
  1342. if "x" in coord:
  1343. parts = coord.split("x")
  1344. if len(parts) == 2:
  1345. try:
  1346. x, y = int(parts[0]), int(parts[1])
  1347. max_x = max(max_x, x)
  1348. max_y = max(max_y, y)
  1349. except ValueError:
  1350. pass
  1351. if max_x > 0 and max_y > 0:
  1352. volume["x"] = max_x
  1353. volume["y"] = max_y
  1354. # Parse printable_height
  1355. printable_height = config_data.get("printable_height")
  1356. if printable_height:
  1357. try:
  1358. volume["z"] = int(printable_height)
  1359. except (ValueError, TypeError):
  1360. pass
  1361. # Extract filament colors
  1362. raw_colors = config_data.get("filament_colour", [])
  1363. if raw_colors:
  1364. for color in raw_colors:
  1365. if color and isinstance(color, str):
  1366. colors.append(color)
  1367. except Exception:
  1368. pass
  1369. except zipfile.BadZipFile:
  1370. pass
  1371. return found_mesh, colors, volume
  1372. # First check source 3MF for mesh data and colors (preferred for 3D model viewing)
  1373. if has_source and source_path:
  1374. source_has_mesh, source_colors, source_volume = extract_3mf_info(source_path)
  1375. if source_has_mesh:
  1376. has_model = True
  1377. if source_colors:
  1378. filament_colors = source_colors
  1379. if source_volume["x"] != 256 or source_volume["y"] != 256 or source_volume["z"] != 256:
  1380. build_volume = source_volume
  1381. try:
  1382. with zipfile.ZipFile(file_path, "r") as zf:
  1383. names = zf.namelist()
  1384. # Check for G-code in the sliced file
  1385. has_gcode = any(n.startswith("Metadata/") and n.endswith(".gcode") for n in names)
  1386. # Check for 3D model in sliced file (fallback if no source)
  1387. if not has_model:
  1388. for name in names:
  1389. if name.endswith(".model"):
  1390. try:
  1391. content = zf.read(name).decode("utf-8")
  1392. if "<vertex" in content or "<mesh" in content:
  1393. has_model = True
  1394. break
  1395. except Exception:
  1396. pass
  1397. # Extract filament colors from slice_info.config (for gcode preview)
  1398. # These are the actual filaments used in the print, indexed by tool/extruder
  1399. slice_colors: list[str] = []
  1400. if "Metadata/slice_info.config" in names:
  1401. try:
  1402. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1403. root = ET.fromstring(slice_content)
  1404. filaments = root.findall(".//filament")
  1405. filament_map: dict[int, str] = {}
  1406. for f in filaments:
  1407. fid = f.get("id")
  1408. fcolor = f.get("color")
  1409. used_g = f.get("used_g", "0")
  1410. try:
  1411. used_amount = float(used_g)
  1412. except (ValueError, TypeError):
  1413. used_amount = 0
  1414. if fid is not None and fcolor:
  1415. try:
  1416. tool_id = int(fid) - 1
  1417. if tool_id >= 0 and used_amount > 0:
  1418. filament_map[tool_id] = fcolor
  1419. except ValueError:
  1420. pass
  1421. if filament_map:
  1422. max_tool = max(filament_map.keys())
  1423. for i in range(max_tool + 1):
  1424. slice_colors.append(filament_map.get(i, "#00AE42"))
  1425. except Exception:
  1426. pass
  1427. # Use slice_info colors if we don't have colors from source yet
  1428. if not filament_colors and slice_colors:
  1429. filament_colors = slice_colors
  1430. # Extract build volume from sliced file if not already set from source
  1431. if build_volume["x"] == 256 and build_volume["y"] == 256:
  1432. if "Metadata/project_settings.config" in names:
  1433. try:
  1434. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1435. config_data = json.loads(config_content)
  1436. printable_area = config_data.get("printable_area", [])
  1437. if printable_area and len(printable_area) >= 3:
  1438. max_x = 0
  1439. max_y = 0
  1440. for coord in printable_area:
  1441. if "x" in coord:
  1442. parts = coord.split("x")
  1443. if len(parts) == 2:
  1444. try:
  1445. x, y = int(parts[0]), int(parts[1])
  1446. max_x = max(max_x, x)
  1447. max_y = max(max_y, y)
  1448. except ValueError:
  1449. pass
  1450. if max_x > 0 and max_y > 0:
  1451. build_volume["x"] = max_x
  1452. build_volume["y"] = max_y
  1453. printable_height = config_data.get("printable_height")
  1454. if printable_height:
  1455. try:
  1456. build_volume["z"] = int(printable_height)
  1457. except (ValueError, TypeError):
  1458. pass
  1459. # Fallback colors from project_settings if still empty
  1460. if not filament_colors:
  1461. raw_colors = config_data.get("filament_colour", [])
  1462. if raw_colors:
  1463. for color in raw_colors:
  1464. if color and isinstance(color, str):
  1465. filament_colors.append(color)
  1466. except Exception:
  1467. pass
  1468. except zipfile.BadZipFile:
  1469. raise HTTPException(400, "Invalid 3MF file")
  1470. return {
  1471. "has_model": has_model,
  1472. "has_gcode": has_gcode,
  1473. "has_source": has_source,
  1474. "build_volume": build_volume,
  1475. "filament_colors": filament_colors,
  1476. }
  1477. @router.get("/{archive_id}/gcode")
  1478. async def get_gcode(archive_id: int, db: AsyncSession = Depends(get_db)):
  1479. """Extract and return G-code from the 3MF file."""
  1480. service = ArchiveService(db)
  1481. archive = await service.get_archive(archive_id)
  1482. if not archive:
  1483. raise HTTPException(404, "Archive not found")
  1484. file_path = settings.base_dir / archive.file_path
  1485. if not file_path.exists():
  1486. raise HTTPException(404, "File not found")
  1487. try:
  1488. with zipfile.ZipFile(file_path, "r") as zf:
  1489. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  1490. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  1491. if not gcode_files:
  1492. raise HTTPException(
  1493. 404,
  1494. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  1495. )
  1496. # Get the first plate's G-code (usually plate_1.gcode)
  1497. gcode_content = zf.read(gcode_files[0]).decode("utf-8")
  1498. return Response(content=gcode_content, media_type="text/plain")
  1499. except zipfile.BadZipFile:
  1500. raise HTTPException(400, "Invalid 3MF file")
  1501. except HTTPException:
  1502. raise
  1503. except Exception as e:
  1504. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  1505. @router.get("/{archive_id}/plate-preview")
  1506. async def get_plate_preview(archive_id: int, db: AsyncSession = Depends(get_db)):
  1507. """Get the plate preview image from the 3MF file.
  1508. Returns the slicer-generated plate thumbnail which shows the model
  1509. with correct colors and positioning.
  1510. """
  1511. service = ArchiveService(db)
  1512. archive = await service.get_archive(archive_id)
  1513. if not archive:
  1514. raise HTTPException(404, "Archive not found")
  1515. file_path = settings.base_dir / archive.file_path
  1516. if not file_path.exists():
  1517. raise HTTPException(404, "File not found")
  1518. try:
  1519. with zipfile.ZipFile(file_path, "r") as zf:
  1520. names = zf.namelist()
  1521. # Try to find plate preview images in order of preference
  1522. # First look for the specific plate being printed (check slice_info for plate index)
  1523. plate_num = 1
  1524. if "Metadata/slice_info.config" in names:
  1525. try:
  1526. import xml.etree.ElementTree as ET
  1527. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1528. root = ET.fromstring(slice_content)
  1529. plate_elem = root.find(".//plate/metadata[@key='index']")
  1530. if plate_elem is not None:
  1531. plate_num = int(plate_elem.get("value", "1"))
  1532. except Exception:
  1533. pass
  1534. # Try plate-specific image first, then fall back to plate_1
  1535. preview_paths = [
  1536. f"Metadata/plate_{plate_num}.png",
  1537. "Metadata/plate_1.png",
  1538. "Metadata/thumbnail.png",
  1539. ]
  1540. for preview_path in preview_paths:
  1541. if preview_path in names:
  1542. image_data = zf.read(preview_path)
  1543. return Response(content=image_data, media_type="image/png")
  1544. # If no plate image, try any PNG in Metadata
  1545. for name in names:
  1546. if name.startswith("Metadata/plate_") and name.endswith(".png") and "_small" not in name:
  1547. image_data = zf.read(name)
  1548. return Response(content=image_data, media_type="image/png")
  1549. raise HTTPException(404, "No plate preview found in 3MF file")
  1550. except zipfile.BadZipFile:
  1551. raise HTTPException(400, "Invalid 3MF file")
  1552. except HTTPException:
  1553. raise
  1554. except Exception as e:
  1555. raise HTTPException(500, f"Error extracting plate preview: {str(e)}")
  1556. @router.post("/upload")
  1557. async def upload_archive(
  1558. file: UploadFile = File(...),
  1559. printer_id: int | None = None,
  1560. db: AsyncSession = Depends(get_db),
  1561. ):
  1562. """Manually upload a 3MF file to archive."""
  1563. if not file.filename or not file.filename.endswith(".3mf"):
  1564. raise HTTPException(400, "File must be a .3mf file")
  1565. # Save uploaded file temporarily
  1566. temp_path = settings.archive_dir / "temp" / file.filename
  1567. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1568. try:
  1569. content = await file.read()
  1570. temp_path.write_bytes(content)
  1571. service = ArchiveService(db)
  1572. archive = await service.archive_print(
  1573. printer_id=printer_id,
  1574. source_file=temp_path,
  1575. )
  1576. if not archive:
  1577. raise HTTPException(400, "Failed to archive file")
  1578. return ArchiveResponse.model_validate(archive)
  1579. finally:
  1580. if temp_path.exists():
  1581. temp_path.unlink()
  1582. @router.post("/upload-bulk")
  1583. async def upload_archives_bulk(
  1584. files: list[UploadFile] = File(...),
  1585. printer_id: int | None = None,
  1586. db: AsyncSession = Depends(get_db),
  1587. ):
  1588. """Bulk upload multiple 3MF files to archive."""
  1589. results = []
  1590. errors = []
  1591. for file in files:
  1592. if not file.filename or not file.filename.endswith(".3mf"):
  1593. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  1594. continue
  1595. temp_path = settings.archive_dir / "temp" / file.filename
  1596. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1597. try:
  1598. content = await file.read()
  1599. temp_path.write_bytes(content)
  1600. service = ArchiveService(db)
  1601. archive = await service.archive_print(
  1602. printer_id=printer_id,
  1603. source_file=temp_path,
  1604. )
  1605. if archive:
  1606. results.append(
  1607. {
  1608. "filename": file.filename,
  1609. "id": archive.id,
  1610. "status": "success",
  1611. }
  1612. )
  1613. else:
  1614. errors.append({"filename": file.filename, "error": "Failed to process"})
  1615. except Exception as e:
  1616. errors.append({"filename": file.filename, "error": str(e)})
  1617. finally:
  1618. if temp_path.exists():
  1619. temp_path.unlink()
  1620. return {
  1621. "uploaded": len(results),
  1622. "failed": len(errors),
  1623. "results": results,
  1624. "errors": errors,
  1625. }
  1626. @router.get("/{archive_id}/filament-requirements")
  1627. async def get_filament_requirements(
  1628. archive_id: int,
  1629. db: AsyncSession = Depends(get_db),
  1630. ):
  1631. """Get filament requirements from the archived 3MF file.
  1632. Returns the filaments used in this print with their slot IDs, types, colors,
  1633. and usage amounts. This can be compared with current AMS state before reprinting.
  1634. """
  1635. import xml.etree.ElementTree as ET
  1636. service = ArchiveService(db)
  1637. archive = await service.get_archive(archive_id)
  1638. if not archive:
  1639. raise HTTPException(404, "Archive not found")
  1640. file_path = settings.base_dir / archive.file_path
  1641. if not file_path.exists():
  1642. raise HTTPException(404, "Archive file not found")
  1643. filaments = []
  1644. try:
  1645. with zipfile.ZipFile(file_path, "r") as zf:
  1646. # Parse slice_info.config for filament requirements
  1647. if "Metadata/slice_info.config" in zf.namelist():
  1648. content = zf.read("Metadata/slice_info.config").decode()
  1649. root = ET.fromstring(content)
  1650. # Extract filament elements
  1651. # Format: <filament id="1" type="PLA" color="#FFFFFF" used_g="100" used_m="10" />
  1652. for filament_elem in root.findall(".//filament"):
  1653. filament_id = filament_elem.get("id")
  1654. filament_type = filament_elem.get("type", "")
  1655. filament_color = filament_elem.get("color", "")
  1656. used_g = filament_elem.get("used_g", "0")
  1657. used_m = filament_elem.get("used_m", "0")
  1658. # Only include filaments that are actually used
  1659. try:
  1660. used_grams = float(used_g)
  1661. except (ValueError, TypeError):
  1662. used_grams = 0
  1663. if used_grams > 0 and filament_id:
  1664. filaments.append(
  1665. {
  1666. "slot_id": int(filament_id),
  1667. "type": filament_type,
  1668. "color": filament_color,
  1669. "used_grams": round(used_grams, 1),
  1670. "used_meters": float(used_m) if used_m else 0,
  1671. }
  1672. )
  1673. # Sort by slot ID
  1674. filaments.sort(key=lambda x: x["slot_id"])
  1675. except Exception as e:
  1676. logger.warning(f"Failed to parse filament requirements from archive {archive_id}: {e}")
  1677. return {
  1678. "archive_id": archive_id,
  1679. "filename": archive.filename,
  1680. "filaments": filaments,
  1681. }
  1682. @router.post("/{archive_id}/reprint")
  1683. async def reprint_archive(
  1684. archive_id: int,
  1685. printer_id: int,
  1686. body: ReprintRequest | None = None,
  1687. db: AsyncSession = Depends(get_db),
  1688. ):
  1689. """Send an archived 3MF file to a printer and start printing."""
  1690. from backend.app.main import register_expected_print
  1691. from backend.app.models.printer import Printer
  1692. from backend.app.services.bambu_ftp import (
  1693. get_ftp_retry_settings,
  1694. upload_file_async,
  1695. with_ftp_retry,
  1696. )
  1697. from backend.app.services.printer_manager import printer_manager
  1698. # Use defaults if no body provided
  1699. if body is None:
  1700. body = ReprintRequest()
  1701. # Get archive
  1702. service = ArchiveService(db)
  1703. archive = await service.get_archive(archive_id)
  1704. if not archive:
  1705. raise HTTPException(404, "Archive not found")
  1706. # Get printer
  1707. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1708. printer = result.scalar_one_or_none()
  1709. if not printer:
  1710. raise HTTPException(404, "Printer not found")
  1711. # Check printer is connected
  1712. if not printer_manager.is_connected(printer_id):
  1713. raise HTTPException(400, "Printer is not connected")
  1714. # Get the sliced 3MF file path
  1715. file_path = settings.base_dir / archive.file_path
  1716. if not file_path.exists():
  1717. raise HTTPException(404, "Archive file not found")
  1718. # Upload file to printer via FTP
  1719. from backend.app.services.bambu_ftp import delete_file_async
  1720. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  1721. # The printer might reject filenames with unusual extensions
  1722. base_name = archive.filename
  1723. if base_name.endswith(".gcode.3mf"):
  1724. base_name = base_name[:-10] # Remove .gcode.3mf
  1725. elif base_name.endswith(".3mf"):
  1726. base_name = base_name[:-4] # Remove .3mf
  1727. remote_filename = f"{base_name}.3mf"
  1728. remote_path = f"/{remote_filename}"
  1729. # Get FTP retry settings
  1730. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1731. # Delete existing file if present (avoids 553 error)
  1732. await delete_file_async(
  1733. printer.ip_address,
  1734. printer.access_code,
  1735. remote_path,
  1736. socket_timeout=ftp_timeout,
  1737. printer_model=printer.model,
  1738. )
  1739. if ftp_retry_enabled:
  1740. uploaded = await with_ftp_retry(
  1741. upload_file_async,
  1742. printer.ip_address,
  1743. printer.access_code,
  1744. file_path,
  1745. remote_path,
  1746. socket_timeout=ftp_timeout,
  1747. printer_model=printer.model,
  1748. max_retries=ftp_retry_count,
  1749. retry_delay=ftp_retry_delay,
  1750. operation_name=f"Upload for reprint to {printer.name}",
  1751. )
  1752. else:
  1753. uploaded = await upload_file_async(
  1754. printer.ip_address,
  1755. printer.access_code,
  1756. file_path,
  1757. remote_path,
  1758. socket_timeout=ftp_timeout,
  1759. printer_model=printer.model,
  1760. )
  1761. if not uploaded:
  1762. raise HTTPException(500, "Failed to upload file to printer")
  1763. # Register this as an expected print so we don't create a duplicate archive
  1764. register_expected_print(printer_id, remote_filename, archive_id)
  1765. # Detect plate ID from 3MF file
  1766. plate_id = 1
  1767. try:
  1768. with zipfile.ZipFile(file_path, "r") as zf:
  1769. for name in zf.namelist():
  1770. if name.startswith("Metadata/plate_") and name.endswith(".gcode"):
  1771. # Extract plate number from "Metadata/plate_X.gcode"
  1772. plate_str = name[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1773. plate_id = int(plate_str)
  1774. break
  1775. except Exception:
  1776. pass # Default to plate 1 if detection fails
  1777. logger.info(
  1778. f"Reprint archive {archive_id}: plate_id={plate_id}, "
  1779. f"ams_mapping={body.ams_mapping}, bed_levelling={body.bed_levelling}, "
  1780. f"flow_cali={body.flow_cali}, vibration_cali={body.vibration_cali}, "
  1781. f"layer_inspect={body.layer_inspect}, timelapse={body.timelapse}"
  1782. )
  1783. # Start the print with options
  1784. started = printer_manager.start_print(
  1785. printer_id,
  1786. remote_filename,
  1787. plate_id,
  1788. ams_mapping=body.ams_mapping,
  1789. timelapse=body.timelapse,
  1790. bed_levelling=body.bed_levelling,
  1791. flow_cali=body.flow_cali,
  1792. vibration_cali=body.vibration_cali,
  1793. layer_inspect=body.layer_inspect,
  1794. use_ams=body.use_ams,
  1795. )
  1796. if not started:
  1797. raise HTTPException(500, "Failed to start print")
  1798. return {
  1799. "status": "printing",
  1800. "printer_id": printer_id,
  1801. "archive_id": archive_id,
  1802. "filename": archive.filename,
  1803. }
  1804. # =============================================================================
  1805. # Project Page API
  1806. # =============================================================================
  1807. @router.get("/{archive_id}/project-page")
  1808. async def get_project_page(archive_id: int, db: AsyncSession = Depends(get_db)):
  1809. """Get the project page data from the 3MF file."""
  1810. from backend.app.schemas.archive import ProjectPageResponse
  1811. from backend.app.services.archive import ProjectPageParser
  1812. service = ArchiveService(db)
  1813. archive = await service.get_archive(archive_id)
  1814. if not archive:
  1815. raise HTTPException(404, "Archive not found")
  1816. file_path = settings.base_dir / archive.file_path
  1817. if not file_path.exists():
  1818. raise HTTPException(404, "Archive file not found")
  1819. parser = ProjectPageParser(file_path)
  1820. data = parser.parse(archive_id)
  1821. return ProjectPageResponse(**data)
  1822. @router.patch("/{archive_id}/project-page")
  1823. async def update_project_page(
  1824. archive_id: int,
  1825. update_data: dict,
  1826. db: AsyncSession = Depends(get_db),
  1827. ):
  1828. """Update project page metadata in the 3MF file."""
  1829. from backend.app.services.archive import ProjectPageParser
  1830. service = ArchiveService(db)
  1831. archive = await service.get_archive(archive_id)
  1832. if not archive:
  1833. raise HTTPException(404, "Archive not found")
  1834. file_path = settings.base_dir / archive.file_path
  1835. if not file_path.exists():
  1836. raise HTTPException(404, "Archive file not found")
  1837. parser = ProjectPageParser(file_path)
  1838. success = parser.update_metadata(update_data)
  1839. if not success:
  1840. raise HTTPException(500, "Failed to update project page")
  1841. # Return updated data
  1842. data = parser.parse(archive_id)
  1843. return data
  1844. @router.get("/{archive_id}/project-image/{image_path:path}")
  1845. async def get_project_image(
  1846. archive_id: int,
  1847. image_path: str,
  1848. db: AsyncSession = Depends(get_db),
  1849. ):
  1850. """Get an image from the 3MF project page."""
  1851. from backend.app.services.archive import ProjectPageParser
  1852. service = ArchiveService(db)
  1853. archive = await service.get_archive(archive_id)
  1854. if not archive:
  1855. raise HTTPException(404, "Archive not found")
  1856. file_path = settings.base_dir / archive.file_path
  1857. if not file_path.exists():
  1858. raise HTTPException(404, "Archive file not found")
  1859. parser = ProjectPageParser(file_path)
  1860. result = parser.get_image(image_path)
  1861. if not result:
  1862. raise HTTPException(404, "Image not found in 3MF file")
  1863. image_data, content_type = result
  1864. return Response(
  1865. content=image_data,
  1866. media_type=content_type,
  1867. headers={"Cache-Control": "max-age=3600"},
  1868. )
  1869. # =============================================================================
  1870. # Source 3MF API (Original Project Files)
  1871. # =============================================================================
  1872. @router.post("/{archive_id}/source")
  1873. async def upload_source_3mf(
  1874. archive_id: int,
  1875. file: UploadFile = File(...),
  1876. db: AsyncSession = Depends(get_db),
  1877. ):
  1878. """Upload the original source 3MF project file for an archive."""
  1879. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1880. archive = result.scalar_one_or_none()
  1881. if not archive:
  1882. raise HTTPException(404, "Archive not found")
  1883. if not file.filename or not file.filename.endswith(".3mf"):
  1884. raise HTTPException(400, "File must be a .3mf file")
  1885. # Get archive directory and create source subdirectory
  1886. file_path = settings.base_dir / archive.file_path
  1887. archive_dir = file_path.parent
  1888. source_dir = archive_dir / "source"
  1889. source_dir.mkdir(exist_ok=True)
  1890. # Delete old source file if exists
  1891. if archive.source_3mf_path:
  1892. old_source_path = settings.base_dir / archive.source_3mf_path
  1893. if old_source_path.exists():
  1894. old_source_path.unlink()
  1895. # Save the source 3MF file - preserve original filename
  1896. source_filename = file.filename
  1897. source_path = source_dir / source_filename
  1898. content = await file.read()
  1899. source_path.write_bytes(content)
  1900. # Update archive with source path (relative to base_dir)
  1901. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  1902. await db.commit()
  1903. await db.refresh(archive)
  1904. return {
  1905. "status": "uploaded",
  1906. "source_3mf_path": archive.source_3mf_path,
  1907. "filename": source_filename,
  1908. }
  1909. @router.get("/{archive_id}/source")
  1910. async def download_source_3mf(
  1911. archive_id: int,
  1912. db: AsyncSession = Depends(get_db),
  1913. ):
  1914. """Download the source 3MF project file."""
  1915. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1916. archive = result.scalar_one_or_none()
  1917. if not archive:
  1918. raise HTTPException(404, "Archive not found")
  1919. if not archive.source_3mf_path:
  1920. raise HTTPException(404, "No source 3MF attached to this archive")
  1921. source_path = settings.base_dir / archive.source_3mf_path
  1922. if not source_path.exists():
  1923. raise HTTPException(404, "Source 3MF file not found on disk")
  1924. # Use the actual filename from the path
  1925. filename = source_path.name
  1926. return FileResponse(
  1927. path=source_path,
  1928. filename=filename,
  1929. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1930. )
  1931. @router.get("/{archive_id}/source/{filename}")
  1932. async def download_source_3mf_for_slicer(
  1933. archive_id: int,
  1934. filename: str,
  1935. db: AsyncSession = Depends(get_db),
  1936. ):
  1937. """Download source 3MF with filename in URL (for Bambu Studio compatibility)."""
  1938. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1939. archive = result.scalar_one_or_none()
  1940. if not archive:
  1941. raise HTTPException(404, "Archive not found")
  1942. if not archive.source_3mf_path:
  1943. raise HTTPException(404, "No source 3MF attached to this archive")
  1944. source_path = settings.base_dir / archive.source_3mf_path
  1945. if not source_path.exists():
  1946. raise HTTPException(404, "Source 3MF file not found on disk")
  1947. return FileResponse(
  1948. path=source_path,
  1949. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  1950. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1951. )
  1952. @router.post("/upload-source")
  1953. async def upload_source_3mf_by_name(
  1954. file: UploadFile = File(...),
  1955. print_name: str = Query(None, description="Match archive by print name"),
  1956. db: AsyncSession = Depends(get_db),
  1957. ):
  1958. """Upload source 3MF and match to archive by print name.
  1959. This endpoint is designed for slicer post-processing scripts.
  1960. It finds the most recent archive matching the print name and attaches the source.
  1961. """
  1962. if not file.filename or not file.filename.endswith(".3mf"):
  1963. raise HTTPException(400, "File must be a .3mf file")
  1964. # Derive print name from filename if not provided
  1965. if not print_name:
  1966. # Remove .3mf extension and common suffixes
  1967. print_name = file.filename.rsplit(".3mf", 1)[0]
  1968. # Remove _source suffix if present
  1969. if print_name.endswith("_source"):
  1970. print_name = print_name[:-7]
  1971. # Find matching archive - try exact match first, then fuzzy
  1972. result = await db.execute(
  1973. select(PrintArchive)
  1974. .where(PrintArchive.print_name == print_name)
  1975. .order_by(PrintArchive.created_at.desc())
  1976. .limit(1)
  1977. )
  1978. archive = result.scalar_one_or_none()
  1979. if not archive:
  1980. # Try matching filename without .gcode.3mf
  1981. result = await db.execute(
  1982. select(PrintArchive)
  1983. .where(PrintArchive.filename.like(f"{print_name}%"))
  1984. .order_by(PrintArchive.created_at.desc())
  1985. .limit(1)
  1986. )
  1987. archive = result.scalar_one_or_none()
  1988. if not archive:
  1989. # Try case-insensitive partial match on print_name
  1990. result = await db.execute(
  1991. select(PrintArchive)
  1992. .where(PrintArchive.print_name.ilike(f"%{print_name}%"))
  1993. .order_by(PrintArchive.created_at.desc())
  1994. .limit(1)
  1995. )
  1996. archive = result.scalar_one_or_none()
  1997. if not archive:
  1998. raise HTTPException(404, f"No archive found matching '{print_name}'")
  1999. # Get archive directory and create source subdirectory
  2000. file_path = settings.base_dir / archive.file_path
  2001. archive_dir = file_path.parent
  2002. source_dir = archive_dir / "source"
  2003. source_dir.mkdir(exist_ok=True)
  2004. # Delete old source file if exists
  2005. if archive.source_3mf_path:
  2006. old_source_path = settings.base_dir / archive.source_3mf_path
  2007. if old_source_path.exists():
  2008. old_source_path.unlink()
  2009. # Save the source 3MF file - preserve original filename
  2010. source_filename = file.filename
  2011. source_path = source_dir / source_filename
  2012. content = await file.read()
  2013. source_path.write_bytes(content)
  2014. # Update archive with source path
  2015. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  2016. await db.commit()
  2017. await db.refresh(archive)
  2018. return {
  2019. "status": "uploaded",
  2020. "archive_id": archive.id,
  2021. "archive_name": archive.print_name or archive.filename,
  2022. "source_3mf_path": archive.source_3mf_path,
  2023. "filename": source_filename,
  2024. }
  2025. @router.delete("/{archive_id}/source")
  2026. async def delete_source_3mf(
  2027. archive_id: int,
  2028. db: AsyncSession = Depends(get_db),
  2029. ):
  2030. """Delete the source 3MF project file from an archive."""
  2031. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2032. archive = result.scalar_one_or_none()
  2033. if not archive:
  2034. raise HTTPException(404, "Archive not found")
  2035. if not archive.source_3mf_path:
  2036. raise HTTPException(404, "No source 3MF attached to this archive")
  2037. # Delete the file
  2038. source_path = settings.base_dir / archive.source_3mf_path
  2039. if source_path.exists():
  2040. source_path.unlink()
  2041. # Clear the path in database
  2042. archive.source_3mf_path = None
  2043. await db.commit()
  2044. return {"status": "deleted"}